我正在为一种名为 C-- 的虚构编程语言(不是实际的 C-- 语言)构建一个解析器。我已经到了需要将语言的语法翻译成 Pyparsing 可以接受的阶段。不幸的是,当我解析我的输入字符串(这是正确的,不应该导致 Pyparsing 出错)时,它没有正确解析。我担心这是由于我的语法错误造成的,但是当我第一次开始 Pyparsing 时,我似乎看不出哪里出错了。
我已经上传了我从这里翻译的语法,供人们阅读。
编辑:根据保罗的建议进行了更新。
这是我目前得到的语法(我知道语法定义的前两行对我来说非常糟糕):
# Lexical structure definition
ifS = Keyword('if')
elseS = Keyword('else')
whileS = Keyword('while')
returnS = Keyword('return')
intVar = Keyword('int')
voidKeyword = Keyword('void')
sumdiff = Literal('+') | Literal('-')
prodquot = Literal('*') | Literal('/')
relation = Literal('<=') | Literal('<') | Literal('==') | \
Literal('!=') | Literal('>') | Literal('=>')
lbrace = Literal('{')
rbrace = Literal('}')
lparn = Literal('(')
rparn = Literal(')')
semi = Literal(';')
comma = Literal(',')
number = Word(nums)
identifier = Word(alphas, alphanums)
# Syntax definition
term = ''
statement = ''
variable = intVar + identifier + semi
locals = ZeroOrMore(variable)
expr = term | OneOrMore(Group(sumdiff + term))
args = ZeroOrMore(OneOrMore(Group(expr + comma)) | expr)
funccall = Group(identifier + lparn + args + rparn)
factor = Group(lparn + expr + rparn) | identifier | funccall | number
term = factor | OneOrMore(prodquot + factor)
cond = Group(lparn + expr + relation + expr + rparn)
returnState = Group(returnS + semi) | Combine(returnS + expr + semi)
assignment = Group(identifier + '=' + expr + semi)
proccall = Group(identifier + lparn + args + rparn + semi)
block = Group(lbrace + locals + statement + rbrace)
iteration = Group(whileS + cond + block)
selection = Group(ifS + cond + block) | Group(ifS + cond + block + elseS + block)
statement = OneOrMore(proccall | assignment | selection | iteration | returnState)
param = Group(intVar + identifier)
paramlist = OneOrMore(Combine(param + comma)) | param
params = paramlist | voidKeyword
procedure = Group(voidKeyword + identifier + lparn + params + rparn + block)
function = Group(intVar + identifier + lparn + params + rparn + block)
declaration = variable | function | procedure
program = OneOrMore(declaration)
我想知道我在翻译语法时是否犯了任何错误,以及在遵守给定语法的同时我可以做哪些改进来简化它。
编辑 2:更新以包含新错误。
这是我正在解析的输入字符串:
int larger ( int first , int second ) {
if ( first > second ) {
return first ;
} else {
return second ;
}
}
void main ( void ) {
int count ;
int sum ;
int max ;
int x ;
x = input ( ) ;
max = x ;
sum = 0 ;
count = 0 ;
while ( x != 0 ) {
count = count + 1 ;
sum = sum + x ;
max = larger ( max , x ) ;
x = input ( ) ;
}
output ( count ) ;
output ( sum ) ;
output ( max ) ;
}
这是我从终端运行程序时收到的错误消息:
/Users/Joe/Documents/Eclipse Projects/Parser/src/pyparsing.py:1156: SyntaxWarning: null string passed to Literal; use Empty() instead
other = Literal( other )
/Users/Joe/Documents/Eclipse Projects/Parser/src/pyparsing.py:1258: SyntaxWarning: null string passed to Literal; use Empty() instead
other = Literal( other )
Expected ")" (at char 30), (line:6, col:26)
None