Token(TOKENTYPES[<运算符>], <运算符>)
Token(TokenType.NUMBER, <运算符>)
Token(TokenType.IDENTIFIER, <运算符>)
Token(KEYWORDSS[<关键字>], <关键字>)
int mod(int a, int b) {
int c = a / b * b;
return a - c;
}
int main() {
int a = 2211247;
int b = 0;
while (a > 0) {
b = b * 10;
b = b + mod(a, 10);
a = a / 10;
}
print b;
return 0;
}
INT: 'int'
IDENTIFIER: 'mod'
LEFT_PAREN: '('
INT: 'int'
IDENTIFIER: 'a'
SEPERATOR: ','
INT: 'int'
IDENTIFIER: 'b'
RIGHT_PAREN: ')'
LEFT_BRACE: '{'
INT: 'int'
IDENTIFIER: 'c'
ASSIGNMENT: '='
IDENTIFIER: 'a'
DIV: '/'
IDENTIFIER: 'b'
MUL: '*'
IDENTIFIER: 'b'
STATEMENT_END: ';'
RETURN: 'return'
IDENTIFIER: 'a'
SUB: '-'
IDENTIFIER: 'c'
STATEMENT_END: ';'
RIGHT_BRACE: '}'
INT: 'int'
IDENTIFIER: 'main'
LEFT_PAREN: '('
RIGHT_PAREN: ')'
LEFT_BRACE: '{'
INT: 'int'
IDENTIFIER: 'a'
ASSIGNMENT: '='
NUMBER: '2211247'
STATEMENT_END: ';'
INT: 'int'
IDENTIFIER: 'b'
ASSIGNMENT: '='
NUMBER: '0'
STATEMENT_END: ';'
WHILE: 'while'
LEFT_PAREN: '('
IDENTIFIER: 'a'
GT: '>'
NUMBER: '0'
RIGHT_PAREN: ')'
LEFT_BRACE: '{'
IDENTIFIER: 'b'
ASSIGNMENT: '='
IDENTIFIER: 'b'
MUL: '*'
NUMBER: '10'
STATEMENT_END: ';'
IDENTIFIER: 'b'
ASSIGNMENT: '='
IDENTIFIER: 'b'
ADD: '+'
IDENTIFIER: 'mod'
LEFT_PAREN: '('
IDENTIFIER: 'a'
SEPERATOR: ','
NUMBER: '10'
RIGHT_PAREN: ')'
STATEMENT_END: ';'
IDENTIFIER: 'a'
ASSIGNMENT: '='
IDENTIFIER: 'a'
DIV: '/'
NUMBER: '10'
STATEMENT_END: ';'
RIGHT_BRACE: '}'
PRINT: 'print'
IDENTIFIER: 'b'
STATEMENT_END: ';'
RETURN: 'return'
NUMBER: '0'
STATEMENT_END: ';'
RIGHT_BRACE: '}'
class Token:
def __init__(self, type_: TokenType, value):
self.type_ = type_
self.value = value
def __repr__(self) -> str:
return f"{self.type_.name}: '{self.value}'"
Token 类型:class TokenType(Enum):
INT = 1
IF = 2
ELSE = 3
WHILE = 4
BREAK = 5
CONTINUE = 6
RETURN = 7
ADD = 8
SUB = 9
MUL = 10
DIV = 11
EQ = 12
NE = 13
GT = 14
LT = 15
GE = 16
LE = 17
AND = 18
OR = 19
NOT = 20
IDENTIFIER = 21
NUMBER = 22
SEPERATOR = 23
STATEMENT_END = 24
LEFT_PAREN = 25
RIGHT_PAREN = 26
LEFT_BRACKET = 27
RIGHT_BRACKET = 28
LEFT_BRACE = 29
RIGHT_BRACE = 30
ASSIGNMENT = 31
INCOMPLETE = 32
PRINT = 33
运算符对应 token 类型字典:TOKENTYPES = {
'+': TokenType.ADD,
'-': TokenType.SUB,
'*': TokenType.MUL,
'/': TokenType.DIV,
'==': TokenType.EQ,
'!=': TokenType.NE,
'>': TokenType.GT,
'<': TokenType.LT,
'>=': TokenType.GE,
'<=': TokenType.LE,
'&': TokenType.AND,
'|': TokenType.OR,
'!': TokenType.NOT,
'(': TokenType.LEFT_PAREN,
')': TokenType.RIGHT_PAREN,
'[': TokenType.LEFT_BRACKET,
']': TokenType.RIGHT_BRACKET,
'{': TokenType.LEFT_BRACE,
'}': TokenType.RIGHT_BRACE,
',': TokenType.SEPERATOR,
';': TokenType.STATEMENT_END,
'=': TokenType.ASSIGNMENT
}
关键字对应 token 类型字典:KEYWORDS = {
'int': TokenType.INT,
'if': TokenType.IF,
'else': TokenType.ELSE,
'while': TokenType.WHILE,
'break': TokenType.BREAK,
'continue': TokenType.CONTINUE,
'return': TokenType.RETURN,
'print': TokenType.PRINT
}