refactor(frontend): 添加对只编译前端的支持

This commit is contained in:
jing
2026-03-17 18:18:55 +08:00
parent 10ea8aad14
commit a091d9108a
6 changed files with 126 additions and 62 deletions

View File

@@ -3,18 +3,66 @@
// 的最小返回表达式编译。
// 后续需要自行添加
grammar SysY;
/*===-------------------------------------------===*/
/* Lexer rules */
/*===-------------------------------------------===*/
INT: 'int';
RETURN: 'return';
ASSIGN: '=';
ADD: '+';
LPAREN: '(';
RPAREN: ')';
LBRACE: '{';
RBRACE: '}';
SEMICOLON: ';';
ID: [a-zA-Z_][a-zA-Z_0-9]*;
ILITERAL: [0-9]+;
WS: [ \t\r\n] -> skip;
LINECOMMENT: '//' ~[\r\n]* -> skip;
BLOCKCOMMENT: '/*' .*? '*/' -> skip;
/*===-------------------------------------------===*/
/* Syntax rules */
/*===-------------------------------------------===*/
compUnit
: funcDef EOF
;
funcDef
: Int Ident L_PAREN R_PAREN block
decl
: btype varDef SEMICOLON
;
block
: L_BRACE blockItem* R_BRACE
btype
: INT
;
varDef
: lValue (ASSIGN initValue)?
;
initValue
: exp
;
funcDef
: funcType ID LPAREN RPAREN blockStmt
;
funcType
: INT
;
blockStmt
: LBRACE blockItem* RBRACE
;
blockItem
@@ -22,63 +70,29 @@ blockItem
| stmt
;
decl
: varDecl
;
stmt
: returnStmt
;
varDecl
: Int Ident (Assign exp)? Semi
;
returnStmt
: Return exp Semi
: RETURN exp SEMICOLON
;
exp
: addExp
: LPAREN exp RPAREN # parenExp
| var # varExp
| number # numberExp
| exp ADD exp # additiveExp
;
addExp
: primary (AddOp primary)*
var
: ID
;
primary
: Number
| Ident
| L_PAREN exp R_PAREN
lValue
: ID
;
Int : 'int';
Return : 'return';
AddOp : '+';
Assign : '=';
Semi : ';';
L_PAREN : '(';
R_PAREN : ')';
L_BRACE : '{';
R_BRACE : '}';
Ident
: [a-zA-Z_][a-zA-Z_0-9]*
;
Number
: [0-9]+
;
WS
: [ \t\r\n]+ -> skip
;
COMMENT
: '//' ~[\r\n]* -> skip
;
BLOCK_COMMENT
: '/*' .*? '*/' -> skip
number
: ILITERAL
;