Created
December 24, 2021 05:05
-
-
Save glyh/c136165e5b858d68bf4fe888ac021618 to your computer and use it in GitHub Desktop.
Indent Parser in Lark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import nimpy, ./macros # the macros in the other GIST | |
assert(pyImport("sys").version_info.major.to(int) >= 3) | |
let | |
lark = pyImport("lark") | |
idt = pyImport("lark.indenter") | |
tree_grammar = """ | |
?start: _NL* tree | |
tree: NAME _NL [_INDENT tree+ _DEDENT] | |
%import common.CNAME -> NAME | |
%import common.WS_INLINE | |
%declare _INDENT _DEDENT | |
%ignore WS_INLINE | |
_NL: /(\r?\n[\t ]*)+/ | |
""" | |
var indenter = pyInstance(idt.Indenter): | |
var | |
NL_type = "_NL" | |
OPEN_PAREN_types = newSeq[string]() | |
CLOSE_PAREN_types = newSeq[string]() | |
INDENT_type = "_INDENT" | |
DEDENT_type = "_DEDENT" | |
tab_len = 8 | |
let | |
parser = lark.Lark(tree_grammar, parser="lalr", postlex=indenter) | |
test_tree = """a | |
b | |
c | |
d | |
e | |
f | |
g | |
""" | |
echo(parser.parse(test_tree).pretty()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment