python - How to generate a list from a * rule in ANTLR3? -
i have following grammar:
grammar test; options { lang = python; } declaration returns [value] : 'enum' id { statement* } { $value = {'id': $id.text, 'fields': $statement.value} } ; statement returns [value] : id ':' int ';' { $value = {'id': $id.text, 'value': int($int.text)} } ; to parse syntax of type:
enum test { foo: 3; bar: 5; } however, struggling getting statement* rule list of statements. want final parsed object like:
declaration = { 'id': 'test', 'fields': [ {'id': 'foo', 'value': 3}, {'id': 'bar', 'value': 5}, } i can parse each of statement results correctly, each $statement.value correct. but, given asterisk on statement* in rule declaration, there way can condense list of fields ? hoping have sort of syntax gets me option free.
right takes last statement, returns:
declaration = { 'id': 'test', 'fields': [ {'id': 'bar', 'value': 5}, } i want generic solution because grammar has lot of rules of form:
some_declaration : keyword id '{' declaration_statement* '}' ; note: coding in python. have tried coding parser followed tree grammar, last element 1 get, rest discarded.
you can this:
declaration returns [value] : 'enum' id { $value = {'id': $id.text, 'fields': []} } '{' (r=statement { $value['fields'].append($r.value) } )* '}' ; or can pass fields list statement rule parameter, , append new values there. this:
declaration returns [value] : 'enum' id { $value = {'id': $id.text, 'fields': []} } { list = $value['fields'] } '{' statement[list]* '}' ; statement[list] : id ':' int ';' { $list.append({'id': $id.text, 'value': int($int.text)}) } ; depends on want, first option bit nicer.
here can find more examples on returning values 1 rule another: two basic antlr questions
Comments
Post a Comment