www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1995/02/02/16:51:21

From: bodfish AT austen DOT notis DOT com (John Bodfish)
Subject: Flex and bison
To: djgpp AT sun DOT soe DOT clarkson DOT edu
Date: Thu, 2 Feb 95 12:05:31 CST

Previously, someone asked:
> 
>    Does 263 flex and/or bison generate C++ code.
> 
And the answer was:
> No and yes.  The code is C; why bother with C++ when the point is to
> generate efficient, formally correct code that is easier to intervene
> in than assembly?

I chose to compile the output from flex/bison as C++ to take advantage of
the String class in the libgpp library. It makes the purpose of the yacc
rules more evident. I'm parsing assembler source, altering some of it, and
writing the altered version back out. I've defined the variable yylval to
be of type String with:

	#include <_string.h>
	#define YYSTYPE String

My rules concatenate the token's values (after processing some of them) for
eventual output. For example, here's the code in one of my actions:

address:        MEMORY_REF
              | NUMERIC_LITERAL
              | address PLUS address { $$ = $1 + $2 + $3; }
              | address MINUS address { $$ = $1 + $2 + $3; }
              | address DIVIDED_BY address { $$ = $1 + $2 + $3; }
              | address MULTIPLIED_BY address { $$ = $1 + $2 + $3; }
              ;

This seemed easier and more expressive to me than using the str*() functions.

It turned out to be tougher to get working than I thought. When I
compiled the bison output as C++ (using the -x c++ option to gcc) the
linkage failed because, I believe, the main() function in the flex and
bison libraries isn't C++-compiled. That meant it didn't have the
mangled names for yyparse that were needed for the C++-compiled version
of my grammar. I had to write my own main() in the bison input.
(I won't swear that I found the "best" solution to the problem, just that
it works, which is good enough for me.)

> You could ask that the code be wrapped in a C++
> class, I suppose.  On the other hand, it will compile under C++.  At
> least the few small examples I have tried do.

You can also have flex generate a C++ scanner class (using the -+ option
to flex) which the flexdoc.1 file says is useful if you require multiple
lexxers in your program. But so far, that's something I haven't tried.

> 
> As I recall, you don't even have to deal with the linkage issue (Bison
> and Flex both come with libraries); the headers are already properly
> "wrapped" with linkage directives.
> 

This is true, the headers are properly "wrapped". But beware the problem
I had with main().

John Bodfish
bodfish AT notis DOT com

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019