开发者

how to setup flex/bison rules for parsing a comma-delimited argument list

I would like to be able to parse a non-empty, one-or-many element, comma-delimited (and optionally parenthesized) list using flex/bison parse ru开发者_运维技巧les.

some e.g. of parseable lists :

  • 1
  • 1,2
  • (1,2)
  • (3)
  • 3,4,5
  • (3,4,5,6)

etc.

I am using the following rules to parse the list (final result is parse element 'top level list'), but they do not seem to give the desired result when parsing (I get a syntax-error when supplying a valid list). Any suggestion on how I might set this up ?

cList :   ELEMENT
           {
              ...
           }
        | cList COMMA ELEMENT
           {
              ...
           }
        ;

topLevelList :  LPAREN cList RPAREN
                 {
                     ...                 
                 }
              | cList
                 {
                     ...
                 }
          ;


This sounds simple. Tell me if i missed something or if my example doesnt work

RvalCommaList:
          RvalCommaListLoop
    | '(' RvalCommaListLoop ')'

RvalCommaListLoop:
      Rval
    | RvalCommaListLoop ',' Rval

Rval: INT_LITERAL | WHATEVER

However if you accept rvals as well as this list you'll have a conflict confusing a regular rval with a single item list. In this case you can use the below which will either require the '('')' around them or require 2 items before it is a list

RvalCommaList2:
      Rval ',' RvalCommaListLoop
    | '(' RvalCommaListLoop ')'


I too want to know how to do this, thinking about it briefly, one way to achieve this would be to use a linked list of the form,

struct list;
struct list {
    void *item;
    struct list *next;
};

struct list *make_list(void *item, struct list *next);

and using the rule:

{ $$ = make_list( $1, $2); }

This solution is very similar in design to: Using bison to parse list of elements

The hard bit is to figure out how to handle lists in the scheme of a (I presume) binary AST.


%start input
%%
input:
%empty
| integer_list
;

integer_list
: integer_loop
| '(' integer_loop ')'
;

integer_loop
: INTEGER
| integer_loop COMMA INTEGER 
;
%%
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜