Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- root/specialists/rel-breeds/manifest.jsonAdded+71
- root/specialists/rel-breeds/organ_relation_v2.pyAdded+55
- root/specialists/rel-breeds/readers.jsonAdded+6
- root/specialists/rel-breeds/relation_panel_v2.jsonAdded+218
- root/specialists/rel-breeds/relspec_scorer.pyAdded+25
- root/specialists/rel-breeds/verdict_dev.jsonAdded+114
- root/specialists/rel-breeds/verdict_heldout.jsonAdded+108
- root/specialists/rel-volleyball/manifest.jsonAdded+77
- root/specialists/rel-volleyball/organ_relation_v2.pyAdded+55
- root/specialists/rel-volleyball/relation_panel_v2.jsonAdded+1073
- root/specialists/rel-volleyball/verdict_dev.jsonAdded+114
- root/specialists/rel-volleyball/verdict_heldout.jsonAdded+114
- root/textbooks/gutenberg/pg10136.txtAdded
- root/textbooks/gutenberg/pg12444.txtAdded
- root/textbooks/gutenberg/pg13923.txtAdded
- root/textbooks/gutenberg/pg15338.txtAdded
- root/textbooks/gutenberg/pg21084.txtAdded
- root/textbooks/gutenberg/pg26558.txtAdded
- root/vendor/antlr4_4_11_1/antlr4/BufferedTokenStream.pyAdded+302
- root/vendor/antlr4_4_11_1/antlr4/CommonTokenFactory.pyAdded+61
- root/vendor/antlr4_4_11_1/antlr4/CommonTokenStream.pyAdded+87
- root/vendor/antlr4_4_11_1/antlr4/FileStream.pyAdded+27
- root/vendor/antlr4_4_11_1/antlr4/InputStream.pyAdded+87
- root/vendor/antlr4_4_11_1/antlr4/IntervalSet.pyAdded+180
- root/vendor/antlr4_4_11_1/antlr4/LL1Analyzer.pyAdded+173
- root/vendor/antlr4_4_11_1/antlr4/Lexer.pyAdded+329
- root/vendor/antlr4_4_11_1/antlr4/ListTokenSource.pyAdded+144
- root/vendor/antlr4_4_11_1/antlr4/Parser.pyAdded+580
- root/vendor/antlr4_4_11_1/antlr4/ParserInterpreter.pyAdded+170
- root/vendor/antlr4_4_11_1/antlr4/ParserRuleContext.pyAdded+186
- root/vendor/antlr4_4_11_1/antlr4/PredictionContext.pyAdded+623
- root/vendor/antlr4_4_11_1/antlr4/Recognizer.pyAdded+147
- root/vendor/antlr4_4_11_1/antlr4/RuleContext.pyAdded+227
- root/vendor/antlr4_4_11_1/antlr4/StdinStream.pyAdded+11
- root/vendor/antlr4_4_11_1/antlr4/Token.pyAdded+155
- root/vendor/antlr4_4_11_1/antlr4/TokenStreamRewriter.pyAdded+255
- root/vendor/antlr4_4_11_1/antlr4/Utils.pyAdded+33
- root/vendor/antlr4_4_11_1/antlr4/__init__.pyAdded+21
- root/vendor/antlr4_4_11_1/antlr4/_pygrun.pyAdded+171
- root/vendor/antlr4_4_11_1/antlr4/atn/ATN.pyAdded+132
- root/vendor/antlr4_4_11_1/antlr4/atn/ATNConfig.pyAdded+159
- root/vendor/antlr4_4_11_1/antlr4/atn/ATNConfigSet.pyAdded+212
- root/vendor/antlr4_4_11_1/antlr4/atn/ATNDeserializationOptions.pyAdded+24
- root/vendor/antlr4_4_11_1/antlr4/atn/ATNDeserializer.pyAdded+446
- root/vendor/antlr4_4_11_1/antlr4/atn/ATNSimulator.pyAdded+47
- root/vendor/antlr4_4_11_1/antlr4/atn/ATNState.pyAdded+264
- root/vendor/antlr4_4_11_1/antlr4/atn/ATNType.pyAdded+17
- root/vendor/antlr4_4_11_1/antlr4/atn/LexerATNSimulator.pyAdded+570
- root/vendor/antlr4_4_11_1/antlr4/atn/LexerAction.pyAdded+298
- root/vendor/antlr4_4_11_1/antlr4/atn/LexerActionExecutor.pyAdded+143
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071{ "id": "rel-breeds", "name": "Oracle7 Relations: Dog, cat and horse breeds", "number": 175, "tier": "R", "sources": [ { "name": "Wikidata (relation store v2: typed statements of the items with an English Wikipedia article)", "licence": "CC0 1.0", "url": "https://www.wikidata.org/" }, { "name": "Readers written by Oracle7, each phrasing measured on TriviaQA / Mintaka / WebQuestions TRAIN questions (>= 90% answering precision kept)", "licence": "Apache-2.0 / CC BY 4.0 (question sets)", "url": "https://huggingface.co/datasets/mandarjoshi/trivia_qa" } ], "store": { "path": "__ORACLE7_ROOT__/specialists/rel-breeds/readers.json", "shared": "__ORACLE7_ROOT__/relstore/relations_v2.sqlite3 (Wikidata relation store, shared by every relation specialist and the core's router; ships once with the release)" }, "organ": { "dir": "__ORACLE7_ROOT__/specialists/rel-breeds", "module": "organ_relation_v2", "class": "RelationOrganV2", "init": { "domain": "breeds", "kind": "breeds" } }, "accept": { "kinds": [ "breeds" ], "declines_in_domain": [ "unverified" ], "context_regex": "" }, "panel": { "path": "__ORACLE7_ROOT__/specialists/rel-breeds/relation_panel_v2.json", "splits": [ "dev", "heldout" ], "exclude_kinds_composed": [], "scorer_module": "relspec_scorer", "scorer_fn": "ok" }, "routing_cues": [], "budgets": { "latency_p50_ms": 1000, "store_mb": 1 }, "core_sample": { "n": 400, "seed": 20261008 }, "domain": { "roots": [ 39367, 43577, 1160573 ], "occupations": [] }, "readers": [ "495" ], "notes": "Exact relation reading over Wikidata within one domain (hand-written readers measured on natural TRAIN questions, plus mined patterns): answers only when one names the relation and the store gives one value; silent otherwise. Panel: two phrasings per relation written for people (dev and held-out differ), entities never seen in mining; expect = the store's value (tests reading, not Wikidata's truth). Same author, disclosed. Recognise-then-decline: a forward relation question about an in-domain entity it cannot read reliably is declined, never left to a weaker route."}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455#!/usr/bin/env python3"""organ_relation_v2 - one RELATION SPECIALIST (v2): a domain read two ways over the Wikidata relation store - 1. its HAND-WRITTEN READERS (wander-train/relation_spec_v2 + relation_readers_v1): whole-question phrasings with an entity slot, each measured on 140k natural TRAIN questions first (phrasings below 90% answering precision dropped); 2. its MINED PATTERNS (wander-train/relation_spec_v1), when the domain has any (>= 90% on both halves of the train pool).It answers only when one of them names the relation and the store gives exactly one value; otherwise it is silent and theturn goes on to the core. Every answer carries its receipt (subject Q-id, property, value).Returns {kind, status, response, value} or None."""import jsonimport os
import relation_spec_v1 as RS1import relation_spec_v2 as RS2
HERE = os.path.dirname(os.path.abspath(__file__))
def _key(k): return k if isinstance(k, str) and not k.lstrip("-").isdigit() else int(k)
class RelationOrganV2: def __init__(self, domain, readers="readers.json", patterns="patterns.json", kind=None): self.domain = domain self.kind = kind or domain r = json.load(open(os.path.join(HERE, readers))) self.readers = [_key(k) for k in r["keys"]] self.dropped = frozenset((_key(k), d, int(i)) for k, d, i in r.get("dropped", [])) p = os.path.join(HERE, patterns) self.patterns = json.load(open(p)) if os.path.exists(p) else {}
def answer(self, text, session_id="default"): q = str(text or "") try: a = RS2.answer(q, self.domain, self.readers, self.dropped) if not a and self.patterns: a = RS1.answer(q, self.domain, self.patterns) except Exception: # noqa: BLE001 - a store problem is silence, never a guess return None if not a: return None rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] return {"kind": "unverified", "status": "withheld", "value": None, "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": receipt = "%s (Q%d) - %s (P%d) - %s" % (subj, a["subject_qid"], plab, a["property"], a["answer"]) else: lab = rs.label(a["linked_qid"]) or "Q%d" % a["linked_qid"] receipt = "%s (Q%d) - %s (P%d) - %s (Q%d)" % (subj, a["subject_qid"], plab, a["property"], lab, a["linked_qid"]) return {"kind": self.kind, "status": "answered", "value": a["answer"], "response": "%s. From the Wikidata relation store: %s." % (a["answer"], receipt)}123456{ "keys": [ "495" ], "dropped": []}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218[ { "split": "dev", "kind": "breeds", "valid": true, "q": "Which country does the Bluetick Coonhound come from?", "expect": "United States", "relation": "fwd P495", "entity": "Q37568" }, { "split": "dev", "kind": "breeds", "valid": true, "q": "Which country does the Alano Espa\u00f1ol come from?", "expect": "Spain", "relation": "fwd P495", "entity": "Q37690" }, { "split": "dev", "kind": "breeds", "valid": true, "q": "Which country does the Japanese Terrier come from?", "expect": "Japan", "relation": "fwd P495", "entity": "Q37976" }, { "split": "dev", "kind": "breeds", "valid": true, "q": "Which country does the Boykin Spaniel come from?", "expect": "United States", "relation": "fwd P495", "entity": "Q37848" }, { "split": "dev", "kind": "breeds", "valid": true, "q": "Which country does the Cymric come from?", "expect": "Canada", "relation": "fwd P495", "entity": "Q42578" }, { "split": "dev", "kind": "breeds", "valid": true, "q": "Which country does the Norwegian Buhund come from?", "expect": "Norway", "relation": "fwd P495", "entity": "Q38478" }, { "split": "dev", "kind": "breeds", "valid": true, "q": "Which country does the American Cream Draft come from?", "expect": "United States", "relation": "fwd P495", "entity": "Q338051" }, { "split": "dev", "kind": "breeds", "valid": true, "q": "Which country does the Hygen Hound come from?", "expect": "Norway", "relation": "fwd P495", "entity": "Q38016" }, { "split": "dev", "kind": "breeds", "valid": true, "q": "Which country does the Old English sheepdog come from?", "expect": "England", "relation": "fwd P495", "entity": "Q37704" }, { "split": "dev", "kind": "breeds", "valid": true, "q": "Which country does the Miniature Bull Terrier come from?", "expect": "England", "relation": "fwd P495", "entity": "Q37967" }, { "split": "dev", "kind": "breeds", "valid": true, "q": "Which country does the Tosa come from?", "expect": "Japan", "relation": "fwd P495", "entity": "Q38991" }, { "split": "dev", "kind": "breeds", "valid": true, "q": "Which country does the Bambino come from?", "expect": "United States", "relation": "fwd P495", "entity": "Q9667" }, { "split": "heldout", "kind": "breeds", "valid": true, "q": "Where did the Welsh Pony and Cob originate?", "expect": "Wales", "relation": "fwd P495", "entity": "Q1096752" }, { "split": "heldout", "kind": "breeds", "valid": true, "q": "Where did the Sphynx originate?", "expect": "Canada", "relation": "fwd P495", "entity": "Q42712" }, { "split": "heldout", "kind": "breeds", "valid": true, "q": "Where did the Wire Fox Terrier originate?", "expect": "England", "relation": "fwd P495", "entity": "Q39491" }, { "split": "heldout", "kind": "breeds", "valid": true, "q": "Where did the English Foxhound originate?", "expect": "England", "relation": "fwd P495", "entity": "Q37789" }, { "split": "heldout", "kind": "breeds", "valid": true, "q": "Where did the Yorkshire Terrier originate?", "expect": "England", "relation": "fwd P495", "entity": "Q39330" }, { "split": "heldout", "kind": "breeds", "valid": true, "q": "Where did the Glen of Imaal Terrier originate?", "expect": "Ireland", "relation": "fwd P495", "entity": "Q38189" }, { "split": "heldout", "kind": "breeds", "valid": true, "q": "Where did the Spanish Mastiff originate?", "expect": "Spain", "relation": "fwd P495", "entity": "Q37939" }, { "split": "heldout", "kind": "breeds", "valid": true, "q": "Where did the Blue Lacy originate?", "expect": "United States", "relation": "fwd P495", "entity": "Q37579" }, { "split": "heldout", "kind": "breeds", "valid": true, "q": "Where did the Basque Shepherd Dog originate?", "expect": "Spain", "relation": "fwd P495", "entity": "Q38653" }, { "split": "heldout", "kind": "breeds", "valid": true, "q": "Where did the Banker horse originate?", "expect": "United States", "relation": "fwd P495", "entity": "Q2877469" }, { "split": "heldout", "kind": "breeds", "valid": true, "q": "Where did the Cleveland Bay originate?", "expect": "England", "relation": "fwd P495", "entity": "Q284617" }, { "split": "heldout", "kind": "breeds", "valid": true, "q": "Where did the Black and Tan Coonhound originate?", "expect": "United States", "relation": "fwd P495", "entity": "Q37537" }]12345678910111213141516171819202122232425#!/usr/bin/env python3"""relspec_scorer - a relation item is right when the reply's ANSWER (its first sentence, before the receipt) contains thepanel's expected value, compared case- and accent-insensitively on whole words; a must-decline item answered is a falseyes. (ok, asserted)"""import reimport unicodedata
def _norm(s): s = unicodedata.normalize("NFKD", str(s)) s = "".join(c for c in s if not unicodedata.combining(c)).lower() return " ".join(re.findall(r"[a-z0-9]+", s))
def ok(p, r): text = str((r or {}).get("response", "")) answered = str((r or {}).get("status", "")) == "answered" if not p["valid"]: return (not answered), answered if not answered: return False, False first = re.split(r"\.\s+From the Wikidata relation store", text)[0] first = re.sub(r"^\s*\[ev:[a-z_]+\]\s*", "", first) want = _norm(p["expect"]) return bool(want) and (" %s " % want) in (" %s " % _norm(first)), True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114{ "id": "rel-breeds", "name": "Oracle7 Relations: Dog, cat and horse breeds", "tier": "R", "split": "dev", "head": "oracle_release_runtime_w525", "time": "2026-10-09T00:18:20Z", "domain": { "head": { "correct": 3, "false_yes": 0, "wrong": 0, "n": 12, "p50_ms": 545.0, "fails": [ [ "breeds", "Which country does the Alano Espa\u00f1ol come from?", "act:clarify|vessel:reinforced", "I didn't fully parse that, so I won't guess. I can summarize a topic, compare two things, " ], [ "breeds", "Which country does the Japanese Terrier come from?", "act:clarify|vessel:reinforced", "I didn't fully parse that, so I won't guess. I can summarize a topic, compare two things, " ], [ "breeds", "Which country does the Cymric come from?", "act:clarify|vessel:reinforced", "I didn't fully parse that, so I won't guess. I can summarize a topic, compare two things, " ], [ "breeds", "Which country does the Norwegian Buhund come from?", "act:clarify|vessel:reinforced", "I didn't fully parse that, so I won't guess. I can summarize a topic, compare two things, " ], [ "breeds", "Which country does the American Cream Draft come from?", "act:clarify|vessel:reinforced", "I didn't fully parse that, so I won't guess. I can summarize a topic, compare two things, " ], [ "breeds", "Which country does the Hygen Hound come from?", "act:clarify|vessel:reinforced", "I didn't fully parse that, so I won't guess. I can summarize a topic, compare two things, " ], [ "breeds", "Which country does the Miniature Bull Terrier come from?", "act:clarify|vessel:reinforced", "I didn't fully parse that, so I won't guess. I can summarize a topic, compare two things, " ], [ "breeds", "Which country does the Tosa come from?", "act:clarify|vessel:reinforced", "I didn't fully parse that, so I won't guess. I can summarize a topic, compare two things, " ] ] }, "spec": { "correct": 12, "false_yes": 0, "wrong": 0, "n": 12, "p50_ms": 1.9, "fails": [] } }, "core": { "head": { "correct": 150, "false_yes": 0 }, "spec": { "correct": 150, "false_yes": 0 }, "n": 400, "swept_in": 0, "taken_by_specialist": [], "head_cache_hits": 400 }, "self": [ { "q": "Who are you?", "same": true }, { "q": "What are you?", "same": true }, { "q": "Are you a human?", "same": true }, { "q": "What do you value?", "same": true }, { "q": "Are you conscious?", "same": true } ], "store_mb": 0.0, "decision": "DEV-PASS", "reasons": []}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108{ "id": "rel-breeds", "name": "Oracle7 Relations: Dog, cat and horse breeds", "tier": "R", "split": "heldout", "head": "oracle_release_runtime_w525", "time": "2026-10-09T00:18:37Z", "domain": { "head": { "correct": 5, "false_yes": 0, "wrong": 3, "n": 12, "p50_ms": 253.58, "fails": [ [ "breeds", "Where did the Sphynx originate?", "act:clarify|vessel:receipt", "I didn't fully parse that, so I won't guess. I can summarize a topic, compare two things, " ], [ "breeds", "Where did the Wire Fox Terrier originate?", "arb:timeline->capability:timeline|vessel", "A timeline needs at least two dated statements; the admitted material on Wire contains 0.\n" ], [ "breeds", "Where did the English Foxhound originate?", "arb:timeline->capability:timeline|vessel", "A timeline needs at least two dated statements; the admitted material on English contains " ], [ "breeds", "Where did the Yorkshire Terrier originate?", "deliberation:where", "[ev:direct] It originated in the United Kingdom in the town of Yorkshire, from where it ge" ], [ "breeds", "Where did the Blue Lacy originate?", "deliberation:where", "[ev:direct] The Lacy Dog or Blue Lacy Dog is a breed of working dog that originated in the" ], [ "breeds", "Where did the Basque Shepherd Dog originate?", "deliberation:where", "[ev:direct] The Basque Shepherd Dog is a traditional Basque breed of sheepdog originating " ], [ "breeds", "Where did the Banker horse originate?", "arb:timeline->capability:timeline|vessel", "A timeline needs at least two dated statements; the admitted material on Banker horse cont" ] ] }, "spec": { "correct": 12, "false_yes": 0, "wrong": 0, "n": 12, "p50_ms": 1.52, "fails": [] } }, "core": { "head": { "correct": 150, "false_yes": 0 }, "spec": { "correct": 150, "false_yes": 0 }, "n": 400, "swept_in": 0, "taken_by_specialist": [], "head_cache_hits": 400 }, "self": [ { "q": "Who are you?", "same": true }, { "q": "What are you?", "same": true }, { "q": "Are you a human?", "same": true }, { "q": "What do you value?", "same": true }, { "q": "Are you conscious?", "same": true } ], "store_mb": 0.0, "decision": "ADMIT", "reasons": []}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677{ "id": "rel-volleyball", "name": "Oracle7 Relations: Volleyball players", "number": 273, "tier": "R", "sources": [ { "name": "Wikidata (relation store v2: typed statements of the items with an English Wikipedia article)", "licence": "CC0 1.0", "url": "https://www.wikidata.org/" }, { "name": "Readers written by Oracle7, each phrasing measured on TriviaQA / Mintaka / WebQuestions TRAIN questions (>= 90% answering precision kept)", "licence": "Apache-2.0 / CC BY 4.0 (question sets)", "url": "https://huggingface.co/datasets/mandarjoshi/trivia_qa" } ], "store": { "path": "__ORACLE7_ROOT__/specialists/rel-volleyball/readers.json", "shared": "__ORACLE7_ROOT__/relstore/relations_v2.sqlite3 (Wikidata relation store, shared by every relation specialist and the core's router; ships once with the release)" }, "organ": { "dir": "__ORACLE7_ROOT__/specialists/rel-volleyball", "module": "organ_relation_v2", "class": "RelationOrganV2", "init": { "domain": "volleyball", "kind": "volleyball" } }, "accept": { "kinds": [ "volleyball" ], "declines_in_domain": [ "unverified" ], "context_regex": "" }, "panel": { "path": "__ORACLE7_ROOT__/specialists/rel-volleyball/relation_panel_v2.json", "splits": [ "dev", "heldout" ], "exclude_kinds_composed": [], "scorer_module": "relspec_scorer", "scorer_fn": "ok" }, "routing_cues": [], "budgets": { "latency_p50_ms": 1000, "store_mb": 1 }, "core_sample": { "n": 400, "seed": 20261008 }, "domain": { "roots": [], "occupations": [ 15117302 ] }, "readers": [ "19", "20", "569", "570", "27", "26", "22", "25", "413" ], "notes": "Exact relation reading over Wikidata within one domain (hand-written readers measured on natural TRAIN questions, plus mined patterns): answers only when one names the relation and the store gives one value; silent otherwise. Panel: two phrasings per relation written for people (dev and held-out differ), entities never seen in mining; expect = the store's value (tests reading, not Wikidata's truth). Same author, disclosed. Recognise-then-decline: a forward relation question about an in-domain entity it cannot read reliably is declined, never left to a weaker route."}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455#!/usr/bin/env python3"""organ_relation_v2 - one RELATION SPECIALIST (v2): a domain read two ways over the Wikidata relation store - 1. its HAND-WRITTEN READERS (wander-train/relation_spec_v2 + relation_readers_v1): whole-question phrasings with an entity slot, each measured on 140k natural TRAIN questions first (phrasings below 90% answering precision dropped); 2. its MINED PATTERNS (wander-train/relation_spec_v1), when the domain has any (>= 90% on both halves of the train pool).It answers only when one of them names the relation and the store gives exactly one value; otherwise it is silent and theturn goes on to the core. Every answer carries its receipt (subject Q-id, property, value).Returns {kind, status, response, value} or None."""import jsonimport os
import relation_spec_v1 as RS1import relation_spec_v2 as RS2
HERE = os.path.dirname(os.path.abspath(__file__))
def _key(k): return k if isinstance(k, str) and not k.lstrip("-").isdigit() else int(k)
class RelationOrganV2: def __init__(self, domain, readers="readers.json", patterns="patterns.json", kind=None): self.domain = domain self.kind = kind or domain r = json.load(open(os.path.join(HERE, readers))) self.readers = [_key(k) for k in r["keys"]] self.dropped = frozenset((_key(k), d, int(i)) for k, d, i in r.get("dropped", [])) p = os.path.join(HERE, patterns) self.patterns = json.load(open(p)) if os.path.exists(p) else {}
def answer(self, text, session_id="default"): q = str(text or "") try: a = RS2.answer(q, self.domain, self.readers, self.dropped) if not a and self.patterns: a = RS1.answer(q, self.domain, self.patterns) except Exception: # noqa: BLE001 - a store problem is silence, never a guess return None if not a: return None rs = RS1._rs() if a.get("decline"): subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] return {"kind": "unverified", "status": "withheld", "value": None, "response": "I can't verify the %s of %s from my records, so I won't guess." % (RS1.prop_label(a["property"]), subj)} subj = rs.label(a["subject_qid"]) or "Q%d" % a["subject_qid"] plab = RS1.prop_label(a["property"]) if a["direction"] == "fwd": receipt = "%s (Q%d) - %s (P%d) - %s" % (subj, a["subject_qid"], plab, a["property"], a["answer"]) else: lab = rs.label(a["linked_qid"]) or "Q%d" % a["linked_qid"] receipt = "%s (Q%d) - %s (P%d) - %s (Q%d)" % (subj, a["subject_qid"], plab, a["property"], lab, a["linked_qid"]) return {"kind": self.kind, "status": "answered", "value": a["answer"], "response": "%s. From the Wikidata relation store: %s." % (a["answer"], receipt)}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073[ { "split": "dev", "kind": "volleyball", "valid": true, "q": "Where was Marcus B\u00f6hme born?", "expect": "Berlin", "relation": "fwd P19", "entity": "Q70652" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Where was Marianne Steinbrecher born?", "expect": "S\u00e3o Paulo", "relation": "fwd P19", "entity": "Q2552065" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Where was Wallace de Souza born?", "expect": "S\u00e3o Paulo", "relation": "fwd P19", "entity": "Q2119880" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Where was Misty May-Treanor born?", "expect": "Los Angeles", "relation": "fwd P19", "entity": "Q182106" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Where was Laura Ludwig born?", "expect": "Berlin", "relation": "fwd P19", "entity": "Q4578" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Where was Leandro Vissotto born?", "expect": "S\u00e3o Paulo", "relation": "fwd P19", "entity": "Q926101" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Where was David Smith born?", "expect": "Los Angeles", "relation": "fwd P19", "entity": "Q1176674" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What is the birthplace of Nicolas Le Goff?", "expect": "Paris", "relation": "fwd P19", "entity": "Q3340505" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What is the birthplace of Daniele Lupo?", "expect": "Rome", "relation": "fwd P19", "entity": "Q375940" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What is the birthplace of Kim Glass?", "expect": "Los Angeles", "relation": "fwd P19", "entity": "Q2713389" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What is the birthplace of Craig Buck?", "expect": "Los Angeles", "relation": "fwd P19", "entity": "Q437627" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What is the birthplace of Flo Hyman?", "expect": "Los Angeles", "relation": "fwd P19", "entity": "Q445270" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What is the birthplace of Anouk Verg\u00e9-D\u00e9pr\u00e9?", "expect": "Bern", "relation": "fwd P19", "entity": "Q568237" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What is the birthplace of Fof\u00e3o?", "expect": "S\u00e3o Paulo", "relation": "fwd P19", "entity": "Q1151335" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What is the birthplace of Ricardo Garcia?", "expect": "S\u00e3o Paulo", "relation": "fwd P19", "entity": "Q6513536" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Where did Vyacheslav Zaytsev die?", "expect": "Saint Petersburg", "relation": "fwd P20", "entity": "Q568621" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Where did Vera Galushka-Duyunova die?", "expect": "Tashkent", "relation": "fwd P20", "entity": "Q460981" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Where did Sara Anzanello die?", "expect": "Milan", "relation": "fwd P20", "entity": "Q2711893" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Where did Lyudmila Buldakova die?", "expect": "Moscow", "relation": "fwd P20", "entity": "Q2495953" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Where did Yuri Chesnokov die?", "expect": "Moscow", "relation": "fwd P20", "entity": "Q2164697" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "In which city did Walewska Oliveira die?", "expect": "S\u00e3o Paulo", "relation": "fwd P20", "entity": "Q794222" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "In which city did Aleksandra Chudina die?", "expect": "Moscow", "relation": "fwd P20", "entity": "Q299741" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "In what year was Bethania de la Cruz born?", "expect": "1987", "relation": "fwd P569", "entity": "Q1072824" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "In what year was Hui Ruoqi born?", "expect": "1991", "relation": "fwd P569", "entity": "Q1101180" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "In what year did Naohiro Ikeda die?", "expect": "2021", "relation": "fwd P570", "entity": "Q1030721" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What nationality was Erika Araki?", "expect": "Japan", "relation": "fwd P27", "entity": "Q242500" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What nationality was Kaori Inoue?", "expect": "Japan", "relation": "fwd P27", "entity": "Q262887" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What nationality was Mai Yamaguchi?", "expect": "Japan", "relation": "fwd P27", "entity": "Q268853" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What nationality was Hitomi Nakamichi?", "expect": "Japan", "relation": "fwd P27", "entity": "Q268877" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What nationality was Anders Mol?", "expect": "Norway", "relation": "fwd P27", "entity": "Q47789432" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What nationality was Katsumi Matsumura?", "expect": "Japan", "relation": "fwd P27", "entity": "Q3364354" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What nationality was Yuko Fujimoto?", "expect": "Japan", "relation": "fwd P27", "entity": "Q977321" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What nationality was Yuko Sano?", "expect": "Japan", "relation": "fwd P27", "entity": "Q257740" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What nationality was Saori Sakoda?", "expect": "Japan", "relation": "fwd P27", "entity": "Q269730" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Which country was Jungo Morita a citizen of?", "expect": "Japan", "relation": "fwd P27", "entity": "Q2994362" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Which country was Saori Kimura a citizen of?", "expect": "Japan", "relation": "fwd P27", "entity": "Q233908" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Which country was Yuriko Handa a citizen of?", "expect": "Japan", "relation": "fwd P27", "entity": "Q3364295" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Which country was Takako Shirai a citizen of?", "expect": "Japan", "relation": "fwd P27", "entity": "Q861165" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Which country was Mayu Ishikawa a citizen of?", "expect": "Japan", "relation": "fwd P27", "entity": "Q68422499" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Which country was Y\u016bki Ishikawa a citizen of?", "expect": "Japan", "relation": "fwd P27", "entity": "Q18335658" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Which country was Miyuki Takahashi a citizen of?", "expect": "Japan", "relation": "fwd P27", "entity": "Q600561" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Which country was Yoshie Takeshita a citizen of?", "expect": "Japan", "relation": "fwd P27", "entity": "Q234659" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Which country was Yukiko Ebata a citizen of?", "expect": "Japan", "relation": "fwd P27", "entity": "Q269725" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Which country was Gavin Schmitt a citizen of?", "expect": "Canada", "relation": "fwd P27", "entity": "Q495842" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Which country was Christian S\u00f8rum a citizen of?", "expect": "Norway", "relation": "fwd P27", "entity": "Q28717743" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Which country was Yuko Arakida a citizen of?", "expect": "Japan", "relation": "fwd P27", "entity": "Q3459539" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Misty May-Treanor married to?", "expect": "Matt Treanor", "relation": "fwd P26", "entity": "Q182106" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Teodor Salparov married to?", "expect": "Ralitsa Paskaleva", "relation": "fwd P26", "entity": "Q578843" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Jelena Nikoli\u0107 married to?", "expect": "Petar Nenadi\u0107", "relation": "fwd P26", "entity": "Q2608891" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Yekaterina Gamova married to?", "expect": "Mikhail Mukasey", "relation": "fwd P26", "entity": "Q253253" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Georg Grozer married to?", "expect": "Helena Grozer", "relation": "fwd P26", "entity": "Q86132" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Natalie Cook married to?", "expect": "Sarah Dawn Maxwell", "relation": "fwd P26", "entity": "Q263886" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Vyacheslav Zaytsev married to?", "expect": "Irina Pozdnyakova", "relation": "fwd P26", "entity": "Q568621" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Leila Barros married to?", "expect": "Emanuel Rego", "relation": "fwd P26", "entity": "Q458463" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Lyudmila Buldakova married to?", "expect": "Igor Buldakov", "relation": "fwd P26", "entity": "Q2495953" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Erika Araki married to?", "expect": "Y\u014dhei Shinomiya", "relation": "fwd P26", "entity": "Q242500" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Francesca Piccinini married to?", "expect": "Gianmarco Pozzecco", "relation": "fwd P26", "entity": "Q130814" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Monica De Gennaro married to?", "expect": "Daniele Santarelli", "relation": "fwd P26", "entity": "Q967009" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who is the spouse of Naz Aydemir Akyol?", "expect": "Cenk Akyol", "relation": "fwd P26", "entity": "Q2610519" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who is the spouse of Gabriel Gardner?", "expect": "Lauren McFall", "relation": "fwd P26", "entity": "Q3269033" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who is the spouse of Ann Meyers?", "expect": "Don Drysdale", "relation": "fwd P26", "entity": "Q2308003" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who is the spouse of Aleksey Obmochaev?", "expect": "Nataliya Honcharova", "relation": "fwd P26", "entity": "Q2119603" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who is the spouse of Zeynep Sever?", "expect": "Volkan Demirel", "relation": "fwd P26", "entity": "Q2530775" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who is the spouse of Yoshie Takeshita?", "expect": "Hirotaka Egusa", "relation": "fwd P26", "entity": "Q234659" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who is the spouse of Manon Flier?", "expect": "Reinder Nummerdor", "relation": "fwd P26", "entity": "Q1890998" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who is the spouse of Murilo Endres?", "expect": "Jaqueline Carvalho", "relation": "fwd P26", "entity": "Q552109" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who is the spouse of Jackie Silva?", "expect": "Amalia Lima", "relation": "fwd P26", "entity": "Q457859" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who is the spouse of Nataliya Honcharova?", "expect": "Aleksey Obmochaev", "relation": "fwd P26", "entity": "Q272838" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Bartosz Kurek's father?", "expect": "Adam Kurek", "relation": "fwd P22", "entity": "Q809573" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Georg Grozer's father?", "expect": "Georg Grozer senior", "relation": "fwd P22", "entity": "Q86132" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Ivan Zaytsev's father?", "expect": "Vyacheslav Zaytsev", "relation": "fwd P22", "entity": "Q661579" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Lukas Kampa's father?", "expect": "Ulrich Kampa", "relation": "fwd P22", "entity": "Q1876909" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Fabian Drzyzga's father?", "expect": "Wojciech Drzyzga", "relation": "fwd P22", "entity": "Q9257482" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Kawika Shoji's father?", "expect": "Dave Shoji", "relation": "fwd P22", "entity": "Q1737351" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Nikola Grbi\u0107's father?", "expect": "Milo\u0161 Grbi\u0107", "relation": "fwd P22", "entity": "Q715898" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Jenia Grebennikov's father?", "expect": "Boris Grebennikov", "relation": "fwd P22", "entity": "Q3176989" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Alessandro Michieletto's father?", "expect": "Riccardo Michilito", "relation": "fwd P22", "entity": "Q84262101" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Bruno Rezende's father?", "expect": "Bernardo Rezende", "relation": "fwd P22", "entity": "Q613695" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Lloy Ball's father?", "expect": "Arnie Ball", "relation": "fwd P22", "entity": "Q2279167" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Misty May-Treanor's father?", "expect": "Butch May", "relation": "fwd P22", "entity": "Q182106" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who was the father of Jean Patry?", "expect": "Christophe Patry", "relation": "fwd P22", "entity": "Q39399417" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who was the father of Earvin Ngapeth?", "expect": "Eric N'Gapeth", "relation": "fwd P22", "entity": "Q3046479" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who was the father of Caterina Bosetti?", "expect": "Giuseppe Bosetti", "relation": "fwd P22", "entity": "Q1748245" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who was the father of Preguinho?", "expect": "Coelho Neto", "relation": "fwd P22", "entity": "Q456600" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who was the father of Leonel Marshall Jr.?", "expect": "Leonel Marshall Sr.", "relation": "fwd P22", "entity": "Q1890805" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who was the father of Clayton Stanley?", "expect": "Jon Stanley", "relation": "fwd P22", "entity": "Q551626" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who was the father of Anne Buijs?", "expect": "Teun Buijs", "relation": "fwd P22", "entity": "Q513667" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who was the father of Erik Shoji?", "expect": "Dave Shoji", "relation": "fwd P22", "entity": "Q16554252" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who was the father of K\u00e9vin Tillie?", "expect": "Laurent Tillie", "relation": "fwd P22", "entity": "Q3201170" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who was the father of Charlotte Flair?", "expect": "Ric Flair", "relation": "fwd P22", "entity": "Q2891336" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Aleksandr Butko's mother?", "expect": "Zhanna Butsko", "relation": "fwd P25", "entity": "Q1892824" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Ivan Zaytsev's mother?", "expect": "Irina Pozdnyakova", "relation": "fwd P25", "entity": "Q661579" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Anders Mol's mother?", "expect": "Merita Mol", "relation": "fwd P25", "entity": "Q47789432" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "Who was Bruno Rezende's mother?", "expect": "Vera Mossa", "relation": "fwd P25", "entity": "Q613695" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "Who was the mother of K\u00e9vin Tillie?", "expect": "Caroline Keulen-Tillie", "relation": "fwd P25", "entity": "Q3201170" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What position does Pawe\u0142 Zagumny play?", "expect": "setter", "relation": "fwd P413", "entity": "Q963591" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What position does Dragan Travica play?", "expect": "setter", "relation": "fwd P413", "entity": "Q1254642" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What position does Marina Babeshina play?", "expect": "setter", "relation": "fwd P413", "entity": "Q2625252" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What position does Luciano De Cecco play?", "expect": "setter", "relation": "fwd P413", "entity": "Q1873310" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What position does Vadim Khamuttskikh play?", "expect": "setter", "relation": "fwd P413", "entity": "Q2313083" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What position does Fabian Drzyzga play?", "expect": "setter", "relation": "fwd P413", "entity": "Q9257482" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What position does Lauren Carlini play?", "expect": "setter", "relation": "fwd P413", "entity": "Q39523178" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What position does Joanna Wo\u0142osz play?", "expect": "setter", "relation": "fwd P413", "entity": "Q3179666" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What position does Maja Ognjenovi\u0107 play?", "expect": "setter", "relation": "fwd P413", "entity": "Q2734878" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What position does Carli Lloyd play?", "expect": "setter", "relation": "fwd P413", "entity": "Q2011185" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What position does Sergey Grankin play?", "expect": "setter", "relation": "fwd P413", "entity": "Q928699" }, { "split": "dev", "kind": "volleyball", "valid": true, "q": "What position does Kawika Shoji play?", "expect": "setter", "relation": "fwd P413", "entity": "Q1737351" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What position did Simone Giannelli play?", "expect": "setter", "relation": "fwd P413", "entity": "Q16657967" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What position did Josef Musil play?", "expect": "setter", "relation": "fwd P413", "entity": "Q929123" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What position did Bojana Dr\u010da play?", "expect": "setter", "relation": "fwd P413", "entity": "Q2909145" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What position did Yoshie Takeshita play?", "expect": "setter", "relation": "fwd P413", "entity": "Q234659" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What position did Ann Meyers play?", "expect": "shooting guard", "relation": "fwd P413", "entity": "Q2308003" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What position did Ricardo Garcia play?", "expect": "setter", "relation": "fwd P413", "entity": "Q6513536" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What position did Carlotta Cambi play?", "expect": "setter", "relation": "fwd P413", "entity": "Q27267670" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What position did Laura Dijkema play?", "expect": "setter", "relation": "fwd P413", "entity": "Q439612" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What position did Micah Christenson play?", "expect": "setter", "relation": "fwd P413", "entity": "Q16578192" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What position did Ra\u00fal Lozano play?", "expect": "setter", "relation": "fwd P413", "entity": "Q772116" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What position did Dani Lins play?", "expect": "setter", "relation": "fwd P413", "entity": "Q262892" }, { "split": "heldout", "kind": "volleyball", "valid": true, "q": "What position did Eleonora Lo Bianco play?", "expect": "setter", "relation": "fwd P413", "entity": "Q291830" }]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114{ "id": "rel-volleyball", "name": "Oracle7 Relations: Volleyball players", "tier": "R", "split": "dev", "head": "oracle_release_runtime_w406", "time": "2026-10-13T03:16:50Z", "domain": { "head": { "correct": 4, "false_yes": 0, "wrong": 9, "n": 61, "p50_ms": 620.29, "fails": [ [ "volleyball", "Where was Marcus B\u00f6hme born?", "cube:read>frame>link>expand>bind>check>v", "[ev:direct] Germany. Marcus B\u00f6hme (born 25 August 1985) is a German professional volleybal" ], [ "volleyball", "Where was Marianne Steinbrecher born?", "deliberation:where", "[ev:direct] She represented her native country at the 2008 Summer Olympics in Beijing, Chi" ], [ "volleyball", "Where was Misty May-Treanor born?", "deliberation:where", "[ev:direct] She has 112 individual championship wins in domestic and international competi" ], [ "volleyball", "Where was Laura Ludwig born?", "deliberation:where", "[ev:direct] Ludwig's first tournament of the 2017 season after her shoulder operation was " ], [ "volleyball", "Where was Leandro Vissotto born?", "deliberation:where", "[ev:direct] In August 2010 his wife gave birth to their first child, a daughter named Cath" ], [ "volleyball", "Where was David Smith born?", "specialist_call>specialist:rel-boxers>bo", "Golborne. From the Wikidata relation store: Davey Boy Smith (Q452557) - POB (P19) - Golbor" ], [ "volleyball", "Where did Vyacheslav Zaytsev die?", "deliberation:where", "[ev:direct] Vyacheslav Alekseyevich Zaytsev (12 November 1952 \u2013 12 June 2023) was a Russia" ], [ "volleyball", "Where did Vera Galushka-Duyunova die?", "act:clarify|vessel:receipt", "I didn't fully parse that, so I won't guess. I can summarize a topic, compare two things, " ] ] }, "spec": { "correct": 61, "false_yes": 0, "wrong": 0, "n": 61, "p50_ms": 3.54, "fails": [] } }, "core": { "head": { "correct": 132, "false_yes": 0 }, "spec": { "correct": 132, "false_yes": 0 }, "n": 400, "swept_in": 0, "taken_by_specialist": [], "head_cache_hits": 400 }, "self": [ { "q": "Who are you?", "same": true }, { "q": "What are you?", "same": true }, { "q": "Are you a human?", "same": true }, { "q": "What do you value?", "same": true }, { "q": "Are you conscious?", "same": true } ], "store_mb": 0.0, "decision": "DEV-PASS", "reasons": []}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114{ "id": "rel-volleyball", "name": "Oracle7 Relations: Volleyball players", "tier": "R", "split": "heldout", "head": "oracle_release_runtime_w406", "time": "2026-10-13T03:17:50Z", "domain": { "head": { "correct": 17, "false_yes": 0, "wrong": 3, "n": 58, "p50_ms": 642.06, "fails": [ [ "volleyball", "What is the birthplace of Nicolas Le Goff?", "corpus_query:property_of|vessel:receipt", "No provenance-admitted sentence in the abstracts corpus answers that.\n\nI have received \"Wh" ], [ "volleyball", "What is the birthplace of Daniele Lupo?", "corpus_query:property_of|vessel:receipt", "No provenance-admitted sentence in the abstracts corpus answers that.\n\nI have received \"Wh" ], [ "volleyball", "What is the birthplace of Kim Glass?", "corpus_query:property_of|vessel:receipt", "No provenance-admitted sentence in the abstracts corpus answers that.\n\nI have received \"Wh" ], [ "volleyball", "What is the birthplace of Craig Buck?", "corpus_query:property_of|vessel:receipt", "No provenance-admitted sentence in the abstracts corpus answers that.\n\nI have received \"Wh" ], [ "volleyball", "What is the birthplace of Flo Hyman?", "corpus_query:property_of|vessel:receipt", "No provenance-admitted sentence in the abstracts corpus answers that.\n\nI have received \"Wh" ], [ "volleyball", "What is the birthplace of Anouk Verg\u00e9-D\u00e9pr\u00e9?", "corpus_query:property_of|vessel:receipt", "No provenance-admitted sentence in the abstracts corpus answers that.\n\nI have received \"Wh" ], [ "volleyball", "What is the birthplace of Fof\u00e3o?", "corpus_query:property_of|vessel:receipt", "No provenance-admitted sentence in the abstracts corpus answers that.\n\nI have received \"Wh" ], [ "volleyball", "What is the birthplace of Ricardo Garcia?", "specialist_call>specialist:rel-cyclists>", "Mexico. From the Wikidata relation store: Ricardo Garc\u00eda (Q1297417) - POB (P19) - Mexico. " ] ] }, "spec": { "correct": 58, "false_yes": 0, "wrong": 0, "n": 58, "p50_ms": 3.38, "fails": [] } }, "core": { "head": { "correct": 132, "false_yes": 0 }, "spec": { "correct": 132, "false_yes": 0 }, "n": 400, "swept_in": 0, "taken_by_specialist": [], "head_cache_hits": 400 }, "self": [ { "q": "Who are you?", "same": true }, { "q": "What are you?", "same": true }, { "q": "Are you a human?", "same": true }, { "q": "What do you value?", "same": true }, { "q": "Are you conscious?", "same": true } ], "store_mb": 0.0, "decision": "ADMIT", "reasons": []}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.
# This implementation of {@link TokenStream} loads tokens from a# {@link TokenSource} on-demand, and places the tokens in a buffer to provide# access to any previous token by index.## <p># This token stream ignores the value of {@link Token#getChannel}. If your# parser requires the token stream filter tokens to only those on a particular# channel, such as {@link Token#DEFAULT_CHANNEL} or# {@link Token#HIDDEN_CHANNEL}, use a filtering token stream such a# {@link CommonTokenStream}.</p>from io import StringIOfrom antlr4.Token import Tokenfrom antlr4.error.Errors import IllegalStateException
# need forward declarationLexer = None
# this is just to keep meaningful parameter types to Parserclass TokenStream(object):
pass
class BufferedTokenStream(TokenStream): __slots__ = ('tokenSource', 'tokens', 'index', 'fetchedEOF')
def __init__(self, tokenSource:Lexer): # The {@link TokenSource} from which tokens for this stream are fetched. self.tokenSource = tokenSource
# A collection of all tokens fetched from the token source. The list is # considered a complete view of the input once {@link #fetchedEOF} is set # to {@code true}. self.tokens = []
# The index into {@link #tokens} of the current token (next token to # {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be # {@link #LT LT(1)}. # # <p>This field is set to -1 when the stream is first constructed or when # {@link #setTokenSource} is called, indicating that the first token has # not yet been fetched from the token source. For additional information, # see the documentation of {@link IntStream} for a description of # Initializing Methods.</p> self.index = -1
# Indicates whether the {@link Token#EOF} token has been fetched from # {@link #tokenSource} and added to {@link #tokens}. This field improves # performance for the following cases: # # <ul> # <li>{@link #consume}: The lookahead check in {@link #consume} to prevent # consuming the EOF symbol is optimized by checking the values of # {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li> # <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into # {@link #tokens} is trivial with this field.</li> # <ul> self.fetchedEOF = False
def mark(self): return 0
def release(self, marker:int): # no resources to release pass
def reset(self): self.seek(0)
def seek(self, index:int): self.lazyInit() self.index = self.adjustSeekIndex(index)
def get(self, index:int): self.lazyInit() return self.tokens[index]
def consume(self): skipEofCheck = False if self.index >= 0: if self.fetchedEOF: # the last token in tokens is EOF. skip check if p indexes any # fetched token except the last. skipEofCheck = self.index < len(self.tokens) - 1 else: # no EOF token in tokens. skip check if p indexes a fetched token. skipEofCheck = self.index < len(self.tokens) else: # not yet initialized skipEofCheck = False
if not skipEofCheck and self.LA(1) == Token.EOF: raise IllegalStateException("cannot consume EOF")
if self.sync(self.index + 1): self.index = self.adjustSeekIndex(self.index + 1)
# Make sure index {@code i} in tokens has a token. # # @return {@code true} if a token is located at index {@code i}, otherwise # {@code false}. # @see #get(int i) #/ def sync(self, i:int): n = i - len(self.tokens) + 1 # how many more elements we need? if n > 0 : fetched = self.fetch(n) return fetched >= n return True
# Add {@code n} elements to buffer. # # @return The actual number of elements added to the buffer. #/ def fetch(self, n:int): if self.fetchedEOF: return 0 for i in range(0, n): t = self.tokenSource.nextToken() t.tokenIndex = len(self.tokens) self.tokens.append(t) if t.type==Token.EOF: self.fetchedEOF = True return i + 1 return n
# Get all tokens from start..stop inclusively#/ def getTokens(self, start:int, stop:int, types:set=None): if start<0 or stop<0: return None self.lazyInit() subset = [] if stop >= len(self.tokens): stop = len(self.tokens)-1 for i in range(start, stop): t = self.tokens[i] if t.type==Token.EOF: break if types is None or t.type in types: subset.append(t) return subset
def LA(self, i:int): return self.LT(i).type
def LB(self, k:int): if (self.index-k) < 0: return None return self.tokens[self.index-k]
def LT(self, k:int): self.lazyInit() if k==0: return None if k < 0: return self.LB(-k) i = self.index + k - 1 self.sync(i) if i >= len(self.tokens): # return EOF token # EOF must be last token return self.tokens[len(self.tokens)-1] return self.tokens[i]
# Allowed derived classes to modify the behavior of operations which change # the current stream position by adjusting the target token index of a seek # operation. The default implementation simply returns {@code i}. If an # exception is thrown in this method, the current stream index should not be # changed. # # <p>For example, {@link CommonTokenStream} overrides this method to ensure that # the seek target is always an on-channel token.</p> # # @param i The target token index. # @return The adjusted target token index.
def adjustSeekIndex(self, i:int): return i
def lazyInit(self): if self.index == -1: self.setup()
def setup(self): self.sync(0) self.index = self.adjustSeekIndex(0)
# Reset this token stream by setting its token source.#/ def setTokenSource(self, tokenSource:Lexer): self.tokenSource = tokenSource self.tokens = [] self.index = -1 self.fetchedEOF = False
# Given a starting index, return the index of the next token on channel. # Return i if tokens[i] is on channel. Return the index of the EOF token # if there are no tokens on channel between i and EOF. #/ def nextTokenOnChannel(self, i:int, channel:int): self.sync(i) if i>=len(self.tokens): return len(self.tokens) - 1 token = self.tokens[i] while token.channel!=channel: if token.type==Token.EOF: return i i += 1 self.sync(i) token = self.tokens[i] return i
# Given a starting index, return the index of the previous token on channel. # Return i if tokens[i] is on channel. Return -1 if there are no tokens # on channel between i and 0. def previousTokenOnChannel(self, i:int, channel:int): while i>=0 and self.tokens[i].channel!=channel: i -= 1 return i
# Collect all tokens on specified channel to the right of # the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or # EOF. If channel is -1, find any non default channel token. def getHiddenTokensToRight(self, tokenIndex:int, channel:int=-1): self.lazyInit() if tokenIndex<0 or tokenIndex>=len(self.tokens): raise Exception(str(tokenIndex) + " not in 0.." + str(len(self.tokens)-1)) from antlr4.Lexer import Lexer nextOnChannel = self.nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL) from_ = tokenIndex+1 # if none onchannel to right, nextOnChannel=-1 so set to = last token to = (len(self.tokens)-1) if nextOnChannel==-1 else nextOnChannel return self.filterForChannel(from_, to, channel)
# Collect all tokens on specified channel to the left of # the current token up until we see a token on DEFAULT_TOKEN_CHANNEL. # If channel is -1, find any non default channel token. def getHiddenTokensToLeft(self, tokenIndex:int, channel:int=-1): self.lazyInit() if tokenIndex<0 or tokenIndex>=len(self.tokens): raise Exception(str(tokenIndex) + " not in 0.." + str(len(self.tokens)-1)) from antlr4.Lexer import Lexer prevOnChannel = self.previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL) if prevOnChannel == tokenIndex - 1: return None # if none on channel to left, prevOnChannel=-1 then from=0 from_ = prevOnChannel+1 to = tokenIndex-1 return self.filterForChannel(from_, to, channel)
def filterForChannel(self, left:int, right:int, channel:int): hidden = [] for i in range(left, right+1): t = self.tokens[i] if channel==-1: from antlr4.Lexer import Lexer if t.channel!= Lexer.DEFAULT_TOKEN_CHANNEL: hidden.append(t) elif t.channel==channel: hidden.append(t) if len(hidden)==0: return None return hidden
def getSourceName(self): return self.tokenSource.getSourceName()
# Get the text of all tokens in this buffer.#/ def getText(self, start:int=None, stop:int=None): self.lazyInit() self.fill() if isinstance(start, Token): start = start.tokenIndex elif start is None: start = 0 if isinstance(stop, Token): stop = stop.tokenIndex elif stop is None or stop >= len(self.tokens): stop = len(self.tokens) - 1 if start < 0 or stop < 0 or stop < start: return "" with StringIO() as buf: for i in range(start, stop+1): t = self.tokens[i] if t.type==Token.EOF: break buf.write(t.text) return buf.getvalue()
# Get all tokens from lexer until EOF#/ def fill(self): self.lazyInit() while self.fetch(1000)==1000: pass12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#
## This default implementation of {@link TokenFactory} creates# {@link CommonToken} objects.#from antlr4.Token import CommonToken
class TokenFactory(object):
pass
class CommonTokenFactory(TokenFactory): __slots__ = 'copyText'
# # The default {@link CommonTokenFactory} instance. # # <p> # This token factory does not explicitly copy token text when constructing # tokens.</p> # DEFAULT = None
def __init__(self, copyText:bool=False): # Indicates whether {@link CommonToken#setText} should be called after # constructing tokens to explicitly set the text. This is useful for cases # where the input stream might not be able to provide arbitrary substrings # of text from the input after the lexer creates a token (e.g. the # implementation of {@link CharStream#getText} in # {@link UnbufferedCharStream} throws an # {@link UnsupportedOperationException}). Explicitly setting the token text # allows {@link Token#getText} to be called at any time regardless of the # input stream implementation. # # <p> # The default value is {@code false} to avoid the performance and memory # overhead of copying text for every token unless explicitly requested.</p> # self.copyText = copyText
def create(self, source, type:int, text:str, channel:int, start:int, stop:int, line:int, column:int): t = CommonToken(source, type, channel, start, stop) t.line = line t.column = column if text is not None: t.text = text elif self.copyText and source[1] is not None: t.text = source[1].getText(start,stop) return t
def createThin(self, type:int, text:str): t = CommonToken(type=type) t.text = text return t
CommonTokenFactory.DEFAULT = CommonTokenFactory()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#/
## This class extends {@link BufferedTokenStream} with functionality to filter# token streams to tokens on a particular channel (tokens where# {@link Token#getChannel} returns a particular value).## <p># This token stream provides access to all tokens by index or when calling# methods like {@link #getText}. The channel filtering is only used for code# accessing tokens via the lookahead methods {@link #LA}, {@link #LT}, and# {@link #LB}.</p>## <p># By default, tokens are placed on the default channel# ({@link Token#DEFAULT_CHANNEL}), but may be reassigned by using the# {@code ->channel(HIDDEN)} lexer command, or by using an embedded action to# call {@link Lexer#setChannel}.# </p>## <p># Note: lexer rules which use the {@code ->skip} lexer command or call# {@link Lexer#skip} do not produce tokens at all, so input text matched by# such a rule will not be available as part of the token stream, regardless of# channel.</p>#/
from antlr4.BufferedTokenStream import BufferedTokenStreamfrom antlr4.Lexer import Lexerfrom antlr4.Token import Token
class CommonTokenStream(BufferedTokenStream): __slots__ = 'channel'
def __init__(self, lexer:Lexer, channel:int=Token.DEFAULT_CHANNEL): super().__init__(lexer) self.channel = channel
def adjustSeekIndex(self, i:int): return self.nextTokenOnChannel(i, self.channel)
def LB(self, k:int): if k==0 or (self.index-k)<0: return None i = self.index n = 1 # find k good tokens looking backwards while n <= k: # skip off-channel tokens i = self.previousTokenOnChannel(i - 1, self.channel) n += 1 if i < 0: return None return self.tokens[i]
def LT(self, k:int): self.lazyInit() if k == 0: return None if k < 0: return self.LB(-k) i = self.index n = 1 # we know tokens[pos] is a good one # find k good tokens while n < k: # skip off-channel tokens, but make sure to not look past EOF if self.sync(i + 1): i = self.nextTokenOnChannel(i + 1, self.channel) n += 1 return self.tokens[i]
# Count EOF just once.#/ def getNumberOfOnChannelTokens(self): n = 0 self.fill() for i in range(0, len(self.tokens)): t = self.tokens[i] if t.channel==self.channel: n += 1 if t.type==Token.EOF: break return n123456789101112131415161718192021222324252627## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#
## This is an InputStream that is loaded from a file all at once# when you construct the object.#
import codecsfrom antlr4.InputStream import InputStream
class FileStream(InputStream): __slots__ = 'fileName'
def __init__(self, fileName:str, encoding:str='ascii', errors:str='strict'): super().__init__(self.readDataFrom(fileName, encoding, errors)) self.fileName = fileName
def readDataFrom(self, fileName:str, encoding:str, errors:str='strict'): # read binary to avoid line ending conversion with open(fileName, 'rb') as file: bytes = file.read() return codecs.decode(bytes, encoding, errors)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#
## Vacuum all input from a string and then treat it like a buffer.#from antlr4.Token import Token
class InputStream (object): __slots__ = ('name', 'strdata', '_index', 'data', '_size')
def __init__(self, data: str): self.name = "<empty>" self.strdata = data self._loadString()
def _loadString(self): self._index = 0 self.data = [ord(c) for c in self.strdata] self._size = len(self.data)
@property def index(self): return self._index
@property def size(self): return self._size
# Reset the stream so that it's in the same state it was # when the object was created *except* the data array is not # touched. # def reset(self): self._index = 0
def consume(self): if self._index >= self._size: assert self.LA(1) == Token.EOF raise Exception("cannot consume EOF") self._index += 1
def LA(self, offset: int): if offset==0: return 0 # undefined if offset<0: offset += 1 # e.g., translate LA(-1) to use offset=0 pos = self._index + offset - 1 if pos < 0 or pos >= self._size: # invalid return Token.EOF return self.data[pos]
def LT(self, offset: int): return self.LA(offset)
# mark/release do nothing; we have entire buffer def mark(self): return -1
def release(self, marker: int): pass
# consume() ahead until p==_index; can't just set p=_index as we must # update line and column. If we seek backwards, just set p # def seek(self, _index: int): if _index<=self._index: self._index = _index # just jump; don't update stream state (line, ...) return # seek forward self._index = min(_index, self._size)
def getText(self, start :int, stop: int): if stop >= self._size: stop = self._size-1 if start >= self._size: return "" else: return self.strdata[start:stop+1]
def __str__(self): return self.strdata123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#
from io import StringIOfrom antlr4.Token import Token
# need forward declarationsIntervalSet = None
class IntervalSet(object): __slots__ = ('intervals', 'readonly')
def __init__(self): self.intervals = None self.readonly = False
def __iter__(self): if self.intervals is not None: for i in self.intervals: for c in i: yield c
def __getitem__(self, item): i = 0 for k in self: if i==item: return k else: i += 1 return Token.INVALID_TYPE
def addOne(self, v:int): self.addRange(range(v, v+1))
def addRange(self, v:range): if self.intervals is None: self.intervals = list() self.intervals.append(v) else: # find insert pos k = 0 for i in self.intervals: # distinct range -> insert if v.stop<i.start: self.intervals.insert(k, v) return # contiguous range -> adjust elif v.stop==i.start: self.intervals[k] = range(v.start, i.stop) return # overlapping range -> adjust and reduce elif v.start<=i.stop: self.intervals[k] = range(min(i.start,v.start), max(i.stop,v.stop)) self.reduce(k) return k += 1 # greater than any existing self.intervals.append(v)
def addSet(self, other:IntervalSet): if other.intervals is not None: for i in other.intervals: self.addRange(i) return self
def reduce(self, k:int): # only need to reduce if k is not the last if k<len(self.intervals)-1: l = self.intervals[k] r = self.intervals[k+1] # if r contained in l if l.stop >= r.stop: self.intervals.pop(k+1) self.reduce(k) elif l.stop >= r.start: self.intervals[k] = range(l.start, r.stop) self.intervals.pop(k+1)
def complement(self, start, stop): result = IntervalSet() result.addRange(range(start,stop+1)) for i in self.intervals: result.removeRange(i) return result
def __contains__(self, item): if self.intervals is None: return False else: return any(item in i for i in self.intervals)
def __len__(self): return sum(len(i) for i in self.intervals)
def removeRange(self, v): if v.start==v.stop-1: self.removeOne(v.start) elif self.intervals is not None: k = 0 for i in self.intervals: # intervals are ordered if v.stop<=i.start: return # check for including range, split it elif v.start>i.start and v.stop<i.stop: self.intervals[k] = range(i.start, v.start) x = range(v.stop, i.stop) self.intervals.insert(k, x) return # check for included range, remove it elif v.start<=i.start and v.stop>=i.stop: self.intervals.pop(k) k -= 1 # need another pass # check for lower boundary elif v.start<i.stop: self.intervals[k] = range(i.start, v.start) # check for upper boundary elif v.stop<i.stop: self.intervals[k] = range(v.stop, i.stop) k += 1
def removeOne(self, v): if self.intervals is not None: k = 0 for i in self.intervals: # intervals is ordered if v<i.start: return # check for single value range elif v==i.start and v==i.stop-1: self.intervals.pop(k) return # check for lower boundary elif v==i.start: self.intervals[k] = range(i.start+1, i.stop) return # check for upper boundary elif v==i.stop-1: self.intervals[k] = range(i.start, i.stop-1) return # split existing range elif v<i.stop-1: x = range(i.start, v) self.intervals[k] = range(v + 1, i.stop) self.intervals.insert(k, x) return k += 1
def toString(self, literalNames:list, symbolicNames:list): if self.intervals is None: return "{}" with StringIO() as buf: if len(self)>1: buf.write("{") first = True for i in self.intervals: for j in i: if not first: buf.write(", ") buf.write(self.elementName(literalNames, symbolicNames, j)) first = False if len(self)>1: buf.write("}") return buf.getvalue()
def elementName(self, literalNames:list, symbolicNames:list, a:int): if a==Token.EOF: return "<EOF>" elif a==Token.EPSILON: return "<EPSILON>" else: if a<len(literalNames) and literalNames[a] != "<INVALID>": return literalNames[a] if a<len(symbolicNames): return symbolicNames[a] return "<UNKNOWN>"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#/from antlr4.IntervalSet import IntervalSetfrom antlr4.Token import Tokenfrom antlr4.PredictionContext import PredictionContext, SingletonPredictionContext, PredictionContextFromRuleContextfrom antlr4.RuleContext import RuleContextfrom antlr4.atn.ATN import ATNfrom antlr4.atn.ATNConfig import ATNConfigfrom antlr4.atn.ATNState import ATNState, RuleStopStatefrom antlr4.atn.Transition import WildcardTransition, NotSetTransition, AbstractPredicateTransition, RuleTransition
class LL1Analyzer (object): __slots__ = 'atn'
#* Special value added to the lookahead sets to indicate that we hit # a predicate during analysis if {@code seeThruPreds==false}. #/ HIT_PRED = Token.INVALID_TYPE
def __init__(self, atn:ATN): self.atn = atn
#* # Calculates the SLL(1) expected lookahead set for each outgoing transition # of an {@link ATNState}. The returned array has one element for each # outgoing transition in {@code s}. If the closure from transition # <em>i</em> leads to a semantic predicate before matching a symbol, the # element at index <em>i</em> of the result will be {@code null}. # # @param s the ATN state # @return the expected symbols for each outgoing transition of {@code s}. #/ def getDecisionLookahead(self, s:ATNState): if s is None: return None
count = len(s.transitions) look = [] * count for alt in range(0, count): look[alt] = set() lookBusy = set() seeThruPreds = False # fail to get lookahead upon pred self._LOOK(s.transition(alt).target, None, PredictionContext.EMPTY, look[alt], lookBusy, set(), seeThruPreds, False) # Wipe out lookahead for this alternative if we found nothing # or we had a predicate when we !seeThruPreds if len(look[alt])==0 or self.HIT_PRED in look[alt]: look[alt] = None return look
#* # Compute set of tokens that can follow {@code s} in the ATN in the # specified {@code ctx}. # # <p>If {@code ctx} is {@code null} and the end of the rule containing # {@code s} is reached, {@link Token#EPSILON} is added to the result set. # If {@code ctx} is not {@code null} and the end of the outermost rule is # reached, {@link Token#EOF} is added to the result set.</p> # # @param s the ATN state # @param stopState the ATN state to stop at. This can be a # {@link BlockEndState} to detect epsilon paths through a closure. # @param ctx the complete parser context, or {@code null} if the context # should be ignored # # @return The set of tokens that can follow {@code s} in the ATN in the # specified {@code ctx}. #/ def LOOK(self, s:ATNState, stopState:ATNState=None, ctx:RuleContext=None): r = IntervalSet() seeThruPreds = True # ignore preds; get all lookahead lookContext = PredictionContextFromRuleContext(s.atn, ctx) if ctx is not None else None self._LOOK(s, stopState, lookContext, r, set(), set(), seeThruPreds, True) return r
#* # Compute set of tokens that can follow {@code s} in the ATN in the # specified {@code ctx}. # # <p>If {@code ctx} is {@code null} and {@code stopState} or the end of the # rule containing {@code s} is reached, {@link Token#EPSILON} is added to # the result set. If {@code ctx} is not {@code null} and {@code addEOF} is # {@code true} and {@code stopState} or the end of the outermost rule is # reached, {@link Token#EOF} is added to the result set.</p> # # @param s the ATN state. # @param stopState the ATN state to stop at. This can be a # {@link BlockEndState} to detect epsilon paths through a closure. # @param ctx The outer context, or {@code null} if the outer context should # not be used. # @param look The result lookahead set. # @param lookBusy A set used for preventing epsilon closures in the ATN # from causing a stack overflow. Outside code should pass # {@code new HashSet<ATNConfig>} for this argument. # @param calledRuleStack A set used for preventing left recursion in the # ATN from causing a stack overflow. Outside code should pass # {@code new BitSet()} for this argument. # @param seeThruPreds {@code true} to true semantic predicates as # implicitly {@code true} and "see through them", otherwise {@code false} # to treat semantic predicates as opaque and add {@link #HIT_PRED} to the # result if one is encountered. # @param addEOF Add {@link Token#EOF} to the result if the end of the # outermost context is reached. This parameter has no effect if {@code ctx} # is {@code null}. #/ def _LOOK(self, s:ATNState, stopState:ATNState , ctx:PredictionContext, look:IntervalSet, lookBusy:set, calledRuleStack:set, seeThruPreds:bool, addEOF:bool): c = ATNConfig(s, 0, ctx)
if c in lookBusy: return lookBusy.add(c)
if s == stopState: if ctx is None: look.addOne(Token.EPSILON) return elif ctx.isEmpty() and addEOF: look.addOne(Token.EOF) return
if isinstance(s, RuleStopState ): if ctx is None: look.addOne(Token.EPSILON) return elif ctx.isEmpty() and addEOF: look.addOne(Token.EOF) return
if ctx != PredictionContext.EMPTY: removed = s.ruleIndex in calledRuleStack try: calledRuleStack.discard(s.ruleIndex) # run thru all possible stack tops in ctx for i in range(0, len(ctx)): returnState = self.atn.states[ctx.getReturnState(i)] self._LOOK(returnState, stopState, ctx.getParent(i), look, lookBusy, calledRuleStack, seeThruPreds, addEOF) finally: if removed: calledRuleStack.add(s.ruleIndex) return
for t in s.transitions: if type(t) == RuleTransition: if t.target.ruleIndex in calledRuleStack: continue
newContext = SingletonPredictionContext.create(ctx, t.followState.stateNumber)
try: calledRuleStack.add(t.target.ruleIndex) self._LOOK(t.target, stopState, newContext, look, lookBusy, calledRuleStack, seeThruPreds, addEOF) finally: calledRuleStack.remove(t.target.ruleIndex) elif isinstance(t, AbstractPredicateTransition ): if seeThruPreds: self._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF) else: look.addOne(self.HIT_PRED) elif t.isEpsilon: self._LOOK(t.target, stopState, ctx, look, lookBusy, calledRuleStack, seeThruPreds, addEOF) elif type(t) == WildcardTransition: look.addRange( range(Token.MIN_USER_TOKEN_TYPE, self.atn.maxTokenType + 1) ) else: set_ = t.label if set_ is not None: if isinstance(t, NotSetTransition): set_ = set_.complement(Token.MIN_USER_TOKEN_TYPE, self.atn.maxTokenType) look.addSet(set_)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#/
# A lexer is recognizer that draws input symbols from a character stream.# lexer grammars result in a subclass of self object. A Lexer object# uses simplified match() and error recovery mechanisms in the interest# of speed.#/from io import StringIO
import sysif sys.version_info[1] > 5: from typing import TextIOelse: from typing.io import TextIOfrom antlr4.CommonTokenFactory import CommonTokenFactoryfrom antlr4.atn.LexerATNSimulator import LexerATNSimulatorfrom antlr4.InputStream import InputStreamfrom antlr4.Recognizer import Recognizerfrom antlr4.Token import Tokenfrom antlr4.error.Errors import IllegalStateException, LexerNoViableAltException, RecognitionException
class TokenSource(object):
pass
class Lexer(Recognizer, TokenSource): __slots__ = ( '_input', '_output', '_factory', '_tokenFactorySourcePair', '_token', '_tokenStartCharIndex', '_tokenStartLine', '_tokenStartColumn', '_hitEOF', '_channel', '_type', '_modeStack', '_mode', '_text' )
DEFAULT_MODE = 0 MORE = -2 SKIP = -3
DEFAULT_TOKEN_CHANNEL = Token.DEFAULT_CHANNEL HIDDEN = Token.HIDDEN_CHANNEL MIN_CHAR_VALUE = 0x0000 MAX_CHAR_VALUE = 0x10FFFF
def __init__(self, input:InputStream, output:TextIO = sys.stdout): super().__init__() self._input = input self._output = output self._factory = CommonTokenFactory.DEFAULT self._tokenFactorySourcePair = (self, input)
self._interp = None # child classes must populate this
# The goal of all lexer rules/methods is to create a token object. # self is an instance variable as multiple rules may collaborate to # create a single token. nextToken will return self object after # matching lexer rule(s). If you subclass to allow multiple token # emissions, then set self to the last token to be matched or # something nonnull so that the auto token emit mechanism will not # emit another token. self._token = None
# What character index in the stream did the current token start at? # Needed, for example, to get the text for current token. Set at # the start of nextToken. self._tokenStartCharIndex = -1
# The line on which the first character of the token resides#/ self._tokenStartLine = -1
# The character position of first character within the line#/ self._tokenStartColumn = -1
# Once we see EOF on char stream, next token will be EOF. # If you have DONE : EOF ; then you see DONE EOF. self._hitEOF = False
# The channel number for the current token#/ self._channel = Token.DEFAULT_CHANNEL
# The token type for the current token#/ self._type = Token.INVALID_TYPE
self._modeStack = [] self._mode = self.DEFAULT_MODE
# You can set the text for the current token to override what is in # the input char buffer. Use setText() or can set self instance var. #/ self._text = None
def reset(self): # wack Lexer state variables if self._input is not None: self._input.seek(0) # rewind the input self._token = None self._type = Token.INVALID_TYPE self._channel = Token.DEFAULT_CHANNEL self._tokenStartCharIndex = -1 self._tokenStartColumn = -1 self._tokenStartLine = -1 self._text = None
self._hitEOF = False self._mode = Lexer.DEFAULT_MODE self._modeStack = []
self._interp.reset()
# Return a token from self source; i.e., match a token on the char # stream. def nextToken(self): if self._input is None: raise IllegalStateException("nextToken requires a non-null input stream.")
# Mark start location in char stream so unbuffered streams are # guaranteed at least have text of current token tokenStartMarker = self._input.mark() try: while True: if self._hitEOF: self.emitEOF() return self._token self._token = None self._channel = Token.DEFAULT_CHANNEL self._tokenStartCharIndex = self._input.index self._tokenStartColumn = self._interp.column self._tokenStartLine = self._interp.line self._text = None continueOuter = False while True: self._type = Token.INVALID_TYPE ttype = self.SKIP try: ttype = self._interp.match(self._input, self._mode) except LexerNoViableAltException as e: self.notifyListeners(e) # report error self.recover(e) if self._input.LA(1)==Token.EOF: self._hitEOF = True if self._type == Token.INVALID_TYPE: self._type = ttype if self._type == self.SKIP: continueOuter = True break if self._type!=self.MORE: break if continueOuter: continue if self._token is None: self.emit() return self._token finally: # make sure we release marker after match or # unbuffered char stream will keep buffering self._input.release(tokenStartMarker)
# Instruct the lexer to skip creating a token for current lexer rule # and look for another token. nextToken() knows to keep looking when # a lexer rule finishes with token set to SKIP_TOKEN. Recall that # if token==null at end of any token rule, it creates one for you # and emits it. #/ def skip(self): self._type = self.SKIP
def more(self): self._type = self.MORE
def mode(self, m:int): self._mode = m
def pushMode(self, m:int): if self._interp.debug: print("pushMode " + str(m), file=self._output) self._modeStack.append(self._mode) self.mode(m)
def popMode(self): if len(self._modeStack)==0: raise Exception("Empty Stack") if self._interp.debug: print("popMode back to "+ self._modeStack[:-1], file=self._output) self.mode( self._modeStack.pop() ) return self._mode
# Set the char stream and reset the lexer#/ @property def inputStream(self): return self._input
@inputStream.setter def inputStream(self, input:InputStream): self._input = None self._tokenFactorySourcePair = (self, self._input) self.reset() self._input = input self._tokenFactorySourcePair = (self, self._input)
@property def sourceName(self): return self._input.sourceName
# By default does not support multiple emits per nextToken invocation # for efficiency reasons. Subclass and override self method, nextToken, # and getToken (to push tokens into a list and pull from that list # rather than a single variable as self implementation does). #/ def emitToken(self, token:Token): self._token = token
# The standard method called to automatically emit a token at the # outermost lexical rule. The token object should point into the # char buffer start..stop. If there is a text override in 'text', # use that to set the token's text. Override self method to emit # custom Token objects or provide a new factory. #/ def emit(self): t = self._factory.create(self._tokenFactorySourcePair, self._type, self._text, self._channel, self._tokenStartCharIndex, self.getCharIndex()-1, self._tokenStartLine, self._tokenStartColumn) self.emitToken(t) return t
def emitEOF(self): cpos = self.column lpos = self.line eof = self._factory.create(self._tokenFactorySourcePair, Token.EOF, None, Token.DEFAULT_CHANNEL, self._input.index, self._input.index-1, lpos, cpos) self.emitToken(eof) return eof
@property def type(self): return self._type
@type.setter def type(self, type:int): self._type = type
@property def line(self): return self._interp.line
@line.setter def line(self, line:int): self._interp.line = line
@property def column(self): return self._interp.column
@column.setter def column(self, column:int): self._interp.column = column
# What is the index of the current character of lookahead?#/ def getCharIndex(self): return self._input.index
# Return the text matched so far for the current token or any # text override. @property def text(self): if self._text is not None: return self._text else: return self._interp.getText(self._input)
# Set the complete text of self token; it wipes any previous # changes to the text. @text.setter def text(self, txt:str): self._text = txt
# Return a list of all Token objects in input char stream. # Forces load of all tokens. Does not include EOF token. #/ def getAllTokens(self): tokens = [] t = self.nextToken() while t.type!=Token.EOF: tokens.append(t) t = self.nextToken() return tokens
def notifyListeners(self, e:LexerNoViableAltException): start = self._tokenStartCharIndex stop = self._input.index text = self._input.getText(start, stop) msg = "token recognition error at: '" + self.getErrorDisplay(text) + "'" listener = self.getErrorListenerDispatch() listener.syntaxError(self, None, self._tokenStartLine, self._tokenStartColumn, msg, e)
def getErrorDisplay(self, s:str): with StringIO() as buf: for c in s: buf.write(self.getErrorDisplayForChar(c)) return buf.getvalue()
def getErrorDisplayForChar(self, c:str): if ord(c[0])==Token.EOF: return "<EOF>" elif c=='\n': return "\\n" elif c=='\t': return "\\t" elif c=='\r': return "\\r" else: return c
def getCharErrorDisplay(self, c:str): return "'" + self.getErrorDisplayForChar(c) + "'"
# Lexers can normally match any char in it's vocabulary after matching # a token, so do the easy thing and just kill a character and hope # it all works out. You can instead use the rule invocation stack # to do sophisticated error recovery if you are in a fragment rule. #/ def recover(self, re:RecognitionException): if self._input.LA(1) != Token.EOF: if isinstance(re, LexerNoViableAltException): # skip a char and try again self._interp.consume(self._input) else: # TODO: Do we lose character or line position information? self._input.consume()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#
## Provides an implementation of {@link TokenSource} as a wrapper around a list# of {@link Token} objects.## <p>If the final token in the list is an {@link Token#EOF} token, it will be used# as the EOF token for every call to {@link #nextToken} after the end of the# list is reached. Otherwise, an EOF token will be created.</p>#from antlr4.CommonTokenFactory import CommonTokenFactoryfrom antlr4.Lexer import TokenSourcefrom antlr4.Token import Token
class ListTokenSource(TokenSource): __slots__ = ('tokens', 'sourceName', 'pos', 'eofToken', '_factory')
# Constructs a new {@link ListTokenSource} instance from the specified # collection of {@link Token} objects and source name. # # @param tokens The collection of {@link Token} objects to provide as a # {@link TokenSource}. # @param sourceName The name of the {@link TokenSource}. If this value is # {@code null}, {@link #getSourceName} will attempt to infer the name from # the next {@link Token} (or the previous token if the end of the input has # been reached). # # @exception NullPointerException if {@code tokens} is {@code null} # def __init__(self, tokens:list, sourceName:str=None): if tokens is None: raise ReferenceError("tokens cannot be null") self.tokens = tokens self.sourceName = sourceName # The index into {@link #tokens} of token to return by the next call to # {@link #nextToken}. The end of the input is indicated by this value # being greater than or equal to the number of items in {@link #tokens}. self.pos = 0 # This field caches the EOF token for the token source. self.eofToken = None # This is the backing field for {@link #getTokenFactory} and self._factory = CommonTokenFactory.DEFAULT
# # {@inheritDoc} # @property def column(self): if self.pos < len(self.tokens): return self.tokens[self.pos].column elif self.eofToken is not None: return self.eofToken.column elif len(self.tokens) > 0: # have to calculate the result from the line/column of the previous # token, along with the text of the token. lastToken = self.tokens[len(self.tokens) - 1] tokenText = lastToken.text if tokenText is not None: lastNewLine = tokenText.rfind('\n') if lastNewLine >= 0: return len(tokenText) - lastNewLine - 1 return lastToken.column + lastToken.stop - lastToken.start + 1
# only reach this if tokens is empty, meaning EOF occurs at the first # position in the input return 0
# # {@inheritDoc} # def nextToken(self): if self.pos >= len(self.tokens): if self.eofToken is None: start = -1 if len(self.tokens) > 0: previousStop = self.tokens[len(self.tokens) - 1].stop if previousStop != -1: start = previousStop + 1 stop = max(-1, start - 1) self.eofToken = self._factory.create((self, self.getInputStream()), Token.EOF, "EOF", Token.DEFAULT_CHANNEL, start, stop, self.line, self.column) return self.eofToken t = self.tokens[self.pos] if self.pos == len(self.tokens) - 1 and t.type == Token.EOF: self.eofToken = t self.pos += 1 return t
# # {@inheritDoc} # @property def line(self): if self.pos < len(self.tokens): return self.tokens[self.pos].line elif self.eofToken is not None: return self.eofToken.line elif len(self.tokens) > 0: # have to calculate the result from the line/column of the previous # token, along with the text of the token. lastToken = self.tokens[len(self.tokens) - 1] line = lastToken.line tokenText = lastToken.text if tokenText is not None: line += tokenText.count('\n')
# if no text is available, assume the token did not contain any newline characters. return line
# only reach this if tokens is empty, meaning EOF occurs at the first # position in the input return 1
# # {@inheritDoc} # def getInputStream(self): if self.pos < len(self.tokens): return self.tokens[self.pos].getInputStream() elif self.eofToken is not None: return self.eofToken.getInputStream() elif len(self.tokens) > 0: return self.tokens[len(self.tokens) - 1].getInputStream() else: # no input stream information is available return None
# # {@inheritDoc} # def getSourceName(self): if self.sourceName is not None: return self.sourceName inputStream = self.getInputStream() if inputStream is not None: return inputStream.getSourceName() else: return "List"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.import sysif sys.version_info[1] > 5: from typing import TextIOelse: from typing.io import TextIOfrom antlr4.BufferedTokenStream import TokenStreamfrom antlr4.CommonTokenFactory import TokenFactoryfrom antlr4.error.ErrorStrategy import DefaultErrorStrategyfrom antlr4.InputStream import InputStreamfrom antlr4.Recognizer import Recognizerfrom antlr4.RuleContext import RuleContextfrom antlr4.ParserRuleContext import ParserRuleContextfrom antlr4.Token import Tokenfrom antlr4.Lexer import Lexerfrom antlr4.atn.ATNDeserializer import ATNDeserializerfrom antlr4.atn.ATNDeserializationOptions import ATNDeserializationOptionsfrom antlr4.error.Errors import UnsupportedOperationException, RecognitionExceptionfrom antlr4.tree.ParseTreePatternMatcher import ParseTreePatternMatcherfrom antlr4.tree.Tree import ParseTreeListener, TerminalNode, ErrorNode
class TraceListener(ParseTreeListener): __slots__ = '_parser'
def __init__(self, parser): self._parser = parser
def enterEveryRule(self, ctx): print("enter " + self._parser.ruleNames[ctx.getRuleIndex()] + ", LT(1)=" + self._parser._input.LT(1).text, file=self._parser._output)
def visitTerminal(self, node):
print("consume " + str(node.symbol) + " rule " + self._parser.ruleNames[self._parser._ctx.getRuleIndex()], file=self._parser._output)
def visitErrorNode(self, node): pass
def exitEveryRule(self, ctx): print("exit " + self._parser.ruleNames[ctx.getRuleIndex()] + ", LT(1)=" + self._parser._input.LT(1).text, file=self._parser._output)
# self is all the parsing support code essentially; most of it is error recovery stuff.#class Parser (Recognizer): __slots__ = ( '_input', '_output', '_errHandler', '_precedenceStack', '_ctx', 'buildParseTrees', '_tracer', '_parseListeners', '_syntaxErrors'
) # self field maps from the serialized ATN string to the deserialized {@link ATN} with # bypass alternatives. # # @see ATNDeserializationOptions#isGenerateRuleBypassTransitions() # bypassAltsAtnCache = dict()
def __init__(self, input:TokenStream, output:TextIO = sys.stdout): super().__init__() # The input stream. self._input = None self._output = output # The error handling strategy for the parser. The default value is a new # instance of {@link DefaultErrorStrategy}. self._errHandler = DefaultErrorStrategy() self._precedenceStack = list() self._precedenceStack.append(0) # The {@link ParserRuleContext} object for the currently executing rule. # self is always non-null during the parsing process. self._ctx = None # Specifies whether or not the parser should construct a parse tree during # the parsing process. The default value is {@code true}. self.buildParseTrees = True # When {@link #setTrace}{@code (true)} is called, a reference to the # {@link TraceListener} is stored here so it can be easily removed in a # later call to {@link #setTrace}{@code (false)}. The listener itself is # implemented as a parser listener so self field is not directly used by # other parser methods. self._tracer = None # The list of {@link ParseTreeListener} listeners registered to receive # events during the parse. self._parseListeners = None # The number of syntax errors reported during parsing. self value is # incremented each time {@link #notifyErrorListeners} is called. self._syntaxErrors = 0 self.setInputStream(input)
# reset the parser's state# def reset(self): if self._input is not None: self._input.seek(0) self._errHandler.reset(self) self._ctx = None self._syntaxErrors = 0 self.setTrace(False) self._precedenceStack = list() self._precedenceStack.append(0) if self._interp is not None: self._interp.reset()
# Match current input symbol against {@code ttype}. If the symbol type # matches, {@link ANTLRErrorStrategy#reportMatch} and {@link #consume} are # called to complete the match process. # # <p>If the symbol type does not match, # {@link ANTLRErrorStrategy#recoverInline} is called on the current error # strategy to attempt recovery. If {@link #getBuildParseTree} is # {@code true} and the token index of the symbol returned by # {@link ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to # the parse tree by calling {@link ParserRuleContext#addErrorNode}.</p> # # @param ttype the token type to match # @return the matched symbol # @throws RecognitionException if the current input symbol did not match # {@code ttype} and the error strategy could not recover from the # mismatched symbol
def match(self, ttype:int): t = self.getCurrentToken() if t.type==ttype: self._errHandler.reportMatch(self) self.consume() else: t = self._errHandler.recoverInline(self) if self.buildParseTrees and t.tokenIndex==-1: # we must have conjured up a new token during single token insertion # if it's not the current symbol self._ctx.addErrorNode(t) return t
# Match current input symbol as a wildcard. If the symbol type matches # (i.e. has a value greater than 0), {@link ANTLRErrorStrategy#reportMatch} # and {@link #consume} are called to complete the match process. # # <p>If the symbol type does not match, # {@link ANTLRErrorStrategy#recoverInline} is called on the current error # strategy to attempt recovery. If {@link #getBuildParseTree} is # {@code true} and the token index of the symbol returned by # {@link ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to # the parse tree by calling {@link ParserRuleContext#addErrorNode}.</p> # # @return the matched symbol # @throws RecognitionException if the current input symbol did not match # a wildcard and the error strategy could not recover from the mismatched # symbol
def matchWildcard(self): t = self.getCurrentToken() if t.type > 0: self._errHandler.reportMatch(self) self.consume() else: t = self._errHandler.recoverInline(self) if self.buildParseTrees and t.tokenIndex == -1: # we must have conjured up a new token during single token insertion # if it's not the current symbol self._ctx.addErrorNode(t)
return t
def getParseListeners(self): return list() if self._parseListeners is None else self._parseListeners
# Registers {@code listener} to receive events during the parsing process. # # <p>To support output-preserving grammar transformations (including but not # limited to left-recursion removal, automated left-factoring, and # optimized code generation), calls to listener methods during the parse # may differ substantially from calls made by # {@link ParseTreeWalker#DEFAULT} used after the parse is complete. In # particular, rule entry and exit events may occur in a different order # during the parse than after the parser. In addition, calls to certain # rule entry methods may be omitted.</p> # # <p>With the following specific exceptions, calls to listener events are # <em>deterministic</em>, i.e. for identical input the calls to listener # methods will be the same.</p> # # <ul> # <li>Alterations to the grammar used to generate code may change the # behavior of the listener calls.</li> # <li>Alterations to the command line options passed to ANTLR 4 when # generating the parser may change the behavior of the listener calls.</li> # <li>Changing the version of the ANTLR Tool used to generate the parser # may change the behavior of the listener calls.</li> # </ul> # # @param listener the listener to add # # @throws NullPointerException if {@code} listener is {@code null} # def addParseListener(self, listener:ParseTreeListener): if listener is None: raise ReferenceError("listener") if self._parseListeners is None: self._parseListeners = [] self._parseListeners.append(listener)
# # Remove {@code listener} from the list of parse listeners. # # <p>If {@code listener} is {@code null} or has not been added as a parse # listener, self method does nothing.</p> # @param listener the listener to remove # def removeParseListener(self, listener:ParseTreeListener): if self._parseListeners is not None: self._parseListeners.remove(listener) if len(self._parseListeners)==0: self._parseListeners = None
# Remove all parse listeners. def removeParseListeners(self): self._parseListeners = None
# Notify any parse listeners of an enter rule event. def triggerEnterRuleEvent(self): if self._parseListeners is not None: for listener in self._parseListeners: listener.enterEveryRule(self._ctx) self._ctx.enterRule(listener)
# # Notify any parse listeners of an exit rule event. # # @see #addParseListener # def triggerExitRuleEvent(self): if self._parseListeners is not None: # reverse order walk of listeners for listener in reversed(self._parseListeners): self._ctx.exitRule(listener) listener.exitEveryRule(self._ctx)
# Gets the number of syntax errors reported during parsing. This value is # incremented each time {@link #notifyErrorListeners} is called. # # @see #notifyErrorListeners # def getNumberOfSyntaxErrors(self): return self._syntaxErrors
def getTokenFactory(self): return self._input.tokenSource._factory
# Tell our token source and error strategy about a new way to create tokens.# def setTokenFactory(self, factory:TokenFactory): self._input.tokenSource._factory = factory
# The ATN with bypass alternatives is expensive to create so we create it # lazily. # # @throws UnsupportedOperationException if the current parser does not # implement the {@link #getSerializedATN()} method. # def getATNWithBypassAlts(self): serializedAtn = self.getSerializedATN() if serializedAtn is None: raise UnsupportedOperationException("The current parser does not support an ATN with bypass alternatives.") result = self.bypassAltsAtnCache.get(serializedAtn, None) if result is None: deserializationOptions = ATNDeserializationOptions() deserializationOptions.generateRuleBypassTransitions = True result = ATNDeserializer(deserializationOptions).deserialize(serializedAtn) self.bypassAltsAtnCache[serializedAtn] = result return result
# The preferred method of getting a tree pattern. For example, here's a # sample use: # # <pre> # ParseTree t = parser.expr(); # ParseTreePattern p = parser.compileParseTreePattern("<ID>+0", MyParser.RULE_expr); # ParseTreeMatch m = p.match(t); # String id = m.get("ID"); # </pre> # def compileParseTreePattern(self, pattern:str, patternRuleIndex:int, lexer:Lexer = None): if lexer is None: if self.getTokenStream() is not None: tokenSource = self.getTokenStream().tokenSource if isinstance( tokenSource, Lexer ): lexer = tokenSource if lexer is None: raise UnsupportedOperationException("Parser can't discover a lexer to use")
m = ParseTreePatternMatcher(lexer, self) return m.compile(pattern, patternRuleIndex)
def getInputStream(self): return self.getTokenStream()
def setInputStream(self, input:InputStream): self.setTokenStream(input)
def getTokenStream(self): return self._input
# Set the token stream and reset the parser.# def setTokenStream(self, input:TokenStream): self._input = None self.reset() self._input = input
# Match needs to return the current input symbol, which gets put # into the label for the associated token ref; e.g., x=ID. # def getCurrentToken(self): return self._input.LT(1)
def notifyErrorListeners(self, msg:str, offendingToken:Token = None, e:RecognitionException = None): if offendingToken is None: offendingToken = self.getCurrentToken() self._syntaxErrors += 1 line = offendingToken.line column = offendingToken.column listener = self.getErrorListenerDispatch() listener.syntaxError(self, offendingToken, line, column, msg, e)
# # Consume and return the {@linkplain #getCurrentToken current symbol}. # # <p>E.g., given the following input with {@code A} being the current # lookahead symbol, self function moves the cursor to {@code B} and returns # {@code A}.</p> # # <pre> # A B # ^ # </pre> # # If the parser is not in error recovery mode, the consumed symbol is added # to the parse tree using {@link ParserRuleContext#addChild(Token)}, and # {@link ParseTreeListener#visitTerminal} is called on any parse listeners. # If the parser <em>is</em> in error recovery mode, the consumed symbol is # added to the parse tree using # {@link ParserRuleContext#addErrorNode(Token)}, and # {@link ParseTreeListener#visitErrorNode} is called on any parse # listeners. # def consume(self): o = self.getCurrentToken() if o.type != Token.EOF: self.getInputStream().consume() hasListener = self._parseListeners is not None and len(self._parseListeners)>0 if self.buildParseTrees or hasListener: if self._errHandler.inErrorRecoveryMode(self): node = self._ctx.addErrorNode(o) else: node = self._ctx.addTokenNode(o) if hasListener: for listener in self._parseListeners: if isinstance(node, ErrorNode): listener.visitErrorNode(node) elif isinstance(node, TerminalNode): listener.visitTerminal(node) return o
def addContextToParseTree(self): # add current context to parent if we have a parent if self._ctx.parentCtx is not None: self._ctx.parentCtx.addChild(self._ctx)
# Always called by generated parsers upon entry to a rule. Access field # {@link #_ctx} get the current context. # def enterRule(self, localctx:ParserRuleContext , state:int , ruleIndex:int): self.state = state self._ctx = localctx self._ctx.start = self._input.LT(1) if self.buildParseTrees: self.addContextToParseTree() if self._parseListeners is not None: self.triggerEnterRuleEvent()
def exitRule(self): self._ctx.stop = self._input.LT(-1) # trigger event on _ctx, before it reverts to parent if self._parseListeners is not None: self.triggerExitRuleEvent() self.state = self._ctx.invokingState self._ctx = self._ctx.parentCtx
def enterOuterAlt(self, localctx:ParserRuleContext, altNum:int): localctx.setAltNumber(altNum) # if we have new localctx, make sure we replace existing ctx # that is previous child of parse tree if self.buildParseTrees and self._ctx != localctx: if self._ctx.parentCtx is not None: self._ctx.parentCtx.removeLastChild() self._ctx.parentCtx.addChild(localctx) self._ctx = localctx
# Get the precedence level for the top-most precedence rule. # # @return The precedence level for the top-most precedence rule, or -1 if # the parser context is not nested within a precedence rule. # def getPrecedence(self): if len(self._precedenceStack)==0: return -1 else: return self._precedenceStack[-1]
def enterRecursionRule(self, localctx:ParserRuleContext, state:int, ruleIndex:int, precedence:int): self.state = state self._precedenceStack.append(precedence) self._ctx = localctx self._ctx.start = self._input.LT(1) if self._parseListeners is not None: self.triggerEnterRuleEvent() # simulates rule entry for left-recursive rules
# # Like {@link #enterRule} but for recursive rules. # def pushNewRecursionContext(self, localctx:ParserRuleContext, state:int, ruleIndex:int): previous = self._ctx previous.parentCtx = localctx previous.invokingState = state previous.stop = self._input.LT(-1)
self._ctx = localctx self._ctx.start = previous.start if self.buildParseTrees: self._ctx.addChild(previous)
if self._parseListeners is not None: self.triggerEnterRuleEvent() # simulates rule entry for left-recursive rules
def unrollRecursionContexts(self, parentCtx:ParserRuleContext): self._precedenceStack.pop() self._ctx.stop = self._input.LT(-1) retCtx = self._ctx # save current ctx (return value) # unroll so _ctx is as it was before call to recursive method if self._parseListeners is not None: while self._ctx is not parentCtx: self.triggerExitRuleEvent() self._ctx = self._ctx.parentCtx else: self._ctx = parentCtx
# hook into tree retCtx.parentCtx = parentCtx
if self.buildParseTrees and parentCtx is not None: # add return ctx into invoking rule's tree parentCtx.addChild(retCtx)
def getInvokingContext(self, ruleIndex:int): ctx = self._ctx while ctx is not None: if ctx.getRuleIndex() == ruleIndex: return ctx ctx = ctx.parentCtx return None
def precpred(self, localctx:RuleContext , precedence:int): return precedence >= self._precedenceStack[-1]
def inContext(self, context:str): # TODO: useful in parser? return False
# # Checks whether or not {@code symbol} can follow the current state in the # ATN. The behavior of self method is equivalent to the following, but is # implemented such that the complete context-sensitive follow set does not # need to be explicitly constructed. # # <pre> # return getExpectedTokens().contains(symbol); # </pre> # # @param symbol the symbol type to check # @return {@code true} if {@code symbol} can follow the current state in # the ATN, otherwise {@code false}. # def isExpectedToken(self, symbol:int): atn = self._interp.atn ctx = self._ctx s = atn.states[self.state] following = atn.nextTokens(s) if symbol in following: return True if not Token.EPSILON in following: return False
while ctx is not None and ctx.invokingState>=0 and Token.EPSILON in following: invokingState = atn.states[ctx.invokingState] rt = invokingState.transitions[0] following = atn.nextTokens(rt.followState) if symbol in following: return True ctx = ctx.parentCtx
if Token.EPSILON in following and symbol == Token.EOF: return True else: return False
# Computes the set of input symbols which could follow the current parser # state and context, as given by {@link #getState} and {@link #getContext}, # respectively. # # @see ATN#getExpectedTokens(int, RuleContext) # def getExpectedTokens(self): return self._interp.atn.getExpectedTokens(self.state, self._ctx)
def getExpectedTokensWithinCurrentRule(self): atn = self._interp.atn s = atn.states[self.state] return atn.nextTokens(s)
# Get a rule's index (i.e., {@code RULE_ruleName} field) or -1 if not found.# def getRuleIndex(self, ruleName:str): ruleIndex = self.getRuleIndexMap().get(ruleName, None) if ruleIndex is not None: return ruleIndex else: return -1
# Return List<String> of the rule names in your parser instance # leading up to a call to the current rule. You could override if # you want more details such as the file/line info of where # in the ATN a rule is invoked. # # this is very useful for error messages. # def getRuleInvocationStack(self, p:RuleContext=None): if p is None: p = self._ctx stack = list() while p is not None: # compute what follows who invoked us ruleIndex = p.getRuleIndex() if ruleIndex<0: stack.append("n/a") else: stack.append(self.ruleNames[ruleIndex]) p = p.parentCtx return stack
# For debugging and other purposes.# def getDFAStrings(self): return [ str(dfa) for dfa in self._interp.decisionToDFA]
# For debugging and other purposes.# def dumpDFA(self): seenOne = False for i in range(0, len(self._interp.decisionToDFA)): dfa = self._interp.decisionToDFA[i] if len(dfa.states)>0: if seenOne: print(file=self._output) print("Decision " + str(dfa.decision) + ":", file=self._output) print(dfa.toString(self.literalNames, self.symbolicNames), end='', file=self._output) seenOne = True
def getSourceName(self): return self._input.sourceName
# During a parse is sometimes useful to listen in on the rule entry and exit # events as well as token matches. self is for quick and dirty debugging. # def setTrace(self, trace:bool): if not trace: self.removeParseListener(self._tracer) self._tracer = None else: if self._tracer is not None: self.removeParseListener(self._tracer) self._tracer = TraceListener(self) self.addParseListener(self._tracer)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#
# A parser simulator that mimics what ANTLR's generated# parser code does. A ParserATNSimulator is used to make# predictions via adaptivePredict but this class moves a pointer through the# ATN to simulate parsing. ParserATNSimulator just# makes us efficient rather than having to backtrack, for example.## This properly creates parse trees even for left recursive rules.## We rely on the left recursive rule invocation and special predicate# transitions to make left recursive rules work.## See TestParserInterpreter for examples.#from antlr4.dfa.DFA import DFAfrom antlr4.BufferedTokenStream import TokenStreamfrom antlr4.Lexer import Lexerfrom antlr4.Parser import Parserfrom antlr4.ParserRuleContext import InterpreterRuleContext, ParserRuleContextfrom antlr4.Token import Tokenfrom antlr4.atn.ATN import ATNfrom antlr4.atn.ATNState import StarLoopEntryState, ATNState, LoopEndStatefrom antlr4.atn.ParserATNSimulator import ParserATNSimulatorfrom antlr4.PredictionContext import PredictionContextCachefrom antlr4.atn.Transition import Transitionfrom antlr4.error.Errors import RecognitionException, UnsupportedOperationException, FailedPredicateException
class ParserInterpreter(Parser): __slots__ = ( 'grammarFileName', 'atn', 'tokenNames', 'ruleNames', 'decisionToDFA', 'sharedContextCache', '_parentContextStack', 'pushRecursionContextStates' )
def __init__(self, grammarFileName:str, tokenNames:list, ruleNames:list, atn:ATN, input:TokenStream): super().__init__(input) self.grammarFileName = grammarFileName self.atn = atn self.tokenNames = tokenNames self.ruleNames = ruleNames self.decisionToDFA = [ DFA(state) for state in atn.decisionToState ] self.sharedContextCache = PredictionContextCache() self._parentContextStack = list() # identify the ATN states where pushNewRecursionContext must be called self.pushRecursionContextStates = set() for state in atn.states: if not isinstance(state, StarLoopEntryState): continue if state.isPrecedenceDecision: self.pushRecursionContextStates.add(state.stateNumber) # get atn simulator that knows how to do predictions self._interp = ParserATNSimulator(self, atn, self.decisionToDFA, self.sharedContextCache)
# Begin parsing at startRuleIndex# def parse(self, startRuleIndex:int): startRuleStartState = self.atn.ruleToStartState[startRuleIndex] rootContext = InterpreterRuleContext(None, ATNState.INVALID_STATE_NUMBER, startRuleIndex) if startRuleStartState.isPrecedenceRule: self.enterRecursionRule(rootContext, startRuleStartState.stateNumber, startRuleIndex, 0) else: self.enterRule(rootContext, startRuleStartState.stateNumber, startRuleIndex) while True: p = self.getATNState() if p.stateType==ATNState.RULE_STOP : # pop; return from rule if len(self._ctx)==0: if startRuleStartState.isPrecedenceRule: result = self._ctx parentContext = self._parentContextStack.pop() self.unrollRecursionContexts(parentContext.a) return result else: self.exitRule() return rootContext self.visitRuleStopState(p)
else: try: self.visitState(p) except RecognitionException as e: self.state = self.atn.ruleToStopState[p.ruleIndex].stateNumber self._ctx.exception = e self._errHandler.reportError(self, e) self._errHandler.recover(self, e)
def enterRecursionRule(self, localctx:ParserRuleContext, state:int, ruleIndex:int, precedence:int): self._parentContextStack.append((self._ctx, localctx.invokingState)) super().enterRecursionRule(localctx, state, ruleIndex, precedence)
def getATNState(self): return self.atn.states[self.state]
def visitState(self, p:ATNState): edge = 0 if len(p.transitions) > 1: self._errHandler.sync(self) edge = self._interp.adaptivePredict(self._input, p.decision, self._ctx) else: edge = 1
transition = p.transitions[edge - 1] tt = transition.serializationType if tt==Transition.EPSILON:
if self.pushRecursionContextStates[p.stateNumber] and not isinstance(transition.target, LoopEndState): t = self._parentContextStack[-1] ctx = InterpreterRuleContext(t[0], t[1], self._ctx.ruleIndex) self.pushNewRecursionContext(ctx, self.atn.ruleToStartState[p.ruleIndex].stateNumber, self._ctx.ruleIndex)
elif tt==Transition.ATOM:
self.match(transition.label)
elif tt in [ Transition.RANGE, Transition.SET, Transition.NOT_SET]:
if not transition.matches(self._input.LA(1), Token.MIN_USER_TOKEN_TYPE, Lexer.MAX_CHAR_VALUE): self._errHandler.recoverInline(self) self.matchWildcard()
elif tt==Transition.WILDCARD:
self.matchWildcard()
elif tt==Transition.RULE:
ruleStartState = transition.target ruleIndex = ruleStartState.ruleIndex ctx = InterpreterRuleContext(self._ctx, p.stateNumber, ruleIndex) if ruleStartState.isPrecedenceRule: self.enterRecursionRule(ctx, ruleStartState.stateNumber, ruleIndex, transition.precedence) else: self.enterRule(ctx, transition.target.stateNumber, ruleIndex)
elif tt==Transition.PREDICATE:
if not self.sempred(self._ctx, transition.ruleIndex, transition.predIndex): raise FailedPredicateException(self)
elif tt==Transition.ACTION:
self.action(self._ctx, transition.ruleIndex, transition.actionIndex)
elif tt==Transition.PRECEDENCE:
if not self.precpred(self._ctx, transition.precedence): msg = "precpred(_ctx, " + str(transition.precedence) + ")" raise FailedPredicateException(self, msg)
else: raise UnsupportedOperationException("Unrecognized ATN transition type.")
self.state = transition.target.stateNumber
def visitRuleStopState(self, p:ATNState): ruleStartState = self.atn.ruleToStartState[p.ruleIndex] if ruleStartState.isPrecedenceRule: parentContext = self._parentContextStack.pop() self.unrollRecursionContexts(parentContext.a) self.state = parentContext[1] else: self.exitRule()
ruleTransition = self.atn.states[self.state].transitions[0] self.state = ruleTransition.followState.stateNumber123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.
#* A rule invocation record for parsing.## Contains all of the information about the current rule not stored in the# RuleContext. It handles parse tree children list, Any ATN state# tracing, and the default values available for rule indications:# start, stop, rule index, current alt number, current# ATN state.## Subclasses made for each rule and grammar track the parameters,# return values, locals, and labels specific to that rule. These# are the objects that are returned from rules.## Note text is not an actual field of a rule return value; it is computed# from start and stop using the input stream's toString() method. I# could add a ctor to this so that we can pass in and store the input# stream, but I'm not sure we want to do that. It would seem to be undefined# to get the .text property anyway if the rule matches tokens from multiple# input streams.## I do not use getters for fields of objects that are used simply to# group values such as this aggregate. The getters/setters are there to# satisfy the superclass interface.
from antlr4.RuleContext import RuleContextfrom antlr4.Token import Tokenfrom antlr4.tree.Tree import ParseTreeListener, ParseTree, TerminalNodeImpl, ErrorNodeImpl, TerminalNode, \ INVALID_INTERVAL
# need forward declarationParserRuleContext = None
class ParserRuleContext(RuleContext): __slots__ = ('children', 'start', 'stop', 'exception') def __init__(self, parent:ParserRuleContext = None, invokingStateNumber:int = None ): super().__init__(parent, invokingStateNumber) #* If we are debugging or building a parse tree for a visitor, # we need to track all of the tokens and rule invocations associated # with this rule's context. This is empty for parsing w/o tree constr. # operation because we don't the need to track the details about # how we parse this rule. #/ self.children = None self.start = None self.stop = None # The exception that forced this rule to return. If the rule successfully # completed, this is {@code null}. self.exception = None
#* COPY a ctx (I'm deliberately not using copy constructor)#/ # # This is used in the generated parser code to flip a generic XContext # node for rule X to a YContext for alt label Y. In that sense, it is # not really a generic copy function. # # If we do an error sync() at start of a rule, we might add error nodes # to the generic XContext so this function must copy those nodes to # the YContext as well else they are lost! #/ def copyFrom(self, ctx:ParserRuleContext): # from RuleContext self.parentCtx = ctx.parentCtx self.invokingState = ctx.invokingState self.children = None self.start = ctx.start self.stop = ctx.stop
# copy any error nodes to alt label node if ctx.children is not None: self.children = [] # reset parent pointer for any error nodes for child in ctx.children: if isinstance(child, ErrorNodeImpl): self.children.append(child) child.parentCtx = self
# Double dispatch methods for listeners def enterRule(self, listener:ParseTreeListener): pass
def exitRule(self, listener:ParseTreeListener): pass
#* Does not set parent link; other add methods do that#/ def addChild(self, child:ParseTree): if self.children is None: self.children = [] self.children.append(child) return child
#* Used by enterOuterAlt to toss out a RuleContext previously added as # we entered a rule. If we have # label, we will need to remove # generic ruleContext object. #/ def removeLastChild(self): if self.children is not None: del self.children[len(self.children)-1]
def addTokenNode(self, token:Token): node = TerminalNodeImpl(token) self.addChild(node) node.parentCtx = self return node
def addErrorNode(self, badToken:Token): node = ErrorNodeImpl(badToken) self.addChild(node) node.parentCtx = self return node
def getChild(self, i:int, ttype:type = None): if ttype is None: return self.children[i] if len(self.children)>i else None else: for child in self.getChildren(): if not isinstance(child, ttype): continue if i==0: return child i -= 1 return None
def getChildren(self, predicate = None): if self.children is not None: for child in self.children: if predicate is not None and not predicate(child): continue yield child
def getToken(self, ttype:int, i:int): for child in self.getChildren(): if not isinstance(child, TerminalNode): continue if child.symbol.type != ttype: continue if i==0: return child i -= 1 return None
def getTokens(self, ttype:int ): if self.getChildren() is None: return [] tokens = [] for child in self.getChildren(): if not isinstance(child, TerminalNode): continue if child.symbol.type != ttype: continue tokens.append(child) return tokens
def getTypedRuleContext(self, ctxType:type, i:int): return self.getChild(i, ctxType)
def getTypedRuleContexts(self, ctxType:type): children = self.getChildren() if children is None: return [] contexts = [] for child in children: if not isinstance(child, ctxType): continue contexts.append(child) return contexts
def getChildCount(self): return len(self.children) if self.children else 0
def getSourceInterval(self): if self.start is None or self.stop is None: return INVALID_INTERVAL else: return (self.start.tokenIndex, self.stop.tokenIndex)
RuleContext.EMPTY = ParserRuleContext()
class InterpreterRuleContext(ParserRuleContext):
def __init__(self, parent:ParserRuleContext, invokingStateNumber:int, ruleIndex:int): super().__init__(parent, invokingStateNumber) self.ruleIndex = ruleIndex123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#/from io import StringIO
from antlr4.error.Errors import IllegalStateException
from antlr4.RuleContext import RuleContextfrom antlr4.atn.ATN import ATNfrom antlr4.atn.ATNState import ATNState
class PredictionContext(object):
# Represents {@code $} in local context prediction, which means wildcard. # {@code#+x =#}. #/ EMPTY = None
# Represents {@code $} in an array in full context mode, when {@code $} # doesn't mean wildcard: {@code $ + x = [$,x]}. Here, # {@code $} = {@link #EMPTY_RETURN_STATE}. #/ EMPTY_RETURN_STATE = 0x7FFFFFFF
globalNodeCount = 1 id = globalNodeCount
# Stores the computed hash code of this {@link PredictionContext}. The hash # code is computed in parts to match the following reference algorithm. # # <pre> # private int referenceHashCode() { # int hash = {@link MurmurHash#initialize MurmurHash.initialize}({@link #INITIAL_HASH}); # # for (int i = 0; i < {@link #size()}; i++) { # hash = {@link MurmurHash#update MurmurHash.update}(hash, {@link #getParent getParent}(i)); # } # # for (int i = 0; i < {@link #size()}; i++) { # hash = {@link MurmurHash#update MurmurHash.update}(hash, {@link #getReturnState getReturnState}(i)); # } # # hash = {@link MurmurHash#finish MurmurHash.finish}(hash, 2# {@link #size()}); # return hash; # } # </pre> #/
def __init__(self, cachedHashCode:int): self.cachedHashCode = cachedHashCode
def __len__(self): return 0
# This means only the {@link #EMPTY} context is in set. def isEmpty(self): return self is self.EMPTY
def hasEmptyPath(self): return self.getReturnState(len(self) - 1) == self.EMPTY_RETURN_STATE
def getReturnState(self, index:int): raise IllegalStateException("illegal!")
def __hash__(self): return self.cachedHashCode
def calculateHashCode(parent:PredictionContext, returnState:int): return hash("") if parent is None else hash((hash(parent), returnState))
def calculateListsHashCode(parents:[], returnStates:[] ): h = 0 for parent, returnState in zip(parents, returnStates): h = hash((h, calculateHashCode(parent, returnState))) return h
# Used to cache {@link PredictionContext} objects. Its used for the shared# context cash associated with contexts in DFA states. This cache# can be used for both lexers and parsers.
class PredictionContextCache(object):
def __init__(self): self.cache = dict()
# Add a context to the cache and return it. If the context already exists, # return that one instead and do not add a new context to the cache. # Protect shared cache from unsafe thread access. # def add(self, ctx:PredictionContext): if ctx==PredictionContext.EMPTY: return PredictionContext.EMPTY existing = self.cache.get(ctx, None) if existing is not None: return existing self.cache[ctx] = ctx return ctx
def get(self, ctx:PredictionContext): return self.cache.get(ctx, None)
def __len__(self): return len(self.cache)
class SingletonPredictionContext(PredictionContext):
@staticmethod def create(parent:PredictionContext , returnState:int ): if returnState == PredictionContext.EMPTY_RETURN_STATE and parent is None: # someone can pass in the bits of an array ctx that mean $ return SingletonPredictionContext.EMPTY else: return SingletonPredictionContext(parent, returnState)
def __init__(self, parent:PredictionContext, returnState:int): hashCode = calculateHashCode(parent, returnState) super().__init__(hashCode) self.parentCtx = parent self.returnState = returnState
def __len__(self): return 1
def getParent(self, index:int): return self.parentCtx
def getReturnState(self, index:int): return self.returnState
def __eq__(self, other): if self is other: return True elif other is None: return False elif not isinstance(other, SingletonPredictionContext): return False else: return self.returnState == other.returnState and self.parentCtx == other.parentCtx
def __hash__(self): return self.cachedHashCode
def __str__(self): up = "" if self.parentCtx is None else str(self.parentCtx) if len(up)==0: if self.returnState == self.EMPTY_RETURN_STATE: return "$" else: return str(self.returnState) else: return str(self.returnState) + " " + up
class EmptyPredictionContext(SingletonPredictionContext):
def __init__(self): super().__init__(None, PredictionContext.EMPTY_RETURN_STATE)
def isEmpty(self): return True
def __eq__(self, other): return self is other
def __hash__(self): return self.cachedHashCode
def __str__(self): return "$"
PredictionContext.EMPTY = EmptyPredictionContext()
class ArrayPredictionContext(PredictionContext): # Parent can be null only if full ctx mode and we make an array # from {@link #EMPTY} and non-empty. We merge {@link #EMPTY} by using null parent and # returnState == {@link #EMPTY_RETURN_STATE}.
def __init__(self, parents:list, returnStates:list): super().__init__(calculateListsHashCode(parents, returnStates)) self.parents = parents self.returnStates = returnStates
def isEmpty(self): # since EMPTY_RETURN_STATE can only appear in the last position, we # don't need to verify that size==1 return self.returnStates[0]==PredictionContext.EMPTY_RETURN_STATE
def __len__(self): return len(self.returnStates)
def getParent(self, index:int): return self.parents[index]
def getReturnState(self, index:int): return self.returnStates[index]
def __eq__(self, other): if self is other: return True elif not isinstance(other, ArrayPredictionContext): return False elif hash(self) != hash(other): return False # can't be same if hash is different else: return self.returnStates==other.returnStates and self.parents==other.parents
def __str__(self): if self.isEmpty(): return "[]" with StringIO() as buf: buf.write("[") for i in range(0,len(self.returnStates)): if i>0: buf.write(", ") if self.returnStates[i]==PredictionContext.EMPTY_RETURN_STATE: buf.write("$") continue buf.write(str(self.returnStates[i])) if self.parents[i] is not None: buf.write(' ') buf.write(str(self.parents[i])) else: buf.write("null") buf.write("]") return buf.getvalue()
def __hash__(self): return self.cachedHashCode
# Convert a {@link RuleContext} tree to a {@link PredictionContext} graph.# Return {@link #EMPTY} if {@code outerContext} is empty or null.#/def PredictionContextFromRuleContext(atn:ATN, outerContext:RuleContext=None): if outerContext is None: outerContext = RuleContext.EMPTY
# if we are in RuleContext of start rule, s, then PredictionContext # is EMPTY. Nobody called us. (if we are empty, return empty) if outerContext.parentCtx is None or outerContext is RuleContext.EMPTY: return PredictionContext.EMPTY
# If we have a parent, convert it to a PredictionContext graph parent = PredictionContextFromRuleContext(atn, outerContext.parentCtx) state = atn.states[outerContext.invokingState] transition = state.transitions[0] return SingletonPredictionContext.create(parent, transition.followState.stateNumber)
def merge(a:PredictionContext, b:PredictionContext, rootIsWildcard:bool, mergeCache:dict):
# share same graph if both same if a==b: return a
if isinstance(a, SingletonPredictionContext) and isinstance(b, SingletonPredictionContext): return mergeSingletons(a, b, rootIsWildcard, mergeCache)
# At least one of a or b is array # If one is $ and rootIsWildcard, return $ as# wildcard if rootIsWildcard: if isinstance( a, EmptyPredictionContext ): return a if isinstance( b, EmptyPredictionContext ): return b
# convert singleton so both are arrays to normalize if isinstance( a, SingletonPredictionContext ): a = ArrayPredictionContext([a.parentCtx], [a.returnState]) if isinstance( b, SingletonPredictionContext): b = ArrayPredictionContext([b.parentCtx], [b.returnState]) return mergeArrays(a, b, rootIsWildcard, mergeCache)
## Merge two {@link SingletonPredictionContext} instances.## <p>Stack tops equal, parents merge is same; return left graph.<br># <embed src="images/SingletonMerge_SameRootSamePar.svg" type="image/svg+xml"/></p>## <p>Same stack top, parents differ; merge parents giving array node, then# remainders of those graphs. A new root node is created to point to the# merged parents.<br># <embed src="images/SingletonMerge_SameRootDiffPar.svg" type="image/svg+xml"/></p>## <p>Different stack tops pointing to same parent. Make array node for the# root where both element in the root point to the same (original)# parent.<br># <embed src="images/SingletonMerge_DiffRootSamePar.svg" type="image/svg+xml"/></p>## <p>Different stack tops pointing to different parents. Make array node for# the root where each element points to the corresponding original# parent.<br># <embed src="images/SingletonMerge_DiffRootDiffPar.svg" type="image/svg+xml"/></p>## @param a the first {@link SingletonPredictionContext}# @param b the second {@link SingletonPredictionContext}# @param rootIsWildcard {@code true} if this is a local-context merge,# otherwise false to indicate a full-context merge# @param mergeCache#/def mergeSingletons(a:SingletonPredictionContext, b:SingletonPredictionContext, rootIsWildcard:bool, mergeCache:dict): if mergeCache is not None: previous = mergeCache.get((a,b), None) if previous is not None: return previous previous = mergeCache.get((b,a), None) if previous is not None: return previous
merged = mergeRoot(a, b, rootIsWildcard) if merged is not None: if mergeCache is not None: mergeCache[(a, b)] = merged return merged
if a.returnState==b.returnState: parent = merge(a.parentCtx, b.parentCtx, rootIsWildcard, mergeCache) # if parent is same as existing a or b parent or reduced to a parent, return it if parent == a.parentCtx: return a # ax + bx = ax, if a=b if parent == b.parentCtx: return b # ax + bx = bx, if a=b # else: ax + ay = a'[x,y] # merge parents x and y, giving array node with x,y then remainders # of those graphs. dup a, a' points at merged array # new joined parent so create new singleton pointing to it, a' merged = SingletonPredictionContext.create(parent, a.returnState) if mergeCache is not None: mergeCache[(a, b)] = merged return merged else: # a != b payloads differ # see if we can collapse parents due to $+x parents if local ctx singleParent = None if a is b or (a.parentCtx is not None and a.parentCtx==b.parentCtx): # ax + bx = [a,b]x singleParent = a.parentCtx if singleParent is not None: # parents are same # sort payloads and use same parent payloads = [ a.returnState, b.returnState ] if a.returnState > b.returnState: payloads = [ b.returnState, a.returnState ] parents = [singleParent, singleParent] merged = ArrayPredictionContext(parents, payloads) if mergeCache is not None: mergeCache[(a, b)] = merged return merged # parents differ and can't merge them. Just pack together # into array; can't merge. # ax + by = [ax,by] payloads = [ a.returnState, b.returnState ] parents = [ a.parentCtx, b.parentCtx ] if a.returnState > b.returnState: # sort by payload payloads = [ b.returnState, a.returnState ] parents = [ b.parentCtx, a.parentCtx ] merged = ArrayPredictionContext(parents, payloads) if mergeCache is not None: mergeCache[(a, b)] = merged return merged
## Handle case where at least one of {@code a} or {@code b} is# {@link #EMPTY}. In the following diagrams, the symbol {@code $} is used# to represent {@link #EMPTY}.## <h2>Local-Context Merges</h2>## <p>These local-context merge operations are used when {@code rootIsWildcard}# is true.</p>## <p>{@link #EMPTY} is superset of any graph; return {@link #EMPTY}.<br># <embed src="images/LocalMerge_EmptyRoot.svg" type="image/svg+xml"/></p>## <p>{@link #EMPTY} and anything is {@code #EMPTY}, so merged parent is# {@code #EMPTY}; return left graph.<br># <embed src="images/LocalMerge_EmptyParent.svg" type="image/svg+xml"/></p>## <p>Special case of last merge if local context.<br># <embed src="images/LocalMerge_DiffRoots.svg" type="image/svg+xml"/></p>## <h2>Full-Context Merges</h2>## <p>These full-context merge operations are used when {@code rootIsWildcard}# is false.</p>## <p><embed src="images/FullMerge_EmptyRoots.svg" type="image/svg+xml"/></p>## <p>Must keep all contexts; {@link #EMPTY} in array is a special value (and# null parent).<br># <embed src="images/FullMerge_EmptyRoot.svg" type="image/svg+xml"/></p>## <p><embed src="images/FullMerge_SameRoot.svg" type="image/svg+xml"/></p>## @param a the first {@link SingletonPredictionContext}# @param b the second {@link SingletonPredictionContext}# @param rootIsWildcard {@code true} if this is a local-context merge,# otherwise false to indicate a full-context merge#/def mergeRoot(a:SingletonPredictionContext, b:SingletonPredictionContext, rootIsWildcard:bool): if rootIsWildcard: if a == PredictionContext.EMPTY: return PredictionContext.EMPTY ## + b =# if b == PredictionContext.EMPTY: return PredictionContext.EMPTY # a +# =# else: if a == PredictionContext.EMPTY and b == PredictionContext.EMPTY: return PredictionContext.EMPTY # $ + $ = $ elif a == PredictionContext.EMPTY: # $ + x = [$,x] payloads = [ b.returnState, PredictionContext.EMPTY_RETURN_STATE ] parents = [ b.parentCtx, None ] return ArrayPredictionContext(parents, payloads) elif b == PredictionContext.EMPTY: # x + $ = [$,x] ($ is always first if present) payloads = [ a.returnState, PredictionContext.EMPTY_RETURN_STATE ] parents = [ a.parentCtx, None ] return ArrayPredictionContext(parents, payloads) return None
## Merge two {@link ArrayPredictionContext} instances.## <p>Different tops, different parents.<br># <embed src="images/ArrayMerge_DiffTopDiffPar.svg" type="image/svg+xml"/></p>## <p>Shared top, same parents.<br># <embed src="images/ArrayMerge_ShareTopSamePar.svg" type="image/svg+xml"/></p>## <p>Shared top, different parents.<br># <embed src="images/ArrayMerge_ShareTopDiffPar.svg" type="image/svg+xml"/></p>## <p>Shared top, all shared parents.<br># <embed src="images/ArrayMerge_ShareTopSharePar.svg" type="image/svg+xml"/></p>## <p>Equal tops, merge parents and reduce top to# {@link SingletonPredictionContext}.<br># <embed src="images/ArrayMerge_EqualTop.svg" type="image/svg+xml"/></p>#/def mergeArrays(a:ArrayPredictionContext, b:ArrayPredictionContext, rootIsWildcard:bool, mergeCache:dict): if mergeCache is not None: previous = mergeCache.get((a,b), None) if previous is not None: return previous previous = mergeCache.get((b,a), None) if previous is not None: return previous
# merge sorted payloads a + b => M i = 0 # walks a j = 0 # walks b k = 0 # walks target M array
mergedReturnStates = [None] * (len(a.returnStates) + len( b.returnStates)) mergedParents = [None] * len(mergedReturnStates) # walk and merge to yield mergedParents, mergedReturnStates while i<len(a.returnStates) and j<len(b.returnStates): a_parent = a.parents[i] b_parent = b.parents[j] if a.returnStates[i]==b.returnStates[j]: # same payload (stack tops are equal), must yield merged singleton payload = a.returnStates[i] # $+$ = $ bothDollars = payload == PredictionContext.EMPTY_RETURN_STATE and \ a_parent is None and b_parent is None ax_ax = (a_parent is not None and b_parent is not None) and a_parent==b_parent # ax+ax -> ax if bothDollars or ax_ax: mergedParents[k] = a_parent # choose left mergedReturnStates[k] = payload else: # ax+ay -> a'[x,y] mergedParent = merge(a_parent, b_parent, rootIsWildcard, mergeCache) mergedParents[k] = mergedParent mergedReturnStates[k] = payload i += 1 # hop over left one as usual j += 1 # but also skip one in right side since we merge elif a.returnStates[i]<b.returnStates[j]: # copy a[i] to M mergedParents[k] = a_parent mergedReturnStates[k] = a.returnStates[i] i += 1 else: # b > a, copy b[j] to M mergedParents[k] = b_parent mergedReturnStates[k] = b.returnStates[j] j += 1 k += 1
# copy over any payloads remaining in either array if i < len(a.returnStates): for p in range(i, len(a.returnStates)): mergedParents[k] = a.parents[p] mergedReturnStates[k] = a.returnStates[p] k += 1 else: for p in range(j, len(b.returnStates)): mergedParents[k] = b.parents[p] mergedReturnStates[k] = b.returnStates[p] k += 1
# trim merged if we combined a few that had same stack tops if k < len(mergedParents): # write index < last position; trim if k == 1: # for just one merged element, return singleton top merged = SingletonPredictionContext.create(mergedParents[0], mergedReturnStates[0]) if mergeCache is not None: mergeCache[(a,b)] = merged return merged mergedParents = mergedParents[0:k] mergedReturnStates = mergedReturnStates[0:k]
merged = ArrayPredictionContext(mergedParents, mergedReturnStates)
# if we created same array as a or b, return that instead # TODO: track whether this is possible above during merge sort for speed if merged==a: if mergeCache is not None: mergeCache[(a,b)] = a return a if merged==b: if mergeCache is not None: mergeCache[(a,b)] = b return b combineCommonParents(mergedParents)
if mergeCache is not None: mergeCache[(a,b)] = merged return merged
## Make pass over all <em>M</em> {@code parents}; merge any {@code equals()}# ones.#/def combineCommonParents(parents:list): uniqueParents = dict()
for p in range(0, len(parents)): parent = parents[p] if uniqueParents.get(parent, None) is None: uniqueParents[parent] = parent
for p in range(0, len(parents)): parents[p] = uniqueParents[parents[p]]
def getCachedPredictionContext(context:PredictionContext, contextCache:PredictionContextCache, visited:dict): if context.isEmpty(): return context existing = visited.get(context) if existing is not None: return existing existing = contextCache.get(context) if existing is not None: visited[context] = existing return existing changed = False parents = [None] * len(context) for i in range(0, len(parents)): parent = getCachedPredictionContext(context.getParent(i), contextCache, visited) if changed or parent is not context.getParent(i): if not changed: parents = [context.getParent(j) for j in range(len(context))] changed = True parents[i] = parent if not changed: contextCache.add(context) visited[context] = context return context
updated = None if len(parents) == 0: updated = PredictionContext.EMPTY elif len(parents) == 1: updated = SingletonPredictionContext.create(parents[0], context.getReturnState(0)) else: updated = ArrayPredictionContext(parents, context.returnStates)
contextCache.add(updated) visited[updated] = updated visited[context] = updated
return updated
# # extra structures, but cut/paste/morphed works, so leave it.# # seems to do a breadth-first walk# public static List<PredictionContext> getAllNodes(PredictionContext context) {# Map<PredictionContext, PredictionContext> visited =# new IdentityHashMap<PredictionContext, PredictionContext>();# Deque<PredictionContext> workList = new ArrayDeque<PredictionContext>();# workList.add(context);# visited.put(context, context);# List<PredictionContext> nodes = new ArrayList<PredictionContext>();# while (!workList.isEmpty()) {# PredictionContext current = workList.pop();# nodes.add(current);# for (int i = 0; i < current.size(); i++) {# PredictionContext parent = current.getParent(i);# if ( parent!=null && visited.put(parent, parent) == null) {# workList.push(parent);# }# }# }# return nodes;# }
# ter's recursive version of Sam's getAllNodes()def getAllContextNodes(context:PredictionContext, nodes:list=None, visited:dict=None): if nodes is None: nodes = list() return getAllContextNodes(context, nodes, visited) elif visited is None: visited = dict() return getAllContextNodes(context, nodes, visited) else: if context is None or visited.get(context, None) is not None: return nodes visited.put(context, context) nodes.add(context) for i in range(0, len(context)): getAllContextNodes(context.getParent(i), nodes, visited) return nodes
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#from antlr4.RuleContext import RuleContextfrom antlr4.Token import Tokenfrom antlr4.error.ErrorListener import ProxyErrorListener, ConsoleErrorListener
# need forward delcarationRecognitionException = None
class Recognizer(object): __slots__ = ('_listeners', '_interp', '_stateNumber')
tokenTypeMapCache = dict() ruleIndexMapCache = dict()
def __init__(self): self._listeners = [ ConsoleErrorListener.INSTANCE ] self._interp = None self._stateNumber = -1
def extractVersion(self, version): pos = version.find(".") major = version[0:pos] version = version[pos+1:] pos = version.find(".") if pos==-1: pos = version.find("-") if pos==-1: pos = len(version) minor = version[0:pos] return major, minor
def checkVersion(self, toolVersion): runtimeVersion = "4.11.1" rvmajor, rvminor = self.extractVersion(runtimeVersion) tvmajor, tvminor = self.extractVersion(toolVersion) if rvmajor!=tvmajor or rvminor!=tvminor: print("ANTLR runtime and generated code versions disagree: "+runtimeVersion+"!="+toolVersion)
def addErrorListener(self, listener): self._listeners.append(listener)
def removeErrorListener(self, listener): self._listeners.remove(listener)
def removeErrorListeners(self): self._listeners = []
def getTokenTypeMap(self): tokenNames = self.getTokenNames() if tokenNames is None: from antlr4.error.Errors import UnsupportedOperationException raise UnsupportedOperationException("The current recognizer does not provide a list of token names.") result = self.tokenTypeMapCache.get(tokenNames, None) if result is None: result = zip( tokenNames, range(0, len(tokenNames))) result["EOF"] = Token.EOF self.tokenTypeMapCache[tokenNames] = result return result
# Get a map from rule names to rule indexes. # # <p>Used for XPath and tree pattern compilation.</p> # def getRuleIndexMap(self): ruleNames = self.getRuleNames() if ruleNames is None: from antlr4.error.Errors import UnsupportedOperationException raise UnsupportedOperationException("The current recognizer does not provide a list of rule names.") result = self.ruleIndexMapCache.get(ruleNames, None) if result is None: result = zip( ruleNames, range(0, len(ruleNames))) self.ruleIndexMapCache[ruleNames] = result return result
def getTokenType(self, tokenName:str): ttype = self.getTokenTypeMap().get(tokenName, None) if ttype is not None: return ttype else: return Token.INVALID_TYPE
# What is the error header, normally line/character position information?# def getErrorHeader(self, e:RecognitionException): line = e.getOffendingToken().line column = e.getOffendingToken().column return "line "+line+":"+column
# How should a token be displayed in an error message? The default # is to display just the text, but during development you might # want to have a lot of information spit out. Override in that case # to use t.toString() (which, for CommonToken, dumps everything about # the token). This is better than forcing you to override a method in # your token objects because you don't have to go modify your lexer # so that it creates a new Java type. # # @deprecated This method is not called by the ANTLR 4 Runtime. Specific # implementations of {@link ANTLRErrorStrategy} may provide a similar # feature when necessary. For example, see # {@link DefaultErrorStrategy#getTokenErrorDisplay}. # def getTokenErrorDisplay(self, t:Token): if t is None: return "<no token>" s = t.text if s is None: if t.type==Token.EOF: s = "<EOF>" else: s = "<" + str(t.type) + ">" s = s.replace("\n","\\n") s = s.replace("\r","\\r") s = s.replace("\t","\\t") return "'" + s + "'"
def getErrorListenerDispatch(self): return ProxyErrorListener(self._listeners)
# subclass needs to override these if there are sempreds or actions # that the ATN interp needs to execute def sempred(self, localctx:RuleContext, ruleIndex:int, actionIndex:int): return True
def precpred(self, localctx:RuleContext , precedence:int): return True
@property def state(self): return self._stateNumber
# Indicate that the recognizer has changed internal state that is # consistent with the ATN state passed in. This way we always know # where we are in the ATN as the parser goes along. The rule # context objects form a stack that lets us see the stack of # invoking rules. Combine this and we have complete ATN # configuration information.
@state.setter def state(self, atnState:int): self._stateNumber = atnState
del RecognitionException123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#/
# A rule context is a record of a single rule invocation. It knows# which context invoked it, if any. If there is no parent context, then# naturally the invoking state is not valid. The parent link# provides a chain upwards from the current rule invocation to the root# of the invocation tree, forming a stack. We actually carry no# information about the rule associated with this context (except# when parsing). We keep only the state number of the invoking state from# the ATN submachine that invoked this. Contrast this with the s# pointer inside ParserRuleContext that tracks the current state# being "executed" for the current rule.## The parent contexts are useful for computing lookahead sets and# getting error information.## These objects are used during parsing and prediction.# For the special case of parsers, we use the subclass# ParserRuleContext.## @see ParserRuleContext#/from io import StringIOfrom antlr4.tree.Tree import RuleNode, INVALID_INTERVAL, ParseTreeVisitorfrom antlr4.tree.Trees import Trees
# need forward declarationsRuleContext = NoneParser = None
class RuleContext(RuleNode): __slots__ = ('parentCtx', 'invokingState') EMPTY = None
def __init__(self, parent:RuleContext=None, invokingState:int=-1): super().__init__() # What context invoked this rule? self.parentCtx = parent # What state invoked the rule associated with this context? # The "return address" is the followState of invokingState # If parent is null, this should be -1. self.invokingState = invokingState
def depth(self): n = 0 p = self while p is not None: p = p.parentCtx n += 1 return n
# A context is empty if there is no invoking state; meaning nobody call # current context. def isEmpty(self): return self.invokingState == -1
# satisfy the ParseTree / SyntaxTree interface
def getSourceInterval(self): return INVALID_INTERVAL
def getRuleContext(self): return self
def getPayload(self): return self
# Return the combined text of all child nodes. This method only considers # tokens which have been added to the parse tree. # <p> # Since tokens on hidden channels (e.g. whitespace or comments) are not # added to the parse trees, they will not appear in the output of this # method. #/ def getText(self): if self.getChildCount() == 0: return "" with StringIO() as builder: for child in self.getChildren(): builder.write(child.getText()) return builder.getvalue()
def getRuleIndex(self): return -1
# For rule associated with this parse tree internal node, return # the outer alternative number used to match the input. Default # implementation does not compute nor store this alt num. Create # a subclass of ParserRuleContext with backing field and set # option contextSuperClass. # to set it. def getAltNumber(self): return 0 # should use ATN.INVALID_ALT_NUMBER but won't compile
# Set the outer alternative number for this context node. Default # implementation does nothing to avoid backing field overhead for # trees that don't need it. Create # a subclass of ParserRuleContext with backing field and set # option contextSuperClass. def setAltNumber(self, altNumber:int): pass
def getChild(self, i:int): return None
def getChildCount(self): return 0
def getChildren(self): for c in []: yield c
def accept(self, visitor:ParseTreeVisitor): return visitor.visitChildren(self)
# # Call this method to view a parse tree in a dialog box visually.#/ # public Future<JDialog> inspect(@Nullable Parser parser) { # List<String> ruleNames = parser != null ? Arrays.asList(parser.getRuleNames()) : null; # return inspect(ruleNames); # } # # public Future<JDialog> inspect(@Nullable List<String> ruleNames) { # TreeViewer viewer = new TreeViewer(ruleNames, this); # return viewer.open(); # } # # # Save this tree in a postscript file#/ # public void save(@Nullable Parser parser, String fileName) # throws IOException, PrintException # { # List<String> ruleNames = parser != null ? Arrays.asList(parser.getRuleNames()) : null; # save(ruleNames, fileName); # } # # # Save this tree in a postscript file using a particular font name and size#/ # public void save(@Nullable Parser parser, String fileName, # String fontName, int fontSize) # throws IOException # { # List<String> ruleNames = parser != null ? Arrays.asList(parser.getRuleNames()) : null; # save(ruleNames, fileName, fontName, fontSize); # } # # # Save this tree in a postscript file#/ # public void save(@Nullable List<String> ruleNames, String fileName) # throws IOException, PrintException # { # Trees.writePS(this, ruleNames, fileName); # } # # # Save this tree in a postscript file using a particular font name and size#/ # public void save(@Nullable List<String> ruleNames, String fileName, # String fontName, int fontSize) # throws IOException # { # Trees.writePS(this, ruleNames, fileName, fontName, fontSize); # } # # # Print out a whole tree, not just a node, in LISP format # # (root child1 .. childN). Print just a node if this is a leaf. # # We have to know the recognizer so we can get rule names. # #/ # @Override # public String toStringTree(@Nullable Parser recog) { # return Trees.toStringTree(this, recog); # } # # Print out a whole tree, not just a node, in LISP format # (root child1 .. childN). Print just a node if this is a leaf. # def toStringTree(self, ruleNames:list=None, recog:Parser=None): return Trees.toStringTree(self, ruleNames=ruleNames, recog=recog) # } # # @Override # public String toStringTree() { # return toStringTree((List<String>)null); # } # def __str__(self): return self.toString(None, None)
# @Override # public String toString() { # return toString((List<String>)null, (RuleContext)null); # } # # public final String toString(@Nullable Recognizer<?,?> recog) { # return toString(recog, ParserRuleContext.EMPTY); # } # # public final String toString(@Nullable List<String> ruleNames) { # return toString(ruleNames, null); # } # # // recog null unless ParserRuleContext, in which case we use subclass toString(...) # public String toString(@Nullable Recognizer<?,?> recog, @Nullable RuleContext stop) { # String[] ruleNames = recog != null ? recog.getRuleNames() : null; # List<String> ruleNamesList = ruleNames != null ? Arrays.asList(ruleNames) : null; # return toString(ruleNamesList, stop); # }
def toString(self, ruleNames:list, stop:RuleContext)->str: with StringIO() as buf: p = self buf.write("[") while p is not None and p is not stop: if ruleNames is None: if not p.isEmpty(): buf.write(str(p.invokingState)) else: ri = p.getRuleIndex() ruleName = ruleNames[ri] if ri >= 0 and ri < len(ruleNames) else str(ri) buf.write(ruleName)
if p.parentCtx is not None and (ruleNames is not None or not p.parentCtx.isEmpty()): buf.write(" ")
p = p.parentCtx
buf.write("]") return buf.getvalue()1234567891011import codecsimport sys
from antlr4.InputStream import InputStream
class StdinStream(InputStream): def __init__(self, encoding:str='ascii', errors:str='strict') -> None: bytes = sys.stdin.buffer.read() data = codecs.decode(bytes, encoding, errors) super().__init__(data)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#
# A token has properties: text, type, line, character position in the line# (so we can ignore tabs), token channel, index, and source from which# we obtained this token.from io import StringIO
class Token (object): __slots__ = ('source', 'type', 'channel', 'start', 'stop', 'tokenIndex', 'line', 'column', '_text')
INVALID_TYPE = 0
# During lookahead operations, this "token" signifies we hit rule end ATN state # and did not follow it despite needing to. EPSILON = -2
MIN_USER_TOKEN_TYPE = 1
EOF = -1
# All tokens go to the parser (unless skip() is called in that rule) # on a particular "channel". The parser tunes to a particular channel # so that whitespace etc... can go to the parser on a "hidden" channel.
DEFAULT_CHANNEL = 0
# Anything on different channel than DEFAULT_CHANNEL is not parsed # by parser.
HIDDEN_CHANNEL = 1
def __init__(self): self.source = None self.type = None # token type of the token self.channel = None # The parser ignores everything not on DEFAULT_CHANNEL self.start = None # optional; return -1 if not implemented. self.stop = None # optional; return -1 if not implemented. self.tokenIndex = None # from 0..n-1 of the token object in the input stream self.line = None # line=1..n of the 1st character self.column = None # beginning of the line at which it occurs, 0..n-1 self._text = None # text of the token.
@property def text(self): return self._text
# Explicitly set the text for this token. If {code text} is not # {@code null}, then {@link #getText} will return this value rather than # extracting the text from the input. # # @param text The explicit text of the token, or {@code null} if the text # should be obtained from the input along with the start and stop indexes # of the token.
@text.setter def text(self, text:str): self._text = text
def getTokenSource(self): return self.source[0]
def getInputStream(self): return self.source[1]
class CommonToken(Token):
# An empty {@link Pair} which is used as the default value of # {@link #source} for tokens that do not have a source. EMPTY_SOURCE = (None, None)
def __init__(self, source:tuple = EMPTY_SOURCE, type:int = None, channel:int=Token.DEFAULT_CHANNEL, start:int=-1, stop:int=-1): super().__init__() self.source = source self.type = type self.channel = channel self.start = start self.stop = stop self.tokenIndex = -1 if source[0] is not None: self.line = source[0].line self.column = source[0].column else: self.column = -1
# Constructs a new {@link CommonToken} as a copy of another {@link Token}. # # <p> # If {@code oldToken} is also a {@link CommonToken} instance, the newly # constructed token will share a reference to the {@link #text} field and # the {@link Pair} stored in {@link #source}. Otherwise, {@link #text} will # be assigned the result of calling {@link #getText}, and {@link #source} # will be constructed from the result of {@link Token#getTokenSource} and # {@link Token#getInputStream}.</p> # # @param oldToken The token to copy. # def clone(self): t = CommonToken(self.source, self.type, self.channel, self.start, self.stop) t.tokenIndex = self.tokenIndex t.line = self.line t.column = self.column t.text = self.text return t
@property def text(self): if self._text is not None: return self._text input = self.getInputStream() if input is None: return None n = input.size if self.start < n and self.stop < n: return input.getText(self.start, self.stop) else: return "<EOF>"
@text.setter def text(self, text:str): self._text = text
def __str__(self): with StringIO() as buf: buf.write("[@") buf.write(str(self.tokenIndex)) buf.write(",") buf.write(str(self.start)) buf.write(":") buf.write(str(self.stop)) buf.write("='") txt = self.text if txt is not None: txt = txt.replace("\n","\\n") txt = txt.replace("\r","\\r") txt = txt.replace("\t","\\t") else: txt = "<no text>" buf.write(txt) buf.write("',<") buf.write(str(self.type)) buf.write(">") if self.channel > 0: buf.write(",channel=") buf.write(str(self.channel)) buf.write(",") buf.write(str(self.line)) buf.write(":") buf.write(str(self.column)) buf.write("]") return buf.getvalue()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#
from io import StringIOfrom antlr4.Token import Token
from antlr4.CommonTokenStream import CommonTokenStream
class TokenStreamRewriter(object): __slots__ = ('tokens', 'programs', 'lastRewriteTokenIndexes')
DEFAULT_PROGRAM_NAME = "default" PROGRAM_INIT_SIZE = 100 MIN_TOKEN_INDEX = 0
def __init__(self, tokens): """ :type tokens: antlr4.BufferedTokenStream.BufferedTokenStream :param tokens: :return: """ super(TokenStreamRewriter, self).__init__() self.tokens = tokens self.programs = {self.DEFAULT_PROGRAM_NAME: []} self.lastRewriteTokenIndexes = {}
def getTokenStream(self): return self.tokens
def rollback(self, instruction_index, program_name): ins = self.programs.get(program_name, None) if ins: self.programs[program_name] = ins[self.MIN_TOKEN_INDEX: instruction_index]
def deleteProgram(self, program_name=DEFAULT_PROGRAM_NAME): self.rollback(self.MIN_TOKEN_INDEX, program_name)
def insertAfterToken(self, token, text, program_name=DEFAULT_PROGRAM_NAME): self.insertAfter(token.tokenIndex, text, program_name)
def insertAfter(self, index, text, program_name=DEFAULT_PROGRAM_NAME): op = self.InsertAfterOp(self.tokens, index + 1, text) rewrites = self.getProgram(program_name) op.instructionIndex = len(rewrites) rewrites.append(op)
def insertBeforeIndex(self, index, text): self.insertBefore(self.DEFAULT_PROGRAM_NAME, index, text)
def insertBeforeToken(self, token, text, program_name=DEFAULT_PROGRAM_NAME): self.insertBefore(program_name, token.tokenIndex, text)
def insertBefore(self, program_name, index, text): op = self.InsertBeforeOp(self.tokens, index, text) rewrites = self.getProgram(program_name) op.instructionIndex = len(rewrites) rewrites.append(op)
def replaceIndex(self, index, text): self.replace(self.DEFAULT_PROGRAM_NAME, index, index, text)
def replaceRange(self, from_idx, to_idx, text): self.replace(self.DEFAULT_PROGRAM_NAME, from_idx, to_idx, text)
def replaceSingleToken(self, token, text): self.replace(self.DEFAULT_PROGRAM_NAME, token.tokenIndex, token.tokenIndex, text)
def replaceRangeTokens(self, from_token, to_token, text, program_name=DEFAULT_PROGRAM_NAME): self.replace(program_name, from_token.tokenIndex, to_token.tokenIndex, text)
def replace(self, program_name, from_idx, to_idx, text): if any((from_idx > to_idx, from_idx < 0, to_idx < 0, to_idx >= len(self.tokens.tokens))): raise ValueError( 'replace: range invalid: {}..{}(size={})'.format(from_idx, to_idx, len(self.tokens.tokens))) op = self.ReplaceOp(from_idx, to_idx, self.tokens, text) rewrites = self.getProgram(program_name) op.instructionIndex = len(rewrites) rewrites.append(op)
def deleteToken(self, token): self.delete(self.DEFAULT_PROGRAM_NAME, token, token)
def deleteIndex(self, index): self.delete(self.DEFAULT_PROGRAM_NAME, index, index)
def delete(self, program_name, from_idx, to_idx): if isinstance(from_idx, Token): self.replace(program_name, from_idx.tokenIndex, to_idx.tokenIndex, "") else: self.replace(program_name, from_idx, to_idx, "")
def lastRewriteTokenIndex(self, program_name=DEFAULT_PROGRAM_NAME): return self.lastRewriteTokenIndexes.get(program_name, -1)
def setLastRewriteTokenIndex(self, program_name, i): self.lastRewriteTokenIndexes[program_name] = i
def getProgram(self, program_name): return self.programs.setdefault(program_name, [])
def getDefaultText(self): return self.getText(self.DEFAULT_PROGRAM_NAME, 0, len(self.tokens.tokens) - 1)
def getText(self, program_name, start:int, stop:int): """ :return: the text in tokens[start, stop](closed interval) """ rewrites = self.programs.get(program_name)
# ensure start/end are in range if stop > len(self.tokens.tokens) - 1: stop = len(self.tokens.tokens) - 1 if start < 0: start = 0
# if no instructions to execute if not rewrites: return self.tokens.getText(start, stop) buf = StringIO() indexToOp = self._reduceToSingleOperationPerIndex(rewrites) i = start while all((i <= stop, i < len(self.tokens.tokens))): op = indexToOp.pop(i, None) token = self.tokens.get(i) if op is None: if token.type != Token.EOF: buf.write(token.text) i += 1 else: i = op.execute(buf)
if stop == len(self.tokens.tokens)-1: for op in indexToOp.values(): if op.index >= len(self.tokens.tokens)-1: buf.write(op.text)
return buf.getvalue()
def _reduceToSingleOperationPerIndex(self, rewrites): # Walk replaces for i, rop in enumerate(rewrites): if any((rop is None, not isinstance(rop, TokenStreamRewriter.ReplaceOp))): continue # Wipe prior inserts within range inserts = [op for op in rewrites[:i] if isinstance(op, TokenStreamRewriter.InsertBeforeOp)] for iop in inserts: if iop.index == rop.index: rewrites[iop.instructionIndex] = None rop.text = '{}{}'.format(iop.text, rop.text) elif all((iop.index > rop.index, iop.index <= rop.last_index)): rewrites[iop.instructionIndex] = None
# Drop any prior replaces contained within prevReplaces = [op for op in rewrites[:i] if isinstance(op, TokenStreamRewriter.ReplaceOp)] for prevRop in prevReplaces: if all((prevRop.index >= rop.index, prevRop.last_index <= rop.last_index)): rewrites[prevRop.instructionIndex] = None continue isDisjoint = any((prevRop.last_index<rop.index, prevRop.index>rop.last_index)) if all((prevRop.text is None, rop.text is None, not isDisjoint)): rewrites[prevRop.instructionIndex] = None rop.index = min(prevRop.index, rop.index) rop.last_index = min(prevRop.last_index, rop.last_index) print('New rop {}'.format(rop)) elif (not(isDisjoint)): raise ValueError("replace op boundaries of {} overlap with previous {}".format(rop, prevRop))
# Walk inserts for i, iop in enumerate(rewrites): if any((iop is None, not isinstance(iop, TokenStreamRewriter.InsertBeforeOp))): continue prevInserts = [op for op in rewrites[:i] if isinstance(op, TokenStreamRewriter.InsertBeforeOp)] for prev_index, prevIop in enumerate(prevInserts): if prevIop.index == iop.index and type(prevIop) is TokenStreamRewriter.InsertBeforeOp: iop.text += prevIop.text rewrites[prev_index] = None elif prevIop.index == iop.index and type(prevIop) is TokenStreamRewriter.InsertAfterOp: iop.text = prevIop.text + iop.text rewrites[prev_index] = None # look for replaces where iop.index is in range; error prevReplaces = [op for op in rewrites[:i] if isinstance(op, TokenStreamRewriter.ReplaceOp)] for rop in prevReplaces: if iop.index == rop.index: rop.text = iop.text + rop.text rewrites[i] = None continue if all((iop.index >= rop.index, iop.index <= rop.last_index)): raise ValueError("insert op {} within boundaries of previous {}".format(iop, rop))
reduced = {} for i, op in enumerate(rewrites): if op is None: continue if reduced.get(op.index): raise ValueError('should be only one op per index') reduced[op.index] = op
return reduced
class RewriteOperation(object): __slots__ = ('tokens', 'index', 'text', 'instructionIndex')
def __init__(self, tokens, index, text=""): """ :type tokens: CommonTokenStream :param tokens: :param index: :param text: :return: """ self.tokens = tokens self.index = index self.text = text self.instructionIndex = 0
def execute(self, buf): """ :type buf: StringIO.StringIO :param buf: :return: """ return self.index
def __str__(self): return '<{}@{}:"{}">'.format(self.__class__.__name__, self.tokens.get(self.index), self.text)
class InsertBeforeOp(RewriteOperation):
def __init__(self, tokens, index, text=""): super(TokenStreamRewriter.InsertBeforeOp, self).__init__(tokens, index, text)
def execute(self, buf): buf.write(self.text) if self.tokens.get(self.index).type != Token.EOF: buf.write(self.tokens.get(self.index).text) return self.index + 1
class InsertAfterOp(InsertBeforeOp): pass
class ReplaceOp(RewriteOperation): __slots__ = 'last_index'
def __init__(self, from_idx, to_idx, tokens, text): super(TokenStreamRewriter.ReplaceOp, self).__init__(tokens, from_idx, text) self.last_index = to_idx
def execute(self, buf): if self.text: buf.write(self.text) return self.last_index + 1
def __str__(self): if self.text: return '<ReplaceOp@{}..{}:"{}">'.format(self.tokens.get(self.index), self.tokens.get(self.last_index), self.text)123456789101112131415161718192021222324252627282930313233# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#
from io import StringIO
def str_list(val): with StringIO() as buf: buf.write('[') first = True for item in val: if not first: buf.write(', ') buf.write(str(item)) first = False buf.write(']') return buf.getvalue()
def escapeWhitespace(s:str, escapeSpaces:bool): with StringIO() as buf: for c in s: if c==' ' and escapeSpaces: buf.write('\u00B7') elif c=='\t': buf.write("\\t") elif c=='\n': buf.write("\\n") elif c=='\r': buf.write("\\r") else: buf.write(c) return buf.getvalue()123456789101112131415161718192021from antlr4.Token import Tokenfrom antlr4.InputStream import InputStreamfrom antlr4.FileStream import FileStreamfrom antlr4.StdinStream import StdinStreamfrom antlr4.BufferedTokenStream import TokenStreamfrom antlr4.CommonTokenStream import CommonTokenStreamfrom antlr4.Lexer import Lexerfrom antlr4.Parser import Parserfrom antlr4.dfa.DFA import DFAfrom antlr4.atn.ATN import ATNfrom antlr4.atn.ATNDeserializer import ATNDeserializerfrom antlr4.atn.LexerATNSimulator import LexerATNSimulatorfrom antlr4.atn.ParserATNSimulator import ParserATNSimulatorfrom antlr4.atn.PredictionMode import PredictionModefrom antlr4.PredictionContext import PredictionContextCachefrom antlr4.ParserRuleContext import RuleContext, ParserRuleContextfrom antlr4.tree.Tree import ParseTreeListener, ParseTreeVisitor, ParseTreeWalker, TerminalNode, ErrorNode, RuleNodefrom antlr4.error.Errors import RecognitionException, IllegalStateException, NoViableAltExceptionfrom antlr4.error.ErrorStrategy import BailErrorStrategyfrom antlr4.error.DiagnosticErrorListener import DiagnosticErrorListenerfrom antlr4.Utils import str_list123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171#!python__author__ = 'jszheng'import optparseimport sysimport osimport importlibfrom antlr4 import *
# this is a python version of TestRigdef beautify_lisp_string(in_string): indent_size = 3 add_indent = ' '*indent_size out_string = in_string[0] # no indent for 1st ( indent = '' for i in range(1, len(in_string)): if in_string[i] == '(' and in_string[i+1] != ' ': indent += add_indent out_string += "\n" + indent + '(' elif in_string[i] == ')': out_string += ')' if len(indent) > 0: indent = indent.replace(add_indent, '', 1) else: out_string += in_string[i] return out_string
def main():
############################################################# # parse options # not support -gui -encoding -ps ############################################################# usage = "Usage: %prog [options] Grammar_Name Start_Rule" parser = optparse.OptionParser(usage=usage) # parser.add_option('-t', '--tree', # dest="out_file", # default="default.out", # help='set output file name', # ) parser.add_option('-t', '--tree', default=False, action='store_true', help='Print AST tree' ) parser.add_option('-k', '--tokens', dest="token", default=False, action='store_true', help='Show Tokens' ) parser.add_option('-s', '--sll', dest="sll", default=False, action='store_true', help='Show SLL' ) parser.add_option('-d', '--diagnostics', dest="diagnostics", default=False, action='store_true', help='Enable diagnostics error listener' ) parser.add_option('-a', '--trace', dest="trace", default=False, action='store_true', help='Enable Trace' )
options, remainder = parser.parse_args() if len(remainder) < 2: print('ERROR: You have to provide at least 2 arguments!') parser.print_help() exit(1) else: grammar = remainder.pop(0) start_rule = remainder.pop(0) file_list = remainder
############################################################# # check and load antlr generated files ############################################################# # dynamic load the module and class lexerName = grammar + 'Lexer' parserName = grammar + 'Parser' # check if the generate file exist lexer_file = lexerName + '.py' parser_file = parserName + '.py' if not os.path.exists(lexer_file): print("[ERROR] Can't find lexer file {}!".format(lexer_file)) print(os.path.realpath('.')) exit(1) if not os.path.exists(parser_file): print("[ERROR] Can't find parser file {}!".format(lexer_file)) print(os.path.realpath('.')) exit(1)
# current directory is where the generated file loaded # the script might be in different place. sys.path.append('.') # print(sys.path)
# add current directory to python global namespace in case of relative imports globals().update({'__package__': os.path.basename(os.getcwd())})
# print("Load Lexer {}".format(lexerName)) module_lexer = __import__(lexerName, globals(), locals(), lexerName) class_lexer = getattr(module_lexer, lexerName) # print(class_lexer)
# print("Load Parser {}".format(parserName)) module_parser = __import__(parserName, globals(), locals(), parserName) class_parser = getattr(module_parser, parserName) # print(class_parser)
############################################################# # main process steps. ############################################################# def process(input_stream, class_lexer, class_parser): lexer = class_lexer(input_stream) token_stream = CommonTokenStream(lexer) token_stream.fill() if options.token: # need to show token for tok in token_stream.tokens: print(tok) if start_rule == 'tokens': return
parser = class_parser(token_stream)
if options.diagnostics: parser.addErrorListener(DiagnosticErrorListener()) parser._interp.predictionMode = PredictionMode.LL_EXACT_AMBIG_DETECTION if options.tree: parser.buildParseTrees = True if options.sll: parser._interp.predictionMode = PredictionMode.SLL #parser.setTokenStream(token_stream) parser.setTrace(options.trace) if hasattr(parser, start_rule): func_start_rule = getattr(parser, start_rule) parser_ret = func_start_rule() if options.tree: lisp_tree_str = parser_ret.toStringTree(recog=parser) print(beautify_lisp_string(lisp_tree_str)) else: print("[ERROR] Can't find start rule '{}' in parser '{}'".format(start_rule, parserName))
############################################################# # use stdin if not provide file as input stream ############################################################# if len(file_list) == 0: input_stream = InputStream(sys.stdin.read()) process(input_stream, class_lexer, class_parser) exit(0)
############################################################# # iterate all input file ############################################################# for file_name in file_list: if os.path.exists(file_name) and os.path.isfile(file_name): input_stream = FileStream(file_name) process(input_stream, class_lexer, class_parser) else: print("[ERROR] file {} not exist".format(os.path.normpath(file_name)))
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#/from antlr4.IntervalSet import IntervalSet
from antlr4.RuleContext import RuleContext
from antlr4.Token import Tokenfrom antlr4.atn.ATNType import ATNTypefrom antlr4.atn.ATNState import ATNState, DecisionState
class ATN(object): __slots__ = ( 'grammarType', 'maxTokenType', 'states', 'decisionToState', 'ruleToStartState', 'ruleToStopState', 'modeNameToStartState', 'ruleToTokenType', 'lexerActions', 'modeToStartState' )
INVALID_ALT_NUMBER = 0
# Used for runtime deserialization of ATNs from strings#/ def __init__(self, grammarType:ATNType , maxTokenType:int ): # The type of the ATN. self.grammarType = grammarType # The maximum value for any symbol recognized by a transition in the ATN. self.maxTokenType = maxTokenType self.states = [] # Each subrule/rule is a decision point and we must track them so we # can go back later and build DFA predictors for them. This includes # all the rules, subrules, optional blocks, ()+, ()* etc... self.decisionToState = [] # Maps from rule index to starting state number. self.ruleToStartState = [] # Maps from rule index to stop state number. self.ruleToStopState = None self.modeNameToStartState = dict() # For lexer ATNs, this maps the rule index to the resulting token type. # For parser ATNs, this maps the rule index to the generated bypass token # type if the # {@link ATNDeserializationOptions#isGenerateRuleBypassTransitions} # deserialization option was specified; otherwise, this is {@code null}. self.ruleToTokenType = None # For lexer ATNs, this is an array of {@link LexerAction} objects which may # be referenced by action transitions in the ATN. self.lexerActions = None self.modeToStartState = []
# Compute the set of valid tokens that can occur starting in state {@code s}. # If {@code ctx} is null, the set of tokens will not include what can follow # the rule surrounding {@code s}. In other words, the set will be # restricted to tokens reachable staying within {@code s}'s rule. def nextTokensInContext(self, s:ATNState, ctx:RuleContext): from antlr4.LL1Analyzer import LL1Analyzer anal = LL1Analyzer(self) return anal.LOOK(s, ctx=ctx)
# Compute the set of valid tokens that can occur starting in {@code s} and # staying in same rule. {@link Token#EPSILON} is in set if we reach end of # rule. def nextTokensNoContext(self, s:ATNState): if s.nextTokenWithinRule is not None: return s.nextTokenWithinRule s.nextTokenWithinRule = self.nextTokensInContext(s, None) s.nextTokenWithinRule.readonly = True return s.nextTokenWithinRule
def nextTokens(self, s:ATNState, ctx:RuleContext = None): if ctx==None: return self.nextTokensNoContext(s) else: return self.nextTokensInContext(s, ctx)
def addState(self, state:ATNState): if state is not None: state.atn = self state.stateNumber = len(self.states) self.states.append(state)
def removeState(self, state:ATNState): self.states[state.stateNumber] = None # just free mem, don't shift states in list
def defineDecisionState(self, s:DecisionState): self.decisionToState.append(s) s.decision = len(self.decisionToState)-1 return s.decision
def getDecisionState(self, decision:int): if len(self.decisionToState)==0: return None else: return self.decisionToState[decision]
# Computes the set of input symbols which could follow ATN state number # {@code stateNumber} in the specified full {@code context}. This method # considers the complete parser context, but does not evaluate semantic # predicates (i.e. all predicates encountered during the calculation are # assumed true). If a path in the ATN exists from the starting state to the # {@link RuleStopState} of the outermost context without matching any # symbols, {@link Token#EOF} is added to the returned set. # # <p>If {@code context} is {@code null}, it is treated as # {@link ParserRuleContext#EMPTY}.</p> # # @param stateNumber the ATN state number # @param context the full parse context # @return The set of potentially valid input symbols which could follow the # specified state in the specified context. # @throws IllegalArgumentException if the ATN does not contain a state with # number {@code stateNumber} #/ def getExpectedTokens(self, stateNumber:int, ctx:RuleContext ): if stateNumber < 0 or stateNumber >= len(self.states): raise Exception("Invalid state number.") s = self.states[stateNumber] following = self.nextTokens(s) if Token.EPSILON not in following: return following expected = IntervalSet() expected.addSet(following) expected.removeOne(Token.EPSILON) while (ctx != None and ctx.invokingState >= 0 and Token.EPSILON in following): invokingState = self.states[ctx.invokingState] rt = invokingState.transitions[0] following = self.nextTokens(rt.followState) expected.addSet(following) expected.removeOne(Token.EPSILON) ctx = ctx.parentCtx if Token.EPSILON in following: expected.addOne(Token.EOF) return expected123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#/
# A tuple: (ATN state, predicted alt, syntactic, semantic context).# The syntactic context is a graph-structured stack node whose# path(s) to the root is the rule invocation(s)# chain used to arrive at the state. The semantic context is# the tree of semantic predicates encountered before reaching# an ATN state.#/from io import StringIOfrom antlr4.PredictionContext import PredictionContextfrom antlr4.atn.ATNState import ATNState, DecisionStatefrom antlr4.atn.LexerActionExecutor import LexerActionExecutorfrom antlr4.atn.SemanticContext import SemanticContext
# need a forward declarationATNConfig = None
class ATNConfig(object): __slots__ = ( 'state', 'alt', 'context', 'semanticContext', 'reachesIntoOuterContext', 'precedenceFilterSuppressed' )
def __init__(self, state:ATNState=None, alt:int=None, context:PredictionContext=None, semantic:SemanticContext=None, config:ATNConfig=None): if config is not None: if state is None: state = config.state if alt is None: alt = config.alt if context is None: context = config.context if semantic is None: semantic = config.semanticContext if semantic is None: semantic = SemanticContext.NONE # The ATN state associated with this configuration#/ self.state = state # What alt (or lexer rule) is predicted by this configuration#/ self.alt = alt # The stack of invoking states leading to the rule/states associated # with this config. We track only those contexts pushed during # execution of the ATN simulator. self.context = context self.semanticContext = semantic # We cannot execute predicates dependent upon local context unless # we know for sure we are in the correct context. Because there is # no way to do this efficiently, we simply cannot evaluate # dependent predicates unless we are in the rule that initially # invokes the ATN simulator. # # closure() tracks the depth of how far we dip into the # outer context: depth > 0. Note that it may not be totally # accurate depth since I don't ever decrement. TODO: make it a boolean then self.reachesIntoOuterContext = 0 if config is None else config.reachesIntoOuterContext self.precedenceFilterSuppressed = False if config is None else config.precedenceFilterSuppressed
# An ATN configuration is equal to another if both have # the same state, they predict the same alternative, and # syntactic/semantic contexts are the same. #/ def __eq__(self, other): if self is other: return True elif not isinstance(other, ATNConfig): return False else: return self.state.stateNumber==other.state.stateNumber \ and self.alt==other.alt \ and ((self.context is other.context) or (self.context==other.context)) \ and self.semanticContext==other.semanticContext \ and self.precedenceFilterSuppressed==other.precedenceFilterSuppressed
def __hash__(self): return hash((self.state.stateNumber, self.alt, self.context, self.semanticContext))
def hashCodeForConfigSet(self): return hash((self.state.stateNumber, self.alt, hash(self.semanticContext)))
def equalsForConfigSet(self, other): if self is other: return True elif not isinstance(other, ATNConfig): return False else: return self.state.stateNumber==other.state.stateNumber \ and self.alt==other.alt \ and self.semanticContext==other.semanticContext
def __str__(self): with StringIO() as buf: buf.write('(') buf.write(str(self.state)) buf.write(",") buf.write(str(self.alt)) if self.context is not None: buf.write(",[") buf.write(str(self.context)) buf.write("]") if self.semanticContext is not None and self.semanticContext is not SemanticContext.NONE: buf.write(",") buf.write(str(self.semanticContext)) if self.reachesIntoOuterContext>0: buf.write(",up=") buf.write(str(self.reachesIntoOuterContext)) buf.write(')') return buf.getvalue()
# need a forward declarationLexerATNConfig = None
class LexerATNConfig(ATNConfig): __slots__ = ('lexerActionExecutor', 'passedThroughNonGreedyDecision')
def __init__(self, state:ATNState, alt:int=None, context:PredictionContext=None, semantic:SemanticContext=SemanticContext.NONE, lexerActionExecutor:LexerActionExecutor=None, config:LexerATNConfig=None): super().__init__(state=state, alt=alt, context=context, semantic=semantic, config=config) if config is not None: if lexerActionExecutor is None: lexerActionExecutor = config.lexerActionExecutor # This is the backing field for {@link #getLexerActionExecutor}. self.lexerActionExecutor = lexerActionExecutor self.passedThroughNonGreedyDecision = False if config is None else self.checkNonGreedyDecision(config, state)
def __hash__(self): return hash((self.state.stateNumber, self.alt, self.context, self.semanticContext, self.passedThroughNonGreedyDecision, self.lexerActionExecutor))
def __eq__(self, other): if self is other: return True elif not isinstance(other, LexerATNConfig): return False if self.passedThroughNonGreedyDecision != other.passedThroughNonGreedyDecision: return False if not(self.lexerActionExecutor == other.lexerActionExecutor): return False return super().__eq__(other)
def hashCodeForConfigSet(self): return hash(self)
def equalsForConfigSet(self, other): return self==other
def checkNonGreedyDecision(self, source:LexerATNConfig, target:ATNState): return source.passedThroughNonGreedyDecision \ or isinstance(target, DecisionState) and target.nonGreedy123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.
## Specialized {@link Set}{@code <}{@link ATNConfig}{@code >} that can track# info about the set, with support for combining similar configurations using a# graph-structured stack.#/from io import StringIOfrom functools import reducefrom antlr4.PredictionContext import PredictionContext, mergefrom antlr4.Utils import str_listfrom antlr4.atn.ATN import ATNfrom antlr4.atn.ATNConfig import ATNConfigfrom antlr4.atn.SemanticContext import SemanticContextfrom antlr4.error.Errors import UnsupportedOperationException, IllegalStateException
ATNSimulator = None
class ATNConfigSet(object): __slots__ = ( 'configLookup', 'fullCtx', 'readonly', 'configs', 'uniqueAlt', 'conflictingAlts', 'hasSemanticContext', 'dipsIntoOuterContext', 'cachedHashCode' )
# # The reason that we need this is because we don't want the hash map to use # the standard hash code and equals. We need all configurations with the same # {@code (s,i,_,semctx)} to be equal. Unfortunately, this key effectively doubles # the number of objects associated with ATNConfigs. The other solution is to # use a hash table that lets us specify the equals/hashcode operation.
def __init__(self, fullCtx:bool=True): # All configs but hashed by (s, i, _, pi) not including context. Wiped out # when we go readonly as this set becomes a DFA state. self.configLookup = dict() # Indicates that this configuration set is part of a full context # LL prediction. It will be used to determine how to merge $. With SLL # it's a wildcard whereas it is not for LL context merge. self.fullCtx = fullCtx # Indicates that the set of configurations is read-only. Do not # allow any code to manipulate the set; DFA states will point at # the sets and they must not change. This does not protect the other # fields; in particular, conflictingAlts is set after # we've made this readonly. self.readonly = False # Track the elements as they are added to the set; supports get(i)#/ self.configs = []
# TODO: these fields make me pretty uncomfortable but nice to pack up info together, saves recomputation # TODO: can we track conflicts as they are added to save scanning configs later? self.uniqueAlt = 0 self.conflictingAlts = None
# Used in parser and lexer. In lexer, it indicates we hit a pred # while computing a closure operation. Don't make a DFA state from this. self.hasSemanticContext = False self.dipsIntoOuterContext = False
self.cachedHashCode = -1
def __iter__(self): return self.configs.__iter__()
# Adding a new config means merging contexts with existing configs for # {@code (s, i, pi, _)}, where {@code s} is the # {@link ATNConfig#state}, {@code i} is the {@link ATNConfig#alt}, and # {@code pi} is the {@link ATNConfig#semanticContext}. We use # {@code (s,i,pi)} as key. # # <p>This method updates {@link #dipsIntoOuterContext} and # {@link #hasSemanticContext} when necessary.</p> #/ def add(self, config:ATNConfig, mergeCache=None): if self.readonly: raise Exception("This set is readonly") if config.semanticContext is not SemanticContext.NONE: self.hasSemanticContext = True if config.reachesIntoOuterContext > 0: self.dipsIntoOuterContext = True existing = self.getOrAdd(config) if existing is config: self.cachedHashCode = -1 self.configs.append(config) # track order here return True # a previous (s,i,pi,_), merge with it and save result rootIsWildcard = not self.fullCtx merged = merge(existing.context, config.context, rootIsWildcard, mergeCache) # no need to check for existing.context, config.context in cache # since only way to create new graphs is "call rule" and here. # We cache at both places. existing.reachesIntoOuterContext = max(existing.reachesIntoOuterContext, config.reachesIntoOuterContext) # make sure to preserve the precedence filter suppression during the merge if config.precedenceFilterSuppressed: existing.precedenceFilterSuppressed = True existing.context = merged # replace context; no need to alt mapping return True
def getOrAdd(self, config:ATNConfig): h = config.hashCodeForConfigSet() l = self.configLookup.get(h, None) if l is not None: r = next((cfg for cfg in l if config.equalsForConfigSet(cfg)), None) if r is not None: return r if l is None: l = [config] self.configLookup[h] = l else: l.append(config) return config
def getStates(self): return set(c.state for c in self.configs)
def getPredicates(self): return list(cfg.semanticContext for cfg in self.configs if cfg.semanticContext!=SemanticContext.NONE)
def get(self, i:int): return self.configs[i]
def optimizeConfigs(self, interpreter:ATNSimulator): if self.readonly: raise IllegalStateException("This set is readonly") if len(self.configs)==0: return for config in self.configs: config.context = interpreter.getCachedContext(config.context)
def addAll(self, coll:list): for c in coll: self.add(c) return False
def __eq__(self, other): if self is other: return True elif not isinstance(other, ATNConfigSet): return False
same = self.configs is not None and \ self.configs==other.configs and \ self.fullCtx == other.fullCtx and \ self.uniqueAlt == other.uniqueAlt and \ self.conflictingAlts == other.conflictingAlts and \ self.hasSemanticContext == other.hasSemanticContext and \ self.dipsIntoOuterContext == other.dipsIntoOuterContext
return same
def __hash__(self): if self.readonly: if self.cachedHashCode == -1: self.cachedHashCode = self.hashConfigs() return self.cachedHashCode return self.hashConfigs()
def hashConfigs(self): return reduce(lambda h, cfg: hash((h, cfg)), self.configs, 0)
def __len__(self): return len(self.configs)
def isEmpty(self): return len(self.configs)==0
def __contains__(self, config): if self.configLookup is None: raise UnsupportedOperationException("This method is not implemented for readonly sets.") h = config.hashCodeForConfigSet() l = self.configLookup.get(h, None) if l is not None: for c in l: if config.equalsForConfigSet(c): return True return False
def clear(self): if self.readonly: raise IllegalStateException("This set is readonly") self.configs.clear() self.cachedHashCode = -1 self.configLookup.clear()
def setReadonly(self, readonly:bool): self.readonly = readonly self.configLookup = None # can't mod, no need for lookup cache
def __str__(self): with StringIO() as buf: buf.write(str_list(self.configs)) if self.hasSemanticContext: buf.write(",hasSemanticContext=") buf.write(str(self.hasSemanticContext)) if self.uniqueAlt!=ATN.INVALID_ALT_NUMBER: buf.write(",uniqueAlt=") buf.write(str(self.uniqueAlt)) if self.conflictingAlts is not None: buf.write(",conflictingAlts=") buf.write(str(self.conflictingAlts)) if self.dipsIntoOuterContext: buf.write(",dipsIntoOuterContext") return buf.getvalue()
class OrderedATNConfigSet(ATNConfigSet):
def __init__(self): super().__init__()123456789101112131415161718192021222324# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.
# need a forward declarationATNDeserializationOptions = None
class ATNDeserializationOptions(object): __slots__ = ('readonly', 'verifyATN', 'generateRuleBypassTransitions')
defaultOptions = None
def __init__(self, copyFrom:ATNDeserializationOptions = None): self.readonly = False self.verifyATN = True if copyFrom is None else copyFrom.verifyATN self.generateRuleBypassTransitions = False if copyFrom is None else copyFrom.generateRuleBypassTransitions
def __setattr__(self, key, value): if key!="readonly" and self.readonly: raise Exception("The object is read only.") super(type(self), self).__setattr__(key,value)
ATNDeserializationOptions.defaultOptions = ATNDeserializationOptions()ATNDeserializationOptions.defaultOptions.readonly = True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#/from io import StringIOfrom typing import Callablefrom antlr4.Token import Tokenfrom antlr4.atn.ATN import ATNfrom antlr4.atn.ATNType import ATNTypefrom antlr4.atn.ATNState import *from antlr4.atn.Transition import *from antlr4.atn.LexerAction import *from antlr4.atn.ATNDeserializationOptions import ATNDeserializationOptions
SERIALIZED_VERSION = 4
class ATNDeserializer (object): __slots__ = ('deserializationOptions', 'data', 'pos')
def __init__(self, options : ATNDeserializationOptions = None): if options is None: options = ATNDeserializationOptions.defaultOptions self.deserializationOptions = options
def deserialize(self, data : int): self.data = data self.pos = 0 self.checkVersion() atn = self.readATN() self.readStates(atn) self.readRules(atn) self.readModes(atn) sets = [] self.readSets(atn, sets) self.readEdges(atn, sets) self.readDecisions(atn) self.readLexerActions(atn) self.markPrecedenceDecisions(atn) self.verifyATN(atn) if self.deserializationOptions.generateRuleBypassTransitions \ and atn.grammarType == ATNType.PARSER: self.generateRuleBypassTransitions(atn) # re-verify after modification self.verifyATN(atn) return atn
def checkVersion(self): version = self.readInt() if version != SERIALIZED_VERSION: raise Exception("Could not deserialize ATN with version " + str(version) + " (expected " + str(SERIALIZED_VERSION) + ").")
def readATN(self): idx = self.readInt() grammarType = ATNType.fromOrdinal(idx) maxTokenType = self.readInt() return ATN(grammarType, maxTokenType)
def readStates(self, atn:ATN): loopBackStateNumbers = [] endStateNumbers = [] nstates = self.readInt() for i in range(0, nstates): stype = self.readInt() # ignore bad type of states if stype==ATNState.INVALID_TYPE: atn.addState(None) continue ruleIndex = self.readInt() s = self.stateFactory(stype, ruleIndex) if stype == ATNState.LOOP_END: # special case loopBackStateNumber = self.readInt() loopBackStateNumbers.append((s, loopBackStateNumber)) elif isinstance(s, BlockStartState): endStateNumber = self.readInt() endStateNumbers.append((s, endStateNumber))
atn.addState(s)
# delay the assignment of loop back and end states until we know all the state instances have been initialized for pair in loopBackStateNumbers: pair[0].loopBackState = atn.states[pair[1]]
for pair in endStateNumbers: pair[0].endState = atn.states[pair[1]]
numNonGreedyStates = self.readInt() for i in range(0, numNonGreedyStates): stateNumber = self.readInt() atn.states[stateNumber].nonGreedy = True
numPrecedenceStates = self.readInt() for i in range(0, numPrecedenceStates): stateNumber = self.readInt() atn.states[stateNumber].isPrecedenceRule = True
def readRules(self, atn:ATN): nrules = self.readInt() if atn.grammarType == ATNType.LEXER: atn.ruleToTokenType = [0] * nrules
atn.ruleToStartState = [0] * nrules for i in range(0, nrules): s = self.readInt() startState = atn.states[s] atn.ruleToStartState[i] = startState if atn.grammarType == ATNType.LEXER: tokenType = self.readInt() atn.ruleToTokenType[i] = tokenType
atn.ruleToStopState = [0] * nrules for state in atn.states: if not isinstance(state, RuleStopState): continue atn.ruleToStopState[state.ruleIndex] = state atn.ruleToStartState[state.ruleIndex].stopState = state
def readModes(self, atn:ATN): nmodes = self.readInt() for i in range(0, nmodes): s = self.readInt() atn.modeToStartState.append(atn.states[s])
def readSets(self, atn:ATN, sets:list): m = self.readInt() for i in range(0, m): iset = IntervalSet() sets.append(iset) n = self.readInt() containsEof = self.readInt() if containsEof!=0: iset.addOne(-1) for j in range(0, n): i1 = self.readInt() i2 = self.readInt() iset.addRange(range(i1, i2 + 1)) # range upper limit is exclusive
def readEdges(self, atn:ATN, sets:list): nedges = self.readInt() for i in range(0, nedges): src = self.readInt() trg = self.readInt() ttype = self.readInt() arg1 = self.readInt() arg2 = self.readInt() arg3 = self.readInt() trans = self.edgeFactory(atn, ttype, src, trg, arg1, arg2, arg3, sets) srcState = atn.states[src] srcState.addTransition(trans)
# edges for rule stop states can be derived, so they aren't serialized for state in atn.states: for i in range(0, len(state.transitions)): t = state.transitions[i] if not isinstance(t, RuleTransition): continue outermostPrecedenceReturn = -1 if atn.ruleToStartState[t.target.ruleIndex].isPrecedenceRule: if t.precedence == 0: outermostPrecedenceReturn = t.target.ruleIndex trans = EpsilonTransition(t.followState, outermostPrecedenceReturn) atn.ruleToStopState[t.target.ruleIndex].addTransition(trans)
for state in atn.states: if isinstance(state, BlockStartState): # we need to know the end state to set its start state if state.endState is None: raise Exception("IllegalState") # block end states can only be associated to a single block start state if state.endState.startState is not None: raise Exception("IllegalState") state.endState.startState = state
if isinstance(state, PlusLoopbackState): for i in range(0, len(state.transitions)): target = state.transitions[i].target if isinstance(target, PlusBlockStartState): target.loopBackState = state elif isinstance(state, StarLoopbackState): for i in range(0, len(state.transitions)): target = state.transitions[i].target if isinstance(target, StarLoopEntryState): target.loopBackState = state
def readDecisions(self, atn:ATN): ndecisions = self.readInt() for i in range(0, ndecisions): s = self.readInt() decState = atn.states[s] atn.decisionToState.append(decState) decState.decision = i
def readLexerActions(self, atn:ATN): if atn.grammarType == ATNType.LEXER: count = self.readInt() atn.lexerActions = [ None ] * count for i in range(0, count): actionType = self.readInt() data1 = self.readInt() data2 = self.readInt() lexerAction = self.lexerActionFactory(actionType, data1, data2) atn.lexerActions[i] = lexerAction
def generateRuleBypassTransitions(self, atn:ATN):
count = len(atn.ruleToStartState) atn.ruleToTokenType = [ 0 ] * count for i in range(0, count): atn.ruleToTokenType[i] = atn.maxTokenType + i + 1
for i in range(0, count): self.generateRuleBypassTransition(atn, i)
def generateRuleBypassTransition(self, atn:ATN, idx:int):
bypassStart = BasicBlockStartState() bypassStart.ruleIndex = idx atn.addState(bypassStart)
bypassStop = BlockEndState() bypassStop.ruleIndex = idx atn.addState(bypassStop)
bypassStart.endState = bypassStop atn.defineDecisionState(bypassStart)
bypassStop.startState = bypassStart
excludeTransition = None
if atn.ruleToStartState[idx].isPrecedenceRule: # wrap from the beginning of the rule to the StarLoopEntryState endState = None for state in atn.states: if self.stateIsEndStateFor(state, idx): endState = state excludeTransition = state.loopBackState.transitions[0] break
if excludeTransition is None: raise Exception("Couldn't identify final state of the precedence rule prefix section.")
else:
endState = atn.ruleToStopState[idx]
# all non-excluded transitions that currently target end state need to target blockEnd instead for state in atn.states: for transition in state.transitions: if transition == excludeTransition: continue if transition.target == endState: transition.target = bypassStop
# all transitions leaving the rule start state need to leave blockStart instead ruleToStartState = atn.ruleToStartState[idx] count = len(ruleToStartState.transitions) while count > 0: bypassStart.addTransition(ruleToStartState.transitions[count-1]) del ruleToStartState.transitions[-1]
# link the new states atn.ruleToStartState[idx].addTransition(EpsilonTransition(bypassStart)) bypassStop.addTransition(EpsilonTransition(endState))
matchState = BasicState() atn.addState(matchState) matchState.addTransition(AtomTransition(bypassStop, atn.ruleToTokenType[idx])) bypassStart.addTransition(EpsilonTransition(matchState))
def stateIsEndStateFor(self, state:ATNState, idx:int): if state.ruleIndex != idx: return None if not isinstance(state, StarLoopEntryState): return None
maybeLoopEndState = state.transitions[len(state.transitions) - 1].target if not isinstance(maybeLoopEndState, LoopEndState): return None
if maybeLoopEndState.epsilonOnlyTransitions and \ isinstance(maybeLoopEndState.transitions[0].target, RuleStopState): return state else: return None
# # Analyze the {@link StarLoopEntryState} states in the specified ATN to set # the {@link StarLoopEntryState#isPrecedenceDecision} field to the # correct value. # # @param atn The ATN. # def markPrecedenceDecisions(self, atn:ATN): for state in atn.states: if not isinstance(state, StarLoopEntryState): continue
# We analyze the ATN to determine if this ATN decision state is the # decision for the closure block that determines whether a # precedence rule should continue or complete. # if atn.ruleToStartState[state.ruleIndex].isPrecedenceRule: maybeLoopEndState = state.transitions[len(state.transitions) - 1].target if isinstance(maybeLoopEndState, LoopEndState): if maybeLoopEndState.epsilonOnlyTransitions and \ isinstance(maybeLoopEndState.transitions[0].target, RuleStopState): state.isPrecedenceDecision = True
def verifyATN(self, atn:ATN): if not self.deserializationOptions.verifyATN: return # verify assumptions for state in atn.states: if state is None: continue
self.checkCondition(state.epsilonOnlyTransitions or len(state.transitions) <= 1)
if isinstance(state, PlusBlockStartState): self.checkCondition(state.loopBackState is not None)
if isinstance(state, StarLoopEntryState): self.checkCondition(state.loopBackState is not None) self.checkCondition(len(state.transitions) == 2)
if isinstance(state.transitions[0].target, StarBlockStartState): self.checkCondition(isinstance(state.transitions[1].target, LoopEndState)) self.checkCondition(not state.nonGreedy) elif isinstance(state.transitions[0].target, LoopEndState): self.checkCondition(isinstance(state.transitions[1].target, StarBlockStartState)) self.checkCondition(state.nonGreedy) else: raise Exception("IllegalState")
if isinstance(state, StarLoopbackState): self.checkCondition(len(state.transitions) == 1) self.checkCondition(isinstance(state.transitions[0].target, StarLoopEntryState))
if isinstance(state, LoopEndState): self.checkCondition(state.loopBackState is not None)
if isinstance(state, RuleStartState): self.checkCondition(state.stopState is not None)
if isinstance(state, BlockStartState): self.checkCondition(state.endState is not None)
if isinstance(state, BlockEndState): self.checkCondition(state.startState is not None)
if isinstance(state, DecisionState): self.checkCondition(len(state.transitions) <= 1 or state.decision >= 0) else: self.checkCondition(len(state.transitions) <= 1 or isinstance(state, RuleStopState))
def checkCondition(self, condition:bool, message=None): if not condition: if message is None: message = "IllegalState" raise Exception(message)
def readInt(self): i = self.data[self.pos] self.pos += 1 return i
edgeFactories = [ lambda args : None, lambda atn, src, trg, arg1, arg2, arg3, sets, target : EpsilonTransition(target), lambda atn, src, trg, arg1, arg2, arg3, sets, target : \ RangeTransition(target, Token.EOF, arg2) if arg3 != 0 else RangeTransition(target, arg1, arg2), lambda atn, src, trg, arg1, arg2, arg3, sets, target : \ RuleTransition(atn.states[arg1], arg2, arg3, target), lambda atn, src, trg, arg1, arg2, arg3, sets, target : \ PredicateTransition(target, arg1, arg2, arg3 != 0), lambda atn, src, trg, arg1, arg2, arg3, sets, target : \ AtomTransition(target, Token.EOF) if arg3 != 0 else AtomTransition(target, arg1), lambda atn, src, trg, arg1, arg2, arg3, sets, target : \ ActionTransition(target, arg1, arg2, arg3 != 0), lambda atn, src, trg, arg1, arg2, arg3, sets, target : \ SetTransition(target, sets[arg1]), lambda atn, src, trg, arg1, arg2, arg3, sets, target : \ NotSetTransition(target, sets[arg1]), lambda atn, src, trg, arg1, arg2, arg3, sets, target : \ WildcardTransition(target), lambda atn, src, trg, arg1, arg2, arg3, sets, target : \ PrecedencePredicateTransition(target, arg1) ]
def edgeFactory(self, atn:ATN, type:int, src:int, trg:int, arg1:int, arg2:int, arg3:int, sets:list): target = atn.states[trg] if type > len(self.edgeFactories) or self.edgeFactories[type] is None: raise Exception("The specified transition type: " + str(type) + " is not valid.") else: return self.edgeFactories[type](atn, src, trg, arg1, arg2, arg3, sets, target)
stateFactories = [ lambda : None, lambda : BasicState(), lambda : RuleStartState(), lambda : BasicBlockStartState(), lambda : PlusBlockStartState(), lambda : StarBlockStartState(), lambda : TokensStartState(), lambda : RuleStopState(), lambda : BlockEndState(), lambda : StarLoopbackState(), lambda : StarLoopEntryState(), lambda : PlusLoopbackState(), lambda : LoopEndState() ]
def stateFactory(self, type:int, ruleIndex:int): if type> len(self.stateFactories) or self.stateFactories[type] is None: raise Exception("The specified state type " + str(type) + " is not valid.") else: s = self.stateFactories[type]() if s is not None: s.ruleIndex = ruleIndex return s
CHANNEL = 0 #The type of a {@link LexerChannelAction} action. CUSTOM = 1 #The type of a {@link LexerCustomAction} action. MODE = 2 #The type of a {@link LexerModeAction} action. MORE = 3 #The type of a {@link LexerMoreAction} action. POP_MODE = 4 #The type of a {@link LexerPopModeAction} action. PUSH_MODE = 5 #The type of a {@link LexerPushModeAction} action. SKIP = 6 #The type of a {@link LexerSkipAction} action. TYPE = 7 #The type of a {@link LexerTypeAction} action.
actionFactories = [ lambda data1, data2: LexerChannelAction(data1), lambda data1, data2: LexerCustomAction(data1, data2), lambda data1, data2: LexerModeAction(data1), lambda data1, data2: LexerMoreAction.INSTANCE, lambda data1, data2: LexerPopModeAction.INSTANCE, lambda data1, data2: LexerPushModeAction(data1), lambda data1, data2: LexerSkipAction.INSTANCE, lambda data1, data2: LexerTypeAction(data1) ]
def lexerActionFactory(self, type:int, data1:int, data2:int):
if type > len(self.actionFactories) or self.actionFactories[type] is None: raise Exception("The specified lexer action type " + str(type) + " is not valid.") else: return self.actionFactories[type](data1, data2)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#/from antlr4.PredictionContext import PredictionContextCache, PredictionContext, getCachedPredictionContextfrom antlr4.atn.ATN import ATNfrom antlr4.atn.ATNConfigSet import ATNConfigSetfrom antlr4.dfa.DFAState import DFAState
class ATNSimulator(object): __slots__ = ('atn', 'sharedContextCache', '__dict__')
# Must distinguish between missing edge and edge we know leads nowhere#/ ERROR = DFAState(configs=ATNConfigSet()) ERROR.stateNumber = 0x7FFFFFFF
# The context cache maps all PredictionContext objects that are == # to a single cached copy. This cache is shared across all contexts # in all ATNConfigs in all DFA states. We rebuild each ATNConfigSet # to use only cached nodes/graphs in addDFAState(). We don't want to # fill this during closure() since there are lots of contexts that # pop up but are not used ever again. It also greatly slows down closure(). # # <p>This cache makes a huge difference in memory and a little bit in speed. # For the Java grammar on java.*, it dropped the memory requirements # at the end from 25M to 16M. We don't store any of the full context # graphs in the DFA because they are limited to local context only, # but apparently there's a lot of repetition there as well. We optimize # the config contexts before storing the config set in the DFA states # by literally rebuilding them with cached subgraphs only.</p> # # <p>I tried a cache for use during closure operations, that was # whacked after each adaptivePredict(). It cost a little bit # more time I think and doesn't save on the overall footprint # so it's not worth the complexity.</p> #/ def __init__(self, atn:ATN, sharedContextCache:PredictionContextCache): self.atn = atn self.sharedContextCache = sharedContextCache
def getCachedContext(self, context:PredictionContext): if self.sharedContextCache is None: return context visited = dict() return getCachedPredictionContext(context, self.sharedContextCache, visited)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#
# The following images show the relation of states and# {@link ATNState#transitions} for various grammar constructs.## <ul>## <li>Solid edges marked with an ε indicate a required# {@link EpsilonTransition}.</li>## <li>Dashed edges indicate locations where any transition derived from# {@link Transition} might appear.</li>## <li>Dashed nodes are place holders for either a sequence of linked# {@link BasicState} states or the inclusion of a block representing a nested# construct in one of the forms below.</li>## <li>Nodes showing multiple outgoing alternatives with a {@code ...} support# any number of alternatives (one or more). Nodes without the {@code ...} only# support the exact number of alternatives shown in the diagram.</li>## </ul>## <h2>Basic Blocks</h2>## <h3>Rule</h3>## <embed src="images/Rule.svg" type="image/svg+xml"/>## <h3>Block of 1 or more alternatives</h3>## <embed src="images/Block.svg" type="image/svg+xml"/>## <h2>Greedy Loops</h2>## <h3>Greedy Closure: {@code (...)*}</h3>## <embed src="images/ClosureGreedy.svg" type="image/svg+xml"/>## <h3>Greedy Positive Closure: {@code (...)+}</h3>## <embed src="images/PositiveClosureGreedy.svg" type="image/svg+xml"/>## <h3>Greedy Optional: {@code (...)?}</h3>## <embed src="images/OptionalGreedy.svg" type="image/svg+xml"/>## <h2>Non-Greedy Loops</h2>## <h3>Non-Greedy Closure: {@code (...)*?}</h3>## <embed src="images/ClosureNonGreedy.svg" type="image/svg+xml"/>## <h3>Non-Greedy Positive Closure: {@code (...)+?}</h3>## <embed src="images/PositiveClosureNonGreedy.svg" type="image/svg+xml"/>## <h3>Non-Greedy Optional: {@code (...)??}</h3>## <embed src="images/OptionalNonGreedy.svg" type="image/svg+xml"/>#
from antlr4.atn.Transition import Transition
INITIAL_NUM_TRANSITIONS = 4
class ATNState(object): __slots__ = ( 'atn', 'stateNumber', 'stateType', 'ruleIndex', 'epsilonOnlyTransitions', 'transitions', 'nextTokenWithinRule', )
# constants for serialization INVALID_TYPE = 0 BASIC = 1 RULE_START = 2 BLOCK_START = 3 PLUS_BLOCK_START = 4 STAR_BLOCK_START = 5 TOKEN_START = 6 RULE_STOP = 7 BLOCK_END = 8 STAR_LOOP_BACK = 9 STAR_LOOP_ENTRY = 10 PLUS_LOOP_BACK = 11 LOOP_END = 12
serializationNames = [ "INVALID", "BASIC", "RULE_START", "BLOCK_START", "PLUS_BLOCK_START", "STAR_BLOCK_START", "TOKEN_START", "RULE_STOP", "BLOCK_END", "STAR_LOOP_BACK", "STAR_LOOP_ENTRY", "PLUS_LOOP_BACK", "LOOP_END" ]
INVALID_STATE_NUMBER = -1
def __init__(self): # Which ATN are we in? self.atn = None self.stateNumber = ATNState.INVALID_STATE_NUMBER self.stateType = None self.ruleIndex = 0 # at runtime, we don't have Rule objects self.epsilonOnlyTransitions = False # Track the transitions emanating from this ATN state. self.transitions = [] # Used to cache lookahead during parsing, not used during construction self.nextTokenWithinRule = None
def __hash__(self): return self.stateNumber
def __eq__(self, other): return isinstance(other, ATNState) and self.stateNumber==other.stateNumber
def onlyHasEpsilonTransitions(self): return self.epsilonOnlyTransitions
def isNonGreedyExitState(self): return False
def __str__(self): return str(self.stateNumber)
def addTransition(self, trans:Transition, index:int=-1): if len(self.transitions)==0: self.epsilonOnlyTransitions = trans.isEpsilon elif self.epsilonOnlyTransitions != trans.isEpsilon: self.epsilonOnlyTransitions = False # TODO System.err.format(Locale.getDefault(), "ATN state %d has both epsilon and non-epsilon transitions.\n", stateNumber); if index==-1: self.transitions.append(trans) else: self.transitions.insert(index, trans)
class BasicState(ATNState):
def __init__(self): super().__init__() self.stateType = self.BASIC
class DecisionState(ATNState): __slots__ = ('decision', 'nonGreedy') def __init__(self): super().__init__() self.decision = -1 self.nonGreedy = False
# The start of a regular {@code (...)} block.class BlockStartState(DecisionState): __slots__ = 'endState'
def __init__(self): super().__init__() self.endState = None
class BasicBlockStartState(BlockStartState):
def __init__(self): super().__init__() self.stateType = self.BLOCK_START
# Terminal node of a simple {@code (a|b|c)} block.class BlockEndState(ATNState): __slots__ = 'startState'
def __init__(self): super().__init__() self.stateType = self.BLOCK_END self.startState = None
# The last node in the ATN for a rule, unless that rule is the start symbol.# In that case, there is one transition to EOF. Later, we might encode# references to all calls to this rule to compute FOLLOW sets for# error handling.#class RuleStopState(ATNState):
def __init__(self): super().__init__() self.stateType = self.RULE_STOP
class RuleStartState(ATNState): __slots__ = ('stopState', 'isPrecedenceRule')
def __init__(self): super().__init__() self.stateType = self.RULE_START self.stopState = None self.isPrecedenceRule = False
# Decision state for {@code A+} and {@code (A|B)+}. It has two transitions:# one to the loop back to start of the block and one to exit.#class PlusLoopbackState(DecisionState):
def __init__(self): super().__init__() self.stateType = self.PLUS_LOOP_BACK
# Start of {@code (A|B|...)+} loop. Technically a decision state, but# we don't use for code generation; somebody might need it, so I'm defining# it for completeness. In reality, the {@link PlusLoopbackState} node is the# real decision-making note for {@code A+}.#class PlusBlockStartState(BlockStartState): __slots__ = 'loopBackState'
def __init__(self): super().__init__() self.stateType = self.PLUS_BLOCK_START self.loopBackState = None
# The block that begins a closure loop.class StarBlockStartState(BlockStartState):
def __init__(self): super().__init__() self.stateType = self.STAR_BLOCK_START
class StarLoopbackState(ATNState):
def __init__(self): super().__init__() self.stateType = self.STAR_LOOP_BACK
class StarLoopEntryState(DecisionState): __slots__ = ('loopBackState', 'isPrecedenceDecision')
def __init__(self): super().__init__() self.stateType = self.STAR_LOOP_ENTRY self.loopBackState = None # Indicates whether this state can benefit from a precedence DFA during SLL decision making. self.isPrecedenceDecision = None
# Mark the end of a * or + loop.class LoopEndState(ATNState): __slots__ = 'loopBackState'
def __init__(self): super().__init__() self.stateType = self.LOOP_END self.loopBackState = None
# The Tokens rule start state linking to each lexer rule start state */class TokensStartState(DecisionState):
def __init__(self): super().__init__() self.stateType = self.TOKEN_START1234567891011121314151617# Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#/
from enum import IntEnum
# Represents the type of recognizer an ATN applies to.
class ATNType(IntEnum):
LEXER = 0 PARSER = 1
@classmethod def fromOrdinal(cls, i:int): return cls._value2member_map_[i]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#/
# When we hit an accept state in either the DFA or the ATN, we# have to notify the character stream to start buffering characters# via {@link IntStream#mark} and record the current state. The current sim state# includes the current index into the input, the current line,# and current character position in that line. Note that the Lexer is# tracking the starting line and characterization of the token. These# variables track the "state" of the simulator when it hits an accept state.## <p>We track these variables separately for the DFA and ATN simulation# because the DFA simulation often has to fail over to the ATN# simulation. If the ATN simulation fails, we need the DFA to fall# back to its previously accepted state, if any. If the ATN succeeds,# then the ATN does the accept and the DFA simulator that invoked it# can simply return the predicted token type.</p>#/
from antlr4.PredictionContext import PredictionContextCache, SingletonPredictionContext, PredictionContextfrom antlr4.InputStream import InputStreamfrom antlr4.Token import Tokenfrom antlr4.atn.ATN import ATNfrom antlr4.atn.ATNConfig import LexerATNConfigfrom antlr4.atn.ATNSimulator import ATNSimulatorfrom antlr4.atn.ATNConfigSet import ATNConfigSet, OrderedATNConfigSetfrom antlr4.atn.ATNState import RuleStopState, ATNStatefrom antlr4.atn.LexerActionExecutor import LexerActionExecutorfrom antlr4.atn.Transition import Transitionfrom antlr4.dfa.DFAState import DFAStatefrom antlr4.error.Errors import LexerNoViableAltException, UnsupportedOperationException
class SimState(object): __slots__ = ('index', 'line', 'column', 'dfaState')
def __init__(self): self.reset()
def reset(self): self.index = -1 self.line = 0 self.column = -1 self.dfaState = None
# need forward declarationLexer = NoneLexerATNSimulator = None
class LexerATNSimulator(ATNSimulator): __slots__ = ( 'decisionToDFA', 'recog', 'startIndex', 'line', 'column', 'mode', 'DEFAULT_MODE', 'MAX_CHAR_VALUE', 'prevAccept' )
debug = False dfa_debug = False
MIN_DFA_EDGE = 0 MAX_DFA_EDGE = 127 # forces unicode to stay in ATN
ERROR = None
def __init__(self, recog:Lexer, atn:ATN, decisionToDFA:list, sharedContextCache:PredictionContextCache): super().__init__(atn, sharedContextCache) self.decisionToDFA = decisionToDFA self.recog = recog # The current token's starting index into the character stream. # Shared across DFA to ATN simulation in case the ATN fails and the # DFA did not have a previous accept state. In this case, we use the # ATN-generated exception object. self.startIndex = -1 # line number 1..n within the input#/ self.line = 1 # The index of the character relative to the beginning of the line 0..n-1#/ self.column = 0 from antlr4.Lexer import Lexer self.mode = Lexer.DEFAULT_MODE # Cache Lexer properties to avoid further imports self.DEFAULT_MODE = Lexer.DEFAULT_MODE self.MAX_CHAR_VALUE = Lexer.MAX_CHAR_VALUE # Used during DFA/ATN exec to record the most recent accept configuration info self.prevAccept = SimState()
def copyState(self, simulator:LexerATNSimulator ): self.column = simulator.column self.line = simulator.line self.mode = simulator.mode self.startIndex = simulator.startIndex
def match(self, input:InputStream , mode:int): self.mode = mode mark = input.mark() try: self.startIndex = input.index self.prevAccept.reset() dfa = self.decisionToDFA[mode] if dfa.s0 is None: return self.matchATN(input) else: return self.execATN(input, dfa.s0) finally: input.release(mark)
def reset(self): self.prevAccept.reset() self.startIndex = -1 self.line = 1 self.column = 0 self.mode = self.DEFAULT_MODE
def matchATN(self, input:InputStream): startState = self.atn.modeToStartState[self.mode]
if LexerATNSimulator.debug: print("matchATN mode " + str(self.mode) + " start: " + str(startState))
old_mode = self.mode s0_closure = self.computeStartState(input, startState) suppressEdge = s0_closure.hasSemanticContext s0_closure.hasSemanticContext = False
next = self.addDFAState(s0_closure) if not suppressEdge: self.decisionToDFA[self.mode].s0 = next
predict = self.execATN(input, next)
if LexerATNSimulator.debug: print("DFA after matchATN: " + str(self.decisionToDFA[old_mode].toLexerString()))
return predict
def execATN(self, input:InputStream, ds0:DFAState): if LexerATNSimulator.debug: print("start state closure=" + str(ds0.configs))
if ds0.isAcceptState: # allow zero-length tokens self.captureSimState(self.prevAccept, input, ds0)
t = input.LA(1) s = ds0 # s is current/from DFA state
while True: # while more work if LexerATNSimulator.debug: print("execATN loop starting closure:", str(s.configs))
# As we move src->trg, src->trg, we keep track of the previous trg to # avoid looking up the DFA state again, which is expensive. # If the previous target was already part of the DFA, we might # be able to avoid doing a reach operation upon t. If s!=null, # it means that semantic predicates didn't prevent us from # creating a DFA state. Once we know s!=null, we check to see if # the DFA state has an edge already for t. If so, we can just reuse # it's configuration set; there's no point in re-computing it. # This is kind of like doing DFA simulation within the ATN # simulation because DFA simulation is really just a way to avoid # computing reach/closure sets. Technically, once we know that # we have a previously added DFA state, we could jump over to # the DFA simulator. But, that would mean popping back and forth # a lot and making things more complicated algorithmically. # This optimization makes a lot of sense for loops within DFA. # A character will take us back to an existing DFA state # that already has lots of edges out of it. e.g., .* in comments. # print("Target for:" + str(s) + " and:" + str(t)) target = self.getExistingTargetState(s, t) # print("Existing:" + str(target)) if target is None: target = self.computeTargetState(input, s, t) # print("Computed:" + str(target))
if target == self.ERROR: break
# If this is a consumable input element, make sure to consume before # capturing the accept state so the input index, line, and char # position accurately reflect the state of the interpreter at the # end of the token. if t != Token.EOF: self.consume(input)
if target.isAcceptState: self.captureSimState(self.prevAccept, input, target) if t == Token.EOF: break
t = input.LA(1)
s = target # flip; current DFA target becomes new src/from state
return self.failOrAccept(self.prevAccept, input, s.configs, t)
# Get an existing target state for an edge in the DFA. If the target state # for the edge has not yet been computed or is otherwise not available, # this method returns {@code null}. # # @param s The current DFA state # @param t The next input symbol # @return The existing target DFA state for the given input symbol # {@code t}, or {@code null} if the target state for this edge is not # already cached def getExistingTargetState(self, s:DFAState, t:int): if s.edges is None or t < self.MIN_DFA_EDGE or t > self.MAX_DFA_EDGE: return None
target = s.edges[t - self.MIN_DFA_EDGE] if LexerATNSimulator.debug and target is not None: print("reuse state", str(s.stateNumber), "edge to", str(target.stateNumber))
return target
# Compute a target state for an edge in the DFA, and attempt to add the # computed state and corresponding edge to the DFA. # # @param input The input stream # @param s The current DFA state # @param t The next input symbol # # @return The computed target DFA state for the given input symbol # {@code t}. If {@code t} does not lead to a valid DFA state, this method # returns {@link #ERROR}. def computeTargetState(self, input:InputStream, s:DFAState, t:int): reach = OrderedATNConfigSet()
# if we don't find an existing DFA state # Fill reach starting from closure, following t transitions self.getReachableConfigSet(input, s.configs, reach, t)
if len(reach)==0: # we got nowhere on t from s if not reach.hasSemanticContext: # we got nowhere on t, don't throw out this knowledge; it'd # cause a failover from DFA later. self. addDFAEdge(s, t, self.ERROR)
# stop when we can't match any more char return self.ERROR
# Add an edge from s to target DFA found/created for reach return self.addDFAEdge(s, t, cfgs=reach)
def failOrAccept(self, prevAccept:SimState , input:InputStream, reach:ATNConfigSet, t:int): if self.prevAccept.dfaState is not None: lexerActionExecutor = prevAccept.dfaState.lexerActionExecutor self.accept(input, lexerActionExecutor, self.startIndex, prevAccept.index, prevAccept.line, prevAccept.column) return prevAccept.dfaState.prediction else: # if no accept and EOF is first char, return EOF if t==Token.EOF and input.index==self.startIndex: return Token.EOF raise LexerNoViableAltException(self.recog, input, self.startIndex, reach)
# Given a starting configuration set, figure out all ATN configurations # we can reach upon input {@code t}. Parameter {@code reach} is a return # parameter. def getReachableConfigSet(self, input:InputStream, closure:ATNConfigSet, reach:ATNConfigSet, t:int): # this is used to skip processing for configs which have a lower priority # than a config that already reached an accept state for the same rule skipAlt = ATN.INVALID_ALT_NUMBER for cfg in closure: currentAltReachedAcceptState = ( cfg.alt == skipAlt ) if currentAltReachedAcceptState and cfg.passedThroughNonGreedyDecision: continue
if LexerATNSimulator.debug: print("testing", self.getTokenName(t), "at", str(cfg))
for trans in cfg.state.transitions: # for each transition target = self.getReachableTarget(trans, t) if target is not None: lexerActionExecutor = cfg.lexerActionExecutor if lexerActionExecutor is not None: lexerActionExecutor = lexerActionExecutor.fixOffsetBeforeMatch(input.index - self.startIndex)
treatEofAsEpsilon = (t == Token.EOF) config = LexerATNConfig(state=target, lexerActionExecutor=lexerActionExecutor, config=cfg) if self.closure(input, config, reach, currentAltReachedAcceptState, True, treatEofAsEpsilon): # any remaining configs for this alt have a lower priority than # the one that just reached an accept state. skipAlt = cfg.alt
def accept(self, input:InputStream, lexerActionExecutor:LexerActionExecutor, startIndex:int, index:int, line:int, charPos:int): if LexerATNSimulator.debug: print("ACTION", lexerActionExecutor)
# seek to after last char in token input.seek(index) self.line = line self.column = charPos
if lexerActionExecutor is not None and self.recog is not None: lexerActionExecutor.execute(self.recog, input, startIndex)
def getReachableTarget(self, trans:Transition, t:int): if trans.matches(t, 0, self.MAX_CHAR_VALUE): return trans.target else: return None
def computeStartState(self, input:InputStream, p:ATNState): initialContext = PredictionContext.EMPTY configs = OrderedATNConfigSet() for i in range(0,len(p.transitions)): target = p.transitions[i].target c = LexerATNConfig(state=target, alt=i+1, context=initialContext) self.closure(input, c, configs, False, False, False) return configs
# Since the alternatives within any lexer decision are ordered by # preference, this method stops pursuing the closure as soon as an accept # state is reached. After the first accept state is reached by depth-first # search from {@code config}, all other (potentially reachable) states for # this rule would have a lower priority. # # @return {@code true} if an accept state is reached, otherwise # {@code false}. def closure(self, input:InputStream, config:LexerATNConfig, configs:ATNConfigSet, currentAltReachedAcceptState:bool, speculative:bool, treatEofAsEpsilon:bool): if LexerATNSimulator.debug: print("closure(" + str(config) + ")")
if isinstance( config.state, RuleStopState ): if LexerATNSimulator.debug: if self.recog is not None: print("closure at", self.recog.symbolicNames[config.state.ruleIndex], "rule stop", str(config)) else: print("closure at rule stop", str(config))
if config.context is None or config.context.hasEmptyPath(): if config.context is None or config.context.isEmpty(): configs.add(config) return True else: configs.add(LexerATNConfig(state=config.state, config=config, context=PredictionContext.EMPTY)) currentAltReachedAcceptState = True
if config.context is not None and not config.context.isEmpty(): for i in range(0,len(config.context)): if config.context.getReturnState(i) != PredictionContext.EMPTY_RETURN_STATE: newContext = config.context.getParent(i) # "pop" return state returnState = self.atn.states[config.context.getReturnState(i)] c = LexerATNConfig(state=returnState, config=config, context=newContext) currentAltReachedAcceptState = self.closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon)
return currentAltReachedAcceptState
# optimization if not config.state.epsilonOnlyTransitions: if not currentAltReachedAcceptState or not config.passedThroughNonGreedyDecision: configs.add(config)
for t in config.state.transitions: c = self.getEpsilonTarget(input, config, t, configs, speculative, treatEofAsEpsilon) if c is not None: currentAltReachedAcceptState = self.closure(input, c, configs, currentAltReachedAcceptState, speculative, treatEofAsEpsilon)
return currentAltReachedAcceptState
# side-effect: can alter configs.hasSemanticContext def getEpsilonTarget(self, input:InputStream, config:LexerATNConfig, t:Transition, configs:ATNConfigSet, speculative:bool, treatEofAsEpsilon:bool): c = None if t.serializationType==Transition.RULE: newContext = SingletonPredictionContext.create(config.context, t.followState.stateNumber) c = LexerATNConfig(state=t.target, config=config, context=newContext)
elif t.serializationType==Transition.PRECEDENCE: raise UnsupportedOperationException("Precedence predicates are not supported in lexers.")
elif t.serializationType==Transition.PREDICATE: # Track traversing semantic predicates. If we traverse, # we cannot add a DFA state for this "reach" computation # because the DFA would not test the predicate again in the # future. Rather than creating collections of semantic predicates # like v3 and testing them on prediction, v4 will test them on the # fly all the time using the ATN not the DFA. This is slower but # semantically it's not used that often. One of the key elements to # this predicate mechanism is not adding DFA states that see # predicates immediately afterwards in the ATN. For example,
# a : ID {p1}? | ID {p2}? ;
# should create the start state for rule 'a' (to save start state # competition), but should not create target of ID state. The # collection of ATN states the following ID references includes # states reached by traversing predicates. Since this is when we # test them, we cannot cash the DFA state target of ID.
if LexerATNSimulator.debug: print("EVAL rule "+ str(t.ruleIndex) + ":" + str(t.predIndex)) configs.hasSemanticContext = True if self.evaluatePredicate(input, t.ruleIndex, t.predIndex, speculative): c = LexerATNConfig(state=t.target, config=config)
elif t.serializationType==Transition.ACTION: if config.context is None or config.context.hasEmptyPath(): # execute actions anywhere in the start rule for a token. # # TODO: if the entry rule is invoked recursively, some # actions may be executed during the recursive call. The # problem can appear when hasEmptyPath() is true but # isEmpty() is false. In this case, the config needs to be # split into two contexts - one with just the empty path # and another with everything but the empty path. # Unfortunately, the current algorithm does not allow # getEpsilonTarget to return two configurations, so # additional modifications are needed before we can support # the split operation. lexerActionExecutor = LexerActionExecutor.append(config.lexerActionExecutor, self.atn.lexerActions[t.actionIndex]) c = LexerATNConfig(state=t.target, config=config, lexerActionExecutor=lexerActionExecutor)
else: # ignore actions in referenced rules c = LexerATNConfig(state=t.target, config=config)
elif t.serializationType==Transition.EPSILON: c = LexerATNConfig(state=t.target, config=config)
elif t.serializationType in [ Transition.ATOM, Transition.RANGE, Transition.SET ]: if treatEofAsEpsilon: if t.matches(Token.EOF, 0, self.MAX_CHAR_VALUE): c = LexerATNConfig(state=t.target, config=config)
return c
# Evaluate a predicate specified in the lexer. # # <p>If {@code speculative} is {@code true}, this method was called before # {@link #consume} for the matched character. This method should call # {@link #consume} before evaluating the predicate to ensure position # sensitive values, including {@link Lexer#getText}, {@link Lexer#getLine}, # and {@link Lexer#getcolumn}, properly reflect the current # lexer state. This method should restore {@code input} and the simulator # to the original state before returning (i.e. undo the actions made by the # call to {@link #consume}.</p> # # @param input The input stream. # @param ruleIndex The rule containing the predicate. # @param predIndex The index of the predicate within the rule. # @param speculative {@code true} if the current index in {@code input} is # one character before the predicate's location. # # @return {@code true} if the specified predicate evaluates to # {@code true}. #/ def evaluatePredicate(self, input:InputStream, ruleIndex:int, predIndex:int, speculative:bool): # assume true if no recognizer was provided if self.recog is None: return True
if not speculative: return self.recog.sempred(None, ruleIndex, predIndex)
savedcolumn = self.column savedLine = self.line index = input.index marker = input.mark() try: self.consume(input) return self.recog.sempred(None, ruleIndex, predIndex) finally: self.column = savedcolumn self.line = savedLine input.seek(index) input.release(marker)
def captureSimState(self, settings:SimState, input:InputStream, dfaState:DFAState): settings.index = input.index settings.line = self.line settings.column = self.column settings.dfaState = dfaState
def addDFAEdge(self, from_:DFAState, tk:int, to:DFAState=None, cfgs:ATNConfigSet=None) -> DFAState:
if to is None and cfgs is not None: # leading to this call, ATNConfigSet.hasSemanticContext is used as a # marker indicating dynamic predicate evaluation makes this edge # dependent on the specific input sequence, so the static edge in the # DFA should be omitted. The target DFAState is still created since # execATN has the ability to resynchronize with the DFA state cache # following the predicate evaluation step. # # TJP notes: next time through the DFA, we see a pred again and eval. # If that gets us to a previously created (but dangling) DFA # state, we can continue in pure DFA mode from there. #/ suppressEdge = cfgs.hasSemanticContext cfgs.hasSemanticContext = False
to = self.addDFAState(cfgs)
if suppressEdge: return to
# add the edge if tk < self.MIN_DFA_EDGE or tk > self.MAX_DFA_EDGE: # Only track edges within the DFA bounds return to
if LexerATNSimulator.debug: print("EDGE " + str(from_) + " -> " + str(to) + " upon "+ chr(tk))
if from_.edges is None: # make room for tokens 1..n and -1 masquerading as index 0 from_.edges = [ None ] * (self.MAX_DFA_EDGE - self.MIN_DFA_EDGE + 1)
from_.edges[tk - self.MIN_DFA_EDGE] = to # connect
return to
# Add a new DFA state if there isn't one with this set of # configurations already. This method also detects the first # configuration containing an ATN rule stop state. Later, when # traversing the DFA, we will know which rule to accept. def addDFAState(self, configs:ATNConfigSet) -> DFAState:
proposed = DFAState(configs=configs) firstConfigWithRuleStopState = next((cfg for cfg in configs if isinstance(cfg.state, RuleStopState)), None)
if firstConfigWithRuleStopState is not None: proposed.isAcceptState = True proposed.lexerActionExecutor = firstConfigWithRuleStopState.lexerActionExecutor proposed.prediction = self.atn.ruleToTokenType[firstConfigWithRuleStopState.state.ruleIndex]
dfa = self.decisionToDFA[self.mode] existing = dfa.states.get(proposed, None) if existing is not None: return existing
newState = proposed
newState.stateNumber = len(dfa.states) configs.setReadonly(True) newState.configs = configs dfa.states[newState] = newState return newState
def getDFA(self, mode:int): return self.decisionToDFA[mode]
# Get the text matched so far for the current token. def getText(self, input:InputStream): # index is first lookahead char, don't include. return input.getText(self.startIndex, input.index-1)
def consume(self, input:InputStream): curChar = input.LA(1) if curChar==ord('\n'): self.line += 1 self.column = 0 else: self.column += 1 input.consume()
def getTokenName(self, t:int): if t==-1: return "EOF" else: return "'" + chr(t) + "'"
LexerATNSimulator.ERROR = DFAState(0x7FFFFFFF, ATNConfigSet())
del Lexer123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root. #
from enum import IntEnum
# need forward declarationLexer = None
class LexerActionType(IntEnum):
CHANNEL = 0 #The type of a {@link LexerChannelAction} action. CUSTOM = 1 #The type of a {@link LexerCustomAction} action. MODE = 2 #The type of a {@link LexerModeAction} action. MORE = 3 #The type of a {@link LexerMoreAction} action. POP_MODE = 4 #The type of a {@link LexerPopModeAction} action. PUSH_MODE = 5 #The type of a {@link LexerPushModeAction} action. SKIP = 6 #The type of a {@link LexerSkipAction} action. TYPE = 7 #The type of a {@link LexerTypeAction} action.
class LexerAction(object): __slots__ = ('actionType', 'isPositionDependent')
def __init__(self, action:LexerActionType): self.actionType = action self.isPositionDependent = False
def __hash__(self): return hash(self.actionType)
def __eq__(self, other): return self is other
## Implements the {@code skip} lexer action by calling {@link Lexer#skip}.## <p>The {@code skip} command does not have any parameters, so this action is# implemented as a singleton instance exposed by {@link #INSTANCE}.</p>class LexerSkipAction(LexerAction):
# Provides a singleton instance of this parameterless lexer action. INSTANCE = None
def __init__(self): super().__init__(LexerActionType.SKIP)
def execute(self, lexer:Lexer): lexer.skip()
def __str__(self): return "skip"
LexerSkipAction.INSTANCE = LexerSkipAction()
# Implements the {@code type} lexer action by calling {@link Lexer#setType}# with the assigned type.class LexerTypeAction(LexerAction): __slots__ = 'type'
def __init__(self, type:int): super().__init__(LexerActionType.TYPE) self.type = type
def execute(self, lexer:Lexer): lexer.type = self.type
def __hash__(self): return hash((self.actionType, self.type))
def __eq__(self, other): if self is other: return True elif not isinstance(other, LexerTypeAction): return False else: return self.type == other.type
def __str__(self): return "type(" + str(self.type) + ")"
# Implements the {@code pushMode} lexer action by calling# {@link Lexer#pushMode} with the assigned mode.class LexerPushModeAction(LexerAction): __slots__ = 'mode'
def __init__(self, mode:int): super().__init__(LexerActionType.PUSH_MODE) self.mode = mode
# <p>This action is implemented by calling {@link Lexer#pushMode} with the # value provided by {@link #getMode}.</p> def execute(self, lexer:Lexer): lexer.pushMode(self.mode)
def __hash__(self): return hash((self.actionType, self.mode))
def __eq__(self, other): if self is other: return True elif not isinstance(other, LexerPushModeAction): return False else: return self.mode == other.mode
def __str__(self): return "pushMode(" + str(self.mode) + ")"
# Implements the {@code popMode} lexer action by calling {@link Lexer#popMode}.## <p>The {@code popMode} command does not have any parameters, so this action is# implemented as a singleton instance exposed by {@link #INSTANCE}.</p>class LexerPopModeAction(LexerAction):
INSTANCE = None
def __init__(self): super().__init__(LexerActionType.POP_MODE)
# <p>This action is implemented by calling {@link Lexer#popMode}.</p> def execute(self, lexer:Lexer): lexer.popMode()
def __str__(self): return "popMode"
LexerPopModeAction.INSTANCE = LexerPopModeAction()
# Implements the {@code more} lexer action by calling {@link Lexer#more}.## <p>The {@code more} command does not have any parameters, so this action is# implemented as a singleton instance exposed by {@link #INSTANCE}.</p>class LexerMoreAction(LexerAction):
INSTANCE = None
def __init__(self): super().__init__(LexerActionType.MORE)
# <p>This action is implemented by calling {@link Lexer#popMode}.</p> def execute(self, lexer:Lexer): lexer.more()
def __str__(self): return "more"
LexerMoreAction.INSTANCE = LexerMoreAction()
# Implements the {@code mode} lexer action by calling {@link Lexer#mode} with# the assigned mode.class LexerModeAction(LexerAction): __slots__ = 'mode'
def __init__(self, mode:int): super().__init__(LexerActionType.MODE) self.mode = mode
# <p>This action is implemented by calling {@link Lexer#mode} with the # value provided by {@link #getMode}.</p> def execute(self, lexer:Lexer): lexer.mode(self.mode)
def __hash__(self): return hash((self.actionType, self.mode))
def __eq__(self, other): if self is other: return True elif not isinstance(other, LexerModeAction): return False else: return self.mode == other.mode
def __str__(self): return "mode(" + str(self.mode) + ")"
# Executes a custom lexer action by calling {@link Recognizer#action} with the# rule and action indexes assigned to the custom action. The implementation of# a custom action is added to the generated code for the lexer in an override# of {@link Recognizer#action} when the grammar is compiled.## <p>This class may represent embedded actions created with the <code>{...}</code># syntax in ANTLR 4, as well as actions created for lexer commands where the# command argument could not be evaluated when the grammar was compiled.</p>
class LexerCustomAction(LexerAction): __slots__ = ('ruleIndex', 'actionIndex')
# Constructs a custom lexer action with the specified rule and action # indexes. # # @param ruleIndex The rule index to use for calls to # {@link Recognizer#action}. # @param actionIndex The action index to use for calls to # {@link Recognizer#action}. #/ def __init__(self, ruleIndex:int, actionIndex:int): super().__init__(LexerActionType.CUSTOM) self.ruleIndex = ruleIndex self.actionIndex = actionIndex self.isPositionDependent = True
# <p>Custom actions are implemented by calling {@link Lexer#action} with the # appropriate rule and action indexes.</p> def execute(self, lexer:Lexer): lexer.action(None, self.ruleIndex, self.actionIndex)
def __hash__(self): return hash((self.actionType, self.ruleIndex, self.actionIndex))
def __eq__(self, other): if self is other: return True elif not isinstance(other, LexerCustomAction): return False else: return self.ruleIndex == other.ruleIndex and self.actionIndex == other.actionIndex
# Implements the {@code channel} lexer action by calling# {@link Lexer#setChannel} with the assigned channel.class LexerChannelAction(LexerAction): __slots__ = 'channel'
# Constructs a new {@code channel} action with the specified channel value. # @param channel The channel value to pass to {@link Lexer#setChannel}. def __init__(self, channel:int): super().__init__(LexerActionType.CHANNEL) self.channel = channel
# <p>This action is implemented by calling {@link Lexer#setChannel} with the # value provided by {@link #getChannel}.</p> def execute(self, lexer:Lexer): lexer._channel = self.channel
def __hash__(self): return hash((self.actionType, self.channel))
def __eq__(self, other): if self is other: return True elif not isinstance(other, LexerChannelAction): return False else: return self.channel == other.channel
def __str__(self): return "channel(" + str(self.channel) + ")"
# This implementation of {@link LexerAction} is used for tracking input offsets# for position-dependent actions within a {@link LexerActionExecutor}.## <p>This action is not serialized as part of the ATN, and is only required for# position-dependent lexer actions which appear at a location other than the# end of a rule. For more information about DFA optimizations employed for# lexer actions, see {@link LexerActionExecutor#append} and# {@link LexerActionExecutor#fixOffsetBeforeMatch}.</p>class LexerIndexedCustomAction(LexerAction): __slots__ = ('offset', 'action')
# Constructs a new indexed custom action by associating a character offset # with a {@link LexerAction}. # # <p>Note: This class is only required for lexer actions for which # {@link LexerAction#isPositionDependent} returns {@code true}.</p> # # @param offset The offset into the input {@link CharStream}, relative to # the token start index, at which the specified lexer action should be # executed. # @param action The lexer action to execute at a particular offset in the # input {@link CharStream}. def __init__(self, offset:int, action:LexerAction): super().__init__(action.actionType) self.offset = offset self.action = action self.isPositionDependent = True
# <p>This method calls {@link #execute} on the result of {@link #getAction} # using the provided {@code lexer}.</p> def execute(self, lexer:Lexer): # assume the input stream position was properly set by the calling code self.action.execute(lexer)
def __hash__(self): return hash((self.actionType, self.offset, self.action))
def __eq__(self, other): if self is other: return True elif not isinstance(other, LexerIndexedCustomAction): return False else: return self.offset == other.offset and self.action == other.action123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143## Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.# Use of this file is governed by the BSD 3-clause license that# can be found in the LICENSE.txt file in the project root.#/
# Represents an executor for a sequence of lexer actions which traversed during# the matching operation of a lexer rule (token).## <p>The executor tracks position information for position-dependent lexer actions# efficiently, ensuring that actions appearing only at the end of the rule do# not cause bloating of the {@link DFA} created for the lexer.</p>
from antlr4.InputStream import InputStreamfrom antlr4.atn.LexerAction import LexerAction, LexerIndexedCustomAction
# need a forward declarationLexer = NoneLexerActionExecutor = None
class LexerActionExecutor(object): __slots__ = ('lexerActions', 'hashCode')
def __init__(self, lexerActions:list=list()): self.lexerActions = lexerActions # Caches the result of {@link #hashCode} since the hash code is an element # of the performance-critical {@link LexerATNConfig#hashCode} operation. self.hashCode = hash("".join([str(la) for la in lexerActions]))
# Creates a {@link LexerActionExecutor} which executes the actions for # the input {@code lexerActionExecutor} followed by a specified # {@code lexerAction}. # # @param lexerActionExecutor The executor for actions already traversed by # the lexer while matching a token within a particular # {@link LexerATNConfig}. If this is {@code null}, the method behaves as # though it were an empty executor. # @param lexerAction The lexer action to execute after the actions # specified in {@code lexerActionExecutor}. # # @return A {@link LexerActionExecutor} for executing the combine actions # of {@code lexerActionExecutor} and {@code lexerAction}. @staticmethod def append(lexerActionExecutor:LexerActionExecutor , lexerAction:LexerAction ): if lexerActionExecutor is None: return LexerActionExecutor([ lexerAction ])
lexerActions = lexerActionExecutor.lexerActions + [ lexerAction ] return LexerActionExecutor(lexerActions)
# Creates a {@link LexerActionExecutor} which encodes the current offset # for position-dependent lexer actions. # # <p>Normally, when the executor encounters lexer actions where # {@link LexerAction#isPositionDependent} returns {@code true}, it calls # {@link IntStream#seek} on the input {@link CharStream} to set the input # position to the <em>end</em> of the current token. This behavior provides # for efficient DFA representation of lexer actions which appear at the end # of a lexer rule, even when the lexer rule matches a variable number of # characters.</p> # # <p>Prior to traversing a match transition in the ATN, the current offset # from the token start index is assigned to all position-dependent lexer # actions which have not already been assigned a fixed offset. By storing # the offsets relative to the token start index, the DFA representation of # lexer actions which appear in the middle of tokens remains efficient due # to sharing among tokens of the same length, regardless of their absolute # position in the input stream.</p> # # <p>If the current executor already has offsets assigned to all # position-dependent lexer actions, the method returns {@code this}.</p> # # @param offset The current offset to assign to all position-dependent # lexer actions which do not already have offsets assigned. # # @return A {@link LexerActionExecutor} which stores input stream offsets # for all position-dependent lexer actions. #/ def fixOffsetBeforeMatch(self, offset:int): updatedLexerActions = None for i in range(0, len(self.lexerActions)): if self.lexerActions[i].isPositionDependent and not isinstance(self.lexerActions[i], LexerIndexedCustomAction): if updatedLexerActions is None: updatedLexerActions = [ la for la in self.lexerActions ] updatedLexerActions[i] = LexerIndexedCustomAction(offset, self.lexerActions[i])
if updatedLexerActions is None: return self else: return LexerActionExecutor(updatedLexerActions)
# Execute the actions encapsulated by this executor within the context of a # particular {@link Lexer}. # # <p>This method calls {@link IntStream#seek} to set the position of the # {@code input} {@link CharStream} prior to calling # {@link LexerAction#execute} on a position-dependent action. Before the # method returns, the input position will be restored to the same position # it was in when the method was invoked.</p> # # @param lexer The lexer instance. # @param input The input stream which is the source for the current token. # When this method is called, the current {@link IntStream#index} for # {@code input} should be the start of the following token, i.e. 1 # character past the end of the current token. # @param startIndex The token start index. This value may be passed to # {@link IntStream#seek} to set the {@code input} position to the beginning # of the token. #/ def execute(self, lexer:Lexer, input:InputStream, startIndex:int): requiresSeek = False stopIndex = input.index try: for lexerAction in self.lexerActions: if isinstance(lexerAction, LexerIndexedCustomAction): offset = lexerAction.offset input.seek(startIndex + offset) lexerAction = lexerAction.action requiresSeek = (startIndex + offset) != stopIndex elif lexerAction.isPositionDependent: input.seek(stopIndex) requiresSeek = False lexerAction.execute(lexer) finally: if requiresSeek: input.seek(stopIndex)
def __hash__(self): return self.hashCode
def __eq__(self, other): if self is other: return True elif not isinstance(other, LexerActionExecutor): return False else: return self.hashCode == other.hashCode \ and self.lexerActions == other.lexerActions
del Lexerroot/specialists/rel-breeds/manifest.jsonAdded+71
root/specialists/rel-breeds/organ_relation_v2.pyAdded+55
root/specialists/rel-breeds/readers.jsonAdded+6
root/specialists/rel-breeds/relation_panel_v2.jsonAdded+218
root/specialists/rel-breeds/relspec_scorer.pyAdded+25
root/specialists/rel-breeds/verdict_dev.jsonAdded+114
root/specialists/rel-breeds/verdict_heldout.jsonAdded+108
root/specialists/rel-volleyball/manifest.jsonAdded+77
root/specialists/rel-volleyball/organ_relation_v2.pyAdded+55
root/specialists/rel-volleyball/relation_panel_v2.jsonAdded+1073
root/specialists/rel-volleyball/verdict_dev.jsonAdded+114
root/specialists/rel-volleyball/verdict_heldout.jsonAdded+114
root/textbooks/gutenberg/pg10136.txtAdded
root/textbooks/gutenberg/pg12444.txtAdded
root/textbooks/gutenberg/pg13923.txtAdded
root/textbooks/gutenberg/pg15338.txtAdded
root/textbooks/gutenberg/pg21084.txtAdded
root/textbooks/gutenberg/pg26558.txtAdded
root/vendor/antlr4_4_11_1/antlr4/BufferedTokenStream.pyAdded+302
root/vendor/antlr4_4_11_1/antlr4/CommonTokenFactory.pyAdded+61
root/vendor/antlr4_4_11_1/antlr4/CommonTokenStream.pyAdded+87
root/vendor/antlr4_4_11_1/antlr4/FileStream.pyAdded+27
root/vendor/antlr4_4_11_1/antlr4/InputStream.pyAdded+87
root/vendor/antlr4_4_11_1/antlr4/IntervalSet.pyAdded+180
root/vendor/antlr4_4_11_1/antlr4/LL1Analyzer.pyAdded+173
root/vendor/antlr4_4_11_1/antlr4/Lexer.pyAdded+329
root/vendor/antlr4_4_11_1/antlr4/ListTokenSource.pyAdded+144
root/vendor/antlr4_4_11_1/antlr4/Parser.pyAdded+580
root/vendor/antlr4_4_11_1/antlr4/ParserInterpreter.pyAdded+170
root/vendor/antlr4_4_11_1/antlr4/ParserRuleContext.pyAdded+186
root/vendor/antlr4_4_11_1/antlr4/PredictionContext.pyAdded+623
root/vendor/antlr4_4_11_1/antlr4/Recognizer.pyAdded+147
root/vendor/antlr4_4_11_1/antlr4/RuleContext.pyAdded+227
root/vendor/antlr4_4_11_1/antlr4/StdinStream.pyAdded+11
root/vendor/antlr4_4_11_1/antlr4/Token.pyAdded+155
root/vendor/antlr4_4_11_1/antlr4/TokenStreamRewriter.pyAdded+255
root/vendor/antlr4_4_11_1/antlr4/Utils.pyAdded+33
root/vendor/antlr4_4_11_1/antlr4/__init__.pyAdded+21
root/vendor/antlr4_4_11_1/antlr4/_pygrun.pyAdded+171
root/vendor/antlr4_4_11_1/antlr4/atn/ATN.pyAdded+132
root/vendor/antlr4_4_11_1/antlr4/atn/ATNConfig.pyAdded+159
root/vendor/antlr4_4_11_1/antlr4/atn/ATNConfigSet.pyAdded+212
root/vendor/antlr4_4_11_1/antlr4/atn/ATNDeserializationOptions.pyAdded+24
root/vendor/antlr4_4_11_1/antlr4/atn/ATNDeserializer.pyAdded+446
root/vendor/antlr4_4_11_1/antlr4/atn/ATNSimulator.pyAdded+47
root/vendor/antlr4_4_11_1/antlr4/atn/ATNState.pyAdded+264
root/vendor/antlr4_4_11_1/antlr4/atn/ATNType.pyAdded+17
root/vendor/antlr4_4_11_1/antlr4/atn/LexerATNSimulator.pyAdded+570
root/vendor/antlr4_4_11_1/antlr4/atn/LexerAction.pyAdded+298
root/vendor/antlr4_4_11_1/antlr4/atn/LexerActionExecutor.pyAdded+143