cscg24-lolpython

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

yacc_badprec2.py (1496B)


      1# -----------------------------------------------------------------------------
      2# yacc_badprec2.py
      3#
      4# Bad precedence
      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
     15precedence = (
     16    42,
     17    ('left','TIMES','DIVIDE'),
     18    ('right','UMINUS'),
     19    )
     20
     21# dictionary of names
     22names = { }
     23
     24def p_statement_assign(t):
     25    'statement : NAME EQUALS expression'
     26    names[t[1]] = t[3]
     27
     28def p_statement_expr(t):
     29    'statement : expression'
     30    print t[1]
     31
     32def p_expression_binop(t):
     33    '''expression : expression PLUS expression
     34                  | expression MINUS expression
     35                  | expression TIMES expression
     36                  | expression DIVIDE expression'''
     37    if t[2] == '+'  : t[0] = t[1] + t[3]
     38    elif t[2] == '-': t[0] = t[1] - t[3]
     39    elif t[2] == '*': t[0] = t[1] * t[3]
     40    elif t[3] == '/': t[0] = t[1] / t[3]
     41
     42def p_expression_uminus(t):
     43    'expression : MINUS expression %prec UMINUS'
     44    t[0] = -t[2]
     45
     46def p_expression_group(t):
     47    'expression : LPAREN expression RPAREN'
     48    t[0] = t[2]
     49
     50def p_expression_number(t):
     51    'expression : NUMBER'
     52    t[0] = t[1]
     53
     54def p_expression_name(t):
     55    'expression : NAME'
     56    try:
     57        t[0] = names[t[1]]
     58    except LookupError:
     59        print "Undefined name '%s'" % t[1]
     60        t[0] = 0
     61
     62def p_error(t):
     63    print "Syntax error at '%s'" % t.value
     64
     65yacc.yacc()
     66
     67
     68
     69