cscg24-lolpython

CSCG 2024 Challenge 'Can I Haz Lolpython?'
git clone https://git.sinitax.com/sinitax/cscg24-lolpython
Log | Files | Refs | sfeed.txt

yacc_sr.py (1416B)


      1# -----------------------------------------------------------------------------
      2# yacc_sr.py
      3#
      4# A grammar with shift-reduce conflicts
      5# -----------------------------------------------------------------------------
      6import sys
      7sys.tracebacklimit = 0
      8
      9sys.path.insert(0,"..")
     10import ply.yacc as yacc
     11
     12from calclex import tokens
     13
     14# Parsing rules
     15
     16# dictionary of names
     17names = { }
     18
     19def p_statement_assign(t):
     20    'statement : NAME EQUALS expression'
     21    names[t[1]] = t[3]
     22
     23def p_statement_expr(t):
     24    'statement : expression'
     25    print t[1]
     26
     27def p_expression_binop(t):
     28    '''expression : expression PLUS expression
     29                  | expression MINUS expression
     30                  | expression TIMES expression
     31                  | expression DIVIDE expression'''
     32    if t[2] == '+'  : t[0] = t[1] + t[3]
     33    elif t[2] == '-': t[0] = t[1] - t[3]
     34    elif t[2] == '*': t[0] = t[1] * t[3]
     35    elif t[3] == '/': t[0] = t[1] / t[3]
     36
     37def p_expression_uminus(t):
     38    'expression : MINUS expression'
     39    t[0] = -t[2]
     40
     41def p_expression_group(t):
     42    'expression : LPAREN expression RPAREN'
     43    t[0] = t[2]
     44
     45def p_expression_number(t):
     46    'expression : NUMBER'
     47    t[0] = t[1]
     48
     49def p_expression_name(t):
     50    'expression : NAME'
     51    try:
     52        t[0] = names[t[1]]
     53    except LookupError:
     54        print "Undefined name '%s'" % t[1]
     55        t[0] = 0
     56
     57def p_error(t):
     58    print "Syntax error at '%s'" % t.value
     59
     60yacc.yacc()
     61
     62
     63
     64