from mode import Fundamental
from lex import Grammar, PatternRule, RegionRule, PatternMatchRule
from mode.python import StringGrammar1, StringGrammar2, StringGrammar3, StringGrammar4

chr1 = '[a-zA-Z_.?]'
chr2 = '[a-zA-Z0-9_.?$#@~]'
word = chr1 + chr2 + '*'

class NasmGrammar(Grammar):
    rules = [
        PatternRule('comment', ';.*$'),
        PatternRule('nasm.keyword', "(?:section|global|extern)(?!" + chr2 + ")"),
        PatternRule('nasm.macro', "%(?:define|undef|assign|strlen|macro|endmacro|if|elif|else|endif|ifdef|ifndef|include|push|pop|stacksize)(?!" + chr2 + ")"),
        PatternRule('nasm.instruction', "(?:jeq|jne|ja|jmp|push|pushad|pushfd|call|ret|sub|add|pop|popa|popad|popfd|call|and|cwd|cdq|cmp|cmpxchg|cpuid|div|divpd|enter|leave|fadd|fld|fmul|fsqrt|fsub|hlt|imul|inc|int|int3|lea|mov|movd|mul|neg|not|nop|or|sal|sar|shl|shr|shld|shrd|syscall|sysenter|sysexit|test|xchg|xadd|xor)(?!" + chr2 + ")"),
        PatternRule('nasm.register', "(?:eax|ax|ah|al|ebx|bx|bh|bl|ecx|cx|ch|cl|esi|edi|esp|ebp)(?!" + chr2 + ")"),
        PatternRule('nasm.prefix', "(?:dword|word|lock)(?!" + chr2 + ")"),
        PatternMatchRule('x', '(' + word + ')(:)', 'nasm.label', 'delimiter'),
        PatternRule("nasm.identifier", r'\$?' + word),
        PatternRule("nasm.integer", "(0|[1-9][0-9]*|0[0-7]+|0[xX][0-9a-fA-F]+)[lL]?"),
        PatternRule("nasm.float", r"[0-9]+\.[0-9]*|\.[0-9]+|([0-9]|[0-9]+\.[0-9]*|\.[0-9]+)[eE][\+-]?[0-9]+"),
        PatternRule('delimiter', r'(?://|%%|<<|>>|[~!\.\*/%\-\+\(\)\[\],\|\^\&])'),
        RegionRule('string', '"""', StringGrammar4, '"""'),
        RegionRule('string', "'''", StringGrammar3, "'''"),
        RegionRule('string', '"', StringGrammar2, '"'),
        RegionRule('string', "'", StringGrammar1, "'"),
        PatternRule('spaces', ' +'),
        PatternRule('eol', '\n'),
        PatternRule('continuation', r'\\\n$'),
    ]

class Nasm(Fundamental):
    name       = 'nasm'
    extensions = ['.s']
    grammar    = NasmGrammar
    commentc   = ';'
    colors     = {
        'nasm.keyword':     ('cyan', 'default', 'bold'),
        'nasm.macro':       ('blue', 'default', 'bold'),
        'nasm.register':    ('yellow', 'default', 'bold'),
        'nasm.instruction': ('magenta', 'default', 'bold'),
        'nasm.label':       ('blue', 'default', 'bold'),
    }
    _bindings = {
        'close-paren':   (')',),
        'close-brace':   ('}',),
        'close-bracket': (']',),
    }

install = Nasm.install