from .htmllex import tokens

def p_html_document(p):
    'document : html_elements'
    p[0] = [el for el in p if el != None]

def p_html_elements(p):
    '''html_elements : html_elements html_element
                     | html_element
                     | empty'''
    if len(p) == 3:
        p[0] = p[1]
        p[0].append(p[2])
    elif len(p) == 2:
        p[0] = [p[1]]

def p_html_element_open(p):
    '''html_element : TAG_OPEN TAG_NAME html_attributes TAG_CLOSE'''
    if p[3]:
        p[0] = ('open', p[2], p[3])
    else:
        p[0] = ('open', p[2])

def p_html_elment_close(p):
    '''html_element : TAG_OPEN TAG_SLASH TAG_NAME TAG_CLOSE'''
    p[0] = ('close', p[3])

def p_html_elment_open_close(p):
    '''html_element : TAG_OPEN TAG_NAME html_attributes TAG_SLASH_CLOSE'''
    if p[3]:
        p[0] = ('open-close', p[2], p[3])
    else:
        p[0] = ('open-close', p[2])

def p_html_element_other(p):
    '''html_element : dtd
                    | xml
                    | scriptlet
                    | cdata
                    | html_text
                    | html_comment
                    | script
                    | style'''
    p[0] = p[1]

def p_html_attributes(p):
    '''html_attributes : html_attributes html_attribute
                       | html_attribute
                       | empty'''
    if len(p) == 3:
        p[0] = p[1]
        p[0].append(p[2])
    elif len(p) == 2:
        p[0] = [p[1]]

def p_html_attribute(p):
    '''html_attribute : TAG_NAME
                      | TAG_NAME TAG_EQUALS ATTRIBUTE'''
    if len(p) == 2:
        p[0] = ('attribute', p[1])
    else:
        p[0] = ('attribute', p[1], p[3])

def p_dtd(p):
    '''dtd : DTD
           | empty'''
    if p[1]:
        p[0] = ('dtd', p[1])

def p_xml(p):
    '''xml : XML
           | empty'''
    if p[1]:
        p[0] = ('xml', p[1])

def p_scriptlet(p):
    '''scriptlet : SCRIPTLET'''
    p[0] = ('scriptlet', p[1])

def p_cdata(p):
    '''cdata : CDATA'''
    p[0] = ('cdata', p[1])

def p_html_text(p):
    '''html_text : HTML_TEXT'''
    p[0] = ('text', p[1])

def p_html_comment(p):
    '''html_comment : COMMENT
                    | CONDITIONAL_COMMENT'''
    p[0] = ('comment', p[1])

def p_script(p):
    '''script : SCRIPT_OPEN SCRIPT_BODY
              | SCRIPT_OPEN SCRIPT_SHORT_BODY'''
    p[0] = ('script', p[1])

def p_style(p):
    '''style : STYLE_OPEN STYLE_BODY
             | STYLE_OPEN STYLE_SHORT_BODY'''
    p[0] = ('style', p[1])

def p_whitespace(p):
    '''ws : WHITESPACE
          | empty'''
    p[0] = p[1]

def p_empty(p):
    'empty :'
    pass

def p_error(p):
    if p:
         print('Syntax error at token', p.type)
         # just discard the token and tell the parser it's okay.
         #parser.errok()
    else:
         print('Syntax error at EOF')

