dynos-ddl 0.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dynos_ddl/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ """Dynos Domain Language (DDL).
2
+
3
+ Public interface:
4
+ - `parse(source)`: Program AST
5
+ - `ast`: the AST module (node types)
6
+ - `errors`: DDL exception classes
7
+ """
8
+
9
+ from . import ast, errors
10
+ from .env import Environment, EvalBackend, MockEvalBackend, make_test_env
11
+ from .eval import Result, evaluate
12
+ from .parser import parse
13
+ from .render_source import render_source
14
+ from .resolve import RESERVED_ATTRS, Resolution, ResolverEnv, Tier, resolve
15
+ from .typecheck import typecheck
16
+
17
+ __all__ = [
18
+ "parse",
19
+ "render_source",
20
+ "typecheck",
21
+ "resolve",
22
+ "evaluate",
23
+ "Result",
24
+ "Environment",
25
+ "EvalBackend",
26
+ "MockEvalBackend",
27
+ "make_test_env",
28
+ "ast",
29
+ "errors",
30
+ "Resolution",
31
+ "ResolverEnv",
32
+ "Tier",
33
+ "RESERVED_ATTRS",
34
+ ]
dynos_ddl/ast.py ADDED
@@ -0,0 +1,346 @@
1
+ """DDL AST node types."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Optional, Tuple, Union
7
+
8
+ # Base classes ---------------------------------------------------------
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Node:
13
+ """Base for every AST node."""
14
+
15
+
16
+ class Stmt(Node):
17
+ """A top-level statement."""
18
+
19
+
20
+ class Expr(Node):
21
+ """An expression."""
22
+
23
+
24
+ class CtxLhs(Node):
25
+ """A context-LHS expression (target of a block or broadcast)."""
26
+
27
+
28
+ class FilterPred(Node):
29
+ """A predicate inside a filter `{...}`."""
30
+
31
+
32
+ # Program --------------------------------------------------------------
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Program(Node):
37
+ """Top-level statement list."""
38
+
39
+ stmts: Tuple[Stmt, ...] = ()
40
+
41
+
42
+ # Statements -----------------------------------------------------------
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Mutation(Stmt):
47
+ """`lhs op rhs` where op is `+`, `-`, or `=`.
48
+
49
+ Position-bound: covers rule 1 (mutation LHS) and the
50
+ universal mutation rule of.
51
+ """
52
+
53
+ op: str = "" # '+', '-', '='
54
+ lhs: Expr = field(default_factory=lambda: Ident(name=""))
55
+ rhs: Expr = field(default_factory=lambda: Nil())
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class Block(Stmt):
60
+ """`target:(stmts...)` block-scope form."""
61
+
62
+ target: CtxLhs = field(default_factory=lambda: ActiveContext())
63
+ stmts: Tuple[Stmt, ...] = ()
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class CreateBlock(Stmt):
68
+ """`@+name(=source)?:(stmts)`; create-and-run form."""
69
+
70
+ name: str = ""
71
+ source: Optional[str] = None # for the `=src` form; None if absent
72
+ stmts: Tuple[Stmt, ...] = ()
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class Prefix(Stmt, Expr):
77
+ """`<prefix> <body>`; a query (`?`), guard (`??`), cost (`$`),"""
78
+
79
+ op: str = "" # '?', '??', '$', '$%', '%', '#'
80
+ body: Union[Expr, "Batch"] = field(default_factory=lambda: Nil())
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class Batch(Node):
85
+ """`(a, b, c)`; only valid as a Prefix body. The grammar requires"""
86
+
87
+ items: Tuple[Expr, ...] = ()
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class Command(Stmt):
92
+ """`!cmd(args, kwargs)`; ensure current action."""
93
+
94
+ call: "Call" = field(default_factory=lambda: Call(target=Ident(name="")))
95
+
96
+
97
+ @dataclass(frozen=True)
98
+ class Halt(Stmt):
99
+ """`!!`; clear `.A` and `.G` in one keystroke."""
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class Promote(Stmt):
104
+ """`!@<name>`; commit a staged clone into the live mission. The
105
+ snapshot's state and goal become the live orchestrator's state and
106
+ goal; the snapshot itself is archived (one-way: this is the
107
+ "commit a staged variant" workflow).
108
+
109
+ `!@` (active) promotes whichever context is currently active;
110
+ common when the operator did `@=staged` then wants the staged
111
+ edits to take effect.
112
+
113
+ Mirrors `!cmd(...)` syntactically: `!` is "do this thing now."
114
+ """
115
+
116
+ target: "Expr" = field(default_factory=lambda: ActiveContext())
117
+
118
+
119
+ @dataclass(frozen=True)
120
+ class Import(Stmt):
121
+ """`/import "path"` directive.
122
+
123
+ Decision 11: v1 evaluator returns DDLRuntimeError; parser still
124
+ accepts the form so the language surface is consistent across
125
+ versions.
126
+ """
127
+
128
+ path: str = ""
129
+
130
+
131
+ @dataclass(frozen=True)
132
+ class Extend(Stmt):
133
+ """`/extend "name" as alias?` directive.
134
+
135
+ Decision 11: v1 evaluator returns DDLRuntimeError.
136
+ """
137
+
138
+ name: str = ""
139
+ alias: Optional[str] = None
140
+
141
+
142
+ @dataclass(frozen=True)
143
+ class ExtCall(Stmt):
144
+ """`/alias::keyword payload?`; dispatch to a loaded extension."""
145
+
146
+ path: Tuple[str, ...] = () # e.g. ('ep', 'tell')
147
+ payload: Optional[Union[Expr, Block, Command, "TupleArgs"]] = None
148
+
149
+
150
+ @dataclass(frozen=True)
151
+ class TupleArgs(Node):
152
+ """`( args, kwargs )` payload form for extension calls."""
153
+
154
+ args: Tuple[Expr, ...] = ()
155
+ kwargs: Tuple[Tuple[str, Expr], ...] = ()
156
+
157
+
158
+ @dataclass(frozen=True)
159
+ class CommentStmt(Stmt):
160
+ """A bare string literal on its own as a statement. Parsed and
161
+ discarded by the runtime; preserved in the AST for round-trip and
162
+ transcript replay."""
163
+
164
+ text: str = ""
165
+
166
+
167
+ @dataclass(frozen=True)
168
+ class ContextSwitch(Stmt):
169
+ """`@=name`; switch the active context. Client-side state change;"""
170
+
171
+ name: str = ""
172
+
173
+
174
+ # Context-LHS ----------------------------------------------------------
175
+
176
+
177
+ @dataclass(frozen=True)
178
+ class ActiveContext(CtxLhs, Expr):
179
+ """`@`; the active context. Valid in both ctx-LHS and expression"""
180
+
181
+
182
+ @dataclass(frozen=True)
183
+ class AllContexts(CtxLhs, Expr):
184
+ """`@*`; the set of all known contexts."""
185
+
186
+
187
+ @dataclass(frozen=True)
188
+ class NamedContext(CtxLhs, Expr):
189
+ """`@name`; a named context by binding name."""
190
+
191
+ name: str = ""
192
+
193
+
194
+ # Expressions ----------------------------------------------------------
195
+
196
+
197
+ @dataclass(frozen=True)
198
+ class BinaryOp(Expr):
199
+ """Binary infix expression. `op` is one of the set / comparison /"""
200
+
201
+ op: str = "" # '+', '-', '^', '&', '<', '<=', '>', '>=', 'in', '!in', '==', '!='
202
+ lhs: Expr = field(default_factory=lambda: Nil())
203
+ rhs: Expr = field(default_factory=lambda: Nil())
204
+
205
+
206
+ # Postfix operators are each their own node, applied to a base Expr.
207
+ # This keeps the AST flat (no nested PostfixChain).
208
+
209
+
210
+ @dataclass(frozen=True)
211
+ class AttrAccess(Expr):
212
+ """`target.attr`; attribute access."""
213
+
214
+ target: Expr = field(default_factory=lambda: Nil())
215
+ attr: str = ""
216
+
217
+
218
+ @dataclass(frozen=True)
219
+ class MetaAccess(Expr):
220
+ """`target::attr`; shorthand for `target.meta.attr`."""
221
+
222
+ target: Expr = field(default_factory=lambda: Nil())
223
+ attr: str = ""
224
+
225
+
226
+ @dataclass(frozen=True)
227
+ class Index(Expr):
228
+ """`target[i]`; list/sequence index."""
229
+
230
+ target: Expr = field(default_factory=lambda: Nil())
231
+ index: Expr = field(default_factory=lambda: Nil())
232
+
233
+
234
+ @dataclass(frozen=True)
235
+ class Slice(Expr):
236
+ """`target[start:stop]`; slice access."""
237
+
238
+ target: Expr = field(default_factory=lambda: Nil())
239
+ start: Optional[Expr] = None
240
+ stop: Optional[Expr] = None
241
+
242
+
243
+ @dataclass(frozen=True)
244
+ class Filter(Expr):
245
+ """`target{pred1, pred2, ...}`; set filter."""
246
+
247
+ target: Expr = field(default_factory=lambda: Nil())
248
+ preds: Tuple[FilterPred, ...] = ()
249
+
250
+
251
+ @dataclass(frozen=True)
252
+ class Call(Expr):
253
+ """`target(arg, ..., kwarg=val, ...)`; function call.
254
+
255
+ `target` is typically an Ident (bare-name call like `goto(z)`) but
256
+ may be any Expr for postfix-chain calls.
257
+ """
258
+
259
+ target: Expr = field(default_factory=lambda: Ident(name=""))
260
+ args: Tuple[Expr, ...] = ()
261
+ kwargs: Tuple[Tuple[str, Expr], ...] = ()
262
+
263
+
264
+ # Primaries ------------------------------------------------------------
265
+
266
+
267
+ @dataclass(frozen=True)
268
+ class Ident(Expr):
269
+ """A bare identifier. Resolution happens at eval time via the"""
270
+
271
+ name: str = ""
272
+
273
+
274
+ @dataclass(frozen=True)
275
+ class Wildcard(Expr):
276
+ """`_`; the iteration placeholder. Admissible only inside filter"""
277
+
278
+
279
+ @dataclass(frozen=True)
280
+ class PatternVar(Expr):
281
+ """`_NAME`; a pattern variable. Admissible only inside schema-"""
282
+
283
+ name: str = ""
284
+
285
+
286
+ @dataclass(frozen=True)
287
+ class Number(Expr):
288
+ """A numeric literal."""
289
+
290
+ value: Union[int, float] = 0
291
+
292
+
293
+ @dataclass(frozen=True)
294
+ class String(Expr):
295
+ """A string literal."""
296
+
297
+ value: str = ""
298
+
299
+
300
+ @dataclass(frozen=True)
301
+ class Nil(Expr):
302
+ """The `nil` literal."""
303
+
304
+
305
+ @dataclass(frozen=True)
306
+ class SetLiteral(Expr):
307
+ """`{a, b, c}` set literal."""
308
+
309
+ items: Tuple[Expr, ...] = ()
310
+
311
+
312
+ @dataclass(frozen=True)
313
+ class ListLiteral(Expr):
314
+ """`[a, b, c]` list literal."""
315
+
316
+ items: Tuple[Expr, ...] = ()
317
+
318
+
319
+ @dataclass(frozen=True)
320
+ class LitNegation(Expr):
321
+ """`~call(...)`; literal-position negation.
322
+
323
+ rule 7 /, admissible only in literal-set
324
+ slots (.G, pre, conds, adds/removes). The grammar accepts it
325
+ anywhere; the typechecker enforces the position constraint.
326
+ """
327
+
328
+ call: Call = field(default_factory=lambda: Call())
329
+
330
+
331
+ # Filter predicates ----------------------------------------------------
332
+
333
+
334
+ @dataclass(frozen=True)
335
+ class FilterQuery(FilterPred):
336
+ """`?expr` form; interpreted as a one-statement block per member."""
337
+
338
+ expr: Expr = field(default_factory=lambda: Nil())
339
+
340
+
341
+ @dataclass(frozen=True)
342
+ class FilterExpr(FilterPred):
343
+ """An arbitrary boolean expression evaluated against the iteration
344
+ member (bound to `_` and accessible via `_.attr`)."""
345
+
346
+ expr: Expr = field(default_factory=lambda: Nil())
dynos_ddl/cli.py ADDED
@@ -0,0 +1,238 @@
1
+ """CLI registration hooks for dynos-ddl.
2
+
3
+ Discovered via the ``dynos.cli`` entry-point group declared in this
4
+ package's ``pyproject.toml``. The ``dynos-client`` CLI loader calls
5
+ ``register_repl(app)`` and ``register_ddl(app)`` at startup.
6
+
7
+ Heavy dependencies (``prompt_toolkit``, ``requests``, ``rich``) are
8
+ imported lazily inside the command bodies so that simply loading this
9
+ module is cheap.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ from pathlib import Path
16
+ from typing import Optional
17
+
18
+ import typer
19
+
20
+ _DEFAULT_DDL_HOST = "http://127.0.0.1:8421"
21
+
22
+
23
+ def _probe_host(url: str, timeout: float = 0.5) -> bool:
24
+ """Quick reachability check on /health."""
25
+ try:
26
+ import requests
27
+
28
+ r = requests.get(url.rstrip("/") + "/health", timeout=timeout)
29
+ return r.status_code == 200
30
+ except Exception:
31
+ return False
32
+
33
+
34
+ def _make_console():
35
+ """rich Console if available, else a stdlib-print fallback shim."""
36
+ try:
37
+ from rich.console import Console
38
+
39
+ return Console()
40
+ except ImportError:
41
+ class _PlainConsole:
42
+ def print(self, msg, *args, **kwargs):
43
+ import re
44
+
45
+ print(re.sub(r"\[[^\]]+\]", "", str(msg)))
46
+
47
+ return _PlainConsole()
48
+
49
+
50
+ def register_repl(app: typer.Typer) -> None:
51
+ @app.command("repl")
52
+ def ddl_repl(
53
+ connect: Optional[str] = typer.Option(
54
+ None,
55
+ "--connect",
56
+ help=(
57
+ f"Connect to a dynos host (URL). Default: {_DEFAULT_DDL_HOST}. "
58
+ "If no host is reachable, the REPL refuses to start; use "
59
+ "`--mock` for offline language exploration."
60
+ ),
61
+ ),
62
+ mock: bool = typer.Option(
63
+ False,
64
+ "--mock",
65
+ help=(
66
+ "Run an offline REPL against an in-memory mock backend "
67
+ "(no live orchestrator). For language exploration only; "
68
+ "operations do NOT affect any real mission."
69
+ ),
70
+ ),
71
+ grammar: bool = typer.Option(
72
+ False, "--grammar", help="Dump the EBNF grammar reference and exit."
73
+ ),
74
+ no_gloss: bool = typer.Option(
75
+ False, "--no-gloss", help="Disable the live structural gloss."
76
+ ),
77
+ gloss_verbose: bool = typer.Option(
78
+ False,
79
+ "--gloss-verbose",
80
+ help="Enable host-roundtrip gloss additions.",
81
+ ),
82
+ no_color: bool = typer.Option(
83
+ False,
84
+ "--no-color",
85
+ help=(
86
+ "Disable syntax highlighting and gloss colors. Sets "
87
+ "NO_COLOR=1 for the process; also honors NO_COLOR in the "
88
+ "environment."
89
+ ),
90
+ ),
91
+ ) -> None:
92
+ """Start the DDL interactive REPL.
93
+
94
+ By default, connects to a running `dynos host`. If no host is
95
+ reachable, refuses to start with an actionable message;
96
+ operators are never silently sent to a mock.
97
+
98
+ Use `--connect <url>` to target a different host. Use `--mock`
99
+ for explicit offline language exploration (operations do NOT
100
+ affect any real mission).
101
+ """
102
+ console = _make_console()
103
+
104
+ if no_gloss and gloss_verbose:
105
+ console.print(
106
+ "[red]error:[/red] --no-gloss and --gloss-verbose are mutually exclusive"
107
+ )
108
+ raise typer.Exit(2)
109
+ gloss_mode = "off" if no_gloss else ("verbose" if gloss_verbose else "on")
110
+ if no_color:
111
+ os.environ["NO_COLOR"] = "1"
112
+ if grammar:
113
+ from importlib import resources as _resources
114
+
115
+ grammar_text = (
116
+ _resources.files("dynos_ddl").joinpath("grammar.lark").read_text()
117
+ )
118
+ print(grammar_text)
119
+ return
120
+
121
+ if mock:
122
+ if connect is not None:
123
+ console.print(
124
+ "[red]error:[/red] --mock and --connect are mutually exclusive"
125
+ )
126
+ raise typer.Exit(2)
127
+ console.print(
128
+ "[yellow]Starting offline REPL with mock backend. "
129
+ "Operations do NOT affect any real mission.[/yellow]"
130
+ )
131
+ from dynos_ddl import make_test_env
132
+ from dynos_ddl.repl import run_interactive
133
+
134
+ env = make_test_env()
135
+ raise SystemExit(run_interactive(env, gloss_mode=gloss_mode))
136
+
137
+ target = connect or _DEFAULT_DDL_HOST
138
+ if not _probe_host(target):
139
+ console.print(
140
+ f"[red]error:[/red] no dynos host reachable at {target}."
141
+ )
142
+ console.print(
143
+ "Start one in another terminal with: "
144
+ "[cyan]dynos run <robot>[/cyan] or [cyan]dynos host[/cyan]"
145
+ )
146
+ console.print(
147
+ "Or run the REPL offline against a mock backend: "
148
+ "[cyan]dynos repl --mock[/cyan]"
149
+ )
150
+ raise typer.Exit(1)
151
+
152
+ from dynos_ddl.protocol import run_protocol_repl
153
+
154
+ raise SystemExit(run_protocol_repl(target, gloss_mode=gloss_mode))
155
+
156
+
157
+ def register_ddl(app: typer.Typer) -> None:
158
+ @app.command("ddl")
159
+ def ddl_run(
160
+ file: Optional[Path] = typer.Argument(
161
+ None, help="Path to a .ddl mission file to execute."
162
+ ),
163
+ eval_source: Optional[str] = typer.Option(
164
+ None, "--eval", help="Execute a single DDL statement and exit."
165
+ ),
166
+ replay: Optional[Path] = typer.Option(
167
+ None, "--replay", help="Replay a transcript against a dry-run runtime."
168
+ ),
169
+ connect: Optional[str] = typer.Option(
170
+ None,
171
+ "--connect",
172
+ help=(
173
+ f"Send to a dynos host (URL). Default: {_DEFAULT_DDL_HOST}. "
174
+ "If no host is reachable, refuses to start; use --mock for "
175
+ "offline."
176
+ ),
177
+ ),
178
+ mock: bool = typer.Option(
179
+ False,
180
+ "--mock",
181
+ help=(
182
+ "Execute against an in-memory mock backend. For language "
183
+ "exploration only; does NOT affect any real mission."
184
+ ),
185
+ ),
186
+ ) -> None:
187
+ """Execute DDL non-interactively against a live host (default) or
188
+ an offline mock (`--mock`)."""
189
+ console = _make_console()
190
+ if mock and connect is not None:
191
+ print("error: --mock and --connect are mutually exclusive")
192
+ raise typer.Exit(2)
193
+
194
+ # --replay implies a dry-run: replay executes a transcript against
195
+ # an in-memory mock environment, not the live host.
196
+ if replay is not None:
197
+ if connect is not None:
198
+ console.print(
199
+ "[yellow]--replay runs against a mock backend; "
200
+ "--connect is ignored for replay.[/yellow]"
201
+ )
202
+ from dynos_ddl import make_test_env
203
+ from dynos_ddl.repl import run_file
204
+
205
+ console.print(
206
+ f"[cyan]Replaying {replay} in dry-run mode (mock backend).[/cyan]"
207
+ )
208
+ raise SystemExit(run_file(make_test_env(), replay))
209
+
210
+ if not mock:
211
+ target_url = connect or _DEFAULT_DDL_HOST
212
+ if not _probe_host(target_url):
213
+ console.print(
214
+ f"[red]error:[/red] no dynos host reachable at {target_url}. "
215
+ "Start one with `dynos run <robot>` or `dynos host`, or "
216
+ "pass --mock for offline."
217
+ )
218
+ raise typer.Exit(1)
219
+ from dynos_ddl.protocol import run_protocol_eval, run_protocol_file
220
+
221
+ if eval_source is not None:
222
+ raise SystemExit(run_protocol_eval(target_url, eval_source))
223
+ if file is None:
224
+ print("error: supply <file>, --eval, or --replay")
225
+ raise SystemExit(2)
226
+ raise SystemExit(run_protocol_file(target_url, file))
227
+
228
+ # Mock path
229
+ from dynos_ddl import make_test_env
230
+ from dynos_ddl.repl import run_eval, run_file
231
+
232
+ env = make_test_env()
233
+ if eval_source is not None:
234
+ raise SystemExit(run_eval(env, eval_source))
235
+ if file is None:
236
+ print("error: supply <file>, --eval, or --replay")
237
+ raise SystemExit(2)
238
+ raise SystemExit(run_file(env, file))