diff --git a/scripts/grammar_obligations/_helpers/cases.py b/scripts/grammar_obligations/_helpers/cases.py index a51e132640..87be7d7eef 100644 --- a/scripts/grammar_obligations/_helpers/cases.py +++ b/scripts/grammar_obligations/_helpers/cases.py @@ -49,7 +49,7 @@ WITHDRAWN_FILE, ) from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Draft, Node, ReceiptView, Rendered +from scripts.grammar_obligations.models import DialectConfig, Draft, Node, ReceiptView, Rendered from scripts.grammar_obligations.types import Row @@ -65,6 +65,7 @@ def canonical(value: object) -> str: def family_cases( # noqa: PLR0913 *, + config: DialectConfig, root: Path, evidence: Path, family: str, @@ -74,7 +75,9 @@ def family_cases( # noqa: PLR0913 unpacked: frozenset[str] = frozenset(), ) -> tuple[list[Row], dict[str, set[str]], list[Row], set[str], set[str], set[str]]: """Cases, outcomes, arity cases, extremes, documented SQL, disputed positive obligations.""" - numbered, trees, _, _, arity = family_obligations(root=root, family=family, unpacked=unpacked) + numbered, trees, _, _, arity = family_obligations( + config=config, root=root, family=family, unpacked=unpacked + ) by_sql: dict[str, tuple[str, Rendered, list[str]]] = {} expected: dict[str, set[str]] = {} documented: set[str] = set() @@ -83,7 +86,7 @@ def family_cases( # noqa: PLR0913 undisputed: set[str] = set() conflicts: list[str] = [] for identifier, draft in numbered: - found: list[Rendered] = _rendered(draft=draft, trees=trees, family=family) + found: list[Rendered] = _rendered(config=config, draft=draft, trees=trees, family=family) if not found: raise ObligationError(f"{identifier}: no case could be rendered") for rendered in found: @@ -127,6 +130,7 @@ def family_cases( # noqa: PLR0913 ) if to_derive_one_option_per_case: return family_cases( + config=config, root=root, evidence=evidence, family=family, @@ -316,13 +320,18 @@ def _arity_cases( def _rendered( - *, draft: Draft, trees: dict[str, list[tuple[Node, ...]]], family: str + *, + config: DialectConfig, + draft: Draft, + trees: dict[str, list[tuple[Node, ...]]], + family: str, ) -> list[Rendered]: if draft.spec is None: return [] return submissions( + config=config, trees=trees[draft.form], - style=style_of(family=family, form=draft.form), + style=style_of(config=config, family=family, form=draft.form), spec=draft.spec, depths=draft.depths, ) @@ -527,6 +536,7 @@ def _observed_outcome( def settled_cases( # noqa: PLR0913 *, + config: DialectConfig, root: Path, evidence: Path, family: str, @@ -536,6 +546,7 @@ def settled_cases( # noqa: PLR0913 ) -> tuple[list[Row], list[Row], list[Row]]: """The merged cases with their receipts' stages, unscored arity cases, case marks.""" generated, expected, arity, extremes, documented, disputed_positives = family_cases( + config=config, root=root, evidence=evidence, family=family, @@ -623,6 +634,7 @@ def packet_text(cases: list[Row]) -> str: def family_outputs( # noqa: PLR0913 *, + config: DialectConfig, root: Path, evidence: Path, family: str, @@ -632,6 +644,7 @@ def family_outputs( # noqa: PLR0913 ) -> tuple[list[Row], list[Row], list[tuple[Path, str | None]]]: """One family's cases and arity cases, and each of its files' text (None: no file).""" cases, arity, marked = settled_cases( + config=config, root=root, evidence=evidence, family=family, diff --git a/scripts/grammar_obligations/_helpers/definitions.py b/scripts/grammar_obligations/_helpers/definitions.py index bb92309435..ace117b8fe 100644 --- a/scripts/grammar_obligations/_helpers/definitions.py +++ b/scripts/grammar_obligations/_helpers/definitions.py @@ -17,17 +17,17 @@ OPEN_PAREN, TOKEN_KEYWORD, ) -from scripts.grammar_obligations.models import Node +from scripts.grammar_obligations.models import DialectConfig, Node from scripts.grammar_obligations.types import NodePath as Path def definition_branches( - *, name: str, definitions: dict[str, str] + *, name: str, definitions: dict[str, str], config: DialectConfig ) -> list[tuple[tuple[str, str], str, str]]: """(definition and branch, label, operand taking it) per keyword branch `name` reaches.""" - body: tuple[Node, ...] = parse(definitions[name]) + body: tuple[Node, ...] = parse(production=definitions[name], config=config) expanded: dict[int, tuple[Node, ...]] = _expansions( - nodes=body, definitions=definitions, stack=(name,) + nodes=body, definitions=definitions, stack=(name,), config=config ) found: list[tuple[tuple[str, str], str, str]] = [] for path, owner, choice in _keyword_choices( @@ -46,24 +46,36 @@ def definition_branches( expanded=expanded, definitions=definitions, stack=(name,), + config=config, ) found.append(((owner, render(branch)), label, text)) return found def _expansions( - *, nodes: tuple[Node, ...], definitions: dict[str, str], stack: tuple[str, ...] + *, + nodes: tuple[Node, ...], + definitions: dict[str, str], + stack: tuple[str, ...], + config: DialectConfig, ) -> dict[int, tuple[Node, ...]]: """The parsed definition of each placeholder under `nodes` that names one not on `stack`.""" found: dict[int, tuple[Node, ...]] = {} for node in nodes: for branch in node.branches: - found.update(_expansions(nodes=branch, definitions=definitions, stack=stack)) + found.update( + _expansions(nodes=branch, definitions=definitions, stack=stack, config=config) + ) name: str = placeholder_name(node) if node.kind == NODE_TOKEN and name in definitions and name not in stack: - found[id(node)] = parse(definitions[name]) + found[id(node)] = parse(production=definitions[name], config=config) found.update( - _expansions(nodes=found[id(node)], definitions=definitions, stack=(*stack, name)) + _expansions( + nodes=found[id(node)], + definitions=definitions, + stack=(*stack, name), + config=config, + ) ) return found @@ -109,6 +121,7 @@ def _written( # noqa: PLR0913 expanded: dict[int, tuple[Node, ...]], definitions: dict[str, str], stack: tuple[str, ...], + config: DialectConfig, ) -> str: """`nodes` as grammar text: `choice` as branch `index`, `path` opened, definitions inlined.""" pieces: list[str] = [] @@ -124,6 +137,7 @@ def _written( # noqa: PLR0913 expanded=expanded, definitions=definitions, stack=stack, + config=config, ) ) elif path and node is path[0]: @@ -144,6 +158,7 @@ def _written( # noqa: PLR0913 expanded=expanded, definitions=definitions, stack=(*stack, name) if name else stack, + config=config, ) ) elif node.kind in (NODE_CHOICE, NODE_OPTIONAL): @@ -156,6 +171,7 @@ def _written( # noqa: PLR0913 expanded=expanded, definitions=definitions, stack=stack, + config=config, ) for branch in node.branches ] @@ -164,13 +180,14 @@ def _written( # noqa: PLR0913 elif name in definitions and name not in stack: pieces.append( _written( - nodes=parse(definitions[name]), + nodes=parse(production=definitions[name], config=config), path=(), choice=choice, index=index, expanded=expanded, definitions=definitions, stack=(*stack, name), + config=config, ) ) else: diff --git a/scripts/grammar_obligations/_helpers/derive.py b/scripts/grammar_obligations/_helpers/derive.py index 3e9355680b..7ec706bd0e 100644 --- a/scripts/grammar_obligations/_helpers/derive.py +++ b/scripts/grammar_obligations/_helpers/derive.py @@ -26,16 +26,17 @@ QUOTED_WITHOUT_BLANK, QUOTED_WITHOUT_BLANK_NAMES, ) -from scripts.grammar_obligations.models import Draft, Node, Spec +from scripts.grammar_obligations.models import DialectConfig, Draft, Node, Spec -def derive(*, form: str, grammar: list[str]) -> list[Draft]: +def derive(*, config: DialectConfig, form: str, grammar: list[str]) -> list[Draft]: """Drafts in a fixed order: positive, then per production its parts, then form-wide cases.""" - return derive_trees(form=form, grammar=grammar)[0] + return config.derive_trees(config=config, form=form, grammar=grammar)[0] def derive_trees( *, + config: DialectConfig, form: str, grammar: list[str], unpacked: bool = False, @@ -44,13 +45,13 @@ def derive_trees( """Drafts, parsed productions, skipped argument classes; unpacked gives one case per option.""" if not grammar: return [], [], Counter() - walk: Walk = Walk(form, unpacked=unpacked, definitions=definitions) + walk: Walk = config.walk(form, config=config, unpacked=unpacked, definitions=definitions) note: str = "the documented form with every required part and no optional part" walk.add(kind=KIND_POSITIVE, target="", note=note, spec=walk.spec(action=ACTION_MIN_OPTIONS)) trees: list[tuple[Node, ...]] = [] for index, production in enumerate(grammar): walk.production = index - trees.append(parse(production)) + trees.append(parse(production=production, config=config)) walk.sequence(nodes=trees[-1], where="", top=True) if index and not any(d.spec and d.spec.production == index for d in walk.drafts): walk.add( @@ -78,7 +79,9 @@ def derive_trees( form=form, kind=KIND_IDENTIFIER, target=placeholder, - note=_class_note(label=label, description=description, placeholder=placeholder), + note=config.class_note( + label=label, description=description, placeholder=placeholder + ), anchor=IDENTIFIER_ANCHOR, spec=reserved if label == IDENTIFIER_RESERVED @@ -99,7 +102,7 @@ def derive_trees( return walk.drafts, trees, walk.argument_classes -def _class_note(*, label: str, description: str, placeholder: str) -> str: +def class_note(*, label: str, description: str, placeholder: str) -> str: """The identifier class note, blank-free for names where a blank breaks Snowflake.""" if label == IDENTIFIER_QUOTED and placeholder.strip("<>") in QUOTED_WITHOUT_BLANK_NAMES: return f"{label}: {QUOTED_WITHOUT_BLANK}" diff --git a/scripts/grammar_obligations/_helpers/dialect.py b/scripts/grammar_obligations/_helpers/dialect.py new file mode 100644 index 0000000000..deafa7b942 --- /dev/null +++ b/scripts/grammar_obligations/_helpers/dialect.py @@ -0,0 +1,146 @@ +"""The shared dialect config, and the writes to shared names a dialect must not make.""" + +from __future__ import annotations + +import ast +from pathlib import Path + +from scripts.grammar_obligations._helpers import derive, ids, obligations, render +from scripts.grammar_obligations.classes.renderer import Renderer +from scripts.grammar_obligations.classes.walk import Walk +from scripts.grammar_obligations.constants import ( + BARE_VALUE_CLASS, + CASED_KEYWORD, + CLASS_RULES, + CLAUSE_CALLEES, + FAMILY_STYLES, + FILL_CLASSES, + LEXICAL_WRONG, + LEXICALLY_DISTINCT_WRONG_FILL, + MUTATORS, + ONE_OF_OPTIONS, + QUOTE_MIXED_CASE, + REPEAT_FILLS, + REPEATED_ITEMS, + RESERVED_WORD, + SETATTR, + SHARED_PACKAGE, + TEMPLATE_OPERANDS, + TOKEN, +) +from scripts.grammar_obligations.models import DialectConfig, FormStyle + + +def shared_config() -> DialectConfig: + """The shared tokens, classes, fills, styles and root readers, before any dialect's own.""" + return DialectConfig( + token=TOKEN, + class_rules=CLASS_RULES, + cased_keyword=CASED_KEYWORD, + template_operands=TEMPLATE_OPERANDS, + repeated_items=REPEATED_ITEMS, + fill_classes=FILL_CLASSES, + bare_value_class=BARE_VALUE_CLASS, + clause_callees=CLAUSE_CALLEES, + quote_mixed_case=QUOTE_MIXED_CASE, + one_of_options=ONE_OF_OPTIONS, + repeat_fills=dict(REPEAT_FILLS), + reserved_word=RESERVED_WORD, + lexical_wrong=dict(LEXICAL_WRONG), + lexically_distinct_wrong_fill=dict(LEXICALLY_DISTINCT_WRONG_FILL), + family_styles={family: dict(styles) for family, styles in FAMILY_STYLES.items()}, + walk=Walk, + renderer=Renderer, + class_note=derive.class_note, + derive_trees=derive.derive_trees, + grammar_read=obligations._grammar_read, # noqa: SLF001 + definitions=obligations._definitions, # noqa: SLF001 + suppressions=obligations.suppressions, + suppressed=obligations._suppressed, # noqa: SLF001 + limit_drafts=obligations.limit_drafts, + existing_ids=ids.existing_ids, + style_of=render.style_of, + ) + + +def with_styles( + *, config: DialectConfig, styles: dict[str, dict[str, FormStyle]] +) -> dict[str, dict[str, FormStyle]]: + """The config's family styles with a dialect's own prefix styles added to each family.""" + merged: dict[str, dict[str, FormStyle]] = { + family: dict(found) for family, found in config.family_styles.items() + } + for family, own in styles.items(): + merged.setdefault(family, {}).update(own) + return merged + + +def shared_writes(source: str) -> list[str]: + """Each global statement, and each set, delete or in-place change of a shared package name.""" + tree: ast.Module = ast.parse(source) + shared: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and (node.module or "").startswith(SHARED_PACKAGE): + shared.update(alias.asname or alias.name for alias in node.names) + elif isinstance(node, ast.Import): + shared.update( + (alias.asname or alias.name).split(".")[0] + for alias in node.names + if alias.name.startswith(SHARED_PACKAGE) + ) + return [ + f"{node.lineno}: {ast.unparse(node)}" + for node in ast.walk(tree) + if isinstance(node, ast.stmt | ast.expr) + and (isinstance(node, ast.Global) or not shared.isdisjoint(_written_roots(node))) + ] + + +def _written_roots(node: ast.AST) -> set[str]: + """The name each chain a statement or call writes in place starts from.""" + return {_root(target) for target in _written(node)} + + +def _written(node: ast.AST) -> list[ast.expr]: + """Attribute, item and in-place targets, setattr's object, or what a mutating call changes.""" + if isinstance(node, ast.Assign | ast.Delete): + return [target for target in _unpacked(node.targets) if not isinstance(target, ast.Name)] + if isinstance(node, ast.AnnAssign | ast.For): + return [target for target in _unpacked([node.target]) if not isinstance(target, ast.Name)] + if isinstance(node, ast.AugAssign): + return [node.target] + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): + return node.args[:1] if node.func.id == SETATTR else [] + if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute): + return [node.func.value] if node.func.attr in MUTATORS else [] + return [] + + +def _unpacked(targets: list[ast.expr]) -> list[ast.expr]: + """Each target inside tuple, list and starred targets.""" + found: list[ast.expr] = [] + for target in targets: + if isinstance(target, ast.Tuple | ast.List): + found += _unpacked(target.elts) + elif isinstance(target, ast.Starred): + found += _unpacked([target.value]) + else: + found.append(target) + return found + + +def _root(node: ast.expr) -> str: + """The name an attribute, item or call chain starts from.""" + while isinstance(node, ast.Attribute | ast.Subscript | ast.Call): + node = node.func if isinstance(node, ast.Call) else node.value + return node.id if isinstance(node, ast.Name) else "" + + +def tree_writes(*, root: Path, directory: str) -> dict[str, list[str]]: + """Each module under the directory that writes a shared name, with what it writes.""" + writes: dict[str, list[str]] = {} + for path in sorted((root / directory).rglob("*.py")): + found: list[str] = shared_writes(path.read_text()) + if found: + writes[str(path.relative_to(root))] = found + return writes diff --git a/scripts/grammar_obligations/_helpers/grammar.py b/scripts/grammar_obligations/_helpers/grammar.py index 1501e5439e..f88fc053d0 100644 --- a/scripts/grammar_obligations/_helpers/grammar.py +++ b/scripts/grammar_obligations/_helpers/grammar.py @@ -8,8 +8,6 @@ ASSIGNMENT_SIZE, ASSIGNMENTS, BAR, - CASED_KEYWORD, - CLASS_RULES, CLOSERS, DEFAULT_CLASS, GRAMMAR_DEFINITION, @@ -23,8 +21,6 @@ QUOTED_PLACEHOLDER, SINGLE_QUOTE, TEMPLATE_FILLS, - TEMPLATE_OPERANDS, - TOKEN, TOKEN_BRACKET, TOKEN_ELISION, TOKEN_KEYWORD, @@ -33,30 +29,32 @@ TOKEN_PUNCT, VALUE_TOKENS, ) -from scripts.grammar_obligations.models import Node +from scripts.grammar_obligations.models import DialectConfig, Node -def tokens(production: str) -> list[tuple[str, str]]: +def tokens(*, production: str, config: DialectConfig) -> list[tuple[str, str]]: """(kind, text) pairs of a production; a definition's ` ::=` head is dropped.""" text: str = GRAMMAR_DEFINITION.sub("", production) pairs: list[tuple[str, str]] = [ (match.lastgroup, match.group(match.lastgroup)) - for match in TOKEN.finditer(text) + for match in config.token.finditer(text) if match.lastgroup is not None ] found: list[tuple[str, str]] = [] for index, (kind, word) in enumerate(pairs): named: bool = index + 1 < len(pairs) and pairs[index + 1][1] == NAMED_ARGUMENT - cased: bool = CASED_KEYWORD is not None and CASED_KEYWORD.fullmatch(word) is not None + cased: bool = ( + config.cased_keyword is not None and config.cased_keyword.fullmatch(word) is not None + ) lower: bool = any(char.islower() for char in word) bare: bool = kind == TOKEN_KEYWORD and not named and not cased and lower found.append((TOKEN_PLACEHOLDER if bare else kind, word)) return found -def parse(production: str) -> tuple[Node, ...]: +def parse(*, production: str, config: DialectConfig) -> tuple[Node, ...]: """The top-level sequence of a production. Unbalanced brackets are kept as plain tokens.""" - stream: list[tuple[str, str]] = tokens(production) + stream: list[tuple[str, str]] = tokens(production=production, config=config) sequence, _ = _sequence(stream=stream, start=0, closer="") return sequence @@ -170,18 +168,18 @@ def placeholder_name(node: Node) -> str: return "" -def template_name(node: Node) -> str: +def template_name(*, node: Node, config: DialectConfig) -> str: """Lower-cased unquoted text of a placeholder-built value like `' MINUTE'`; else empty.""" - if not TEMPLATE_OPERANDS or node.kind != NODE_TOKEN or node.token_kind != TOKEN_LITERAL: + if not config.template_operands or node.kind != NODE_TOKEN or node.token_kind != TOKEN_LITERAL: return "" if QUOTED_PLACEHOLDER.fullmatch(node.text) or not PLACEHOLDER_IN_LITERAL.search(node.text): return "" return node.text.strip("'").lower() -def template_alternatives(literal: str) -> list[tuple[str, str]]: +def template_alternatives(*, literal: str, config: DialectConfig) -> list[tuple[str, str]]: """Each branch of a quoted template's choices, with the template written taking that branch.""" - nodes: tuple[Node, ...] = parse(literal.strip(SINGLE_QUOTE)) + nodes: tuple[Node, ...] = parse(production=literal.strip(SINGLE_QUOTE), config=config) found: list[tuple[str, str]] = [] for node in filter(lambda node: node.kind == NODE_CHOICE, nodes): for index, branch in enumerate(node.branches): @@ -204,9 +202,9 @@ def _template_text(*, nodes: tuple[Node, ...], picks: dict[int, int]) -> str: return " ".join(filter(None, words)) -def operand_class(name: str) -> str: +def operand_class(*, name: str, config: DialectConfig) -> str: """The operand class of a placeholder name, by the first matching rule.""" - for pattern, label in CLASS_RULES: + for pattern, label in config.class_rules: if pattern.search(name): return label return DEFAULT_CLASS diff --git a/scripts/grammar_obligations/_helpers/obligations.py b/scripts/grammar_obligations/_helpers/obligations.py index 8b1350fb40..dd83fbf565 100644 --- a/scripts/grammar_obligations/_helpers/obligations.py +++ b/scripts/grammar_obligations/_helpers/obligations.py @@ -9,9 +9,8 @@ from dataclasses import replace from pathlib import Path -from scripts.grammar_obligations._helpers.derive import derive_trees -from scripts.grammar_obligations._helpers.ids import assign, existing_ids -from scripts.grammar_obligations._helpers.render import style_of, submissions +from scripts.grammar_obligations._helpers.ids import assign +from scripts.grammar_obligations._helpers.render import submissions from scripts.grammar_obligations.constants import ( ACTION_HAND, ARGUMENT_CLASS_REASON, @@ -32,14 +31,13 @@ KIND_OPTION_PRESENT, KIND_PROSE, LATER_ERROR_STAGES, - LEXICAL_WRONG, OBSERVED_NEIGHBOUR_REASON, PAIR_SIZE, REJECTING, STATUS_CATALOGUED, ) from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Draft, Node, Rendered, Spec +from scripts.grammar_obligations.models import DialectConfig, Draft, Node, Rendered, Spec from scripts.grammar_obligations.types import Row @@ -146,7 +144,7 @@ def obligation_rows(numbered: list[tuple[str, Draft]]) -> list[Row]: def family_obligations( - *, root: Path, family: str, unpacked: frozenset[str] = frozenset() + *, config: DialectConfig, root: Path, family: str, unpacked: frozenset[str] = frozenset() ) -> tuple[ list[tuple[str, Draft]], dict[str, list[tuple[Node, ...]]], list[Row], list[Row], list[Row] ]: @@ -165,36 +163,41 @@ def family_obligations( trees: dict[str, list[tuple[Node, ...]]] = {} argument_classes: Counter[str] = Counter() for form in forms: - found, trees[str(form["id"])], skipped = derive_trees( + found, trees[str(form["id"])], skipped = config.derive_trees( + config=config, form=str(form["id"]), - grammar=_grammar_read(form=form, readings=readings), + grammar=config.grammar_read(form=form, readings=readings), unpacked=form["id"] in unpacked, - definitions=_definitions( + definitions=config.definitions( rows=document.get("definition", []), form=form, readings=rereadings ), ) drafts += found argument_classes.update(skipped) - suppressed: list[Row] = suppressions(path=root / "limits.toml") - limits: list[Draft] = limit_drafts( + suppressed: list[Row] = config.suppressions(path=root / "limits.toml") + limits: list[Draft] = config.limit_drafts( path=root / "limits.toml", family=family, forms={str(form["id"]) for form in forms} ) written: set[tuple[str, str, str, str]] = {(d.form, d.kind, d.target, d.note) for d in limits} drafts = [ d for d in drafts - if not _suppressed(draft=d, rows=suppressed) + if not config.suppressed(draft=d, rows=suppressed) and (d.form, d.kind, d.target, d.note) not in written ] drafts += limits drafts.sort(key=lambda draft: draft.form) - drafts, withdrawn = _without_coincident_negatives(drafts=drafts, trees=trees, family=family) - drafts, arity = _without_arity(drafts=drafts, trees=trees, family=family) + drafts, withdrawn = _without_coincident_negatives( + config=config, drafts=drafts, trees=trees, family=family + ) + drafts, arity = _without_arity(config=config, drafts=drafts, trees=trees, family=family) path: Path = root / "obligations" / f"{family}.toml" classes: list[Row] = [ { "class": label, - "derived_negative": f"{LEXICAL_WRONG[label]} in place of an operand of class {label}", + "derived_negative": ( + f"{config.lexical_wrong[label]} in place of an operand of class {label}" + ), "count": count, "reason": ARGUMENT_CLASS_REASON, } @@ -209,18 +212,24 @@ def family_obligations( "reason": ARITY_REASON, } ) - numbered: list[tuple[str, Draft]] = assign(drafts=drafts, kept=existing_ids(path)) + numbered: list[tuple[str, Draft]] = assign(drafts=drafts, kept=config.existing_ids(path)) return numbered, trees, withdrawn, classes, arity def _without_arity( - *, drafts: list[Draft], trees: dict[str, list[tuple[Node, ...]]], family: str + *, + config: DialectConfig, + drafts: list[Draft], + trees: dict[str, list[tuple[Node, ...]]], + family: str, ) -> tuple[list[Draft], list[Row]]: """Drafts minus omissions whose SQL is still a well-formed call, with each such case.""" kept: list[Draft] = [] arity: list[Row] = [] for draft in drafts: - found: list[Rendered] = _draft_submissions(draft=draft, trees=trees, family=family) + found: list[Rendered] = _draft_submissions( + config=config, draft=draft, trees=trees, family=family + ) if not draft.arity or any(DANGLING_CALL.search(case.sql) for case in found): kept.append(draft) continue @@ -238,13 +247,20 @@ def _without_arity( def _without_coincident_negatives( - *, drafts: list[Draft], trees: dict[str, list[tuple[Node, ...]]], family: str + *, + config: DialectConfig, + drafts: list[Draft], + trees: dict[str, list[tuple[Node, ...]]], + family: str, ) -> tuple[list[Draft], list[Row]]: """Drafts minus rejections whose SQL a form also renders as valid, with each withdrawal.""" accepted: dict[str, Draft] = {} observed: dict[str, Draft] = {} rendered: list[tuple[Draft, list[Rendered]]] = _refused_positives_observed( - [(d, _draft_submissions(draft=d, trees=trees, family=family)) for d in drafts] + [ + (d, _draft_submissions(config=config, draft=d, trees=trees, family=family)) + for d in drafts + ] ) for draft, found in rendered: for case in found: @@ -338,13 +354,18 @@ def _syntax_key(sql: str) -> str: def _draft_submissions( - *, draft: Draft, trees: dict[str, list[tuple[Node, ...]]], family: str + *, + config: DialectConfig, + draft: Draft, + trees: dict[str, list[tuple[Node, ...]]], + family: str, ) -> list[Rendered]: if draft.spec is None or draft.form not in trees: return [] return submissions( + config=config, trees=trees[draft.form], - style=style_of(family=family, form=draft.form), + style=config.style_of(config=config, family=family, form=draft.form), spec=draft.spec, depths=draft.depths, ) diff --git a/scripts/grammar_obligations/_helpers/render.py b/scripts/grammar_obligations/_helpers/render.py index 022b22071c..17b7cd7b6d 100644 --- a/scripts/grammar_obligations/_helpers/render.py +++ b/scripts/grammar_obligations/_helpers/render.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections.abc import Mapping from dataclasses import replace from scripts.grammar_obligations._helpers.qualify import qualified_references @@ -17,21 +18,24 @@ EXPECT_ACCEPT, EXPECT_OBSERVE, EXPECT_REJECT, - FAMILY_STYLES, SCHEMA_QUALIFIER, SCHEMA_REFERENCES, ) from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import FormStyle, Node, Rendered, Spec +from scripts.grammar_obligations.models import DialectConfig, FormStyle, Node, Rendered, Spec def submissions( - *, trees: list[tuple[Node, ...]], style: FormStyle, spec: Spec, depths: tuple[int, ...] + *, + config: DialectConfig, + trees: list[tuple[Node, ...]], + style: FormStyle, + spec: Spec, + depths: tuple[int, ...], ) -> list[Rendered]: """A case spec's submissions; empty properties, clauses and `= ( )` lists observed if asked.""" - rendered: list[Rendered] = Renderer(trees=trees, style=style).submissions( - spec=spec, depths=depths - ) + renderer: Renderer = config.renderer(trees=trees, style=style, config=config) + rendered: list[Rendered] = renderer.submissions(spec=spec, depths=depths) repeating: list[str] = [ f"{r.sql} repeats {r.repeats}" for r in rendered if r.expect == EXPECT_ACCEPT and r.repeats ] @@ -62,9 +66,9 @@ def submissions( ] -def style_of(*, family: str, form: str) -> FormStyle: +def style_of(*, config: DialectConfig, family: str, form: str) -> FormStyle: """The longest matching form-id prefix style of the family.""" - styles: dict[str, FormStyle] = FAMILY_STYLES[family] + styles: Mapping[str, FormStyle] = config.family_styles[family] best: str = max((prefix for prefix in styles if form.startswith(prefix)), key=len) if form not in DEFINE_QUALIFIED_NAMES: return styles[best] diff --git a/scripts/grammar_obligations/_helpers/shared_state.py b/scripts/grammar_obligations/_helpers/shared_state.py deleted file mode 100644 index a239c5bd5a..0000000000 --- a/scripts/grammar_obligations/_helpers/shared_state.py +++ /dev/null @@ -1,29 +0,0 @@ -"""The shared modules a dialect's install() sets, restored when the dialect is done with them.""" - -from __future__ import annotations - -from collections.abc import Generator -from contextlib import contextmanager - -from scripts.grammar_obligations.classes.shared_modules import SharedModules -from scripts.grammar_obligations.types import ModuleState - -_PRISTINE: ModuleState = SharedModules.snapshot() - - -@contextmanager -def restored_shared_state() -> Generator[None]: - """Whatever runs inside leaves the shared modules as it found them.""" - state: ModuleState = SharedModules.snapshot() - try: - yield - finally: - SharedModules.restore(state) - - -@contextmanager -def isolated_shared_state() -> Generator[None]: - """The shared modules as they were imported, whatever ran before, and as found on exit.""" - with restored_shared_state(): - SharedModules.restore(_PRISTINE) - yield diff --git a/scripts/grammar_obligations/classes/renderer.py b/scripts/grammar_obligations/classes/renderer.py index 89cdb08d16..1520ecb30a 100644 --- a/scripts/grammar_obligations/classes/renderer.py +++ b/scripts/grammar_obligations/classes/renderer.py @@ -57,16 +57,12 @@ NODE_OPTIONAL, NODE_TOKEN, NUMBERED_FILL, - ONE_OF_OPTIONS, OPEN_PAREN, OPENED, PROCEDURE_WRAPPER, QUERY_CLASS, - QUOTE_MIXED_CASE, QUOTED_WITHOUT_BLANK_NAMES, - REPEAT_FILLS, REPEAT_SLOT, - RESERVED_WORD, SET_ANCHOR_PREFERENCE, SET_KEYWORDS, SINGLE_CHARACTER_LITERAL_LENGTH, @@ -82,15 +78,26 @@ TOKEN_PLACEHOLDER, TOKEN_PUNCT, ) -from scripts.grammar_obligations.models import Choices, FormStyle, Node, Rendered, Spec +from scripts.grammar_obligations.models import ( + Choices, + DialectConfig, + FormStyle, + Node, + Rendered, + Spec, +) class Renderer: """Renders the cases of one form.""" - def __init__(self, *, trees: list[tuple[Node, ...]], style: FormStyle) -> None: + def __init__( + self, *, trees: list[tuple[Node, ...]], style: FormStyle, config: DialectConfig + ) -> None: self.trees: list[tuple[Node, ...]] = trees self.style: FormStyle = style + self.config: DialectConfig = config + self.reserved_word: str = config.reserved_word self._used: dict[str, list[str]] = {} self._keywords: list[str] = [] self._last_choice: tuple[Node, int, list[str]] | None = None @@ -130,8 +137,8 @@ def submissions(self, *, spec: Spec, depths: tuple[int, ...] = ()) -> list[Rende expect, ) for word, expect in ( - (RESERVED_WORD, EXPECT_REJECT), - (f'"{RESERVED_WORD}"', EXPECT_ACCEPT), + (self.reserved_word, EXPECT_REJECT), + (f'"{self.reserved_word}"', EXPECT_ACCEPT), ) ] text: str = self.text(production=spec.production, choices=self._choices(spec)) @@ -148,7 +155,7 @@ def wrap(self, text: str) -> str: opened: str = "".join( f"OPEN {name} ; " for name in dict.fromkeys(self._used.get(self.style.opens, [])) - if name != RESERVED_WORD + if name != self.reserved_word ) if self.style.embedded: text = text.rstrip().removesuffix(STATEMENT_TERMINATOR).rstrip() @@ -175,7 +182,8 @@ def text(self, *, production: int, choices: Choices) -> str: staged: str = _stage_glued(GLUED_INFIX_LEFT.sub("!", glued)) keywords: set[str] = set(self._keywords) return STAGE_KEYWORD.sub( - lambda m: f"{m[1]} {m[2]}" if m[2] in keywords - {RESERVED_WORD} else m[0], staged + lambda m: f"{m[1]} {m[2]}" if m[2] in keywords - {self.reserved_word} else m[0], + staged, ) def _declarations(self) -> str: @@ -184,7 +192,7 @@ def _declarations(self) -> str: seen: set[str] = set() for name, template in self.style.uses.items(): for used in self._used.get(name, []): - if used in seen or used == RESERVED_WORD or used in BUILTIN_NAMES: + if used in seen or used == self.reserved_word or used in BUILTIN_NAMES: continue seen.add(used) parts.append(f"{template.replace('{}', used)} ;") @@ -363,10 +371,12 @@ def _replaced(self, *, node: Node, choices: Choices) -> list[str]: """A replaced operand's text, or an expanded one's grammar rendered in its place.""" key: int = id(node) if key in choices.expand: - return self._sequence(nodes=parse(choices.expand[key]), choices=Choices()) + return self._sequence( + nodes=parse(production=choices.expand[key], config=self.config), choices=Choices() + ) text: str = choices.replace[key] name: str = placeholder_name(node) - if text in (RESERVED_WORD, f'"{RESERVED_WORD}"'): + if text in (self.reserved_word, f'"{self.reserved_word}"'): self._used.setdefault(name, []).append(text) elif name: self._token(node=node, choices=Choices()) @@ -442,8 +452,7 @@ def _optional( return [*rendered, LIST_SEPARATOR, *copied] return rendered - @staticmethod - def _one_option(*, nodes: tuple[Node, ...], choices: Choices) -> Choices: + def _one_option(self, *, nodes: tuple[Node, ...], choices: Choices) -> Choices: """Choices writing the first option when `nodes` hold only unwritten options.""" options: list[Node] = [node for node in nodes if not is_pure_elision(node)] while len(options) == 1 and options[0].kind == NODE_CHOICE: @@ -451,7 +460,7 @@ def _one_option(*, nodes: tuple[Node, ...], choices: Choices) -> Choices: break options = [node for node in options[0].branches[0] if not is_pure_elision(node)] if ( - not ONE_OF_OPTIONS + not self.config.one_of_options or choices.full or not options or any(node.kind != NODE_OPTIONAL for node in options) @@ -549,7 +558,7 @@ def _next_copy(self, text: str) -> str: def _repeat(self, text: str) -> str: """A copied list item, continued with its REPEAT_FILLS value when one is declared.""" - for (name, first), second in REPEAT_FILLS.items(): + for (name, first), second in self.config.repeat_fills.items(): if first == text and text in self._used.get(name, []): return second return text @@ -567,13 +576,13 @@ def _token(self, *, node: Node, choices: Choices, dollar_quoted: bool = False) - fill: str = self.style.fills.get(name) or NAME_FILL.get(name) or "" if node.token_kind == TOKEN_LITERAL and fill and not fill.startswith("'"): fill = "" - label: str = operand_class(name) + label: str = operand_class(name=name, config=self.config) if not fill: fill = CLASS_FILL.get(STRING_CLASS if node.token_kind == TOKEN_LITERAL else label, "v1") if self._used.get(name): - fill = REPEAT_FILLS.get((name, fill), fill) + fill = self.config.repeat_fills.get((name, fill), fill) if choices.quote == name and node.token_kind == TOKEN_PLACEHOLDER: - if QUOTE_MIXED_CASE and not any(char.islower() for char in fill): + if self.config.quote_mixed_case and not any(char.islower() for char in fill): fill = fill.lower() fill = f'"{fill}Q"' if name in QUOTED_WITHOUT_BLANK_NAMES else f'"{fill} Q"' prefix: str = self.style.qualify.get(name, "") diff --git a/scripts/grammar_obligations/classes/shared_modules.py b/scripts/grammar_obligations/classes/shared_modules.py deleted file mode 100644 index bb931ab28c..0000000000 --- a/scripts/grammar_obligations/classes/shared_modules.py +++ /dev/null @@ -1,100 +0,0 @@ -"""The shared grammar-obligations modules and classes, with all they hold, saved and put back.""" - -from __future__ import annotations - -from copy import copy -from dataclasses import fields, is_dataclass -from types import ModuleType -from typing import Any - -from scripts.grammar_obligations import constants, models -from scripts.grammar_obligations._helpers import ( - cases, - definitions, - derive, - elisions, - grammar, - ids, - obligations, - qualify, - render, -) -from scripts.grammar_obligations.classes import renderer, walk -from scripts.grammar_obligations.types import Container, ModuleState - - -class SharedModules: - """What a dialect's install() sets on the shared modules and classes, saved and restored.""" - - @staticmethod - def snapshot() -> ModuleState: - """Each shared module's and class's names, and every dict, list and set they reach.""" - names: dict[Any, dict[str, Any]] = {} - for module in SharedModules._modules(): - names[module] = SharedModules._names(module) - names.update( - {kind: SharedModules._names(kind) for kind in SharedModules._classes(module)} - ) - contents: dict[int, tuple[Container, Container]] = {} - pending: list[Any] = [] - for saved in names.values(): - pending += saved.values() - while pending: - value: Any = pending.pop() - if isinstance(value, (dict, list, set)) and id(value) not in contents: - contents[id(value)] = (value, copy(value)) - pending += [*value.keys(), *value.values()] if isinstance(value, dict) else value - if isinstance(value, (tuple, frozenset)): - pending += value - if is_dataclass(value) and not isinstance(value, type): - pending += [getattr(value, field.name) for field in fields(value)] - return names, contents - - @staticmethod - def restore(state: ModuleState) -> None: - """Put each module's and class's names back, then each container's contents, in place.""" - names, contents = state - for owner, saved in names.items(): - for name in set(SharedModules._names(owner)) - set(saved): - delattr(owner, name) - for name, value in saved.items(): - setattr(owner, name, value) - for value, items in contents.values(): - value.clear() - if isinstance(value, list): - value.extend(items) - else: - value.update(items) - - @staticmethod - def _modules() -> tuple[ModuleType, ...]: - """Every module of the shared package a dialect's install() may set.""" - return ( - constants, - models, - cases, - definitions, - derive, - elisions, - grammar, - ids, - obligations, - qualify, - render, - renderer, - walk, - ) - - @staticmethod - def _classes(module: ModuleType) -> list[type]: - """The classes a module defines itself.""" - return [ - value - for value in vars(module).values() - if isinstance(value, type) and value.__module__ == module.__name__ - ] - - @staticmethod - def _names(owner: Any) -> dict[str, Any]: - """A module's or class's own names and their values, without its dunder entries.""" - return {name: value for name, value in vars(owner).items() if not name.startswith("__")} diff --git a/scripts/grammar_obligations/classes/walk.py b/scripts/grammar_obligations/classes/walk.py index 884a51f5cb..592ffe744e 100644 --- a/scripts/grammar_obligations/classes/walk.py +++ b/scripts/grammar_obligations/classes/walk.py @@ -3,6 +3,7 @@ from __future__ import annotations from collections import Counter +from collections.abc import Mapping from dataclasses import replace from scripts.grammar_obligations._helpers.definitions import definition_branches @@ -27,10 +28,8 @@ ACTION_RESERVED_WORD, ARGUMENT_STARTS, ARROWS, - BARE_VALUE_CLASS, CALL_SEPARATORS, CALLEE_STARTS, - CLAUSE_CALLEES, CLOSE_PAREN, COMMAND_FAMILIES, COMMAND_NON_CALL_KEYWORDS, @@ -38,8 +37,6 @@ EXPECT_OBSERVE, EXPECT_REJECT, EXPRESSION_ARGUMENT_FAMILIES, - FAMILY_STYLES, - FILL_CLASSES, IDENTIFIER_CLASS, KIND_ALTERNATIVE, KIND_NEGATIVE, @@ -47,8 +44,6 @@ KIND_OPERAND_MISSING, KIND_OPTION_ABSENT, KIND_OPTION_PRESENT, - LEXICAL_WRONG, - LEXICALLY_DISTINCT_WRONG_FILL, LIST_SEPARATOR, NAME_FILL, NESTED_CLASSES, @@ -62,7 +57,6 @@ OPTION_ASSIGNMENTS, PARENS, PATH_SEPARATORS, - REPEATED_ITEMS, SINGLE_QUOTE, STRING_CLASS, SUBGRAMMAR_CLASS, @@ -77,16 +71,22 @@ TOP_LEVEL_FAMILIES, UNPACKED_FORMS, ) -from scripts.grammar_obligations.models import Draft, FormStyle, Node, Spec +from scripts.grammar_obligations.models import DialectConfig, Draft, FormStyle, Node, Spec class Walk: """Collects drafts for one form while walking its grammar trees.""" def __init__( - self, form: str, *, unpacked: bool = False, definitions: dict[str, str] | None = None + self, + form: str, + *, + config: DialectConfig, + unpacked: bool = False, + definitions: dict[str, str] | None = None, ) -> None: self.form: str = form + self.config: DialectConfig = config self.definitions: dict[str, str] = definitions or {} self.definition_branches: set[tuple[str, str]] = set() self.unpacked: bool = unpacked or form in UNPACKED_FORMS @@ -237,7 +237,7 @@ def _call_argument(self) -> bool: return ( self.expression_arguments and bool(self.callees) - and self.callees[-1] not in CLAUSE_CALLEES + and self.callees[-1] not in self.config.clause_callees and self.callees[-1][:1].isalpha() and self.previous in CALL_SEPARATORS ) @@ -263,14 +263,14 @@ def _droppable(node: Node) -> bool: def token(self, *, node: Node, where: str, omission_is_absence: bool) -> None: """Operand drafts; a lone operand of an option or branch gets no missing-operand case.""" - name: str = placeholder_name(node) or template_name(node) + name: str = placeholder_name(node) or template_name(node=node, config=self.config) if not name: return - label: str = STRING_CLASS if node.token_kind == TOKEN_LITERAL else operand_class(name) - if FILL_CLASSES and self._string_fill(name): + label: str = STRING_CLASS if node.token_kind == TOKEN_LITERAL else self.operand_class(name) + if self.config.fill_classes and self._string_fill(name): label = STRING_CLASS - if BARE_VALUE_CLASS and self._bare_value(node): - label = BARE_VALUE_CLASS + if self.config.bare_value_class and self._bare_value(node): + label = self.config.bare_value_class self.classes.add(label) suffix: str = f" in {where}" if where else "" if label == IDENTIFIER_CLASS: @@ -303,31 +303,31 @@ def token(self, *, node: Node, where: str, omission_is_absence: bool) -> None: self.add( kind=KIND_OPERAND_CLASS, target=target, note=f"a valid {label}", spec=self.valid() ) - if label in LEXICAL_WRONG and self._whole_argument(): + if label in self.config.lexical_wrong and self._whole_argument(): self.argument_classes[label] += 1 - elif label in LEXICAL_WRONG: + elif label in self.config.lexical_wrong: wrong: Spec = self._unsure( spec=self.reject( action=ACTION_REPLACE_NODE, node=node, - payload=LEXICALLY_DISTINCT_WRONG_FILL[label], + payload=self.config.lexically_distinct_wrong_fill[label], ), after=OPTION_ASSIGNMENTS, ) self.add( kind=KIND_NEGATIVE, target=target, - note=f"{LEXICAL_WRONG[label]} in place of {node.text}", + note=f"{self.config.lexical_wrong[label]} in place of {node.text}", spec=replace(wrong, expect=EXPECT_OBSERVE) if label in OBSERVED_WRONG else wrong, ) - if template_name(node): + if template_name(node=node, config=self.config): self._template_alternatives(node=node, suffix=suffix) if name in self.definitions: self._definition_alternatives(node=node, name=name, suffix=suffix) def _template_alternatives(self, *, node: Node, suffix: str) -> None: """One case per alternative written inside a quoted template, such as `'60 hours'`.""" - for branch, text in template_alternatives(node.text): + for branch, text in template_alternatives(literal=node.text, config=self.config): self.add( kind=KIND_ALTERNATIVE, target=self.target(text=f"{node.text}{suffix}", tail=f" → {branch}"), @@ -337,7 +337,9 @@ def _template_alternatives(self, *, node: Node, suffix: str) -> None: def _definition_alternatives(self, *, node: Node, name: str, suffix: str) -> None: """One case per keyword branch inside the operand's definition, once per form.""" - for key, label, text in definition_branches(name=name, definitions=self.definitions): + for key, label, text in definition_branches( + name=name, definitions=self.definitions, config=self.config + ): if key in self.definition_branches: continue self.definition_branches.add(key) @@ -359,11 +361,15 @@ def _bare_value(self, node: Node) -> bool: def _string_fill(self, name: str) -> bool: """Whether the family fills the operand `name` with a quoted string, whatever its name.""" family: str = self.form.split(".")[1] - styles: dict[str, FormStyle] = FAMILY_STYLES.get(family, {}) + styles: Mapping[str, FormStyle] = self.config.family_styles.get(family, {}) prefixes: list[str] = [prefix for prefix in styles if self.form.startswith(prefix)] fills: dict[str, str] = styles[max(prefixes, key=len)].fills if prefixes else {} return (fills.get(name) or NAME_FILL.get(name) or "").startswith(SINGLE_QUOTE) + def operand_class(self, name: str) -> str: + """The operand class of the placeholder `name` in this form.""" + return operand_class(name=name, config=self.config) + def valid(self) -> Spec: """The packed positive case that contains the current position; a list item's own case.""" if self.path and (self.form in UNPACKED_FORMS or self.repeating): @@ -409,7 +415,7 @@ def optional( ) if len(node.branches) > 1: self._alternatives(node=node, text=text) - if repeated and not REPEATED_ITEMS: + if repeated and not self.config.repeated_items: return [present] outer: frozenset[int] = self.path self.path = outer | {id(node)} | continued diff --git a/scripts/grammar_obligations/constants.py b/scripts/grammar_obligations/constants.py index 7460329233..81b9db67d9 100644 --- a/scripts/grammar_obligations/constants.py +++ b/scripts/grammar_obligations/constants.py @@ -3,6 +3,8 @@ from __future__ import annotations import re +from collections.abc import Mapping +from types import MappingProxyType from scripts.grammar_obligations.models import FormStyle @@ -163,27 +165,31 @@ STATEMENT_CLASS: str = "statement" -LEXICALLY_DISTINCT_WRONG_FILL: dict[str, str] = { - "identifier": "'v1'", - "integer_literal": "'x'", - "string_literal": "m1", - "data_type": "'INT'", - "object_kind": "'TABLE'", - "word": "'v1'", - "statement": "1", - "query": "1", -} +LEXICALLY_DISTINCT_WRONG_FILL: Mapping[str, str] = MappingProxyType( + { + "identifier": "'v1'", + "integer_literal": "'x'", + "string_literal": "m1", + "data_type": "'INT'", + "object_kind": "'TABLE'", + "word": "'v1'", + "statement": "1", + "query": "1", + } +) -LEXICAL_WRONG: dict[str, str] = { - "identifier": "a string literal", - "integer_literal": "a string literal", - "string_literal": "an unquoted identifier", - "data_type": "a string literal", - "object_kind": "a string literal", - "word": "a string literal", - "statement": "a bare literal", - "query": "a bare literal", -} +LEXICAL_WRONG: Mapping[str, str] = MappingProxyType( + { + "identifier": "a string literal", + "integer_literal": "a string literal", + "string_literal": "an unquoted identifier", + "data_type": "a string literal", + "object_kind": "a string literal", + "word": "a string literal", + "statement": "a bare literal", + "query": "a bare literal", + } +) OBSERVED_WRONG: frozenset[str] = frozenset({"string_literal"}) @@ -1475,13 +1481,15 @@ "end_column": "v1", } -REPEAT_FILLS: dict[tuple[str, str], str] = { - ("integration_type_name", "SECURITY INTEGRATIONS"): "API INTEGRATIONS", - ("object_type", "DATABASES"): "SHARES", - ("type", "DATABASES"): "DYNAMIC_TABLES", - ("session_parameter", "LOCK_TIMEOUT"): "STATEMENT_TIMEOUT_IN_SECONDS", - ("task_name", "p1"): "p2", -} +REPEAT_FILLS: Mapping[tuple[str, str], str] = MappingProxyType( + { + ("integration_type_name", "SECURITY INTEGRATIONS"): "API INTEGRATIONS", + ("object_type", "DATABASES"): "SHARES", + ("type", "DATABASES"): "DYNAMIC_TABLES", + ("session_parameter", "LOCK_TIMEOUT"): "STATEMENT_TIMEOUT_IN_SECONDS", + ("task_name", "p1"): "p2", + } +) ALERT_PAGES: tuple[str, ...] = ("sf.ddl.create-alert", "sf.ddl.alter-alert") @@ -1731,7 +1739,7 @@ "sf.ddl.create-event-routing-table", ) -FAMILY_STYLES: dict[str, dict[str, FormStyle]] = { +FAMILY_STYLE_TABLES: dict[str, dict[str, FormStyle]] = { "scripting": SCRIPTING_SELF_DECLARING_BLOCKS, "query": QUERY_STYLES, "expressions": EXPRESSIONS_STYLES, @@ -1862,6 +1870,10 @@ }, } +FAMILY_STYLES: Mapping[str, Mapping[str, FormStyle]] = MappingProxyType( + {family: MappingProxyType(dict(styles)) for family, styles in FAMILY_STYLE_TABLES.items()} +) + SCHEMA_QUALIFIER: str = "d1.s1." DATABASE_QUALIFIER: str = "d1." @@ -1939,3 +1951,14 @@ EQUALS_TOKEN: str = "=" DOT_TOKEN: str = "." + +SHARED_PACKAGE: str = "scripts.grammar_obligations" +SETATTR: str = "setattr" +MUTATORS: frozenset[str] = frozenset( + { + *("update", "setdefault", "append", "extend", "add", "insert", "sort", "reverse"), + *("pop", "popitem", "clear", "remove", "discard"), + *("difference_update", "intersection_update", "symmetric_difference_update"), + *("__setitem__", "__delitem__", "__ior__", "__iadd__", "__isub__", "__iand__"), + } +) diff --git a/scripts/grammar_obligations/models.py b/scripts/grammar_obligations/models.py index f5ed9dc050..6fcb2b93dd 100644 --- a/scripts/grammar_obligations/models.py +++ b/scripts/grammar_obligations/models.py @@ -2,7 +2,12 @@ from __future__ import annotations +import re +from collections.abc import Callable, Mapping from dataclasses import dataclass, field +from typing import Any + +from scripts.grammar_obligations.types import RendererClass, WalkClass @dataclass(frozen=True) @@ -107,3 +112,35 @@ class Choices: drop: frozenset[int] = frozenset() quote: str = "" absent: int = 0 + + +@dataclass(frozen=True) +class DialectConfig: + """How one dialect reads its grammar, classes its operands, writes cases and reads its root.""" + + token: re.Pattern[str] + class_rules: tuple[tuple[re.Pattern[str], str], ...] + cased_keyword: re.Pattern[str] | None + template_operands: bool + repeated_items: bool + fill_classes: bool + bare_value_class: str + clause_callees: frozenset[str] + quote_mixed_case: bool + one_of_options: bool + repeat_fills: Mapping[tuple[str, str], str] + reserved_word: str + lexical_wrong: Mapping[str, str] + lexically_distinct_wrong_fill: Mapping[str, str] + family_styles: Mapping[str, Mapping[str, FormStyle]] + walk: WalkClass + renderer: RendererClass + class_note: Callable[..., str] + derive_trees: Callable[..., Any] + grammar_read: Callable[..., list[str]] + definitions: Callable[..., dict[str, str]] + suppressions: Callable[..., list[dict[str, Any]]] + suppressed: Callable[..., bool] + limit_drafts: Callable[..., list[Draft]] + existing_ids: Callable[..., dict[tuple[str, str, str, str, str], str]] + style_of: Callable[..., FormStyle] diff --git a/scripts/grammar_obligations/types.py b/scripts/grammar_obligations/types.py index d0ab4e6ba4..9210e95572 100644 --- a/scripts/grammar_obligations/types.py +++ b/scripts/grammar_obligations/types.py @@ -2,10 +2,14 @@ from __future__ import annotations -from typing import Any +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from scripts.grammar_obligations.classes.renderer import Renderer + from scripts.grammar_obligations.classes.walk import Walk type Row = dict[str, Any] type Key = tuple[str, str, str, str, str] type NodePath = tuple[Any, ...] -type Container = dict[Any, Any] | list[Any] | set[Any] -type ModuleState = tuple[dict[Any, dict[str, Any]], dict[int, tuple[Container, Container]]] +type WalkClass = type[Walk] +type RendererClass = type[Renderer] diff --git a/scripts/syntax_obligations_bigquery/_helpers/adapt.py b/scripts/syntax_obligations_bigquery/_helpers/adapt.py index 64edd484b0..75d6e5b935 100644 --- a/scripts/syntax_obligations_bigquery/_helpers/adapt.py +++ b/scripts/syntax_obligations_bigquery/_helpers/adapt.py @@ -2,6 +2,7 @@ from __future__ import annotations +import dataclasses import json import re import tomllib @@ -10,11 +11,12 @@ from pathlib import Path from scripts.grammar_obligations import constants as shared +from scripts.grammar_obligations._helpers import derive, ids, obligations from scripts.grammar_obligations._helpers import grammar as shared_grammar -from scripts.grammar_obligations._helpers import ids, obligations +from scripts.grammar_obligations._helpers.dialect import shared_config, with_styles from scripts.grammar_obligations.constants import ACTION_HAND, HAND_CASE_KEYS, PAIR_SIZE from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Draft, FormStyle, Node, Spec +from scripts.grammar_obligations.models import DialectConfig, Draft, FormStyle, Node, Spec from scripts.grammar_obligations.types import Key, Row from scripts.syntax_obligations_bigquery.classes.withdrawals import Withdrawals from scripts.syntax_obligations_bigquery.constants import ( @@ -51,10 +53,6 @@ ) _shared_existing_ids: Callable[[Path], dict[Key, str]] = ids.existing_ids -_shared_class_rules: tuple[tuple[re.Pattern[str], str], ...] = shared_grammar.CLASS_RULES -_shared_derive_trees: Callable[..., tuple[list[Draft], list[tuple[Node, ...]], Counter[str]]] = ( - obligations.derive_trees -) _shared_suppressions: Callable[..., list[Row]] = obligations.suppressions _shared_suppressed: Callable[..., bool] = obligations._suppressed # noqa: SLF001 _shared_definitions: Callable[..., dict[str, str]] = obligations._definitions # noqa: SLF001 @@ -231,27 +229,34 @@ def _scoped_class_rules(*, form: str) -> tuple[tuple[re.Pattern[str], str], ...] def bq_derive_trees( *, + config: DialectConfig, form: str, grammar: list[str], unpacked: bool = False, definitions: dict[str, str] | None = None, ) -> tuple[list[Draft], list[tuple[Node, ...]], Counter[str]]: """The shared derivation, with the class rules of the form's FORM_CLASS_RULES entries first.""" - general: tuple[tuple[re.Pattern[str], str], ...] = shared_grammar.CLASS_RULES scoped: tuple[tuple[re.Pattern[str], str], ...] = _scoped_class_rules(form=form) - shared_grammar.CLASS_RULES = (*scoped, *general) - try: - drafts, trees, skipped = _shared_derive_trees( - form=form, grammar=grammar, unpacked=unpacked, definitions=definitions - ) - finally: - shared_grammar.CLASS_RULES = general - drafts, trees = _with_no_over_draft(form=form, grammar=grammar, drafts=drafts, trees=trees) + drafts, trees, skipped = derive.derive_trees( + config=dataclasses.replace(config, class_rules=(*scoped, *config.class_rules)), + form=form, + grammar=grammar, + unpacked=unpacked, + definitions=definitions, + ) + drafts, trees = _with_no_over_draft( + config=config, form=form, grammar=grammar, drafts=drafts, trees=trees + ) return drafts, trees, skipped def _with_no_over_draft( - *, form: str, grammar: list[str], drafts: list[Draft], trees: list[tuple[Node, ...]] + *, + config: DialectConfig, + form: str, + grammar: list[str], + drafts: list[Draft], + trees: list[tuple[Node, ...]], ) -> tuple[list[Draft], list[tuple[Node, ...]]]: """A function form's every option together without its OVER clause, as one more production.""" if not form.startswith(NO_OVER_PREFIX) or not any( @@ -269,7 +274,7 @@ def _with_no_over_draft( draft: Draft = Draft( form=form, kind=shared.KIND_INTERACTION_ALL, target="", note=NO_OVER_NOTE, spec=spec ) - return [*drafts, draft], [*trees, shared_grammar.parse(production)] + return [*drafts, draft], [*trees, shared_grammar.parse(production=production, config=config)] def bq_definitions( @@ -289,21 +294,21 @@ def documented_rows(*, path: Path) -> list[Row]: return suppress_rows(path=path, disposition=DISPOSITION_DOCUMENTED) -def install(root: Path) -> Withdrawals: - """Register the BigQuery styles, classes and readers; the result collects withdrawn drafts.""" +def bigquery_config(root: Path) -> tuple[DialectConfig, Withdrawals]: + """The shared config with the BigQuery styles, classes and readers, and what it withdraws.""" + base: DialectConfig = shared_config() withdrawn: Withdrawals = Withdrawals() - shared_grammar.CLASS_RULES = (*BQ_CLASS_RULES, *_shared_class_rules) fills: dict[str, str] = catalogue_fills(root) typed: dict[str, dict[str, str]] = signature_fills(root=root, fills=fills) forms: set[str] = catalogue_forms(root) shadowed: set[str] = set() for key in typed: shadowed.update(form for form in forms if form != key and form.startswith(key)) + styles: dict[str, dict[str, FormStyle]] = {} for family in FAMILIES: - styles: dict[str, FormStyle] = shared.FAMILY_STYLES.setdefault(family, {}) - styles[f"{FORM_PREFIX}.{family}."] = style(form="", family=family, fills=fills) - styles.update( - { + styles[family] = { + f"{FORM_PREFIX}.{family}.": style(form="", family=family, fills=fills), + **{ form: style(form=form, family=family, fills={**fills, **typed.get(form, {})}) for form in { *FORM_CONTEXTS, @@ -314,13 +319,18 @@ def install(root: Path) -> Withdrawals: *shadowed, } if form.startswith(f"{FORM_PREFIX}.{family}.") - } - ) - setattr(shared_grammar, "TOKEN", BQ_TOKEN) # noqa: B010 - setattr(obligations, "derive_trees", bq_derive_trees) # noqa: B010 - setattr(obligations, "_definitions", bq_definitions) # noqa: B010 - setattr(obligations, "limit_drafts", bq_limit_drafts) # noqa: B010 - setattr(obligations, "existing_ids", bq_existing_ids) # noqa: B010 - setattr(obligations, "suppressions", documented_rows) # noqa: B010 - setattr(obligations, "_suppressed", withdrawn.suppressed) # noqa: B010 - return withdrawn + }, + } + config: DialectConfig = dataclasses.replace( + base, + token=BQ_TOKEN, + class_rules=(*BQ_CLASS_RULES, *base.class_rules), + family_styles=with_styles(config=base, styles=styles), + derive_trees=bq_derive_trees, + definitions=bq_definitions, + limit_drafts=bq_limit_drafts, + existing_ids=bq_existing_ids, + suppressions=documented_rows, + suppressed=withdrawn.suppressed, + ) + return config, withdrawn diff --git a/scripts/syntax_obligations_bigquery/_helpers/cases.py b/scripts/syntax_obligations_bigquery/_helpers/cases.py index 08f62b18e4..5dfbbee2e9 100644 --- a/scripts/syntax_obligations_bigquery/_helpers/cases.py +++ b/scripts/syntax_obligations_bigquery/_helpers/cases.py @@ -20,7 +20,7 @@ from scripts.grammar_obligations._helpers.render import style_of, submissions from scripts.grammar_obligations.constants import CLOSE_PAREN, KIND_EXTREME, OPEN_PAREN from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Draft, Node, ReceiptView, Rendered +from scripts.grammar_obligations.models import DialectConfig, Draft, Node, ReceiptView, Rendered from scripts.grammar_obligations.types import Row from scripts.syntax_obligations_bigquery._helpers.adapt import is_suppressed, suppress_rows from scripts.syntax_obligations_bigquery._helpers.fixtures import case_setup @@ -57,6 +57,7 @@ def family_cases( # noqa: PLR0913 *, + config: DialectConfig, family: str, numbered: list[tuple[str, Draft]], trees: dict[str, list[tuple[Node, ...]]], @@ -73,8 +74,9 @@ def family_cases( # noqa: PLR0913 if draft.form not in trees or draft.spec is None: continue found: list[Rendered] = submissions( + config=config, trees=trees[draft.form], - style=style_of(family=family, form=draft.form), + style=style_of(config=config, family=family, form=draft.form), spec=draft.spec, depths=draft.depths, ) @@ -168,7 +170,11 @@ def observed_reject(rendered: Rendered) -> Rendered: def withdrawn_texts( - *, family: str, drafts: list[Draft], trees: dict[str, list[tuple[Node, ...]]] + *, + config: DialectConfig, + family: str, + drafts: list[Draft], + trees: dict[str, list[tuple[Node, ...]]], ) -> list[tuple[str, str]]: """(form, SQL) of each reject text a `documented` suppression withdrew from the family.""" texts: list[tuple[str, str]] = [] @@ -176,8 +182,9 @@ def withdrawn_texts( if draft.form not in trees or draft.spec is None: continue for rendered in submissions( + config=config, trees=trees[draft.form], - style=style_of(family=family, form=draft.form), + style=style_of(config=config, family=family, form=draft.form), spec=draft.spec, depths=draft.depths, ): @@ -220,14 +227,15 @@ def _check_keys(numbered: list[tuple[str, Draft]]) -> None: def family_rows( - *, root: Path, family: str, receipts: ReceiptView, withdrawn: Withdrawals + *, config: DialectConfig, root: Path, family: str, receipts: ReceiptView, withdrawn: Withdrawals ) -> FamilyPlan: """One family's obligation rows and cases, as the build would write them.""" start: int = len(withdrawn.drafts) - numbered, trees, _, _, _ = family_obligations(root=root, family=family) + numbered, trees, _, _, _ = family_obligations(config=config, root=root, family=family) _check_keys(numbered) observed: list[Row] = suppress_rows(path=root / LIMITS_FILE, disposition=DISPOSITION_OBSERVE) cases, settle = family_cases( + config=config, family=family, numbered=numbered, trees=trees, @@ -240,7 +248,9 @@ def family_rows( cases=cases, settle=frozenset(settle), withdrawn=tuple( - withdrawn_texts(family=family, drafts=withdrawn.drafts[start:], trees=trees) + withdrawn_texts( + config=config, family=family, drafts=withdrawn.drafts[start:], trees=trees + ) ), ) diff --git a/scripts/syntax_obligations_bigquery/_helpers/root.py b/scripts/syntax_obligations_bigquery/_helpers/root.py index 79072f066f..dc185a6214 100644 --- a/scripts/syntax_obligations_bigquery/_helpers/root.py +++ b/scripts/syntax_obligations_bigquery/_helpers/root.py @@ -8,16 +8,14 @@ import tomllib from pathlib import Path -from scripts.grammar_obligations._helpers.shared_state import isolated_shared_state from scripts.grammar_obligations.exceptions import ObligationError from scripts.grammar_obligations.models import ReceiptView -from scripts.syntax_obligations_bigquery._helpers.adapt import install, retired_ids +from scripts.syntax_obligations_bigquery._helpers.adapt import bigquery_config, retired_ids from scripts.syntax_obligations_bigquery._helpers.cases import ( family_rows, receipt_view, write_family, ) -from scripts.syntax_obligations_bigquery.classes.withdrawals import Withdrawals from scripts.syntax_obligations_bigquery.constants import ( CASES_DIR, FAMILIES, @@ -41,13 +39,18 @@ def _issued_ids(root: Path) -> set[str]: def plan(root: Path) -> dict[str, FamilyPlan]: """Every family's obligation rows and cases, as the build would write them.""" - with isolated_shared_state(): - withdrawn: Withdrawals = install(root) - receipts: ReceiptView = receipt_view(root / RECEIPTS_DIR) - return { - family: family_rows(root=root, family=family, receipts=receipts, withdrawn=withdrawn) - for family in FAMILIES - } + config, withdrawn = bigquery_config(root) + receipts: ReceiptView = receipt_view(root / RECEIPTS_DIR) + return { + family: family_rows( + config=config, + root=root, + family=family, + receipts=receipts, + withdrawn=withdrawn, + ) + for family in FAMILIES + } def refuse_vanished(*, root: Path, planned: dict[str, FamilyPlan]) -> None: diff --git a/scripts/syntax_obligations_bigquery/main/build.py b/scripts/syntax_obligations_bigquery/main/build.py index a37b4c40d2..2a36e853fb 100644 --- a/scripts/syntax_obligations_bigquery/main/build.py +++ b/scripts/syntax_obligations_bigquery/main/build.py @@ -8,7 +8,6 @@ import sys from pathlib import Path -from scripts.grammar_obligations._helpers.shared_state import isolated_shared_state from scripts.grammar_obligations.types import Row from scripts.syntax_obligations_bigquery._helpers.cases import receipt_view from scripts.syntax_obligations_bigquery._helpers.parser import ( @@ -27,7 +26,6 @@ from scripts.syntax_obligations_bigquery.models import EngineEvidence, FamilyPlan, Verdict -@isolated_shared_state() def run_build(argv: list[str] | None = None) -> int: """Build the root from the catalogue and receipts, or with --check compare it.""" parser: argparse.ArgumentParser = argparse.ArgumentParser(description=__doc__) diff --git a/scripts/syntax_obligations_clickhouse/_helpers/adapt.py b/scripts/syntax_obligations_clickhouse/_helpers/adapt.py index afb55316df..457be2f168 100644 --- a/scripts/syntax_obligations_clickhouse/_helpers/adapt.py +++ b/scripts/syntax_obligations_clickhouse/_helpers/adapt.py @@ -4,28 +4,23 @@ import dataclasses import json -import re import tomllib from collections.abc import Callable from pathlib import Path -from scripts.grammar_obligations import constants as shared -from scripts.grammar_obligations._helpers import derive, grammar, ids, obligations -from scripts.grammar_obligations.classes import renderer, walk -from scripts.grammar_obligations.classes.renderer import Renderer -from scripts.grammar_obligations.classes.walk import Walk +from scripts.grammar_obligations._helpers import derive, ids, obligations +from scripts.grammar_obligations._helpers.dialect import shared_config, with_styles from scripts.grammar_obligations.constants import ( ACTION_HAND, - ACTION_RESERVED_WORD, - EXPECT_ACCEPT, HAND_CASE_KEYS, - IDENTIFIER_CLASS, IDENTIFIER_RESERVED, PAIR_SIZE, ) from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Draft, FormStyle, Node, Rendered, Spec +from scripts.grammar_obligations.models import DialectConfig, Draft, FormStyle, Spec from scripts.grammar_obligations.types import Key, Row +from scripts.syntax_obligations_clickhouse.classes.renderer import ClickHouseRenderer +from scripts.syntax_obligations_clickhouse.classes.walk import ClickHouseWalk from scripts.syntax_obligations_clickhouse.constants import ( CH_CASED_KEYWORD, CH_CLASS_RULES, @@ -35,23 +30,16 @@ FAMILIES, FAMILY_CONTEXTS, FILLS, - FORM_CLASSES, FORM_CONTEXTS, FORM_ELISIONS, FORM_FILLS, FORM_PREFIX, KEYWORD_NOTE, - NAME_WRONG, - NAME_WRONG_FILL, RETIRED_FILE, RETIRED_KIND, ) _shared_existing_ids: Callable[[Path], dict[Key, str]] = ids.existing_ids -_shared_class_rules: tuple[tuple[re.Pattern[str], str], ...] = grammar.CLASS_RULES -_shared_submissions: Callable[..., list[Rendered]] = Renderer.submissions -_shared_walk_token: Callable[..., None] = Walk.token -_shared_class_note: Callable[..., str] = derive._class_note # noqa: SLF001 def _longest(*, form: str, keys: set[str]) -> str: @@ -134,57 +122,33 @@ def ch_existing_ids(path: Path) -> dict[Key, str]: def ch_class_note(*, label: str, description: str, placeholder: str) -> str: """The shared identifier class note; ClickHouse reserves no keyword (see the README).""" if label != IDENTIFIER_RESERVED: - return _shared_class_note(label=label, description=description, placeholder=placeholder) + return derive.class_note(label=label, description=description, placeholder=placeholder) return KEYWORD_NOTE -def ch_submissions(self: object, *, spec: Spec, depths: tuple[int, ...] = ()) -> list[Rendered]: - """The shared submissions; a keyword in place of a name is accepted unquoted and quoted.""" - found: list[Rendered] = _shared_submissions(self, spec=spec, depths=depths) - if spec.action != ACTION_RESERVED_WORD: - return found - return [dataclasses.replace(item, expect=EXPECT_ACCEPT) for item in found] - - -def ch_walk_token(self: Walk, *, node: Node, where: str, omission_is_absence: bool) -> None: - """The shared operand drafts, with the form's operand classes and a number for a wrong name.""" - overrides: dict[str, str] = FORM_CLASSES.get( - _longest(form=self.form, keys=set(FORM_CLASSES)), {} - ) - shared_class: Callable[[str], str] = walk.operand_class - wrong: dict[str, str] = walk.LEXICAL_WRONG - fill: dict[str, str] = walk.LEXICALLY_DISTINCT_WRONG_FILL - setattr(walk, "operand_class", lambda name: overrides.get(name) or shared_class(name)) # noqa: B010 - setattr(walk, "LEXICAL_WRONG", {**wrong, IDENTIFIER_CLASS: NAME_WRONG}) # noqa: B010 - setattr( # noqa: B010 - walk, "LEXICALLY_DISTINCT_WRONG_FILL", {**fill, IDENTIFIER_CLASS: NAME_WRONG_FILL} - ) - try: - _shared_walk_token(self, node=node, where=where, omission_is_absence=omission_is_absence) - finally: - setattr(walk, "operand_class", shared_class) # noqa: B010 - setattr(walk, "LEXICAL_WRONG", wrong) # noqa: B010 - setattr(walk, "LEXICALLY_DISTINCT_WRONG_FILL", fill) # noqa: B010 - - -def install() -> None: - """Register the ClickHouse styles, tokens, operand classes, cased names and limit reader.""" - grammar.CLASS_RULES = (*CH_CLASS_RULES, *_shared_class_rules) - grammar.CASED_KEYWORD = CH_CASED_KEYWORD - renderer.REPEAT_FILLS.update(CH_REPEAT_FILLS) - setattr(grammar, "TOKEN", CH_TOKEN) # noqa: B010 +def clickhouse_config() -> DialectConfig: + """The shared config with the ClickHouse styles, tokens, classes, cased names and limits.""" + shared: DialectConfig = shared_config() + styles: dict[str, dict[str, FormStyle]] = {} for family in FAMILIES: - styles: dict[str, FormStyle] = shared.FAMILY_STYLES.setdefault(family, {}) - styles[f"{FORM_PREFIX}.{family}."] = style(form="", family=family) - styles.update( - { + styles[family] = { + f"{FORM_PREFIX}.{family}.": style(form="", family=family), + **{ form: style(form=form, family=family) for form in {*FORM_CONTEXTS, *FORM_FILLS, *FORM_ELISIONS} if form.startswith(f"{FORM_PREFIX}.{family}.") - } - ) - setattr(obligations, "limit_drafts", ch_limit_drafts) # noqa: B010 - setattr(obligations, "existing_ids", ch_existing_ids) # noqa: B010 - setattr(Renderer, "submissions", ch_submissions) # noqa: B010 - setattr(Walk, "token", ch_walk_token) # noqa: B010 - setattr(derive, "_class_note", ch_class_note) # noqa: B010 + }, + } + return dataclasses.replace( + shared, + token=CH_TOKEN, + class_rules=(*CH_CLASS_RULES, *shared.class_rules), + cased_keyword=CH_CASED_KEYWORD, + repeat_fills={**shared.repeat_fills, **CH_REPEAT_FILLS}, + family_styles=with_styles(config=shared, styles=styles), + walk=ClickHouseWalk, + renderer=ClickHouseRenderer, + class_note=ch_class_note, + limit_drafts=ch_limit_drafts, + existing_ids=ch_existing_ids, + ) diff --git a/scripts/syntax_obligations_clickhouse/_helpers/cases.py b/scripts/syntax_obligations_clickhouse/_helpers/cases.py index afdee37f0f..bca74cc9b1 100644 --- a/scripts/syntax_obligations_clickhouse/_helpers/cases.py +++ b/scripts/syntax_obligations_clickhouse/_helpers/cases.py @@ -19,12 +19,11 @@ ) from scripts.grammar_obligations._helpers.obligations import family_obligations, obligation_rows from scripts.grammar_obligations._helpers.render import style_of, submissions -from scripts.grammar_obligations._helpers.shared_state import isolated_shared_state from scripts.grammar_obligations.constants import KIND_EXTREME from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Draft, Node, ReceiptView, Rendered +from scripts.grammar_obligations.models import DialectConfig, Draft, Node, ReceiptView, Rendered from scripts.grammar_obligations.types import Row -from scripts.syntax_obligations_clickhouse._helpers.adapt import install +from scripts.syntax_obligations_clickhouse._helpers.adapt import clickhouse_config from scripts.syntax_obligations_clickhouse.constants import ( CAPTURE, CASES_DIR, @@ -42,6 +41,7 @@ def family_cases( # noqa: PLR0913 *, + config: DialectConfig, family: str, numbered: list[tuple[str, Draft]], trees: dict[str, list[tuple[Node, ...]]], @@ -57,8 +57,9 @@ def family_cases( # noqa: PLR0913 if draft.form not in forms or draft.spec is None: continue found: list[Rendered] = submissions( + config=config, trees=trees[draft.form], - style=style_of(family=family, form=draft.form), + style=style_of(config=config, family=family, form=draft.form), spec=draft.spec, depths=draft.depths, ) @@ -125,14 +126,15 @@ def _check_keys(numbered: list[tuple[str, Draft]]) -> None: def family_rows( - *, root: Path, evidence: Path, family: str, receipts: ReceiptView + *, config: DialectConfig, root: Path, evidence: Path, family: str, receipts: ReceiptView ) -> tuple[list[Row], list[Row]]: """One family's obligation rows and cases; a family with no form has neither.""" if not tomllib.loads((root / CATALOGUE_DIR / f"{family}.toml").read_text()).get("form"): return [], [] - numbered, trees, _, _, _ = family_obligations(root=root, family=family) + numbered, trees, _, _, _ = family_obligations(config=config, root=root, family=family) _check_keys(numbered) cases: list[Row] = family_cases( + config=config, family=family, numbered=numbered, trees=trees, @@ -205,12 +207,13 @@ def _unexpected_files(*, root: Path, evidence: Path, expected: list[Path]) -> li ] -@isolated_shared_state() def planned_families(*, root: Path, evidence: Path) -> dict[str, tuple[list[Row], list[Row]]]: """Every family's obligations and cases, as the build would write them.""" - install() + config: DialectConfig = clickhouse_config() receipts: ReceiptView = receipt_view(evidence / RECEIPTS_DIR) return { - family: family_rows(root=root, evidence=evidence, family=family, receipts=receipts) + family: family_rows( + config=config, root=root, evidence=evidence, family=family, receipts=receipts + ) for family in FAMILIES } diff --git a/scripts/syntax_obligations_clickhouse/classes/__init__.py b/scripts/syntax_obligations_clickhouse/classes/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/scripts/syntax_obligations_clickhouse/classes/renderer.py b/scripts/syntax_obligations_clickhouse/classes/renderer.py new file mode 100644 index 0000000000..aefa84cf0a --- /dev/null +++ b/scripts/syntax_obligations_clickhouse/classes/renderer.py @@ -0,0 +1,20 @@ +"""`ClickHouseRenderer`: the shared renderer; a keyword in place of a name is accepted.""" + +from __future__ import annotations + +import dataclasses + +from scripts.grammar_obligations.classes.renderer import Renderer +from scripts.grammar_obligations.constants import ACTION_RESERVED_WORD, EXPECT_ACCEPT +from scripts.grammar_obligations.models import Rendered, Spec + + +class ClickHouseRenderer(Renderer): + """Renders one ClickHouse form's cases; ClickHouse reserves no keyword (see the README).""" + + def submissions(self, *, spec: Spec, depths: tuple[int, ...] = ()) -> list[Rendered]: + """The shared submissions; a keyword in place of a name is accepted unquoted and quoted.""" + found: list[Rendered] = super().submissions(spec=spec, depths=depths) + if spec.action != ACTION_RESERVED_WORD: + return found + return [dataclasses.replace(item, expect=EXPECT_ACCEPT) for item in found] diff --git a/scripts/syntax_obligations_clickhouse/classes/walk.py b/scripts/syntax_obligations_clickhouse/classes/walk.py new file mode 100644 index 0000000000..3c71ba7680 --- /dev/null +++ b/scripts/syntax_obligations_clickhouse/classes/walk.py @@ -0,0 +1,42 @@ +"""`ClickHouseWalk`: the shared walk, classing operands as the page does.""" + +from __future__ import annotations + +import dataclasses + +from scripts.grammar_obligations.classes.walk import Walk +from scripts.grammar_obligations.constants import IDENTIFIER_CLASS +from scripts.grammar_obligations.models import DialectConfig +from scripts.syntax_obligations_clickhouse.constants import ( + FORM_CLASSES, + NAME_WRONG, + NAME_WRONG_FILL, +) + + +class ClickHouseWalk(Walk): + """Collects one ClickHouse form's drafts, classing its operands as its page does.""" + + def __init__( + self, + form: str, + *, + config: DialectConfig, + unpacked: bool = False, + definitions: dict[str, str] | None = None, + ) -> None: + wrong: DialectConfig = dataclasses.replace( + config, + lexical_wrong={**config.lexical_wrong, IDENTIFIER_CLASS: NAME_WRONG}, + lexically_distinct_wrong_fill={ + **config.lexically_distinct_wrong_fill, + IDENTIFIER_CLASS: NAME_WRONG_FILL, + }, + ) + super().__init__(form, config=wrong, unpacked=unpacked, definitions=definitions) + owners: list[str] = [key for key in FORM_CLASSES if form.startswith(key)] + self.overrides: dict[str, str] = FORM_CLASSES[max(owners, key=len)] if owners else {} + + def operand_class(self, name: str) -> str: + """The class the form's page gives the operand, else the shared rules' class.""" + return self.overrides.get(name) or super().operand_class(name) diff --git a/scripts/syntax_obligations_databricks/_helpers/adapt.py b/scripts/syntax_obligations_databricks/_helpers/adapt.py index fcc02e4c7a..11e52924b8 100644 --- a/scripts/syntax_obligations_databricks/_helpers/adapt.py +++ b/scripts/syntax_obligations_databricks/_helpers/adapt.py @@ -4,15 +4,13 @@ import dataclasses import json -import re import tomllib from collections import Counter from collections.abc import Callable from pathlib import Path -from scripts.grammar_obligations import constants as shared from scripts.grammar_obligations._helpers import derive, grammar, ids, obligations, render -from scripts.grammar_obligations.classes import renderer, walk +from scripts.grammar_obligations._helpers.dialect import shared_config, with_styles from scripts.grammar_obligations.classes.renderer import Renderer from scripts.grammar_obligations.classes.walk import Walk from scripts.grammar_obligations.constants import ( @@ -31,7 +29,15 @@ TOKEN_KEYWORD, ) from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Choices, Draft, FormStyle, Node, Rendered, Spec +from scripts.grammar_obligations.models import ( + Choices, + DialectConfig, + Draft, + FormStyle, + Node, + Rendered, + Spec, +) from scripts.grammar_obligations.types import Key, Row from scripts.syntax_obligations_databricks.constants import ( ALIAS_RESERVED_NOTE, @@ -59,17 +65,6 @@ ) _shared_existing_ids: Callable[[Path], dict[Key, str]] = ids.existing_ids -_shared_token: Callable[..., str] = Renderer._token # noqa: SLF001 -_shared_submissions: Callable[..., list[Rendered]] = Renderer.submissions -_shared_spec: Callable[..., Spec] = Walk.spec -_shared_walk_token: Callable[..., None] = Walk.token -_shared_class_note: Callable[..., str] = derive._class_note # noqa: SLF001 -_shared_class_rules: tuple[tuple[re.Pattern[str], str], ...] = grammar.CLASS_RULES -_shared_choices: Callable[..., Choices] = Renderer._choices # noqa: SLF001 -_shared_style_of: Callable[..., FormStyle] = render.style_of -_shared_derive_trees: Callable[..., tuple[list[Draft], list[tuple[Node, ...]], Counter[str]]] = ( - derive.derive_trees -) def _longest(*, form: str, keys: set[str]) -> str: @@ -96,9 +91,9 @@ def style(*, form: str, family: str) -> FormStyle: ) -def db_style_of(*, family: str, form: str) -> FormStyle: +def db_style_of(*, config: DialectConfig, family: str, form: str) -> FormStyle: """The shared style of the form, with the typed fills of its own operands, by its id exactly.""" - found: FormStyle = _shared_style_of(family=family, form=form) + found: FormStyle = render.style_of(config=config, family=family, form=form) typed: dict[str, str] | None = FORM_OPERAND_FILLS.get(form) return dataclasses.replace(found, fills={**found.fills, **typed}) if typed else found @@ -165,64 +160,13 @@ def backticked(text: str) -> str: return text -def db_token(self: object, *, node: Node, choices: object, dollar_quoted: bool = False) -> str: - """The shared token, with a quoted-identifier fill in backticks (double quotes are strings).""" - text: str = _shared_token(self, node=node, choices=choices, dollar_quoted=dollar_quoted) - quoted: str = str(getattr(choices, "quote", "")) - if quoted and quoted == grammar.placeholder_name(node): - return backticked(text) - return text - - -def db_spec(self: object, *, action: str, node: Node | None = None, payload: str = "") -> Spec: - """The shared spec; a reserved-word spec carries its placeholder, which picks the word.""" - if action == ACTION_RESERVED_WORD and node is not None and not payload: - payload = node.text - return _shared_spec(self, action=action, node=node, payload=payload) - - -def db_walk_token(self: Walk, *, node: Node, where: str, omission_is_absence: bool) -> None: - """The shared operand drafts, with the classes the form's page gives its operands.""" - overrides: dict[str, str] = FORM_CLASSES.get( - _longest(form=self.form, keys=set(FORM_CLASSES)), {} - ) - shared: Callable[[str], str] = walk.operand_class - setattr(walk, "operand_class", lambda name: overrides.get(name) or shared(name)) # noqa: B010 - try: - _shared_walk_token(self, node=node, where=where, omission_is_absence=omission_is_absence) - finally: - setattr(walk, "operand_class", shared) # noqa: B010 - - def db_class_note(*, label: str, description: str, placeholder: str) -> str: """The shared identifier class note; the reserved class read from the reserved-words page.""" if label != IDENTIFIER_RESERVED: - return _shared_class_note(label=label, description=description, placeholder=placeholder) + return derive.class_note(label=label, description=description, placeholder=placeholder) return ALIAS_RESERVED_NOTE if placeholder in TABLE_ALIAS_PLACEHOLDERS else KEYWORD_NOTE -def db_submissions(self: object, *, spec: Spec, depths: tuple[int, ...] = ()) -> list[Rendered]: - """The shared submissions, with the reserved word and its backticked twin (see the README).""" - if spec.action != ACTION_RESERVED_WORD: - return _shared_submissions(self, spec=spec, depths=depths) - alias: bool = spec.payload in TABLE_ALIAS_PLACEHOLDERS - word: str = ALIAS_RESERVED_WORD if alias else RESERVED_WORD - renderer.RESERVED_WORD = word - try: - found: list[Rendered] = _shared_submissions(self, spec=spec, depths=depths) - finally: - renderer.RESERVED_WORD = RESERVED_WORD - quoted: str = f'"{word}"' - return [ - dataclasses.replace( - item, - sql=item.sql.replace(quoted, backticked(quoted)), - expect=item.expect if alias else EXPECT_ACCEPT, - ) - for item in found - ] - - def _siblings(*, nodes: tuple[Node, ...], key: int) -> tuple[tuple[Node, ...], int] | None: """The sequence holding the node whose `id()` is `key`, and its position there.""" for position, node in enumerate(nodes): @@ -252,20 +196,6 @@ def _call_parts(*, trees: list[tuple[Node, ...]], spec: Spec) -> tuple[Node, ... return None -def db_choices(self: Renderer, spec: Spec) -> Choices: - """The shared choices; a dropped `(` drops its `)`, and a marked call's operand is a number.""" - choices: Choices = _shared_choices(self, spec) - parts: tuple[Node, ...] | None = _call_parts(trees=self.trees, spec=spec) - if not parts: - return choices - choices = dataclasses.replace(choices, drop=choices.drop | {id(parts[-1])}) - if spec.payload != BARE_OPERAND_FILL: - return choices - if (operand := _first_operand(nodes=parts[:-1], choices=choices)) is not None: - choices.replace[id(operand)] = BARE_OPERAND_FILL - return choices - - def _first_operand(*, nodes: tuple[Node, ...], choices: Choices) -> Node | None: """The first operand the case writes; a required choice's lone keyword (a unit) counts too.""" for node in nodes: @@ -283,14 +213,15 @@ def _first_operand(*, nodes: tuple[Node, ...], choices: Choices) -> Node | None: def db_derive_trees( *, + config: DialectConfig, form: str, grammar: list[str], unpacked: bool = False, definitions: dict[str, str] | None = None, ) -> tuple[list[Draft], list[tuple[Node, ...]], Counter[str]]: """Shared drafts less a missing `(` around no required part where a bare name is valid.""" - drafts, trees, classes = _shared_derive_trees( - form=form, grammar=grammar, unpacked=unpacked, definitions=definitions + drafts, trees, classes = derive.derive_trees( + config=config, form=form, grammar=grammar, unpacked=unpacked, definitions=definitions ) kept: list[Draft] = [] for draft in drafts: @@ -307,28 +238,90 @@ def db_derive_trees( return kept, trees, classes -def install() -> None: - """Register the Databricks styles, tokens, operand classes and limit reader.""" - grammar.CLASS_RULES = (*DB_CLASS_RULES, *_shared_class_rules) - renderer.REPEAT_FILLS.update(DB_REPEAT_FILLS) - setattr(grammar, "TOKEN", DB_TOKEN) # noqa: B010 +class _DatabricksWalk(Walk): + """Collects one Databricks form's drafts, classing its operands as its page does.""" + + def spec(self, *, action: str, node: Node | None = None, payload: str = "") -> Spec: + """The shared spec; a reserved-word spec carries its placeholder, which picks the word.""" + if action == ACTION_RESERVED_WORD and node is not None and not payload: + payload = node.text + return super().spec(action=action, node=node, payload=payload) + + def operand_class(self, name: str) -> str: + """The class the form's page gives the operand, else the shared rules' class.""" + overrides: dict[str, str] = FORM_CLASSES.get( + _longest(form=self.form, keys=set(FORM_CLASSES)), {} + ) + return overrides.get(name) or super().operand_class(name) + + +class _DatabricksRenderer(Renderer): + """Renders one Databricks form's cases, quoting identifiers in backticks.""" + + def submissions(self, *, spec: Spec, depths: tuple[int, ...] = ()) -> list[Rendered]: + """The shared submissions, with the reserved word and its backticked twin (see README).""" + if spec.action != ACTION_RESERVED_WORD: + return super().submissions(spec=spec, depths=depths) + alias: bool = spec.payload in TABLE_ALIAS_PLACEHOLDERS + word: str = ALIAS_RESERVED_WORD if alias else RESERVED_WORD + self.reserved_word = word + found: list[Rendered] = super().submissions(spec=spec, depths=depths) + quoted: str = f'"{word}"' + return [ + dataclasses.replace( + item, + sql=item.sql.replace(quoted, backticked(quoted)), + expect=item.expect if alias else EXPECT_ACCEPT, + ) + for item in found + ] + + def _token(self, *, node: Node, choices: Choices, dollar_quoted: bool = False) -> str: + """The shared token; a quoted-identifier fill in backticks (double quotes are strings).""" + text: str = super()._token(node=node, choices=choices, dollar_quoted=dollar_quoted) + quoted: str = str(getattr(choices, "quote", "")) + if quoted and quoted == grammar.placeholder_name(node): + return backticked(text) + return text + + def _choices(self, spec: Spec) -> Choices: + """The shared choices; a dropped `(` drops its `)`; a marked call's operand is a number.""" + choices: Choices = super()._choices(spec) + parts: tuple[Node, ...] | None = _call_parts(trees=self.trees, spec=spec) + if not parts: + return choices + choices = dataclasses.replace(choices, drop=choices.drop | {id(parts[-1])}) + if spec.payload != BARE_OPERAND_FILL: + return choices + if (operand := _first_operand(nodes=parts[:-1], choices=choices)) is not None: + choices.replace[id(operand)] = BARE_OPERAND_FILL + return choices + + +def databricks_config() -> DialectConfig: + """The shared config with the Databricks styles, tokens, classes, readers and limits.""" + shared: DialectConfig = shared_config() + styles: dict[str, dict[str, FormStyle]] = {} for family in FAMILIES: - styles: dict[str, FormStyle] = shared.FAMILY_STYLES.setdefault(family, {}) - styles[f"{FORM_PREFIX}.{family}."] = style(form="", family=family) - styles.update( - { + styles[family] = { + f"{FORM_PREFIX}.{family}.": style(form="", family=family), + **{ form: style(form=form, family=family) for form in {*FORM_CONTEXTS, *FORM_FILLS, *FORM_ELISIONS, *FORM_QUALIFY} if form.startswith(f"{FORM_PREFIX}.{family}.") - } - ) - setattr(obligations, "limit_drafts", db_limit_drafts) # noqa: B010 - setattr(obligations, "existing_ids", db_existing_ids) # noqa: B010 - setattr(Renderer, "_token", db_token) # noqa: B010 - setattr(Renderer, "submissions", db_submissions) # noqa: B010 - setattr(Walk, "spec", db_spec) # noqa: B010 - setattr(Walk, "token", db_walk_token) # noqa: B010 - setattr(derive, "_class_note", db_class_note) # noqa: B010 - setattr(Renderer, "_choices", db_choices) # noqa: B010 - setattr(obligations, "derive_trees", db_derive_trees) # noqa: B010 - setattr(obligations, "style_of", db_style_of) # noqa: B010 + }, + } + return dataclasses.replace( + shared, + token=DB_TOKEN, + class_rules=(*DB_CLASS_RULES, *shared.class_rules), + repeat_fills={**shared.repeat_fills, **DB_REPEAT_FILLS}, + family_styles=with_styles(config=shared, styles=styles), + walk=_DatabricksWalk, + renderer=_DatabricksRenderer, + class_note=db_class_note, + derive_trees=db_derive_trees, + style_of=db_style_of, + limit_drafts=db_limit_drafts, + existing_ids=db_existing_ids, + ) diff --git a/scripts/syntax_obligations_databricks/_helpers/cases.py b/scripts/syntax_obligations_databricks/_helpers/cases.py index 9de595f869..6b7250788e 100644 --- a/scripts/syntax_obligations_databricks/_helpers/cases.py +++ b/scripts/syntax_obligations_databricks/_helpers/cases.py @@ -30,7 +30,7 @@ STAGE_BY_RECEIPT_PHASE, ) from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Draft, Node, ReceiptView, Rendered +from scripts.grammar_obligations.models import DialectConfig, Draft, Node, ReceiptView, Rendered from scripts.grammar_obligations.types import Row from scripts.syntax_catalogue_databricks.constants import DECISION_RUNTIME_ONLY, SOURCES_FILE from scripts.syntax_obligations_databricks._helpers.adapt import db_style_of @@ -81,6 +81,7 @@ def _on_warehouse(rendered: Rendered) -> Rendered: def family_cases( # noqa: PLR0913 *, + config: DialectConfig, family: str, numbered: list[tuple[str, Draft]], trees: dict[str, list[tuple[Node, ...]]], @@ -99,8 +100,9 @@ def family_cases( # noqa: PLR0913 if draft.form not in forms or draft.spec is None: continue found: list[Rendered] = submissions( + config=config, trees=trees[draft.form], - style=db_style_of(family=family, form=draft.form), + style=db_style_of(config=config, family=family, form=draft.form), spec=draft.spec, depths=draft.depths, ) @@ -260,8 +262,9 @@ def _check_keys(numbered: list[tuple[str, Draft]]) -> None: owner[key] = identifier -def family_rows( +def family_rows( # noqa: PLR0913 *, + config: DialectConfig, root: Path, evidence: Path, family: str, @@ -271,9 +274,10 @@ def family_rows( """One family's obligation rows and cases; a family with no form has neither.""" if not tomllib.loads((root / CATALOGUE_DIR / f"{family}.toml").read_text()).get("form"): return [], [] - numbered, trees, _, _, _ = family_obligations(root=root, family=family) + numbered, trees, _, _, _ = family_obligations(config=config, root=root, family=family) _check_keys(numbered) cases: list[Row] = family_cases( + config=config, family=family, numbered=numbered, trees=trees, diff --git a/scripts/syntax_obligations_databricks/main/build.py b/scripts/syntax_obligations_databricks/main/build.py index 511d45047f..5dc5b1dc24 100644 --- a/scripts/syntax_obligations_databricks/main/build.py +++ b/scripts/syntax_obligations_databricks/main/build.py @@ -9,9 +9,9 @@ from pathlib import Path from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import ReceiptView +from scripts.grammar_obligations.models import DialectConfig, ReceiptView from scripts.grammar_obligations.types import Row -from scripts.syntax_obligations_databricks._helpers.adapt import install, retired_ids +from scripts.syntax_obligations_databricks._helpers.adapt import databricks_config, retired_ids from scripts.syntax_obligations_databricks._helpers.cases import ( family_rows, receipt_view, @@ -53,12 +53,13 @@ def run_build(argv: list[str] | None = None) -> int: arguments: argparse.Namespace = parser.parse_args(argv) evidence: Path = arguments.evidence or arguments.root previous: set[str] = _issued_ids(arguments.root) - install() + config: DialectConfig = databricks_config() receipts: ReceiptView runtime_settled: dict[tuple[str, str, str, str], tuple[str, str]] receipts, runtime_settled = receipt_view(evidence / RECEIPTS_DIR) planned: dict[str, tuple[list[Row], list[Row]]] = { family: family_rows( + config=config, root=arguments.root, evidence=evidence, family=family, diff --git a/scripts/syntax_obligations_duckdb/_helpers/adapt.py b/scripts/syntax_obligations_duckdb/_helpers/adapt.py index b560387302..b2be29771d 100644 --- a/scripts/syntax_obligations_duckdb/_helpers/adapt.py +++ b/scripts/syntax_obligations_duckdb/_helpers/adapt.py @@ -2,18 +2,17 @@ from __future__ import annotations +import dataclasses import json -import re import tomllib from collections.abc import Callable from pathlib import Path -from scripts.grammar_obligations import constants as shared -from scripts.grammar_obligations._helpers import grammar, ids, obligations -from scripts.grammar_obligations.classes import renderer +from scripts.grammar_obligations._helpers import ids, obligations +from scripts.grammar_obligations._helpers.dialect import shared_config, with_styles from scripts.grammar_obligations.constants import ACTION_HAND, HAND_CASE_KEYS, PAIR_SIZE from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Draft, FormStyle, Spec +from scripts.grammar_obligations.models import DialectConfig, Draft, FormStyle, Spec from scripts.grammar_obligations.types import Key, Row from scripts.syntax_obligations_duckdb.constants import ( CALL_NAME, @@ -37,7 +36,6 @@ _shared_grammar_read: Callable[..., list[str]] = obligations._grammar_read # noqa: SLF001 _shared_existing_ids: Callable[[Path], dict[Key, str]] = ids.existing_ids -_shared_class_rules: tuple[tuple[re.Pattern[str], str], ...] = grammar.CLASS_RULES def style(*, form: str, family: str) -> FormStyle: @@ -136,25 +134,30 @@ def dd_existing_ids(path: Path) -> dict[Key, str]: return kept -def install() -> None: - """Register the DuckDB styles, tokens, true/false words, operand classes, reads and limits.""" - grammar.CLASS_RULES = (*DD_CLASS_RULES, *_shared_class_rules) - grammar.CASED_KEYWORD = DD_CASED_KEYWORD - renderer.REPEAT_FILLS.update(DD_REPEAT_FILLS) - setattr(obligations, "_grammar_read", dd_grammar_read) # noqa: B010 - setattr(grammar, "TOKEN", DD_TOKEN) # noqa: B010 +def duckdb_config() -> DialectConfig: + """The shared config with the DuckDB styles, tokens, true/false words, reads and limits.""" + shared: DialectConfig = shared_config() + styles: dict[str, dict[str, FormStyle]] = {} for family in FAMILIES: - styles: dict[str, FormStyle] = shared.FAMILY_STYLES.setdefault(family, {}) - styles[f"{FORM_PREFIX}.{family}."] = style(form="", family=family) - styles.update( - { + styles[family] = { + f"{FORM_PREFIX}.{family}.": style(form="", family=family), + **{ form: style(form=form, family=family) for form in {*FORM_CONTEXTS, *FORM_FILLS, *FORM_ELISIONS} if form.startswith(f"{FORM_PREFIX}.{family}.") - } - ) - setattr(obligations, "limit_drafts", dd_limit_drafts) # noqa: B010 - setattr(obligations, "existing_ids", dd_existing_ids) # noqa: B010 + }, + } + return dataclasses.replace( + shared, + token=DD_TOKEN, + class_rules=(*DD_CLASS_RULES, *shared.class_rules), + cased_keyword=DD_CASED_KEYWORD, + repeat_fills={**shared.repeat_fills, **DD_REPEAT_FILLS}, + family_styles=with_styles(config=shared, styles=styles), + grammar_read=dd_grammar_read, + limit_drafts=dd_limit_drafts, + existing_ids=dd_existing_ids, + ) def issued_ids(root: Path) -> set[str]: diff --git a/scripts/syntax_obligations_duckdb/_helpers/cases.py b/scripts/syntax_obligations_duckdb/_helpers/cases.py index 7ddb04fab1..9795b4a9df 100644 --- a/scripts/syntax_obligations_duckdb/_helpers/cases.py +++ b/scripts/syntax_obligations_duckdb/_helpers/cases.py @@ -19,7 +19,7 @@ from scripts.grammar_obligations._helpers.render import style_of, submissions from scripts.grammar_obligations.constants import EXPECT_OBSERVE, KIND_EXTREME from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Draft, Node, ReceiptView, Rendered +from scripts.grammar_obligations.models import DialectConfig, Draft, Node, ReceiptView, Rendered from scripts.grammar_obligations.types import Row from scripts.syntax_obligations_duckdb.constants import ( CAPTURE_FRESH, @@ -37,6 +37,7 @@ def family_cases( # noqa: PLR0913 *, + config: DialectConfig, family: str, numbered: list[tuple[str, Draft]], trees: dict[str, list[tuple[Node, ...]]], @@ -52,8 +53,9 @@ def family_cases( # noqa: PLR0913 if draft.form not in forms or draft.spec is None: continue found: list[Rendered] = submissions( + config=config, trees=trees[draft.form], - style=style_of(family=family, form=draft.form), + style=style_of(config=config, family=family, form=draft.form), spec=draft.spec, depths=draft.depths, ) @@ -124,9 +126,11 @@ def _check_keys(numbered: list[tuple[str, Draft]]) -> None: owner[key] = identifier -def write_family(*, root: Path, family: str, receipts: ReceiptView) -> tuple[int, int]: +def write_family( + *, config: DialectConfig, root: Path, family: str, receipts: ReceiptView +) -> tuple[int, int]: """Write one family's obligations and cases; return their counts.""" - numbered, trees, _, _, _ = family_obligations(root=root, family=family) + numbered, trees, _, _, _ = family_obligations(config=config, root=root, family=family) _check_keys(numbered) rows: list[Row] = obligation_rows(numbered) path: Path = root / OBLIGATIONS_DIR / f"{family}.toml" @@ -135,6 +139,7 @@ def write_family(*, root: Path, family: str, receipts: ReceiptView) -> tuple[int path=path, header=OBLIGATIONS_HEADER.format(family=family), tables=[("obligation", rows)] ) cases: list[Row] = family_cases( + config=config, family=family, numbered=numbered, trees=trees, diff --git a/scripts/syntax_obligations_duckdb/main/build.py b/scripts/syntax_obligations_duckdb/main/build.py index 1df24cb1be..9279154b33 100644 --- a/scripts/syntax_obligations_duckdb/main/build.py +++ b/scripts/syntax_obligations_duckdb/main/build.py @@ -9,10 +9,9 @@ import tempfile from pathlib import Path -from scripts.grammar_obligations._helpers.shared_state import isolated_shared_state from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import ReceiptView -from scripts.syntax_obligations_duckdb._helpers.adapt import install, issued_ids, retired_ids +from scripts.grammar_obligations.models import DialectConfig, ReceiptView +from scripts.syntax_obligations_duckdb._helpers.adapt import duckdb_config, issued_ids, retired_ids from scripts.syntax_obligations_duckdb._helpers.cases import ( receipt_view, stale_files, @@ -26,7 +25,6 @@ ) -@isolated_shared_state() def run_build(argv: list[str] | None = None) -> int: """Regenerate every family's obligations and cases, or with --check compare them.""" parser: argparse.ArgumentParser = argparse.ArgumentParser(description=__doc__) @@ -42,7 +40,6 @@ def run_build(argv: list[str] | None = None) -> int: arguments: argparse.Namespace = parser.parse_args(argv) if arguments.evidence is not None and not arguments.check: parser.error("--evidence is for --check") - install() if arguments.check: return _check(root=arguments.root, evidence=arguments.evidence or arguments.root) _build(arguments.root) @@ -52,9 +49,12 @@ def run_build(argv: list[str] | None = None) -> int: def _build(root: Path) -> None: """Write every family's obligations and cases into the root; fail if an id vanished.""" previous: set[str] = issued_ids(root) + config: DialectConfig = duckdb_config() receipts: ReceiptView = receipt_view(root / RECEIPTS_DIR) for family in FAMILIES: - obligations, cases = write_family(root=root, family=family, receipts=receipts) + obligations, cases = write_family( + config=config, root=root, family=family, receipts=receipts + ) print(json.dumps({"family": family, "obligations": obligations, "cases": cases})) retired: set[str] = retired_ids(root) issued: set[str] = issued_ids(root) diff --git a/scripts/syntax_obligations_postgres/_helpers/adapt.py b/scripts/syntax_obligations_postgres/_helpers/adapt.py index 08b54b7d42..59e4e7e4a2 100644 --- a/scripts/syntax_obligations_postgres/_helpers/adapt.py +++ b/scripts/syntax_obligations_postgres/_helpers/adapt.py @@ -2,18 +2,17 @@ from __future__ import annotations +import dataclasses import json -import re import tomllib from collections.abc import Callable from pathlib import Path -from scripts.grammar_obligations import constants as shared -from scripts.grammar_obligations._helpers import grammar, ids, obligations -from scripts.grammar_obligations.classes import renderer +from scripts.grammar_obligations._helpers import ids, obligations +from scripts.grammar_obligations._helpers.dialect import shared_config, with_styles from scripts.grammar_obligations.constants import ACTION_HAND, HAND_CASE_KEYS, PAIR_SIZE from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Draft, FormStyle, Spec +from scripts.grammar_obligations.models import DialectConfig, Draft, FormStyle, Spec from scripts.grammar_obligations.types import Key, Row from scripts.syntax_obligations_postgres.constants import ( DEFAULT_ROOT, @@ -38,7 +37,6 @@ _shared_grammar_read: Callable[..., list[str]] = obligations._grammar_read # noqa: SLF001 _shared_existing_ids: Callable[[Path], dict[Key, str]] = ids.existing_ids -_shared_class_rules: tuple[tuple[re.Pattern[str], str], ...] = grammar.CLASS_RULES def typed_fills(*, root: Path) -> dict[str, str]: @@ -149,23 +147,28 @@ def pg_existing_ids(path: Path) -> dict[Key, str]: return kept -def install(*, root: Path = DEFAULT_ROOT) -> None: - """Register the Postgres styles, class rules, tokens, grammar read and limit reader.""" +def postgres_config(*, root: Path = DEFAULT_ROOT) -> DialectConfig: + """The shared config with the Postgres styles, class rules, tokens, grammar read and limits.""" + shared: DialectConfig = shared_config() typed: dict[str, str] = typed_fills(root=root) - grammar.CLASS_RULES = (*PG_CLASS_RULES, *_shared_class_rules) - setattr(obligations, "_grammar_read", pg_grammar_read) # noqa: B010 - setattr(grammar, "TOKEN", PG_TOKEN) # noqa: B010 - renderer.REPEAT_FILLS.update(PG_REPEAT_FILLS) + styles: dict[str, dict[str, FormStyle]] = {} for family in FAMILIES: - styles: dict[str, FormStyle] = shared.FAMILY_STYLES.setdefault(family, {}) own: dict[str, str] = typed if family == TYPED_FAMILY else {} - styles[f"{FORM_PREFIX}.{family}."] = style(form="", family=family, typed=own) - styles.update( - { + styles[family] = { + f"{FORM_PREFIX}.{family}.": style(form="", family=family, typed=own), + **{ form: style(form=form, family=family, typed=own) for form in {*FORM_CONTEXTS, *FORM_FILLS, *FORM_ELISIONS} if form.startswith(f"{FORM_PREFIX}.{family}.") - } - ) - setattr(obligations, "limit_drafts", pg_limit_drafts) # noqa: B010 - setattr(obligations, "existing_ids", pg_existing_ids) # noqa: B010 + }, + } + return dataclasses.replace( + shared, + token=PG_TOKEN, + class_rules=(*PG_CLASS_RULES, *shared.class_rules), + repeat_fills={**shared.repeat_fills, **PG_REPEAT_FILLS}, + family_styles=with_styles(config=shared, styles=styles), + grammar_read=pg_grammar_read, + limit_drafts=pg_limit_drafts, + existing_ids=pg_existing_ids, + ) diff --git a/scripts/syntax_obligations_postgres/_helpers/cases.py b/scripts/syntax_obligations_postgres/_helpers/cases.py index 91adfd9f2e..d4cffdf6b6 100644 --- a/scripts/syntax_obligations_postgres/_helpers/cases.py +++ b/scripts/syntax_obligations_postgres/_helpers/cases.py @@ -20,7 +20,7 @@ from scripts.grammar_obligations._helpers.render import style_of, submissions from scripts.grammar_obligations.constants import KIND_EXTREME from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Draft, Node, ReceiptView, Rendered +from scripts.grammar_obligations.models import DialectConfig, Draft, Node, ReceiptView, Rendered from scripts.grammar_obligations.types import Row from scripts.syntax_obligations_postgres.constants import ( AUTOCOMMIT_PATTERNS, @@ -73,6 +73,7 @@ def capture_for(sql: str) -> str: def family_cases( # noqa: PLR0913 *, + config: DialectConfig, family: str, numbered: list[tuple[str, Draft]], trees: dict[str, list[tuple[Node, ...]]], @@ -88,8 +89,9 @@ def family_cases( # noqa: PLR0913 if draft.form not in forms or draft.spec is None: continue found: list[Rendered] = submissions( + config=config, trees=trees[draft.form], - style=style_of(family=family, form=draft.form), + style=style_of(config=config, family=family, form=draft.form), spec=draft.spec, depths=draft.depths, ) @@ -146,10 +148,10 @@ def receipt_view(directory: Path) -> ReceiptView: def write_family( - *, root: Path, family: str, focus: set[str], receipts: ReceiptView + *, config: DialectConfig, root: Path, family: str, focus: set[str], receipts: ReceiptView ) -> tuple[int, int]: """Write one family's obligations and focus cases; return their counts.""" - numbered, trees, _, _, _ = family_obligations(root=root, family=family) + numbered, trees, _, _, _ = family_obligations(config=config, root=root, family=family) if family in CASED_FAMILIES: focus = focus | set(trees) rows: list[Row] = obligation_rows(numbered) @@ -159,6 +161,7 @@ def write_family( path=path, header=OBLIGATIONS_HEADER.format(family=family), tables=[("obligation", rows)] ) cases: list[Row] = family_cases( + config=config, family=family, numbered=numbered, trees=trees, diff --git a/scripts/syntax_obligations_postgres/main/build.py b/scripts/syntax_obligations_postgres/main/build.py index a821879569..ee96ba41ec 100644 --- a/scripts/syntax_obligations_postgres/main/build.py +++ b/scripts/syntax_obligations_postgres/main/build.py @@ -9,10 +9,9 @@ import tomllib from pathlib import Path -from scripts.grammar_obligations._helpers.shared_state import isolated_shared_state from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import ReceiptView -from scripts.syntax_obligations_postgres._helpers.adapt import install, retired_ids +from scripts.grammar_obligations.models import DialectConfig, ReceiptView +from scripts.syntax_obligations_postgres._helpers.adapt import postgres_config, retired_ids from scripts.syntax_obligations_postgres._helpers.cases import ( focus_forms, receipt_view, @@ -45,7 +44,6 @@ def _issued_ids(root: Path) -> set[str]: return issued -@isolated_shared_state() def run_build(argv: list[str] | None = None) -> int: """Regenerate every family's obligations and the focus forms' cases, or with --check compare.""" parser: argparse.ArgumentParser = argparse.ArgumentParser(description=__doc__) @@ -90,11 +88,13 @@ def run_build(argv: list[str] | None = None) -> int: def _build(*, root: Path, focus_file: Path, previous: set[str]) -> None: """Write every family, then refuse a reissued id or one that left without a tombstone.""" - install(root=root) + config: DialectConfig = postgres_config(root=root) receipts: ReceiptView = receipt_view(root / RECEIPTS_DIR) focus: set[str] = set(focus_forms(focus_file)) for family in FAMILIES: - obligations, cases = write_family(root=root, family=family, focus=focus, receipts=receipts) + obligations, cases = write_family( + config=config, root=root, family=family, focus=focus, receipts=receipts + ) print(json.dumps({"family": family, "obligations": obligations, "cases": cases})) retired: set[str] = retired_ids(root) issued: set[str] = _issued_ids(root) diff --git a/scripts/syntax_obligations_snowflake/_helpers/rules.py b/scripts/syntax_obligations_snowflake/_helpers/rules.py index ce062edfa1..78a7b8c9ea 100644 --- a/scripts/syntax_obligations_snowflake/_helpers/rules.py +++ b/scripts/syntax_obligations_snowflake/_helpers/rules.py @@ -2,10 +2,11 @@ from __future__ import annotations +import dataclasses import re -from scripts.grammar_obligations._helpers import grammar -from scripts.grammar_obligations.classes import renderer, walk +from scripts.grammar_obligations._helpers.dialect import shared_config +from scripts.grammar_obligations.models import DialectConfig from scripts.syntax_obligations_snowflake.constants import ( CASED_KEYWORD, CLAUSE_CALLEES, @@ -18,27 +19,29 @@ WORD_NAMES, ) -_shared_class_rules: tuple[tuple[re.Pattern[str], str], ...] = grammar.CLASS_RULES - -def install() -> None: +def snowflake_config() -> DialectConfig: """Classify operands, widen the integer rule, read templates and numbers, walk lists.""" - grammar.TOKEN = NUMBER_TOKEN - grammar.TEMPLATE_OPERANDS = True - grammar.CASED_KEYWORD = CASED_KEYWORD - walk.REPEATED_ITEMS = True - walk.FILL_CLASSES = True - walk.BARE_VALUE_CLASS = WORD_CLASS - walk.CLAUSE_CALLEES = walk.CLAUSE_CALLEES | CLAUSE_CALLEES - renderer.QUOTE_MIXED_CASE = True - renderer.ONE_OF_OPTIONS = True - grammar.CLASS_RULES = ( - (re.compile(IDENTIFIER_NAMES), IDENTIFIER_CLASS), - (re.compile(WORD_NAMES), WORD_CLASS), - *( - (re.compile(f"{pattern.pattern}|{INTEGER_NAMES}"), label) - if label == INTEGER_CLASS - else (pattern, label) - for pattern, label in _shared_class_rules + shared: DialectConfig = shared_config() + return dataclasses.replace( + shared, + token=NUMBER_TOKEN, + template_operands=True, + cased_keyword=CASED_KEYWORD, + repeated_items=True, + fill_classes=True, + bare_value_class=WORD_CLASS, + clause_callees=shared.clause_callees | CLAUSE_CALLEES, + quote_mixed_case=True, + one_of_options=True, + class_rules=( + (re.compile(IDENTIFIER_NAMES), IDENTIFIER_CLASS), + (re.compile(WORD_NAMES), WORD_CLASS), + *( + (re.compile(f"{pattern.pattern}|{INTEGER_NAMES}"), label) + if label == INTEGER_CLASS + else (pattern, label) + for pattern, label in shared.class_rules + ), ), ) diff --git a/scripts/syntax_obligations_snowflake/main/build.py b/scripts/syntax_obligations_snowflake/main/build.py index 845eb4c932..abad7521b6 100644 --- a/scripts/syntax_obligations_snowflake/main/build.py +++ b/scripts/syntax_obligations_snowflake/main/build.py @@ -10,9 +10,10 @@ from scripts.grammar_obligations._helpers.cases import sync_outputs from scripts.grammar_obligations._helpers.elisions import elision_outputs from scripts.grammar_obligations._helpers.obligations import family_obligations, obligation_rows +from scripts.grammar_obligations.models import DialectConfig from scripts.syntax_obligations_snowflake._helpers.audit import dropped_reasons, omission_audit from scripts.syntax_obligations_snowflake._helpers.changed import changed_families -from scripts.syntax_obligations_snowflake._helpers.rules import install +from scripts.syntax_obligations_snowflake._helpers.rules import snowflake_config from scripts.syntax_obligations_snowflake.constants import ( DEFAULT_ROOT, WITHDRAWN_CLASS_HEADER, @@ -22,7 +23,7 @@ def run_build(argv: list[str] | None = None) -> int: """Regenerate the obligations of the named families, or with --check compare them.""" - install() + config: DialectConfig = snowflake_config() parser: argparse.ArgumentParser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, default=DEFAULT_ROOT) parser.add_argument( @@ -48,7 +49,7 @@ def run_build(argv: list[str] | None = None) -> int: built: dict[str, set[str]] = {} dropped: dict[str, str] = {} for family in families: - outputs, built[family], reasons = _family_outputs(root=root, family=family) + outputs, built[family], reasons = _family_outputs(config=config, root=root, family=family) dropped |= reasons differing += sync_outputs(outputs=outputs, check=arguments.check) omitted: bool = _report_omissions(root=root, built=built, dropped=dropped) @@ -80,10 +81,12 @@ def _report_omissions(*, root: Path, built: dict[str, set[str]], dropped: dict[s def _family_outputs( - *, root: Path, family: str + *, config: DialectConfig, root: Path, family: str ) -> tuple[list[tuple[Path, str | None]], set[str], dict[str, str]]: """One family's written files (None: no file), forms with obligations, and drop reasons.""" - numbered, trees, withdrawn, classes, arity = family_obligations(root=root, family=family) + numbered, trees, withdrawn, classes, arity = family_obligations( + config=config, root=root, family=family + ) obligations: str = tables_text( header=f"# Obligations of family {family}; generated by " "scripts/build_syntax_obligations.py from the catalogue grammar and limits.toml.\n" diff --git a/scripts/syntax_obligations_snowflake/main/cases.py b/scripts/syntax_obligations_snowflake/main/cases.py index a8a333afa2..58c0461d5c 100644 --- a/scripts/syntax_obligations_snowflake/main/cases.py +++ b/scripts/syntax_obligations_snowflake/main/cases.py @@ -16,14 +16,14 @@ run_database_setups, sync_outputs, ) -from scripts.grammar_obligations.models import ReceiptView +from scripts.grammar_obligations.models import DialectConfig, ReceiptView from scripts.grammar_obligations.types import Row -from scripts.syntax_obligations_snowflake._helpers.rules import install +from scripts.syntax_obligations_snowflake._helpers.rules import snowflake_config def run_cases(argv: list[str] | None = None) -> int: """Regenerate the cases of the named families and list those that need a capture.""" - install() + config: DialectConfig = snowflake_config() arguments: argparse.Namespace = _parse_args(argv) receipts: ReceiptView = ReceiptView( phases=receipt_phases(arguments.receipts), @@ -37,6 +37,7 @@ def run_cases(argv: list[str] | None = None) -> int: differing: list[Path] = [] for family in arguments.families: cases, arity, outputs = family_outputs( + config=config, root=arguments.root, evidence=arguments.evidence or arguments.root, family=family, diff --git a/scripts/syntax_obligations_sqlite/_helpers/adapt.py b/scripts/syntax_obligations_sqlite/_helpers/adapt.py index 0e4f810f7b..63664eaa8b 100644 --- a/scripts/syntax_obligations_sqlite/_helpers/adapt.py +++ b/scripts/syntax_obligations_sqlite/_helpers/adapt.py @@ -2,18 +2,17 @@ from __future__ import annotations +import dataclasses import json -import re import tomllib from collections.abc import Callable from pathlib import Path -from scripts.grammar_obligations import constants as shared -from scripts.grammar_obligations._helpers import grammar, ids, obligations -from scripts.grammar_obligations.classes import renderer +from scripts.grammar_obligations._helpers import ids, obligations +from scripts.grammar_obligations._helpers.dialect import shared_config, with_styles from scripts.grammar_obligations.constants import ACTION_HAND, HAND_CASE_KEYS, PAIR_SIZE from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Draft, FormStyle, Spec +from scripts.grammar_obligations.models import DialectConfig, Draft, FormStyle, Spec from scripts.grammar_obligations.types import Key, Row from scripts.syntax_obligations_sqlite.constants import ( FAMILIES, @@ -31,7 +30,6 @@ ) _shared_existing_ids: Callable[[Path], dict[Key, str]] = ids.existing_ids -_shared_class_rules: tuple[tuple[re.Pattern[str], str], ...] = grammar.CLASS_RULES def _longest(*, form: str, keys: set[str]) -> str: @@ -111,20 +109,25 @@ def sl_existing_ids(path: Path) -> dict[Key, str]: return kept -def install() -> None: - """Register the SQLite styles, tokens, operand classes and limit reader.""" - grammar.CLASS_RULES = (*SL_CLASS_RULES, *_shared_class_rules) - renderer.REPEAT_FILLS.update(SL_REPEAT_FILLS) - setattr(grammar, "TOKEN", SL_TOKEN) # noqa: B010 +def sqlite_config() -> DialectConfig: + """The shared config with the SQLite styles, tokens, operand classes and limit reader.""" + shared: DialectConfig = shared_config() + styles: dict[str, dict[str, FormStyle]] = {} for family in FAMILIES: - styles: dict[str, FormStyle] = shared.FAMILY_STYLES.setdefault(family, {}) - styles[f"{FORM_PREFIX}.{family}."] = style(form="", family=family) - styles.update( - { + styles[family] = { + f"{FORM_PREFIX}.{family}.": style(form="", family=family), + **{ form: style(form=form, family=family) for form in {*FORM_CONTEXTS, *FORM_FILLS, *FORM_ELISIONS} if form.startswith(f"{FORM_PREFIX}.{family}.") - } - ) - setattr(obligations, "limit_drafts", sl_limit_drafts) # noqa: B010 - setattr(obligations, "existing_ids", sl_existing_ids) # noqa: B010 + }, + } + return dataclasses.replace( + shared, + token=SL_TOKEN, + class_rules=(*SL_CLASS_RULES, *shared.class_rules), + repeat_fills={**shared.repeat_fills, **SL_REPEAT_FILLS}, + family_styles=with_styles(config=shared, styles=styles), + limit_drafts=sl_limit_drafts, + existing_ids=sl_existing_ids, + ) diff --git a/scripts/syntax_obligations_sqlite/_helpers/cases.py b/scripts/syntax_obligations_sqlite/_helpers/cases.py index ed42cd0fa7..a0f2636ded 100644 --- a/scripts/syntax_obligations_sqlite/_helpers/cases.py +++ b/scripts/syntax_obligations_sqlite/_helpers/cases.py @@ -21,7 +21,7 @@ from scripts.grammar_obligations._helpers.render import style_of, submissions from scripts.grammar_obligations.constants import KIND_EXTREME from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Draft, Node, ReceiptView, Rendered +from scripts.grammar_obligations.models import DialectConfig, Draft, Node, ReceiptView, Rendered from scripts.grammar_obligations.types import Row from scripts.syntax_obligations_sqlite.constants import ( AUTOCOMMIT_WORDS, @@ -40,6 +40,7 @@ def family_cases( # noqa: PLR0913 *, + config: DialectConfig, family: str, numbered: list[tuple[str, Draft]], trees: dict[str, list[tuple[Node, ...]]], @@ -55,8 +56,9 @@ def family_cases( # noqa: PLR0913 if draft.form not in forms or draft.spec is None: continue found: list[Rendered] = submissions( + config=config, trees=trees[draft.form], - style=style_of(family=family, form=draft.form), + style=style_of(config=config, family=family, form=draft.form), spec=draft.spec, depths=draft.depths, ) @@ -128,13 +130,16 @@ def _check_keys(numbered: list[tuple[str, Draft]]) -> None: owner[key] = identifier -def family_rows(*, root: Path, family: str, receipts: ReceiptView) -> tuple[list[Row], list[Row]]: +def family_rows( + *, config: DialectConfig, root: Path, family: str, receipts: ReceiptView +) -> tuple[list[Row], list[Row]]: """One family's obligation rows and cases; a family with no form has neither.""" if not tomllib.loads((root / CATALOGUE_DIR / f"{family}.toml").read_text()).get("form"): return [], [] - numbered, trees, _, _, _ = family_obligations(root=root, family=family) + numbered, trees, _, _, _ = family_obligations(config=config, root=root, family=family) _check_keys(numbered) cases: list[Row] = family_cases( + config=config, family=family, numbered=numbered, trees=trees, diff --git a/scripts/syntax_obligations_sqlite/_helpers/root.py b/scripts/syntax_obligations_sqlite/_helpers/root.py index fe984ca6dd..5873a7be6c 100644 --- a/scripts/syntax_obligations_sqlite/_helpers/root.py +++ b/scripts/syntax_obligations_sqlite/_helpers/root.py @@ -7,9 +7,9 @@ from pathlib import Path from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import ReceiptView +from scripts.grammar_obligations.models import DialectConfig, ReceiptView from scripts.grammar_obligations.types import Row -from scripts.syntax_obligations_sqlite._helpers.adapt import install, retired_ids +from scripts.syntax_obligations_sqlite._helpers.adapt import retired_ids, sqlite_config from scripts.syntax_obligations_sqlite._helpers.cases import family_rows, receipt_view from scripts.syntax_obligations_sqlite.constants import ( CASES_DIR, @@ -47,10 +47,11 @@ def merged_root(*, root: Path, evidence: Path, into: Path) -> Path: def planned_families(root: Path) -> dict[str, tuple[list[Row], list[Row]]]: """Every family's obligations and cases, refusing an id retired and issued, or lost.""" previous: set[str] = _issued_ids(root) - install() + config: DialectConfig = sqlite_config() receipts: ReceiptView = receipt_view(root / RECEIPTS_DIR) planned: dict[str, tuple[list[Row], list[Row]]] = { - family: family_rows(root=root, family=family, receipts=receipts) for family in FAMILIES + family: family_rows(config=config, root=root, family=family, receipts=receipts) + for family in FAMILIES } issued: set[str] = set() for rows, _ in planned.values(): diff --git a/scripts/syntax_obligations_sqlite/main/build.py b/scripts/syntax_obligations_sqlite/main/build.py index 7dbb3761ac..a293cf05f3 100644 --- a/scripts/syntax_obligations_sqlite/main/build.py +++ b/scripts/syntax_obligations_sqlite/main/build.py @@ -8,14 +8,12 @@ import tempfile from pathlib import Path -from scripts.grammar_obligations._helpers.shared_state import isolated_shared_state from scripts.grammar_obligations.types import Row from scripts.syntax_obligations_sqlite._helpers.cases import stale_files, write_family from scripts.syntax_obligations_sqlite._helpers.root import merged_root, planned_families from scripts.syntax_obligations_sqlite.constants import DEFAULT_ROOT -@isolated_shared_state() def run_build(argv: list[str] | None = None) -> int: """Regenerate every family's obligations and cases, or write nothing if an id would vanish.""" parser: argparse.ArgumentParser = argparse.ArgumentParser(description=__doc__) diff --git a/tests/unit/scripts/grammar_obligations/_test_types.py b/tests/unit/scripts/grammar_obligations/_test_types.py index c2f36afcc3..e174104575 100644 --- a/tests/unit/scripts/grammar_obligations/_test_types.py +++ b/tests/unit/scripts/grammar_obligations/_test_types.py @@ -3,6 +3,7 @@ from __future__ import annotations from dataclasses import dataclass +from typing import Any from scripts.grammar_obligations.types import Row @@ -106,10 +107,31 @@ class CheckedBuildersTestCase: class OneProcessTestCase: description: str dialect: str - unisolated: bool expected_outcomes: list[str] +@dataclass(frozen=True) +class SharedWriteTestCase: + description: str + source: str + expected_writes: list[str] + + +@dataclass(frozen=True) +class FrozenTableTestCase: + description: str + table: Any + key: Any + expected_error: str = "'mappingproxy' object does not support item assignment" + + +@dataclass(frozen=True) +class SharedWriteTreeTestCase: + description: str + directory: str + expected_writes: dict[str, list[str]] + + @dataclass(frozen=True) class DistinctListTestCase: description: str diff --git a/tests/unit/scripts/grammar_obligations/test_cases.py b/tests/unit/scripts/grammar_obligations/test_cases.py index 7899cbf144..da15be0bc7 100644 --- a/tests/unit/scripts/grammar_obligations/test_cases.py +++ b/tests/unit/scripts/grammar_obligations/test_cases.py @@ -5,6 +5,7 @@ import hashlib import json +from dataclasses import replace from pathlib import Path import pytest @@ -18,16 +19,16 @@ run_database_setups, settled_cases, ) +from scripts.grammar_obligations._helpers.dialect import shared_config, with_styles from scripts.grammar_obligations._helpers.obligations import family_obligations from scripts.grammar_obligations.constants import ( CASE_CAPTURE_RUN_DATABASE, - FAMILY_STYLES, KIND_ALTERNATIVE, KIND_INTERACTION_ALL, KIND_OPTION_PRESENT, ) from scripts.grammar_obligations.exceptions import ObligationError -from scripts.grammar_obligations.models import Draft, FormStyle, ReceiptView +from scripts.grammar_obligations.models import DialectConfig, Draft, FormStyle, ReceiptView from scripts.grammar_obligations.types import Row from tests.unit.scripts.grammar_obligations._test_types import ( DefinitionAlternativeTestCase, @@ -200,7 +201,12 @@ def test_given_a_form_snowflake_refuses_when_marking_then_only_its_positives_are (tmp_path / "catalogue" / "ddl.toml").write_text(DISPUTED_CATALOGUE) (tmp_path / "limits.toml").write_text(DISPUTED_LIMITS) generated: list[Row] = family_cases( - root=tmp_path, evidence=tmp_path, family="ddl", setups={}, held=frozenset() + config=shared_config(), + root=tmp_path, + evidence=tmp_path, + family="ddl", + setups={}, + held=frozenset(), )[0] positive: Row = {case["sql"]: case for case in generated}["ALTER SEQUENCE v1 ;"] mapped: Row = { @@ -226,6 +232,7 @@ def test_given_a_form_snowflake_refuses_when_marking_then_only_its_positives_are ) settled, _, marked = settled_cases( + config=shared_config(), root=tmp_path, evidence=tmp_path, family="ddl", @@ -296,7 +303,12 @@ def test_given_receipts_against_a_generated_expectation_when_settling_then_recei (tmp_path / "catalogue" / "ddl.toml").write_text(DROP_TAG_CATALOGUE) (tmp_path / "limits.toml").write_text("") generated: list[Row] = family_cases( - root=tmp_path, evidence=tmp_path, family="ddl", setups={}, held=frozenset() + config=shared_config(), + root=tmp_path, + evidence=tmp_path, + family="ddl", + setups={}, + held=frozenset(), )[0] case: Row = {case["sql"]: case for case in generated}[test_case.sql] receipts: ReceiptView = ReceiptView( @@ -312,6 +324,7 @@ def test_given_receipts_against_a_generated_expectation_when_settling_then_recei ) settled, _, marked = settled_cases( + config=shared_config(), root=tmp_path, evidence=tmp_path, family="ddl", @@ -367,7 +380,12 @@ def test_given_probe_role_receipts_when_settling_then_they_bind_any_setup( (tmp_path / "catalogue" / "ddl.toml").write_text(DROP_TAG_CATALOGUE) (tmp_path / "limits.toml").write_text("") generated: list[Row] = family_cases( - root=tmp_path, evidence=tmp_path, family="ddl", setups={}, held=frozenset() + config=shared_config(), + root=tmp_path, + evidence=tmp_path, + family="ddl", + setups={}, + held=frozenset(), )[0] case: Row = {case["sql"]: case for case in generated}["DROP TAG ;"] assert case["setup_sha256"] != PROBE_SETUP @@ -390,6 +408,7 @@ def test_given_probe_role_receipts_when_settling_then_they_bind_any_setup( ) settled, _, marked = settled_cases( + config=shared_config(), root=tmp_path, evidence=tmp_path, family="ddl", @@ -454,11 +473,17 @@ def test_given_a_refused_case_with_every_option_when_building_cases_then_each_op (tmp_path / "catalogue" / "ddl.toml").write_text(ALTER_WIDGET_CATALOGUE) (tmp_path / "limits.toml").write_text("") packed: list[Row] = family_cases( - root=tmp_path, evidence=tmp_path, family="ddl", setups={}, held=frozenset() + config=shared_config(), + root=tmp_path, + evidence=tmp_path, + family="ddl", + setups={}, + held=frozenset(), )[0] refused: Row = {case["sql"]: case for case in packed}[test_case.refused_sql] cases: list[Row] = family_cases( + config=shared_config(), root=tmp_path, evidence=tmp_path, family="ddl", @@ -471,7 +496,9 @@ def test_given_a_refused_case_with_every_option_when_building_cases_then_each_op for case in cases: by_obligation |= dict.fromkeys(case["obligations"], str(case["sql"])) all_options: Row = {case["sql"]: case for case in cases}[ALL_OPTIONS_SQL] - numbered: list[tuple[str, Draft]] = family_obligations(root=tmp_path, family="ddl")[0] + numbered: list[tuple[str, Draft]] = family_obligations( + config=shared_config(), root=tmp_path, family="ddl" + )[0] by_kind: dict[str, list[str]] = {} for found, draft in numbered: by_kind.setdefault(draft.kind, []).append(found) @@ -534,6 +561,7 @@ def test_given_a_catalogued_form_when_building_cases_then_the_case_renders_as_ex (tmp_path / "limits.toml").write_text("") cases: list[Row] = family_cases( + config=shared_config(), root=tmp_path, evidence=tmp_path, family="ddl", @@ -542,7 +570,7 @@ def test_given_a_catalogued_form_when_building_cases_then_the_case_renders_as_ex unpacked=test_case.unpacked, )[0] numbered: list[tuple[str, Draft]] = family_obligations( - root=tmp_path, family="ddl", unpacked=test_case.unpacked + config=shared_config(), root=tmp_path, family="ddl", unpacked=test_case.unpacked )[0] notes: dict[str, str] = {identifier: draft.note for identifier, draft in numbered} @@ -645,6 +673,7 @@ def test_given_an_operand_named_by_a_definition_when_building_cases_then_each_ke (tmp_path / "limits.toml").write_text(test_case.limits) cases: list[Row] = family_cases( + config=shared_config(), root=tmp_path, evidence=tmp_path, family="ddl", @@ -652,7 +681,9 @@ def test_given_an_operand_named_by_a_definition_when_building_cases_then_each_ke held=frozenset(), unpacked=frozenset(), )[0] - numbered: list[tuple[str, Draft]] = family_obligations(root=tmp_path, family="ddl")[0] + numbered: list[tuple[str, Draft]] = family_obligations( + config=shared_config(), root=tmp_path, family="ddl" + )[0] target_of: dict[str, str] = {identifier: draft.target for identifier, draft in numbered} sql_of: dict[str, str] = {} @@ -691,18 +722,25 @@ def test_given_an_operand_named_by_a_definition_when_building_cases_then_each_ke ids=lambda case: case.description, ) def test_given_distinct_list_items_when_an_accept_case_repeats_a_named_item_then_the_build_refuses( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, test_case: RepeatedItemTestCase + tmp_path: Path, test_case: RepeatedItemTestCase ) -> None: (tmp_path / "catalogue").mkdir() (tmp_path / "catalogue" / "ddl.toml").write_text(test_case.catalogue) (tmp_path / "limits.toml").write_text("") - monkeypatch.setitem( - FAMILY_STYLES["ddl"], - test_case.form, - FormStyle( - prefix="", suffix="", fills=test_case.fills, terminate=False, distinct_list_items=True - ), + style: FormStyle = FormStyle( + prefix="", suffix="", fills=test_case.fills, terminate=False, distinct_list_items=True + ) + shared: DialectConfig = shared_config() + config: DialectConfig = replace( + shared, family_styles=with_styles(config=shared, styles={"ddl": {test_case.form: style}}) ) with pytest.raises(ObligationError, match=test_case.expected_message): - family_cases(root=tmp_path, evidence=tmp_path, family="ddl", setups={}, held=frozenset()) + family_cases( + config=config, + root=tmp_path, + evidence=tmp_path, + family="ddl", + setups={}, + held=frozenset(), + ) diff --git a/tests/unit/scripts/grammar_obligations/test_derive.py b/tests/unit/scripts/grammar_obligations/test_derive.py index 1734d3e823..ab9aa1b79b 100644 --- a/tests/unit/scripts/grammar_obligations/test_derive.py +++ b/tests/unit/scripts/grammar_obligations/test_derive.py @@ -7,6 +7,7 @@ import pytest from scripts.grammar_obligations._helpers.derive import derive +from scripts.grammar_obligations._helpers.dialect import shared_config from scripts.grammar_obligations.models import Draft from tests.unit.scripts.grammar_obligations._test_types import ShortenedTargetTestCase @@ -30,7 +31,9 @@ def test_given_a_long_alternative_when_derived_then_its_targets_are_cut_after_a_whole_token( test_case: ShortenedTargetTestCase, ) -> None: - drafts: list[Draft] = derive(form="sf.functions.f", grammar=[test_case.grammar]) + drafts: list[Draft] = derive( + config=shared_config(), form="sf.functions.f", grammar=[test_case.grammar] + ) last: list[str] = re.findall(r"(\S+)…", "\n".join(draft.target for draft in drafts)) assert last diff --git a/tests/unit/scripts/grammar_obligations/test_render.py b/tests/unit/scripts/grammar_obligations/test_render.py index de9d9466a1..5218baade2 100644 --- a/tests/unit/scripts/grammar_obligations/test_render.py +++ b/tests/unit/scripts/grammar_obligations/test_render.py @@ -5,6 +5,7 @@ import pytest from scripts.grammar_obligations._helpers.derive import derive_trees +from scripts.grammar_obligations._helpers.dialect import shared_config from scripts.grammar_obligations._helpers.render import submissions from scripts.grammar_obligations.constants import ACTION_ALL_OPTIONS from scripts.grammar_obligations.models import Draft, FormStyle, Spec @@ -47,14 +48,18 @@ def test_given_a_written_clause_when_rendering_then_only_a_dropped_value_bypasses_it( test_case: ClauseTestCase, ) -> None: - drafts, trees, _ = derive_trees(form="sf.functions.f", grammar=[GRAMMAR]) + drafts, trees, _ = derive_trees( + config=shared_config(), form="sf.functions.f", grammar=[GRAMMAR] + ) found: dict[tuple[str, str], Draft] = {(draft.kind, draft.target): draft for draft in drafts} draft: Draft = found[(test_case.kind, test_case.target)] assert draft.spec is not None sql: tuple[str, ...] = tuple( case.sql - for case in submissions(trees=trees, style=STYLE, spec=draft.spec, depths=draft.depths) + for case in submissions( + config=shared_config(), trees=trees, style=STYLE, spec=draft.spec, depths=draft.depths + ) ) assert sql == test_case.expected_sql, test_case.description @@ -74,7 +79,9 @@ def test_given_a_written_clause_when_rendering_then_only_a_dropped_value_bypasse def test_given_distinct_list_items_when_a_branch_holds_its_own_list_then_that_list_copies_its_item( test_case: DistinctListTestCase, ) -> None: - _, trees, _ = derive_trees(form="sf.functions.g", grammar=[test_case.grammar]) + _, trees, _ = derive_trees( + config=shared_config(), form="sf.functions.g", grammar=[test_case.grammar] + ) style: FormStyle = FormStyle( prefix="", suffix="", @@ -86,7 +93,11 @@ def test_given_distinct_list_items_when_a_branch_holds_its_own_list_then_that_li sql: list[str] = [ case.sql for case in submissions( - trees=trees, style=style, spec=Spec(ACTION_ALL_OPTIONS, 0), depths=() + config=shared_config(), + trees=trees, + style=style, + spec=Spec(ACTION_ALL_OPTIONS, 0), + depths=(), ) ] @@ -127,13 +138,19 @@ def test_given_distinct_list_items_when_a_branch_holds_its_own_list_then_that_li def test_given_distinct_list_items_when_a_list_continues_then_it_names_a_distinct_identifier( test_case: DistinctListTestCase, ) -> None: - _, trees, _ = derive_trees(form="sf.functions.g", grammar=[test_case.grammar]) + _, trees, _ = derive_trees( + config=shared_config(), form="sf.functions.g", grammar=[test_case.grammar] + ) style: FormStyle = FormStyle(prefix="", suffix="", terminate=False, distinct_list_items=True) sql: list[str] = [ case.sql for case in submissions( - trees=trees, style=style, spec=Spec(ACTION_ALL_OPTIONS, 0), depths=() + config=shared_config(), + trees=trees, + style=style, + spec=Spec(ACTION_ALL_OPTIONS, 0), + depths=(), ) ] diff --git a/tests/unit/scripts/grammar_obligations/test_shared_state.py b/tests/unit/scripts/grammar_obligations/test_shared_state.py index a00f7ca23e..c47c22e4c4 100644 --- a/tests/unit/scripts/grammar_obligations/test_shared_state.py +++ b/tests/unit/scripts/grammar_obligations/test_shared_state.py @@ -1,10 +1,24 @@ -"""Each dialect's obligation build is byte-identical whichever dialects were built before it in the process.""" +"""Each dialect's obligation build is byte-identical whichever dialects were built before it in the +process, and no module writes the shared package's names.""" from __future__ import annotations import pytest -from tests.unit.scripts.grammar_obligations._test_types import OneProcessTestCase +from scripts.grammar_obligations._helpers.dialect import shared_writes, tree_writes +from scripts.grammar_obligations.constants import ( + FAMILY_STYLES, + LEXICAL_WRONG, + LEXICALLY_DISTINCT_WRONG_FILL, + REPEAT_FILLS, +) +from tests.unit.scripts.grammar_obligations._test_types import ( + FrozenTableTestCase, + OneProcessTestCase, + SharedWriteTestCase, + SharedWriteTreeTestCase, +) +from tests.unit.scripts.grammar_obligations.helpers import REPOSITORY @pytest.mark.parametrize( @@ -13,43 +27,36 @@ OneProcessTestCase( description="BigQuery", dialect="bigquery", - unisolated=False, expected_outcomes=["exit 0", "exit 0"], ), OneProcessTestCase( description="ClickHouse", dialect="clickhouse", - unisolated=False, expected_outcomes=["exit 0", "exit 0"], ), OneProcessTestCase( - description="Databricks, whose build does not yet run on the shared modules as imported", + description="Databricks", dialect="databricks", - unisolated=True, expected_outcomes=["exit 0", "exit 0"], ), OneProcessTestCase( description="DuckDB", dialect="duckdb", - unisolated=False, expected_outcomes=["exit 0", "exit 0"], ), OneProcessTestCase( description="PostgreSQL", dialect="postgres", - unisolated=False, expected_outcomes=["exit 0", "exit 0"], ), OneProcessTestCase( - description="Snowflake, whose build does not yet run on the shared modules as imported", + description="Snowflake", dialect="snowflake", - unisolated=True, expected_outcomes=["exit 0", "exit 0"], ), OneProcessTestCase( description="SQLite", dialect="sqlite", - unisolated=False, expected_outcomes=["exit 0", "exit 0"], ), ), @@ -58,10 +65,138 @@ def test_given_every_dialect_built_forward_then_in_reverse_in_one_process_when_checked_then_none_is_stale( test_case: OneProcessTestCase, one_process_checks: dict[str, list[str]], - request: pytest.FixtureRequest, ) -> None: - request.applymarker( - pytest.mark.xfail(condition=test_case.unisolated, reason=test_case.description, strict=True) - ) - assert one_process_checks[test_case.dialect] == test_case.expected_outcomes + + +@pytest.mark.parametrize( + "test_case", + ( + SharedWriteTestCase( + description="a shared module's name set by assignment", + source="from scripts.grammar_obligations._helpers import grammar\ngrammar.TOKEN = 'x'\n", + expected_writes=["2: grammar.TOKEN = 'x'"], + ), + SharedWriteTestCase( + description="a shared module's name set by setattr", + source=( + "import scripts.grammar_obligations.classes.walk as walk\n" + "setattr(walk, 'FILL_CLASSES', {})\n" + ), + expected_writes=["2: setattr(walk, 'FILL_CLASSES', {})"], + ), + SharedWriteTestCase( + description="an imported shared table changed in place", + source=( + "from scripts.grammar_obligations.constants import FAMILY_STYLES, REPEAT_FILLS\n" + "FAMILY_STYLES['db'] = {}\nREPEAT_FILLS.update(a='b')\n" + ), + expected_writes=["2: FAMILY_STYLES['db'] = {}", "3: REPEAT_FILLS.update(a='b')"], + ), + SharedWriteTestCase( + description="a shared class's method replaced", + source=( + "from scripts.grammar_obligations.classes.walk import Walk\n" + "Walk.operand_class = len\n" + ), + expected_writes=["2: Walk.operand_class = len"], + ), + SharedWriteTestCase( + description="an imported shared table changed by an augmented assignment", + source=( + "from scripts.grammar_obligations.constants import REPEAT_FILLS, CLASS_RULES\n" + "REPEAT_FILLS |= {('a', 'b'): 'c'}\nCLASS_RULES += ()\n" + ), + expected_writes=["2: REPEAT_FILLS |= {('a', 'b'): 'c'}", "3: CLASS_RULES += ()"], + ), + SharedWriteTestCase( + description="an imported shared table emptied or set through its dunder methods", + source=( + "from scripts.grammar_obligations.constants import LEXICAL_WRONG as wrong\n" + "wrong.popitem()\nwrong.__setitem__('a', 'b')\n" + ), + expected_writes=["2: wrong.popitem()", "3: wrong.__setitem__('a', 'b')"], + ), + SharedWriteTestCase( + description="a shared module's name set inside a tuple target", + source=( + "from scripts.grammar_obligations import constants\n" + "constants.TOKEN, other = 'x', 1\n" + ), + expected_writes=["2: constants.TOKEN, other = ('x', 1)"], + ), + SharedWriteTestCase( + description="a global statement", + source="def f():\n global TOKEN\n", + expected_writes=["2: global TOKEN"], + ), + SharedWriteTestCase( + description="a config replaced and a local copy of a shared table changed", + source=( + "import dataclasses\n" + "from scripts.grammar_obligations._helpers.dialect import shared_config\n" + "from scripts.grammar_obligations.constants import FAMILY_STYLES\n" + "config = dataclasses.replace(shared_config(), token='x')\n" + "styles = dict(FAMILY_STYLES)\nstyles['db'] = {}\nFAMILY_STYLES = {}\n" + ), + expected_writes=[], + ), + ), + ids=lambda case: case.description, +) +def test_given_a_module_when_scanned_then_each_write_to_a_shared_name_is_found( + test_case: SharedWriteTestCase, +) -> None: + assert shared_writes(test_case.source) == test_case.expected_writes, test_case.description + + +@pytest.mark.parametrize( + "test_case", + ( + FrozenTableTestCase(description="the family styles", table=FAMILY_STYLES, key="sf"), + FrozenTableTestCase( + description="one family's styles reached through an alias", + table=FAMILY_STYLES["query"], + key="sf.query.", + ), + FrozenTableTestCase(description="the repeat fills", table=REPEAT_FILLS, key=("a", "b")), + FrozenTableTestCase(description="the lexical wrong fills", table=LEXICAL_WRONG, key="a"), + FrozenTableTestCase( + description="the lexically distinct wrong fills", + table=LEXICALLY_DISTINCT_WRONG_FILL, + key="a", + ), + ), + ids=lambda case: case.description, +) +def test_given_a_shared_table_when_written_through_any_name_then_the_write_is_refused( + test_case: FrozenTableTestCase, +) -> None: + with pytest.raises(TypeError) as raised: + test_case.table[test_case.key] = test_case.table + + assert str(raised.value) == test_case.expected_error, test_case.description + + +@pytest.mark.parametrize( + "test_case", + ( + SharedWriteTreeTestCase( + description="every dialect adapter and builder builds its own config", + directory="scripts", + expected_writes={}, + ), + SharedWriteTreeTestCase( + description="every test passes a config instead of installing one", + directory="tests", + expected_writes={}, + ), + ), + ids=lambda case: case.description, +) +def test_given_the_repository_when_scanned_then_no_module_writes_a_shared_name( + test_case: SharedWriteTreeTestCase, +) -> None: + writes: dict[str, list[str]] = tree_writes(root=REPOSITORY, directory=test_case.directory) + + assert writes == test_case.expected_writes, test_case.description diff --git a/tests/unit/scripts/syntax_obligations_bigquery/_test_types.py b/tests/unit/scripts/syntax_obligations_bigquery/_test_types.py index f39f47ddb7..762d3b4697 100644 --- a/tests/unit/scripts/syntax_obligations_bigquery/_test_types.py +++ b/tests/unit/scripts/syntax_obligations_bigquery/_test_types.py @@ -101,12 +101,6 @@ class CheckTestCase: expected_stale: int -@dataclass(frozen=True) -class RestoredStateTestCase: - description: str - expected_same: dict[str, bool] - - @dataclass(frozen=True) class RepeatedSettingTestCase: description: str diff --git a/tests/unit/scripts/syntax_obligations_bigquery/conftest.py b/tests/unit/scripts/syntax_obligations_bigquery/conftest.py deleted file mode 100644 index ce54189629..0000000000 --- a/tests/unit/scripts/syntax_obligations_bigquery/conftest.py +++ /dev/null @@ -1,16 +0,0 @@ -"""Undo what BigQuery's install() sets on the shared grammar-obligations modules after each test.""" - -from __future__ import annotations - -from collections.abc import Generator - -import pytest - -from scripts.grammar_obligations._helpers.shared_state import restored_shared_state - - -@pytest.fixture(autouse=True) -def shared_state() -> Generator[None]: - """The shared modules as they were before the test, for tests that call install() directly.""" - with restored_shared_state(): - yield diff --git a/tests/unit/scripts/syntax_obligations_bigquery/helpers.py b/tests/unit/scripts/syntax_obligations_bigquery/helpers.py index 893ae7764d..6182fe7024 100644 --- a/tests/unit/scripts/syntax_obligations_bigquery/helpers.py +++ b/tests/unit/scripts/syntax_obligations_bigquery/helpers.py @@ -4,10 +4,7 @@ import shutil from pathlib import Path -from types import ModuleType -from scripts.grammar_obligations import constants as shared -from scripts.grammar_obligations._helpers import grammar, obligations from scripts.grammar_obligations.exceptions import ObligationError from scripts.syntax_obligations_bigquery.constants import FAMILIES from scripts.syntax_obligations_bigquery.main.build import run_build @@ -51,15 +48,3 @@ def build_error(*, root: Path, parser: Path) -> str: except ObligationError as raised: return str(raised) return "" - - -SHARED_MODULES: tuple[ModuleType, ...] = (shared, grammar, obligations) - - -def shared_snapshot() -> dict[str, dict[str, object]]: - """Each shared module's names, and FAMILY_STYLES' styles, by name.""" - names: dict[str, dict[str, object]] = { - module.__name__: dict(vars(module)) for module in SHARED_MODULES - } - names["FAMILY_STYLES"] = {family: dict(forms) for family, forms in shared.FAMILY_STYLES.items()} - return names diff --git a/tests/unit/scripts/syntax_obligations_bigquery/test_class_rules.py b/tests/unit/scripts/syntax_obligations_bigquery/test_class_rules.py index 4462658a56..eea8d7cd4f 100644 --- a/tests/unit/scripts/syntax_obligations_bigquery/test_class_rules.py +++ b/tests/unit/scripts/syntax_obligations_bigquery/test_class_rules.py @@ -4,10 +4,9 @@ import pytest -from scripts.grammar_obligations._helpers import obligations from scripts.grammar_obligations.constants import KIND_OPERAND_CLASS from scripts.grammar_obligations.models import Draft -from scripts.syntax_obligations_bigquery._helpers.adapt import install +from scripts.syntax_obligations_bigquery._helpers.adapt import bigquery_config from tests.unit.scripts.syntax_obligations_bigquery._test_types import ClassTestCase from tests.unit.scripts.syntax_obligations_bigquery.helpers import ROOT @@ -58,9 +57,9 @@ def test_given_a_placeholder_when_deriving_then_it_takes_its_documented_class( test_case: ClassTestCase, ) -> None: - install(ROOT) - drafts: list[Draft] = obligations.derive_trees( - form=test_case.form, grammar=[test_case.grammar] + config, _ = bigquery_config(ROOT) + drafts: list[Draft] = config.derive_trees( + config=config, form=test_case.form, grammar=[test_case.grammar] )[0] notes: dict[tuple[str, str], str] = {(draft.kind, draft.target): draft.note for draft in drafts} assert notes.get((KIND_OPERAND_CLASS, test_case.placeholder), NO_CLASS) == ( diff --git a/tests/unit/scripts/syntax_obligations_bigquery/test_no_over.py b/tests/unit/scripts/syntax_obligations_bigquery/test_no_over.py index 4d5b404932..cd4df23958 100644 --- a/tests/unit/scripts/syntax_obligations_bigquery/test_no_over.py +++ b/tests/unit/scripts/syntax_obligations_bigquery/test_no_over.py @@ -6,10 +6,9 @@ import pytest -from scripts.grammar_obligations._helpers import obligations from scripts.grammar_obligations._helpers.render import style_of, submissions from scripts.grammar_obligations.models import Draft, FormStyle, Rendered, Spec -from scripts.syntax_obligations_bigquery._helpers.adapt import install +from scripts.syntax_obligations_bigquery._helpers.adapt import bigquery_config from scripts.syntax_obligations_bigquery.constants import NO_OVER_NOTE from tests.unit.scripts.syntax_obligations_bigquery._test_types import NoOverTestCase from tests.unit.scripts.syntax_obligations_bigquery.helpers import ROOT @@ -55,13 +54,15 @@ def test_given_a_form_with_options_when_deriving_then_only_function_forms_with_over_add_a_case_without_it( test_case: NoOverTestCase, ) -> None: - install(ROOT) + config, _ = bigquery_config(ROOT) family: str = test_case.form.split(".")[1] - drafts, trees, _ = obligations.derive_trees(form=test_case.form, grammar=test_case.grammar) + drafts, trees, _ = config.derive_trees( + config=config, form=test_case.form, grammar=test_case.grammar + ) found: list[Draft] = list(filter(lambda draft: draft.note == NO_OVER_NOTE, drafts)) - style: FormStyle = style_of(family=family, form=test_case.form) + style: FormStyle = style_of(config=config, family=family, form=test_case.form) rendered: list[list[Rendered]] = [ - submissions(trees=trees, style=style, spec=draft.spec or Spec(""), depths=()) + submissions(config=config, trees=trees, style=style, spec=draft.spec or Spec(""), depths=()) for draft in found ] diff --git a/tests/unit/scripts/syntax_obligations_bigquery/test_shared_state.py b/tests/unit/scripts/syntax_obligations_bigquery/test_shared_state.py deleted file mode 100644 index b9cd5e5efa..0000000000 --- a/tests/unit/scripts/syntax_obligations_bigquery/test_shared_state.py +++ /dev/null @@ -1,39 +0,0 @@ -"""BigQuery installed inside the guard leaves the shared grammar-obligations modules as it found them.""" - -from __future__ import annotations - -import pytest - -from scripts.grammar_obligations._helpers.shared_state import restored_shared_state -from scripts.syntax_obligations_bigquery._helpers.adapt import install -from tests.unit.scripts.syntax_obligations_bigquery._test_types import ( - RestoredStateTestCase, -) -from tests.unit.scripts.syntax_obligations_bigquery.helpers import ROOT, shared_snapshot - - -@pytest.mark.parametrize( - "test_case", - ( - RestoredStateTestCase( - description="every shared name and family style is as it was after BigQuery installs inside the guard", - expected_same={ - "scripts.grammar_obligations.constants": True, - "scripts.grammar_obligations._helpers.grammar": True, - "scripts.grammar_obligations._helpers.obligations": True, - "FAMILY_STYLES": True, - }, - ), - ), - ids=lambda case: case.description, -) -def test_given_bigquery_installed_inside_the_guard_when_it_exits_then_the_shared_modules_are_unchanged( - test_case: RestoredStateTestCase, -) -> None: - before: dict[str, dict[str, object]] = shared_snapshot() - - with restored_shared_state(): - install(ROOT) - after: dict[str, dict[str, object]] = shared_snapshot() - - assert {name: after[name] == before[name] for name in before} == test_case.expected_same diff --git a/tests/unit/scripts/syntax_obligations_bigquery/test_signature_fills.py b/tests/unit/scripts/syntax_obligations_bigquery/test_signature_fills.py index 425725c8d8..1c5683afb7 100644 --- a/tests/unit/scripts/syntax_obligations_bigquery/test_signature_fills.py +++ b/tests/unit/scripts/syntax_obligations_bigquery/test_signature_fills.py @@ -6,7 +6,7 @@ from scripts.grammar_obligations._helpers.render import style_of from scripts.grammar_obligations.models import FormStyle -from scripts.syntax_obligations_bigquery._helpers.adapt import install +from scripts.syntax_obligations_bigquery._helpers.adapt import bigquery_config from scripts.syntax_obligations_bigquery.constants import JSON_FILL, JSON_STRING_FILL from tests.unit.scripts.syntax_obligations_bigquery._test_types import SignatureFillTestCase from tests.unit.scripts.syntax_obligations_bigquery.helpers import ROOT @@ -166,8 +166,8 @@ def test_given_a_typed_function_form_when_its_operands_are_filled_then_each_fill_has_a_documented_type( test_case: SignatureFillTestCase, ) -> None: - install(ROOT) - found: FormStyle = style_of(family=test_case.family, form=test_case.form) + config, _ = bigquery_config(ROOT) + found: FormStyle = style_of(config=config, family=test_case.family, form=test_case.form) assert ( {name: found.fills.get(name) for name in test_case.expected_fills}, diff --git a/tests/unit/scripts/syntax_obligations_bigquery/test_struct_settings.py b/tests/unit/scripts/syntax_obligations_bigquery/test_struct_settings.py index 6c685d971f..5f217a62be 100644 --- a/tests/unit/scripts/syntax_obligations_bigquery/test_struct_settings.py +++ b/tests/unit/scripts/syntax_obligations_bigquery/test_struct_settings.py @@ -6,10 +6,9 @@ import pytest -from scripts.grammar_obligations._helpers import obligations from scripts.grammar_obligations._helpers.render import style_of, submissions from scripts.grammar_obligations.models import FormStyle, Rendered, Spec -from scripts.syntax_obligations_bigquery._helpers.adapt import install +from scripts.syntax_obligations_bigquery._helpers.adapt import bigquery_config from scripts.syntax_obligations_bigquery._helpers.cases import repeated_settings from tests.unit.scripts.syntax_obligations_bigquery._test_types import ( RepeatedSettingTestCase, @@ -74,12 +73,16 @@ def test_given_case_sql_when_reading_its_struct_then_only_a_field_named_twice_is def test_given_a_setting_list_when_rendering_every_case_then_no_case_repeats_a_field( test_case: SettingListTestCase, ) -> None: - install(ROOT) - drafts, trees, _ = obligations.derive_trees(form=test_case.form, grammar=test_case.grammar) - style: FormStyle = style_of(family="functions", form=test_case.form) + config, _ = bigquery_config(ROOT) + drafts, trees, _ = config.derive_trees( + config=config, form=test_case.form, grammar=test_case.grammar + ) + style: FormStyle = style_of(config=config, family="functions", form=test_case.form) rendered: list[Rendered] = list( chain.from_iterable( - submissions(trees=trees, style=style, spec=draft.spec or Spec(""), depths=()) + submissions( + config=config, trees=trees, style=style, spec=draft.spec or Spec(""), depths=() + ) for draft in drafts ) ) diff --git a/tests/unit/scripts/syntax_obligations_snowflake/helpers.py b/tests/unit/scripts/syntax_obligations_snowflake/helpers.py index b0f1c6274c..f03dd39bb6 100644 --- a/tests/unit/scripts/syntax_obligations_snowflake/helpers.py +++ b/tests/unit/scripts/syntax_obligations_snowflake/helpers.py @@ -9,8 +9,8 @@ from scripts.grammar_obligations._helpers.obligations import family_obligations from scripts.grammar_obligations._helpers.render import style_of, submissions -from scripts.grammar_obligations.models import Draft -from scripts.syntax_obligations_snowflake._helpers.rules import install +from scripts.grammar_obligations.models import DialectConfig, Draft +from scripts.syntax_obligations_snowflake._helpers.rules import snowflake_config from scripts.syntax_obligations_snowflake.main.build import run_build from tests.unit.scripts.syntax_obligations_snowflake._test_types import ListItemTestCase @@ -152,8 +152,10 @@ def rendered_sql(*, directory: Path, test_case: ListItemTestCase) -> tuple[str, 'status = "catalogued"\n' ) (directory / "limits.toml").write_text("") - install() - numbered, trees, _, _, _ = family_obligations(root=directory, family=test_case.family) + config: DialectConfig = snowflake_config() + numbered, trees, _, _, _ = family_obligations( + config=config, root=directory, family=test_case.family + ) drafts: dict[tuple[str, str | None], Draft] = { **{(draft.kind, draft.note): draft for _, draft in numbered}, **{(draft.kind, draft.target): draft for _, draft in numbered}, @@ -163,8 +165,9 @@ def rendered_sql(*, directory: Path, test_case: ListItemTestCase) -> tuple[str, return tuple( case.sql for case in submissions( + config=config, trees=trees[draft.form], - style=style_of(family=test_case.family, form=draft.form), + style=style_of(config=config, family=test_case.family, form=draft.form), spec=draft.spec, depths=draft.depths, )