if-then-else under yacc

"Dave Brotherstone" <davegb@nospam.pobox.com>
23 Jul 2001 02:28:54 -0400

          From comp.compilers

Related articles
if-then-else under yacc davegb@nospam.pobox.com (Dave Brotherstone) (2001-07-23)
Re: if-then-else under yacc davegb@pobox.com (Dave Brotherstone) (2001-07-27)
Re: if-then-else under yacc kvinay@ip.eth.net (Vinay Kakade) (2001-07-27)
| List of all articles for this month |
From: "Dave Brotherstone" <davegb@nospam.pobox.com>
Newsgroups: comp.compilers
Date: 23 Jul 2001 02:28:54 -0400
Organization: BT Internet
Keywords: yacc, parse, question
Posted-Date: 23 Jul 2001 02:28:54 EDT

I'm constructing a small compiler to effectively tokenise an simple input
using yacc.


Struggling a bit with if-then-else / if-then to get yacc to do things in the
right order.


if 17 < 45
    no-op
    no-op
endif


what is required out, is a tokenised version (the tests are only allowed to
be simple, i.e. 1 operator)


[if] [<] [17] [45] [jumpto-if-false] [label1] [no-op] [no-op] [label]
[label1]


This will then be binary coded (for interpreting).


However, with the rules


%token IF TEST ENDIF NOOP


stmt_list : /* empty */
                            | stmt stmt_list


stmt : IF expr TEST expr stmt ENDIF terminator { printf("[if] [%2x] [%2x]
[%2x] ", $3, $2, $4); }
                  | noop terminator
noop : NOOP { printf("[no-op] ");




the no-ops come out first, because it has to evaluate "stmt" within the rule
for IF before it evaluates the rule for IF. (Ignoring labels for now, as
this can be done later, it is just the problem with the ordering that is the
main concern).


If anyone can point me in the right direction, I'd be most grateful. I
thought about possibly altering yyparse to get it to traverse the tree in a
different order, but I don't know if there's a better way.


I have control over the design of the language, as it will only be used
internally in the business.


Thanks in Advance,
Dave.
[Plan A: make your tokenized language reverse-polish which is easier to
intepret anyway, in which case the yacc parser will spit out the tokens
in the right order. Plan B: build a parse tree, then walk the tree to
emit the code. Plan C: buffer your almost-emitted tokens in strings,
pass them up the parser creating larger and larger buffered token strings,
then emit at the top. I like Plan A myself. -John]



Post a followup to this message

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