实现词法分析器和语法分析器之前,需要先定义我们将要实现的语言的语法。
一个语言通常包含了变量、函数调用和常量等。为了简便,我们只有32位整数的数值常量,同时,变量是无类型的。
1 numeric expression
numeric_expr := number
2 parenthesis expression
paran_expr := '(' expression ')'
3 identifier expression
identifier_expr := identifier
identifier_expr := identifier '(' expr_list ')'
4
expr_list := (empty)
expr_list := expression (',' expression)*
5 primary expression
primary := identifier_expr
primary := numeric_expr
primary := paran_expr
6 expression can lead to binary expression
expression := primary binoprhs
7 binary expression with RHS can yield combinations of binary operators and expressions
binoprhs := ( binoperator primary)*
binoperator := '+' / '-' / '*' / '/'
8 function declaration
func_decl := identifier '(' identifier_list ')'
identifier_list := (empty)
identifier_list := (identifier)*
9 function definition
function_defn := 'def' func_decl expression
10 top level expression
toplevel_expr := expression
示例
def foo (x, y)
x + y * 16
网友评论