help-bison
[Top][All Lists]
Advanced

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

Re: variables of different classes


From: Bob Smith
Subject: Re: variables of different classes
Date: Wed, 30 Apr 2008 11:51:43 -0400
User-agent: Thunderbird 2.0.0.12 (Windows/20080213)



Jack Andrews wrote:
hi guys,

in the typical calculator example that allows statements like:
 a=2+3
it is fairly easy to parse and interpret code like
 b=a+1
but what if you could assign '+' to a variable:
 p=+
now that a variable could be an number or an operator, it's hard to parse
eg. how can i parse string "a p b" ?  what is the grammar?
is it something like this:
  expr:  variable variable variable
?
after a bit of thought, i wondered whether i could feedback type
information to the lexer
so, when i parse 'a=2+3', i tell the lexer that a is a number
then with input 'b=a+1", the lexer would produce:
 VARIABLE '=' VARIABLE NUMBER '+' LITERAL
(the token NUMBER indicate's the variable's type)
and with input "a p 1", the lexer would produce:
 VARIABLE NUMBER VARIABLE OPERATOR LITERAL

will lookahead make this scheme unworkable?

can i make use of multiple lexer/parsers?

any pointer in the right direction appreciated.

One way is to use the following grammar

%token UNK FCN CON VAR

%start Stmt

%%

Stmt:
      UNK '=' FCN
    | UNK '=' VAR
    | UNK '=' Arg FCN Arg
    ;

Arg:
      VAR
    | CON
    ;
%%

along with some smarts in yylex. The latter examines each name and returns either VAR, FCN, or UNK depending upon the current meaning of the name. Typically, this is done in the semantic action for each assignment by saving the meaning of each name in a symbol table and then looking it up in yylex.

So for the rule UNK '=' FCN, the semantic action is to change the meaning of the name which corresponds to UNK to FCN. When that name occurs again, yylex returns FCN for it which then allows input such as "a p 1" you mention.

UNK is returned if the name is not a VAR or FCN, and of course if that name appears to the right of the assignment, there is no matching rule and Bison signals an error. You can handle this more directly by including the rule | UNK in Arg: and signalling your own error in that rule's semantic action.

To re-assign an existing name (that is, a VAR or FCN), simply duplicate the three assignment rules twice to start with VAR '=' and then FCN '='.

This is just a start to a more complicated and involved grammar.

--
_______________________________________________________________
Bob Smith - address@hidden - http://www.sudleyplace.com





reply via email to

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