import color, mode
from lex import Grammar, PatternRule, RegionRule, PatternMatchRule
from mode.sh import ShGrammar, Sh, StringGrammar1, StringGrammar2

class StanzaGrammar(Grammar): pass
StanzaGrammar.rules = [
    PatternMatchRule('x', r'^( +)([\-@]*)', 'spaces', 'modifier'),
    PatternRule('spaces', r' +'),
    PatternRule('continuation', r'\\\n$'),
    PatternRule('make.extvariable', r'\$\$\{.+?\}'),
    PatternRule('make.extvariable', r'\$\$[a-zA-Z0-9_]+'),
    PatternRule('escaped', r'\$\$'),
    RegionRule('eval', '`', StanzaGrammar, '`'),
    PatternRule('make.variable', r'\$[?@]'),
    PatternRule('make.variable', r'\$[a-zA-Z0-9_]+'),
    PatternRule('make.variable', r'\$\(.+?\)'),
    PatternRule('make.variable', r'\$\{.+?\}'),
    PatternRule('escaped', r'\\.'),
    PatternRule('word', r'[a-zA-Z0-9_]+'),
]

class MakeGrammar(Grammar):
    rules = [
        PatternRule('spaces', ' +'),
        PatternRule('eol', r'\n'),
        PatternRule('make.macro', '[^ :=]+(?= *=)'),
        PatternRule('make.target', '[^ :=]+(?= *:)'),
        PatternRule('comment', r'#.*\n$'),
        RegionRule('make.macro', '=', StanzaGrammar, '^(?=[^ ])'),
        RegionRule('make.target', ':', StanzaGrammar, '^(?=[^ ])'),
    ]

class Make(mode.Fundamental):
    name      = 'Make'
    basenames = ['Makefile']
    grammar   = MakeGrammar
    commentc  = '#'
    savetabs  = True
    colors    = {
        'make.macro':       ('yellow', 'default', 'bold'),
        'make.macro.start': ('default', 'default'),
        'make.macro.word':  ('default', 'default'),
        'make.macro.null':  ('default', 'default'),
        
        'make.macro.eval.start': ('cyan', 'default', 'bold'),
        'make.macro.eval.word':  ('cyan', 'default', 'bold'),
        'make.macro.eval.null':  ('cyan', 'default', 'bold'),
        'make.macro.eval.end':   ('cyan', 'default', 'bold'),

        'make.target':          ('magenta', 'default', 'bold'),
        'make.target.modifier': ('green', 'default', 'bold'),
        'make.target.data':     ('green', 'default', 'bold'),

        'make.target.eval.start': ('cyan', 'default', 'bold'),
        'make.target.eval.word':  ('cyan', 'default', 'bold'),
        'make.target.eval.null':  ('cyan', 'default', 'bold'),
        'make.target.eval.end':   ('cyan', 'default', 'bold'),

        'make.extvariable': ('blue', 'default', 'bold'),
        'make.variable':    ('yellow', 'default', 'bold'),
    }

install = Make.install