# grammar.py, part of Yapps 2 - yet another python parser system
# Copyright 1999-2003 by Amit J. Patel <amitp@cs.stanford.edu>
# Enhancements copyright 2003-2004 by Matthias Urlichs <smurf@debian.org>
#
# This version of the Yapps 2 grammar can be distributed under the
# terms of the MIT open source license, either found in the LICENSE
# file included with the Yapps distribution
# <http://theory.stanford.edu/~amitp/yapps/> or at
# <http://www.opensource.org/licenses/mit-license.php>
#

"""Parser for Yapps grammars.

This file defines the grammar of Yapps grammars.  Naturally, it is
implemented in Yapps.  The grammar.py module needed by Yapps is built
by running Yapps on yapps_grammar.g.  (Holy circularity, Batman!)

"""

import sys, re
from yapps import parsetree

######################################################################
def cleanup_choice(rule, lst):
    if len(lst) == 0: return Sequence(rule, [])
    if len(lst) == 1: return lst[0]
    return parsetree.Choice(rule, *tuple(lst))

def cleanup_sequence(rule, lst):
    if len(lst) == 1: return lst[0]
    return parsetree.Sequence(rule, *tuple(lst))

def resolve_name(rule, tokens, id, args):
    if id in [x[0] for x in tokens]:
        # It's a token
        if args:
            print('Warning: ignoring parameters on TOKEN %s<<%s>>' % (id, args))
        return parsetree.Terminal(rule, id)
    else:
        # It's a name, so assume it's a nonterminal
        return parsetree.NonTerminal(rule, id, args)


# Begin -- grammar generated by Yapps
import sys, re
from yapps import runtime

class ParserDescriptionScanner(runtime.Scanner):
    patterns = [
        ('"rule"', re.compile('rule')),
        ('"ignore"', re.compile('ignore')),
        ('"token"', re.compile('token')),
        ('"option"', re.compile('option')),
        ('":"', re.compile(':')),
        ('"parser"', re.compile('parser')),
        ('[ \t\r\n]+', re.compile('[ \t\r\n]+')),
        ('#.*?\r?\n', re.compile('#.*?\r?\n')),
        ('EOF', re.compile('$')),
        ('ATTR', re.compile('<<.+?>>')),
        ('STMT', re.compile('{{.+?}}')),
        ('ID', re.compile('[a-zA-Z_][a-zA-Z_0-9]*')),
        ('STR', re.compile('[rR]?\'([^\\n\'\\\\]|\\\\.)*\'|[rR]?"([^\\n"\\\\]|\\\\.)*"')),
        ('LP', re.compile('\\(')),
        ('RP', re.compile('\\)')),
        ('LB', re.compile('\\[')),
        ('RB', re.compile('\\]')),
        ('OR', re.compile('[|]')),
        ('STAR', re.compile('[*]')),
        ('PLUS', re.compile('[+]')),
        ('QUEST', re.compile('[?]')),
        ('COLON', re.compile(':')),
    ]