def parser(): yield T.Value("a") a = yield (T.Regexp(r"[a-z]") >> T.Value("b")) if a[0] == "a": raise GeneratorResult("found a") yield T.Value("a") raise GeneratorResult(a)
import unittest as U sys.path.insert(0, os.path.abspath("..")) import trishula as T def realnum(d): if "fractional" in d: return float(d["integer"] + "." + d["fractional"]) return float(d["integer"]) term = ( ((-(T.Value("-")) >= (lambda x: -1.0 if x is not None else 1.0)) >> (T.Namespace((T.Regexp("[1-9][0-9]*") @ "integer") >> -( T.Value(".") >> (T.Regexp("[0-9]*") @ "fractional"))) >= realnum)) >= (lambda x: x[0] * x[1])) | (T.Value("0") >= float) space = T.Value(" ") def mark_as_parenthesis(d): d["parenthesis"] = True return d parenthesis = (T.Namespace( T.Value("(") >> (T.Ref(lambda: grammar) @ "value") >> T.Value(")")) >= mark_as_parenthesis)
import trishula as T def sep_by1(content, separator): single = content >= (lambda x: [x]) another = (separator >> content) >= (lambda x: x[1]) multi = (content >> +another) >= (lambda x: [x[0], *x[1]]) return multi | single def sep_by(content, separator): return sep_by1(content, separator) | (T.Value("") >= (lambda _: [])) json_ws = T.Regexp(r"[ \n\r\t]*") json_quote = T.Value('\\"') >= (lambda: '"') json_backslash = T.Value("\\\\") >= (lambda: "\\") json_slash = T.Value("\\/") >= (lambda: "/") json_backspace = T.Value("\\b") >= (lambda: "\b") json_lf = T.Value("\\n") >= (lambda: "\n") json_cr = T.Value("\\r") >= (lambda: "\r") json_tab = T.Value("\\t") >= (lambda: "\t") json_unicode = (T.Value("\\u") >> T.Regexp(r"[a-zA-Z0-9]{4}")) >= ( lambda x: chr(int(x[1], base=16))) json_char_escaped = (json_quote | json_backslash | json_slash | json_backspace | json_lf
import trishula as T print(dir(T)) print() def m(f): return lambda x: T.Node(x.status, x.index, f(x.value)) p_number = T.Regexp(r"[0-9\.]+") @ m(float) def wrap(begin, end, content): return (T.Value(begin) >> content >> T.Value(end)) @ m(lambda x: x[0][1]) p_list_inner = (p_number | (T.Regexp(r",\s*") >> p_list_inner)) p_list = wrap("[", "]", p_list_inner | (T.Value("") @ mapper(lambda _: []))) result = T.Parser().parse(grammar, "[3.14]") print(vars(result))
import trishula as T inner = T.Namespace( (T.Regexp(r".") @ "first") >> (T.Regexp(r".") @ "last") ) >= (lambda d: d) outer = T.Namespace( (T.Regexp(r".") @ "begin") >> (inner @ "value") >> (T.Regexp(r".") @ "end") ) >= (lambda d: d) def main(): examples = ( "abcd", "ab", ) for ex in examples: result = T.Parser().parse(outer, ex) print(vars(result)) main()