import color, mode, tab
from lex import Grammar, PatternRule, RegionRule
from mode.c import C, CGrammar, CTabber2

# ugh
_rules = list(CGrammar.rules)
_rules.insert(0, PatternRule(r"yacc_directive", r"^%[a-zA-Z_]+"))
_rules.insert(1, PatternRule(r"yacc_section", r"%%"))
_rules.insert(2, PatternRule(r"yacc_delimiter", r"%{|%}"))
_rules.insert(3, PatternRule(r"yacc_production", r"^[a-z_]+:"))
_rules.insert(4, PatternRule(r"yacc_var", r"\$[0-9\$]"))
_rules.insert(5, PatternRule(r"yacc_empty", r"^ +\n$"))

# TODO: don't think we need this anymore
class TrueDict(dict):
    def __contains__(self, k): return True
    def __getitem__(self, k): return True
    def __setitem__(self, k): pass
    def __delitem__(self, k): raise Exception, 'not possible'
    def __len__(self): return 1
    def __repr__(self): return '<TrueDict()>'
    def get(self, k): return True

class YaccGrammar(CGrammar):
    rules = _rules

class YaccTabber(CTabber2):
    open_tokens       = {
        'delimiter': {'{': '}', '(': ')', '[': ']'},
        'yacc_delimiter': {'%{': '%}'},
    }
    close_tokens      = {
        'delimiter': {'}': '{', ')': '(', ']': '['},
        'yacc_delimiter': {'%}': '%{'},
    }
    control_tokens    = {'yacc_production': TrueDict()}
    scope_tokens      = {}
    end_at_eof        = False
    end_at_tokens     = {'yacc_empty': TrueDict()}
    nocontinue_tokens = {}
    start_free_tokens = {'string.start': 'string.end'}
    end_free_tokens   = {'string.end': 'string.start'}

class Yacc(mode.Fundamental):
    name       = 'yacc'
    extensions = ['.y']
    grammar    = YaccGrammar
    tabbercls  = YaccTabber
    colors     = {
        'yacc_directive':  ('yellow', 'default', 'bold'),
        'yacc_section':    ('yellow', 'default', 'bold'),
        'yacc_delimiter':  ('yellow', 'default', 'bold'),
        'yacc_production': ('yellow', 'default', 'bold'),
        'yacc_var':        ('yellow', 'default', 'bold'),
    }

install = Yacc.install