Building Scanners with LexTopSemantic Actions, Semantic Records and All ThatSpecifying Semantic Actions in YACC

Specifying Semantic Actions in YACC

  1. Specifying actions in YACC is easy. You simply place C code which performs the action in braces (i.e. `{' and `}') at the point in the production where you want the action to occur.
  2. Passing semantic values around is a bit trickier. The mechanisms used are illustrated in Figure *. The actions in the example grammar cause the parser to take whatever date is read and echo it in the "standard" form "March 7, 2004".
  3. If semantic values of any type other than integer are used, you must define the type name "YYSTYPE" to describe the type used (This definition can be included in the first section of the input file).
  4. If the type YYSTYPE is a union type (it usually is) you should (can, must) tell YACC which member of the union will be associated with each terminal and non-terminal whose value is set or used.

    %{
    typedef union{
      int num;
      char *str;
    } YYSTYPE;
    
    char *monthtab[] =
      {   "January",      "February",       "March",        "April",
          "May",          "June",           "July",         "August",
          "September",    "October",        "November",     "December"     };
    %}
    
    %token <str> MONTH
    %token <num> NUMBER
    
    %type <str> monthnum
    %type <num> day year
    %%
    date : day MONTH year            { printf("%s %d, %d", $2, $1, $3); }
         | monthnum '/' day '/' year { printf("%s %d, %d", $1, $3, $5); }
         | MONTH day ',' year        { printf("%s %d, %d", $1, $2, $4); }
         ;
    
    monthnum : NUMBER           { $$ = monthtab[$1 - 1 ] ; }
             ;
    
    day  : NUMBER ;
    
    year : NUMBER ;
    
     

Computer Science 434
Department of Computer Science
Williams College

Building Scanners with LexTopSemantic Actions, Semantic Records and All ThatSpecifying Semantic Actions in YACC