help-bison
[Top][All Lists]
Advanced

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

Re: writing output files in adequation with a given grammar


From: Hans Aberg
Subject: Re: writing output files in adequation with a given grammar
Date: Sat, 13 Mar 2004 12:04:39 +0100

At 14:05 +0100 2004/03/09, Thomas Lavergne wrote:
>I have Yet Another Question that I prefered to separate in another mail:
>What if I want to WRITE grammaticaly correct files. The very basic
>exercise would be to have my program parsing an input file, creates
>objects and rewrite the same input file. Of course, I can do that by
>having 'ObjectPrint()' procedures complying with the given grammar for
>each class. However, if my grammar changes, I need to edit the bison.y
>file AND my objects procedure.
>I was just wondering if someone would have a way to re-use a grammar
>bison.y file to deduce correctly formatted outputs?

If you just want to write the input, you do not need a parser: Simply let
the lexer write out the tokens.

The parser generates a parse tree. Thus, if you want to write it out, you
need to decide how you want to display the parse trees. For example take a
simple calculator grammar:

%token NUMBER
%token IDENTIFIER
%token LP "("
%token RP ")"
%token PLUS "+"
%left "+"
%left "*"
%%
  expression:
      NUMBER
    | IDENTIFIER
    | expression "+" expression
    | expression "*" expression
    | "(" expression ")"
  ;

Here, what one usually wants, if somebody enters, for example, (a+(b*c)),
then the printout should be a + b * c, and 2 + 3 * 4 be printed as 14.

You would then need to build objects, in effect ordered trees, that keep
track of suitable information about the parse, built up of object which
need to know how to print out themselves. For example, the tree
      +
     / \
    a   *
       / \
      b   c
would print out as a + b * c, whereas
      *
     / \
    a   +
       / \
      b   c
would print out as a * (b + c), inserting parenthesizes. You can do this by
letting the + and * objects check whether the arguments is an operator of
lower precedence, and if it is, write out the parenthesizes.

You can get more general information about writing compilers in the
newsgroup comp.compilers and its FAQ, posted there monthly.

  Hans Aberg






reply via email to

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