CPSC 411 - Lab Notes - 03-12 (Yacc rules)

We reviewed how to create the abstract syntax tree for a variety of rules. The code we developed in class was:


import yacc
from mplex import tokens
from ast import *

def p_prog(t):
    'prog : block'
    t[0]=t[1]

def p_declarations_empty(t):
    'declarations : empty'
    t[0]=[]

def p_declarations_list(t):
    'declarations : declaration SEMICOLON declarations'
    t[0]=[t[1]]+t[3]

def p_declaration(t):
    '''declaration : var_declaration
                    | fundec'''
    t[0]=t[1]

def p_var_declaration(t):
    'var_declaration :  VAR ID arraydimensions COLON type'
    t[0]=decl('var',varid=t[2], vartype=t[5],arraydim=t[3])

def p_fundec(t):
    'fundec : FUN ID paramlist COLON type CLPAR funblock CRPAR'
    t[0]=decl('fun', funid=t[2],funargdecs=t[3],funtype=t[5],funprog=t[7])

def p_expr_1(t):
    'expr  :   expr OR brint_term'
    t[0]=expr(apply=(t[2],[t[1],t[3]])) # tuple of (OP, explist)

def p_expr_2(t):
    'expr :  brint_term'
    t[0]=t[1]
Last modified by Brett Giles

Last modified: Mon Mar 3 11:36:35 MST 2003 Valid XHTML 1.0!