help-bison
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Tree-like construction while parsing the input file


From: Hans Aberg
Subject: Re: Tree-like construction while parsing the input file
Date: Sat, 10 Jan 2009 23:39:35 +0100

On 10 Jan 2009, at 16:41, Ilyes Gouta wrote:

Here is a snippet of my grammar:

input:
|   declaration input
;

item_list:
|   item_declaration item_list
;

enum_item:
   id                   { add_node_item(handle, &$1); }
|   id '=' expr          { add_node_item(handle, &$1); }
;

declaration:
TYPEDEF ENUM { handle = add_node(TYPE_ENUM); } '{' enum_list '}' id ';'
{ set_node_name(handle, $6.text); check_stack(); }
| STRUCT id { handle = add_node(TYPE_STRUCT); } '{' item_list '}' ';'
{ set_node_name(handle, $2.text); }

add_node(TYPE) will allocate the container as soon as we can tell if we're processing a struct or an enum (for example). Now, I'd like the enum_listand item_list rules to be able to "see" the allocated container so that I can populate it when the parser hits those rules. I don't like to use global variables (such as handle in this example) since declarations may be nested
and thus handle won't point to the correct container.

Any ideas?

The thing is that Bison generates a bottom-up parser. So in your example, the parse tree for item_list is generated only after those of item_declaration and item_list have been generated.

This means that if you want to break that parsing order, you must implement variables global to the parser. If they should not be global to the computer program, they must be put ahead of the parser in the yyparse function.

But sometimes one can do a trick by combining non-terminals into one rule. Then the parse tree of those before will be constructed before those latter. In your example, item_declaration will be constructed before item_list, so one can have actions
  item_declaration {...} item_list {...}
Here, the first action {...} can only use the item_declaration value, but the second can use all that comes before. - See the Bison manual for details.

  Hans







reply via email to

[Prev in Thread] Current Thread [Next in Thread]