编写如下 pascal 子集的词法分析程序
时间: 2023-08-07 09:06:45 浏览: 115
以下是一个简单的基于Pascal子集的词法分析程序:
```pascal
program Lexer;
const
MAXLEN = 100;
type
TokenType = (ID, NUM, PLUS, MINUS, MULT, DIV, LPAREN, RPAREN, ASSIGN, SEMI, ERROR, EOF);
// 定义Token类型
var
TokenString: string;
Token: TokenType;
Line: string;
LineIndex: integer;
function GetChar: char;
begin
if LineIndex <= Length(Line) then
begin
GetChar := Line[LineIndex];
LineIndex := LineIndex + 1;
end
else
GetChar := #0;
end;
procedure GetToken;
var
Ch: char;
begin
TokenString := '';
Token := ERROR;
while (Token = ERROR) and (LineIndex <= Length(Line)) do
begin
Ch := GetChar;
if Ch in ['a'..'z', 'A'..'Z'] then
begin
Token := ID;
while Ch in ['a'..'z', 'A'..'Z', '0'..'9'] do
begin
TokenString := TokenString + Ch;
Ch := GetChar;
end;
LineIndex := LineIndex - 1;
end
else if Ch in ['0'..'9'] then
begin
Token := NUM;
while Ch in ['0'..'9'] do
begin
TokenString := TokenString + Ch;
Ch := GetChar;
end;
LineIndex := LineIndex - 1;
end
else if Ch = '+' then
Token := PLUS
else if Ch = '-' then
Token := MINUS
else if Ch = '*' then
Token := MULT
else if Ch = '/' then
Token := DIV
else if Ch = '(' then
Token := LPAREN
else if Ch = ')' then
Token := RPAREN
else if Ch = '=' then
Token := ASSIGN
else if Ch = ';' then
Token := SEMI;
end;
end;
begin
Line := 'a := 2 + 3;';
LineIndex := 1;
repeat
GetToken;
writeln(TokenString);
until Token = EOF;
end.
```
以上代码实现了一个简单的词法分析程序,可以识别出变量名、数字、加减乘除、括号、赋值符号和分号。你可以根据需要修改 `Line` 的值来测试不同的输入。
阅读全文