help-bison
[Top][All Lists]
Advanced

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

Re: %union and shared pointers to AST nodes


From: Laurence Finston
Subject: Re: %union and shared pointers to AST nodes
Date: Fri, 16 Sep 2005 19:51:43 +0200 (MEST)

On Fri, 16 Sep 2005, Frans Englich wrote:

> From my actions I call factory functions which returns instances I assign to
> the actions($$), in order to build an AST tree. I write in C++, and recently
> converted all code to return/take shared pointers to objects, instead of raw
> pointers.
>
> When it came to converting the Bison grammar, I of course ran into the problem
> that the union can't house class objects(such as shared_ptr instances), but
> only primitive types.

Actually, I think it's that it can't contain objects with constructors or
destructors.  Stroustrup explains this.

> The problem is that the shared pointer goes out of
> scope when the action terminates and hence deletes its object,
> and that's
> before it have been re-attached to a tree, leading to a dangling pointer
> ending up in the union.
>
> What is the best way to solve this?

I use a 'void*' in my '%union' and keep track of "persistent" objects in
the object that I pass to 'yyparse()' as an argument (by means of a
'void*').  For example, in the rule

point_assignment: point_variable ASSIGN point_expression

the semantic value of '$1' is a 'void*' that points to an object of
type 'Id_Map_Entry_Type'.  Since I know this, I can use 'static_cast'
to cast it to the proper type in the rule action.  In fact, the type of
the object is always known from the symbols in the rule, so that I never
need 'dynamic_cast' or run-time type information.
It doesn't matter whether the 'void*' pointer is destroyed.  If '$$' isn't
set to a pointer to your object, the latter will
not be available through a symbol in the next rule to be reduced.
However, there's nothing to stop you from maintaining one or more
references to it in other data  structures, to which you will have access
in the actions.  I would have thought that your tree would be such a data
structure.
If you need to have access to your ojbects as rule symbols, you can "fake"
tokens, i.e., pass pointers to your objects to 'yylex()' and have the
latter return a specific token with a 'void*' pointing to your object as
its semantic value.

Laurence Finston






reply via email to

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