编译原理 SysY语言的词法分析程序

  1. 实验目的与内容
    对SysY语言进行词法分析,可以查出语言中可能包含的词法错误。
    从控制台输入字符串,如有出错则输出错误,没有错误则按照二元组的方式输出
  2. 设计方法
    对SysY语法进行分析如下:
    (1) 保留字: if else for while do continue return break int const main void
      注意:所有关键词都是小写的。
    (2) 标识符ID,与标准C语言一致,即:以下划线或字母开头的字母数字下划线组成的符号串。
    (3)运算符和分界符: +、-、*、/、% 、==、!=、<、>、<=、>= 、!、&&、|| 、(、)、{、}、[、]。
    (4) 空白符包括空格、制表符和换行符,用于分割标识符、保留字、运算符和分界符,词法分析阶段要忽略空白符。
    本程序使用Java编写
    程序启动输入后,字符串保留在instr中。先对字符串进行预处理,去除两个词之间多余的空格,再按空格进行切割。切割完成后逐个单词进行判断,分别判断是否属于保留字、数字、运算符和分界符等等,如果匹配成功则输出。每次判断时使用token逐个读取字符串的各个字符直到一个单词结束并且进行判断。
package cn.hdu;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Word {
   //1.词法分析程序


    public static boolean IsLetter(char ch){
   
        if ((ch >= 'a'&&ch <= 'z') || (ch >= 'A'&&ch <= 'Z'))
            return true;
        return false;
    }

    //判断是否为数字
    public static boolean IsDigit(char ch)
    {
   
        if (ch >= '0'&&ch <= '9')
            return true;
        return false;
    }

    //判断是否为分界符
    public static int IsSymbol(char ch)
    {
   
        char symbol[]= {
    '(',')',',',';','<','>','{','}','[',']'};
        for (int i = 0; i < 8; i++)
        {
   
            if (ch == symbol[i])
                return i;
        }
        return -1;
    }

    //判断是否为关键字
    public static int IsKeyword(String str)
    {
   
        String keyword[] = {
   "if","else","for","while","do", "continue", "return", "break" ,"int", "const", "main", "void" };
        for (int i = 0; i < keyword.length; i++)
        {
   
            if (str.equals(keyword[i]) )
            {
   
                return i;
            }
        }
        //不是关键字即为标识符
        return 30;
    }


    public static boolean IsRight(String str)
    {
   
        char[] chars = str.toCharArray();
       // System.out.println(chars.length);
        int f = 0;
        //for (int i = 0; i < str.length()-1; i++)
        //{
   
           /* if (IsLetter(chars[i]) ||"_".equals( chars[i]))
                f=1;*/
                if (
  • 2
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基本的SysY语言词法分析程序的C++实现: ```c++ #include <iostream> #include <string> #include <vector> using namespace std; // Token类型 enum TokenType { KW_INT, // int KW_VOID, // void KW_IF, // if KW_ELSE, // else KW_WHILE, // while KW_RETURN, // return IDENT, // 标识符 INT_CONST, // 整数常量 PLUS, // + MINUS, // - TIMES, // * DIV, // / ASSIGN, // = EQ, // == NEQ, // != LT, // < LEQ, // <= GT, // > GEQ, // >= LPAREN, // ( RPAREN, // ) LBRACE, // { RBRACE, // } SEMI // ; }; // Token结构体 struct Token { TokenType type; // Token类型 string lexeme; // Token词素 }; // Lexer类 class Lexer { public: // 构造函数 Lexer(string source_code) { this->source_code = source_code; this->current_pos = 0; } // 获取下一个Token Token next_token() { // 跳过空白字符 while (current_pos < source_code.length() && isspace(source_code[current_pos])) { current_pos++; } // 判断是否到达源代码末尾 if (current_pos == source_code.length()) { return { SEMI, "" }; } // 匹配关键字或标识符 if (isalpha(source_code[current_pos])) { string lexeme = ""; while (current_pos < source_code.length() && isalnum(source_code[current_pos])) { lexeme += source_code[current_pos]; current_pos++; } if (lexeme == "int") { return { KW_INT, "" }; } else if (lexeme == "void") { return { KW_VOID, "" }; } else if (lexeme == "if") { return { KW_IF, "" }; } else if (lexeme == "else") { return { KW_ELSE, "" }; } else if (lexeme == "while") { return { KW_WHILE, "" }; } else if (lexeme == "return") { return { KW_RETURN, "" }; } else { return { IDENT, lexeme }; } } // 匹配整数常量 if (isdigit(source_code[current_pos])) { string lexeme = ""; while (current_pos < source_code.length() && isdigit(source_code[current_pos])) { lexeme += source_code[current_pos]; current_pos++; } return { INT_CONST, lexeme }; } // 匹配运算符或其他符号 switch (source_code[current_pos]) { case '+': current_pos++; return { PLUS, "" }; case '-': current_pos++; return { MINUS, "" }; case '*': current_pos++; return { TIMES, "" }; case '/': current_pos++; return { DIV, "" }; case '=': current_pos++; if (current_pos < source_code.length() && source_code[current_pos] == '=') { current_pos++; return { EQ, "" }; } return { ASSIGN, "" }; case '<': current_pos++; if (current_pos < source_code.length() && source_code[current_pos] == '=') { current_pos++; return { LEQ, "" }; } return { LT, "" }; case '>': current_pos++; if (current_pos < source_code.length() && source_code[current_pos] == '=') { current_pos++; return { GEQ, "" }; } return { GT, "" }; case '(': current_pos++; return { LPAREN, "" }; case ')': current_pos++; return { RPAREN, "" }; case '{': current_pos++; return { LBRACE, "" }; case '}': current_pos++; return { RBRACE, "" }; case ';': current_pos++; return { SEMI, "" }; default: cout << "Error: unrecognized character " << source_code[current_pos] << endl; exit(1); } } // 获取所有Token vector<Token> get_all_tokens() { vector<Token> tokens; Token token; do { token = next_token(); tokens.push_back(token); } while (token.type != SEMI); return tokens; } private: string source_code; // 源代码 int current_pos; // 当前位置 }; // 测试程序 int main() { string source_code = "int main() {\n" " int a = 1;\n" " int b = 2;\n" " if (a < b) {\n" " return a + b;\n" " } else {\n" " return a - b;\n" " }\n" "}"; Lexer lexer(source_code); vector<Token> tokens = lexer.get_all_tokens(); for (Token token : tokens) { cout << "Token: type=" << token.type << ", lexeme=" << token.lexeme << endl; } return 0; } ``` 这个词法分析程序可以将SysY源代码转换为Token序列,Token包含类型和词素两个属性。这个程序使用了C++中的类和结构体来实现,同时也使用了C++11的range-based for循环来遍历Token序列并输出结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值