1
votes

I'm writing a Flex/Bison Lexer/Parser in order to parse a script of my own design, as an assignment for University. It's going very well, and my script parses correctly, detects any errors etc. and both recognizes tokens and passes the semantic meanings across.

However, I am a little unsure how to translate this into useful information... I just need to output simple text which is easy enough in itself, however I am struggling with the logic of where to do this in yacc.

For instance, say my yacc is something like this -

statement : 
   DRAW shape AT location  { printf("Draw shape at location"); } 
;

shape : 
   CUBE 
  | PYRAMID
  | SPHERE 
; 

location : 
   '(' NUMBER ',' 'NUMBER' ',' 'NUMBER' ')' { int x = $2; int y = $4; int z = $6;
                                              printf("%d,%d,%d",x,y,z); 
; 

What I would like to do is to have it print out something like drawShape(shape, x, y, z); - but I am unsure how to feed back the semantic values from location into the statement, or how to get whether the shape token found was a cube, a pyramid or a sphere.

At the moment the print statement at location triggers first, so my output is something like

1,2,3Draw shape at location

Is it best just to create some variables to store the semantic values from the location and use them for each statement? (This seems a little sloppy, but I'm not sure how to do this any better.)

2
I have gone ahead and used variables to save any values I wish to use in my output statement which works fine, however I would be interested in a more elegant solution if there is one :) (Or to know if I'm being naive and this is already the best solution!)Eilidh

2 Answers

2
votes

The usual way is to have each action create a data structure that gets returned via $$ and used by later actions. For example, you might have

%union {
    int      ival;
    struct {
        int  x,y,z;
    }        coord;
}

%token<ival>  NUMBER
%type<coord>  location

%%

statement:
    DRAW shape AT location { printf("Draw shape at (%d,%d,%d)\n", $4.x, $4.y, $4.z); }
;

location:
    '(' NUMBER ',' NUMBER ',' NUMBER ')'  { $$.x = $2; $$.y = $4; $$.z = $6; }
;
0
votes

I've gone ahead and changed this to -

statement:
    DRAW shape AT location {printf("Draw shape at (%d, %d, %d)",x,y,z); }
;

location :
    '(' NUMBER ',' NUMBER ',' NUMBER ')' {x=$2; y=$4; z=$6); 
; 

This works correctly, however I would be interested if there is a more elegant solution?