"""Checks UJN files against the grammar in ujn.ebnf (Python standard library only). usage: python ujn_grammar.py [--strict] [--grammar FILE.ebnf] [--quiet] FILE... For each file it prints "ok", or the line and column where parsing stops, with what the grammar expected there. Exit code 1 if any file fails, 2 if the grammar itself cannot be read. --strict drop the rules whose names start with "raw-": every value must then take one of the forms of spec section 5 (text, list, true or false, number, duration, color, trace link, handle, {{auto}}). --grammar another grammar file (default: ujn.ebnf next to this script). --quiet print only the files that fail. The grammar's notation is described at the top of ujn.ebnf. This script reads it as written: rules, terminals, /regex/ lexical classes (where <> stands for the regex of the rule NAME), [ ], { }, ( ) and |. Choices and repetitions are read with full backtracking (each rule returns every place where it can end), so the grammar is a plain context-free grammar, not a PEG. The first rule is the start rule, and it must cover the whole file. Before parsing, a file is read as UTF-8, a byte order mark at its start is dropped, and CR LF and a CR alone are turned into LF, as PlantUML reads line ends. """ from __future__ import annotations import re import sys from pathlib import Path # ------------------------------------------------------------------------------------------------ grammar class GrammarError(Exception): pass class Lit: def __init__(self, text): self.text = text class Rx: def __init__(self, src): self.src = src self.rx = None def compile(self): try: self.rx = re.compile(self.src) except re.error as e: raise GrammarError(f"bad regular expression /{self.src}/: {e}") class Ref: def __init__(self, name): self.name = name class Seq: def __init__(self, items): self.items = items class Alt: def __init__(self, items): self.items = items class Opt: def __init__(self, item): self.item = item class Rep: def __init__(self, item): self.item = item NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_-]*") def tokenize(src: str): """(kind, value, line) for each token: name, lit, rx, or one of = ; | [ ] { } ( ).""" i, n, line = 0, len(src), 1 out = [] while i < n: c = src[i] if c == "\n": line += 1 i += 1 elif c in " \t\r": i += 1 elif src.startswith("(*", i): j = src.find("*)", i + 2) if j < 0: raise GrammarError(f"line {line}: a comment is never closed") line += src.count("\n", i, j) i = j + 2 elif c == '"': j, buf = i + 1, [] while j < n and src[j] != '"': if src[j] == "\\" and j + 1 < n: buf.append({"n": "\n", "t": "\t", '"': '"', "\\": "\\"}.get(src[j + 1], "\\" + src[j + 1])) j += 2 elif src[j] == "\n": raise GrammarError(f"line {line}: a terminal is never closed") else: buf.append(src[j]) j += 1 if j >= n: raise GrammarError(f"line {line}: a terminal is never closed") out.append(("lit", "".join(buf), line)) i = j + 1 elif c == "/": j, buf = i + 1, [] while j < n and src[j] != "/": if src[j] == "\\" and j + 1 < n: buf.append("/" if src[j + 1] == "/" else src[j:j + 2]) j += 2 elif src[j] == "\n": raise GrammarError(f"line {line}: a regular expression is never closed") else: buf.append(src[j]) j += 1 if j >= n: raise GrammarError(f"line {line}: a regular expression is never closed") out.append(("rx", "".join(buf), line)) i = j + 1 elif c in "=;|[]{}()": out.append((c, c, line)) i += 1 else: m = NAME.match(src, i) if not m: raise GrammarError(f"line {line}: unexpected character {c!r}") out.append(("name", m.group(), line)) i = m.end() return out def read_grammar(src: str): """{name: expression} and the name of the start rule (the first rule).""" toks = tokenize(src) pos = 0 def peek(): return toks[pos][0] if pos < len(toks) else None def take(kind): nonlocal pos if peek() != kind: where = f"line {toks[pos][2]}" if pos < len(toks) else "the end" raise GrammarError(f"{where}: expected {kind!r}") pos += 1 return toks[pos - 1] def alt(): items = [seq()] while peek() == "|": take("|") items.append(seq()) return items[0] if len(items) == 1 else Alt(items) def seq(): items = [] while peek() in ("name", "lit", "rx", "[", "{", "("): items.append(term()) return items[0] if len(items) == 1 else Seq(items) def term(): k = peek() if k == "name": return Ref(take("name")[1]) if k == "lit": return Lit(take("lit")[1]) if k == "rx": return Rx(take("rx")[1]) if k == "[": take("[") e = alt() take("]") return Opt(e) if k == "{": take("{") e = alt() take("}") return Rep(e) take("(") e = alt() take(")") return e rules, start = {}, None while pos < len(toks): name = take("name")[1] take("=") if name in rules: raise GrammarError(f"rule {name} is defined twice") rules[name] = alt() take(";") start = start or name if not rules: raise GrammarError("no rules") def refs(e): if isinstance(e, Ref): yield e.name for sub in getattr(e, "items", []): yield from refs(sub) if isinstance(e, (Opt, Rep)): yield from refs(e.item) for name, e in rules.items(): for r in refs(e): if r not in rules: raise GrammarError(f"rule {name} uses {r}, which is not defined") # <> inside a /regex/ stands for the regex of the rule NAME, which must be one /regex/. def regexes(e): if isinstance(e, Rx): yield e for sub in getattr(e, "items", []): yield from regexes(sub) if isinstance(e, (Opt, Rep)): yield from regexes(e.item) def expand(src, seen): def one(m): name = m.group(1) target = rules.get(name) if not isinstance(target, Rx): raise GrammarError(f"<<{name}>>: {name} is not a rule made of one /regex/") if name in seen: raise GrammarError(f"<<{name}>> refers to itself") return expand(target.src, seen | {name}) return FRAGMENT.sub(one, src) for name, e in rules.items(): for rx in regexes(e): rx.src = expand(rx.src, {name} if isinstance(e, Rx) else set()) for e in rules.values(): for rx in regexes(e): rx.compile() return rules, start FRAGMENT = re.compile(r"<<([A-Za-z_][A-Za-z0-9_-]*)>>") def read_source(path) -> str: """The text of a UJN file as the grammar reads it: UTF-8, a leading byte order mark dropped, and every line end (CR LF, or a CR alone, as PlantUML reads them) turned into LF.""" text = Path(path).read_bytes().decode("utf-8") return text.lstrip("\ufeff").replace("\r\n", "\n").replace("\r", "\n") # ------------------------------------------------------------------------------------------------ matching class Matcher: """Every place where each rule can end, from each place it is tried (memoized).""" def __init__(self, rules, text): self.rules, self.text = rules, text self.memo = {} self.far, self.expected = -1, set() def fail(self, pos, what): if pos > self.far: self.far, self.expected = pos, {what} elif pos == self.far: self.expected.add(what) def rule(self, name, pos): key = (name, pos) got = self.memo.get(key) if got is None: self.memo[key] = frozenset() # a rule that calls itself at the same place ends nowhere got = frozenset(self.match(self.rules[name], pos, name)) self.memo[key] = got return got def match(self, e, pos, ctx): if isinstance(e, Ref): return self.rule(e.name, pos) if isinstance(e, Lit): if self.text.startswith(e.text, pos): return {pos + len(e.text)} self.fail(pos, '"' + e.text.replace("\n", "\\n") + '"') return set() if isinstance(e, Rx): m = e.rx.match(self.text, pos) if m: return {m.end()} self.fail(pos, ctx) return set() if isinstance(e, Seq): cur = {pos} for item in e.items: nxt = set() for p in cur: nxt |= self.match(item, p, ctx) cur = nxt if not cur: break return cur if isinstance(e, Alt): out = set() for item in e.items: out |= self.match(item, pos, ctx) return out if isinstance(e, Opt): return {pos} | self.match(e.item, pos, ctx) if isinstance(e, Rep): seen, frontier = {pos}, {pos} while frontier: new = set() for p in frontier: for q in self.match(e.item, p, ctx): if q not in seen: new.add(q) seen |= new frontier = new return seen raise TypeError(e) def check_text(rules, start, text): """None when the text is valid, else (offset, expected names).""" m = Matcher(rules, text) ends = m.rule(start, 0) if len(text) in ends: return None pos = max(m.far, max(ends, default=0)) return pos, sorted(m.expected) if pos == m.far else [] def line_col(text, pos): line = text.count("\n", 0, pos) + 1 col = pos - (text.rfind("\n", 0, pos) + 1) + 1 return line, col def main(argv): if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", errors="replace") args = list(argv) strict = quiet = False grammar = Path(__file__).resolve().with_name("ujn.ebnf") files = [] while args: a = args.pop(0) if a == "--strict": strict = True elif a == "--quiet": quiet = True elif a == "--grammar": if not args: print("--grammar needs a file", file=sys.stderr) return 2 grammar = Path(args.pop(0)) elif a in ("-h", "--help"): print(__doc__) return 0 else: files.append(Path(a)) if not files: print(__doc__, file=sys.stderr) return 2 try: rules, start = read_grammar(grammar.read_text(encoding="utf-8")) except (OSError, GrammarError) as e: print(f"{grammar}: {e}", file=sys.stderr) return 2 if strict: for name in rules: if name.startswith("raw-"): rules[name] = Alt([]) # matches nothing failed = 0 for f in files: try: text = read_source(f) except (OSError, UnicodeDecodeError) as e: print(f"{f}: cannot read: {e}") failed += 1 continue result = check_text(rules, start, text) if result is None: if not quiet: print(f"{f}: ok") continue failed += 1 pos, expected = result line, col = line_col(text, pos) src = text.split("\n")[line - 1] if line - 1 < len(text.split("\n")) else "" exp = ", ".join(expected[:10]) + (" ..." if len(expected) > 10 else "") print(f"{f}: line {line}, column {col}: parsing stops here" + (f" (expected {exp})" if exp else "")) print(f" {src}") print(f" {' ' * (col - 1)}^") return 1 if failed else 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))