-
Notifications
You must be signed in to change notification settings - Fork 0
/
grammar.lox
34 lines (33 loc) · 1.94 KB
/
grammar.lox
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 这个是编写interpreter 的大纲,expression 和 statement 的区别,在这个处理过程中有明显的区别。
// 至于 | 的先后顺序,或者一个特性被定性为什么类型的,主要是有设计上的考量,出发点是处理方便。
program -> declaration * EOF ;
declaration -> classDeclaration | varDeclaration | statement | funcDeclaration;
classDeclaration -> "class" IDENTIFIER ("<" IDENTIFIER)? "{" function* "}" ;
funcDeclaration -> "fun" function ;
function -> IDENTIFIER "(" parameters? ")" block ;
parameters -> IDENTIFIER ("," IDENTIFIER )* ;
varDeclaration -> "var" IDENTIFIER ("=" expression)? ";" ;
statement -> exprStmt | forStmt | ifStmt| printStmt | returnStmt | whiteStemt | block ;
returnStmt -> "return" expression? ";" ;
forStmt -> "for" "(" (varDeclaration | exprStmt | ";") expression? ";"expression? ")" statement;
whiteStemt -> "while" "(" expression")" statement ;
ifStmt -> "if" "(" expression ")" statement ("else" statement)? ;
block -> "{" declaration* "}" ;
exprStmt -> expression ";" ;
printStmt -> "print" expression ";" ;
expression -> assignment ;
assignment -> (call ".")? IDENTIFIER "=" assignment | logic_or ;
logic_or -> logic_and ("or" logic_and)* ;
logic_and -> equality ("and" equality)* ;
literal -> NUMBER | STRING | "true" | "false" | "nil" ;
unary -> ("-" | "+") unary | call ;
call -> primary ( "(" arguments? ")" | "." IDENTIFIER )* ;
arguments -> expression ( "," expression )* ;
binary -> expression operator expression ;
operator -> "+" | "-" | "*" | "/" | "==" | "!=" | "<" | "<=" | ">" | ">=" ;
primary -> "true" | "false" | NUMBER | STRING | IDENTIFIER | "(" expression ")" | "nil" | "super" "." IDENTIFIER;
NUMBER -> DIGIT+ ( "." DIGIT+ )? ;
STRING -> "\"" <any char except "\"">* "\"" ;
IDENTIFIER -> ALPHA ( ALPHA | DIGIT )* ;
ALPHA -> "a" ... "z" | "A" ... "Z" | "_" ;
DIGIT -> "0" ... "9" ;