[antlr-interest] Bug report; generated C(++) code inappropriately initialises non-primitive return values

Richard Thrippleton richard.thrippleton at progress.com
Mon Mar 30 08:16:49 PDT 2009


Gary R. Van Sickle wrote:
>> From: Richard Thrippleton
>> 
>> When I have a rule of the form
>> 
>> "rule returns [std::vector<int> foo] ..."
>> 
> 
> Unfortunately, you can't do that.  Under the hood, in the C runtime, 
> rules return a malloc()'ed struct, so your vector<>'s constructor 
> never gets called and you end up with a bit of a mess.
No, return values seem to be stack allocated; at least this has been my
experience in 3.1.1 and 3.1.2

> The only way to make this work at the moment is to do something like
> this:
> 
> rule returns [std::vector<int> *foo] @init { foo = new 
> std::vector<int>; }
> 
> There was talk a week or two ago on the list regarding replacing 
> explicit calls to malloc() with either a redefineable macro (e.g. 
> ANTLR_MALLOC_OR_NEW_YOU_DECIDE()), or (my preference) something to 
> the effect of:
> 
> #ifdef __cplusplus // We're being built as C++. #define ANTLR_NEW() 
> new ... #else /* We're being built as C */ #define ANTLR_NEW() malloc
>  ... #endif
> 
> This would allow what you have above to "just work".  I don't know 
> what if anything became of it however.
> 
>> the generated code for that rule will start with
>> 
>> "std::vector<int> foo = NULL;"
>> 
> 
> Really, it adds that "= NULL" of its own volition?  That sounds like 
> a bug. All kinds of C PODs (structs for instance) could be in there, 
> none of which could be pointers, and that should then fail on C as 
> well as C++.  What version is this?
Yeah, I'm pretty mystified by this. I'm definitely not trying to NULL
anything myself. By experimentation, it looks like it _tries_ to do the
right thing for different datatypes e.g. it will 0 an int.
> Like I noted above, you will run into problems due to the malloc() 
> vs. new thing.  At least I did the last time I tried it.
Well, I guess this is good news for you then ... should Just Work on
3.1.1 and higher :-)

Richard


More information about the antlr-interest mailing list