import ply.yacc as yacc
from parseractions import *
from fetchlexer import tokens


class ParserError(Exception):
    def __init__(self, msg):
        self.msg = msg

############
# Main rules
##########

precedence = (
    ('left', 'AND', 'OR'),
    ('right', 'BANG'),
)


def p_fetchsection(p):
    """fetchcode : fetchlines"""
    p[0] = p[1]


def p_fetchlines(p):
    """fetchlines : fetchline fetchlines
                  | fetchline"""
    p[0] = [p[1]]
    if len(p) > 2:
        p[0] += p[2]


def p_fetchline_modify(p):
    """fetchline : requestline
                 | paramline
                 | headerline
                 | cookieline
                 | filterline
                 | outputline"""
    p[0] = p[1]


def p_error(p):
    "Error in syntax"
    error_msg = "Invalid token: '%s' at line %d" % (p.value, p.lineno)
    raise ParserError(error_msg)


############
# Fetch section
##########

def p_get(p):
    "get : LARROW"
    p[0] = "GET"


def p_post(p):
    "post : RARROW"
    p[0] = "POST"


def p_fetchline_fetch(p):
    """requestline : NAME get  STRING NEWLINE
                   | NAME post STRING NEWLINE"""