Re: bison/flex grammar

"Robert Monroe" <>
8 Sep 2002 22:51:55 -0400

          From comp.compilers

Related articles
bison/flex grammar (christian visticot) (2002-09-03)
Re: bison/flex grammar (Robert Monroe) (2002-09-08)
Re: bison/flex grammar (Pete Jinks) (2002-09-08)
Re: bison/flex grammar (Robert Monroe) (2002-09-11)
| List of all articles for this month |

From: "Robert Monroe" <>
Newsgroups: comp.compilers
Date: 8 Sep 2002 22:51:55 -0400
References: 02-09-020
Keywords: parse
Posted-Date: 08 Sep 2002 22:51:55 EDT

"christian visticot" <> wrote
> I try to parse a file like following:
> description=a super example keywords=value1 value2
> and the result would be:
> attribute:description
> values:a super example
> attribute keywords
> values: value1 value2
> I dont know how to write bison/flex files to obtain this result ????

That seems like a good problem to tackle to get familiar with
bison/flex (yacc/lex). As always there are countless reasonable
solutions. To produce the output that you've shown, the most simple
yacc/lex solution that comes to my mind goes like this:

The bison/yacc grammar:

int intval;
char *strval;

%token<strval> VALUE

attribute.file: attribute.list
attribute.list: attribute.value.pair
| attribute.list attribute.value.pair
attribute.value.pair: attribute '=' VALUE
printf("%s: %s\n", $1==DESCRIPTION?"description":"keywords", $3);

Right off the bat you have a small problem with token separators. In
your example you use white space as delimiter between attribute names
and the previous attribute value. Not that it couldn't be handled but
it is messy. Simplify your life by using quotes around your values:

description="a super example" keywords="value1 value2"

Now all of your tokens are neatly delimited.

Specify a (f)lexer:

description {return DESCRIPTION;}
keywords {return KEYWORDS;}
= {return *yytext;}
\"[^\"\n]\" {/* One of a million ways to describe a string */ return
.|\n {/* eat everything else */}

That should fill your needs in terms of lex and yacc specifications. I
leave it to you to read the lex and yacc documentation and fill in the
necessary support code (yyparse, yywrap...). One note: Some people
might (rightly) consider it dangerous to use the value of VALUE as I
did in:

printf("%s: %s\n", $1==DESCRIPTION?"description":"keywords",

I leave it to you to figure out why that might not work in other

The code is just typed in, untested. I hope that helps,

Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.