factlang 0.1.0__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.
- factlang/__about__.py +4 -0
- factlang/__init__.py +113 -0
- factlang/__main__.py +5 -0
- factlang/agent/__init__.py +10 -0
- factlang/agent/mcp.py +206 -0
- factlang/agent/reference.py +122 -0
- factlang/agent/tools.py +258 -0
- factlang/api.py +207 -0
- factlang/cli.py +499 -0
- factlang/connectors/__init__.py +44 -0
- factlang/connectors/base.py +475 -0
- factlang/connectors/bigquery.py +135 -0
- factlang/connectors/callable.py +49 -0
- factlang/connectors/catalog.py +134 -0
- factlang/connectors/dbapi.py +180 -0
- factlang/connectors/sqlalchemy.py +104 -0
- factlang/contract.py +603 -0
- factlang/diagnostics.py +141 -0
- factlang/engine.py +865 -0
- factlang/ir/__init__.py +52 -0
- factlang/ir/metrics.py +61 -0
- factlang/ir/primitives.py +462 -0
- factlang/judge/__init__.py +41 -0
- factlang/judge/outcome.py +111 -0
- factlang/judge/predicate.py +369 -0
- factlang/judge/run.py +80 -0
- factlang/optimizer.py +182 -0
- factlang/packs/__init__.py +3 -0
- factlang/packs/standard/__init__.py +46 -0
- factlang/packs/standard/_common.py +131 -0
- factlang/packs/standard/avg.py +58 -0
- factlang/packs/standard/count.py +56 -0
- factlang/packs/standard/dead.py +40 -0
- factlang/packs/standard/distinct.py +58 -0
- factlang/packs/standard/exists.py +56 -0
- factlang/packs/standard/fanout.py +50 -0
- factlang/packs/standard/fresh.py +67 -0
- factlang/packs/standard/join.py +173 -0
- factlang/packs/standard/max.py +61 -0
- factlang/packs/standard/min.py +61 -0
- factlang/packs/standard/note.py +45 -0
- factlang/packs/standard/nulls.py +53 -0
- factlang/packs/standard/pattern.py +54 -0
- factlang/packs/standard/range.py +100 -0
- factlang/packs/standard/rows.py +47 -0
- factlang/packs/standard/sum.py +58 -0
- factlang/packs/standard/type.py +54 -0
- factlang/packs/standard/unique.py +49 -0
- factlang/packs/standard/values.py +90 -0
- factlang/py.typed +0 -0
- factlang/semantics/__init__.py +1 -0
- factlang/semantics/analyzer.py +713 -0
- factlang/semantics/catalog.py +130 -0
- factlang/semantics/checked.py +79 -0
- factlang/semantics/filters.py +165 -0
- factlang/semantics/identity.py +107 -0
- factlang/semantics/refs.py +45 -0
- factlang/semantics/signature.py +140 -0
- factlang/semantics/types.py +297 -0
- factlang/sql/__init__.py +44 -0
- factlang/sql/ast.py +491 -0
- factlang/sql/fragment.py +163 -0
- factlang/sql/lower.py +529 -0
- factlang/sql/printer.py +398 -0
- factlang/sql/probe.py +190 -0
- factlang/sql/profile.py +317 -0
- factlang/sql/profiles/__init__.py +45 -0
- factlang/sql/profiles/_shared.py +67 -0
- factlang/sql/profiles/bigquery.py +104 -0
- factlang/sql/profiles/clickhouse.py +145 -0
- factlang/sql/profiles/databricks.py +94 -0
- factlang/sql/profiles/duckdb.py +93 -0
- factlang/sql/profiles/mysql.py +132 -0
- factlang/sql/profiles/oracle.py +114 -0
- factlang/sql/profiles/postgres.py +88 -0
- factlang/sql/profiles/redshift.py +102 -0
- factlang/sql/profiles/snowflake.py +98 -0
- factlang/sql/profiles/trino.py +90 -0
- factlang/sql/profiles/tsql.py +126 -0
- factlang/sql/registry.py +233 -0
- factlang/sql/sqlglot_bridge.py +763 -0
- factlang/syntax/__init__.py +6 -0
- factlang/syntax/ast.py +163 -0
- factlang/syntax/formatter.py +181 -0
- factlang/syntax/lexer.py +205 -0
- factlang/syntax/parser.py +542 -0
- factlang/syntax/tokens.py +45 -0
- factlang/types.py +41 -0
- factlang-0.1.0.dist-info/METADATA +283 -0
- factlang-0.1.0.dist-info/RECORD +93 -0
- factlang-0.1.0.dist-info/WHEEL +4 -0
- factlang-0.1.0.dist-info/entry_points.txt +2 -0
- factlang-0.1.0.dist-info/licenses/LICENSE +21 -0
factlang/__about__.py
ADDED
factlang/__init__.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""FactLang: a formal language for verifying factual claims against data warehouses.
|
|
2
|
+
|
|
3
|
+
``import factlang as fl``: the names in ``__all__`` are the public API (spec 10, 11 R10);
|
|
4
|
+
they all come from :mod:`factlang.api`, the facade's only import.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from factlang.api import (
|
|
8
|
+
LANGUAGE_VERSION,
|
|
9
|
+
And,
|
|
10
|
+
Attr,
|
|
11
|
+
BigQueryConnector,
|
|
12
|
+
CachedCatalog,
|
|
13
|
+
CallableConnector,
|
|
14
|
+
Catalog,
|
|
15
|
+
Checker,
|
|
16
|
+
ColumnRef,
|
|
17
|
+
Compare,
|
|
18
|
+
CompareUsingClaimOp,
|
|
19
|
+
Contract,
|
|
20
|
+
ContractPack,
|
|
21
|
+
CostEstimate,
|
|
22
|
+
DBAPIConnector,
|
|
23
|
+
EdgeRef,
|
|
24
|
+
Example,
|
|
25
|
+
Ident,
|
|
26
|
+
Measurement,
|
|
27
|
+
Metric,
|
|
28
|
+
Not,
|
|
29
|
+
NullCatalog,
|
|
30
|
+
Operand,
|
|
31
|
+
Or,
|
|
32
|
+
Outcome,
|
|
33
|
+
RenderedFragment,
|
|
34
|
+
Report,
|
|
35
|
+
SQLAlchemyConnector,
|
|
36
|
+
StaticCatalog,
|
|
37
|
+
TableRef,
|
|
38
|
+
Verdict,
|
|
39
|
+
WarehouseCatalog,
|
|
40
|
+
WhenClaimHas,
|
|
41
|
+
Within,
|
|
42
|
+
__version__,
|
|
43
|
+
check,
|
|
44
|
+
check_pack,
|
|
45
|
+
compile,
|
|
46
|
+
connect,
|
|
47
|
+
connectors,
|
|
48
|
+
discover_packs,
|
|
49
|
+
format,
|
|
50
|
+
ir,
|
|
51
|
+
lint,
|
|
52
|
+
measure,
|
|
53
|
+
parse,
|
|
54
|
+
parse_filter,
|
|
55
|
+
run_metadata,
|
|
56
|
+
sql,
|
|
57
|
+
standard_pack,
|
|
58
|
+
types,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
__all__ = [
|
|
62
|
+
"LANGUAGE_VERSION",
|
|
63
|
+
"And",
|
|
64
|
+
"Attr",
|
|
65
|
+
"BigQueryConnector",
|
|
66
|
+
"CachedCatalog",
|
|
67
|
+
"CallableConnector",
|
|
68
|
+
"Catalog",
|
|
69
|
+
"Checker",
|
|
70
|
+
"ColumnRef",
|
|
71
|
+
"Compare",
|
|
72
|
+
"CompareUsingClaimOp",
|
|
73
|
+
"Contract",
|
|
74
|
+
"ContractPack",
|
|
75
|
+
"CostEstimate",
|
|
76
|
+
"DBAPIConnector",
|
|
77
|
+
"EdgeRef",
|
|
78
|
+
"Example",
|
|
79
|
+
"Ident",
|
|
80
|
+
"Measurement",
|
|
81
|
+
"Metric",
|
|
82
|
+
"Not",
|
|
83
|
+
"NullCatalog",
|
|
84
|
+
"Operand",
|
|
85
|
+
"Or",
|
|
86
|
+
"Outcome",
|
|
87
|
+
"RenderedFragment",
|
|
88
|
+
"Report",
|
|
89
|
+
"SQLAlchemyConnector",
|
|
90
|
+
"StaticCatalog",
|
|
91
|
+
"TableRef",
|
|
92
|
+
"Verdict",
|
|
93
|
+
"WarehouseCatalog",
|
|
94
|
+
"WhenClaimHas",
|
|
95
|
+
"Within",
|
|
96
|
+
"__version__",
|
|
97
|
+
"check",
|
|
98
|
+
"check_pack",
|
|
99
|
+
"compile",
|
|
100
|
+
"connect",
|
|
101
|
+
"connectors",
|
|
102
|
+
"discover_packs",
|
|
103
|
+
"format",
|
|
104
|
+
"ir",
|
|
105
|
+
"lint",
|
|
106
|
+
"measure",
|
|
107
|
+
"parse",
|
|
108
|
+
"parse_filter",
|
|
109
|
+
"run_metadata",
|
|
110
|
+
"sql",
|
|
111
|
+
"standard_pack",
|
|
112
|
+
"types",
|
|
113
|
+
]
|
factlang/__main__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""The agent surface (spec 10; layer 17): LLM tool definitions, the prompt-ready verb
|
|
2
|
+
reference and a JSON tool-call dispatcher. The optional MCP server lives in
|
|
3
|
+
:mod:`factlang.agent.mcp` (extra ``factlang[mcp]``) and is not imported here."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from factlang.agent.reference import verb_reference
|
|
8
|
+
from factlang.agent.tools import ERROR_CODES, TOOL_NAMES, handle_tool_call, tool_definitions
|
|
9
|
+
|
|
10
|
+
__all__ = ["ERROR_CODES", "TOOL_NAMES", "handle_tool_call", "tool_definitions", "verb_reference"]
|
factlang/agent/mcp.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""An MCP server exposing the FactLang tools over stdio (spec 10; layer 17, non-core).
|
|
2
|
+
|
|
3
|
+
Needs the extra ``factlang[mcp]`` (the official ``mcp`` package), which is imported lazily
|
|
4
|
+
inside :func:`build_server` and :func:`serve` only; importing this module never imports it.
|
|
5
|
+
The registration data (:func:`tool_registrations`) and the dispatcher (:func:`call_tool`) are
|
|
6
|
+
plain functions, so they are testable without the package.
|
|
7
|
+
|
|
8
|
+
Command line: ``factlang mcp --dsn URL`` (or ``python -m factlang.agent.mcp --dsn URL``);
|
|
9
|
+
with neither ``--dsn`` nor ``--dialect`` the URL comes from ``$FACTLANG_DSN``;
|
|
10
|
+
``--dialect D`` alone serves without a warehouse (``factlang_check`` then returns a
|
|
11
|
+
``no_connector`` error, ``factlang_lint`` and ``factlang_explain`` work).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import asyncio
|
|
18
|
+
import importlib
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import sys
|
|
22
|
+
from collections.abc import Sequence
|
|
23
|
+
from types import ModuleType
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
from factlang.agent.tools import handle_tool_call, tool_definitions
|
|
27
|
+
from factlang.connectors import connect
|
|
28
|
+
from factlang.contract import ContractPack
|
|
29
|
+
from factlang.engine import Checker
|
|
30
|
+
|
|
31
|
+
DSN_ENV = "FACTLANG_DSN" # the same variable ``factlang check`` reads (factlang.cli.DSN_ENV)
|
|
32
|
+
|
|
33
|
+
INSTALL_HINT = "the MCP server needs the mcp package: pip install 'factlang[mcp]'"
|
|
34
|
+
SERVER_NAME = "factlang"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ToolCallFailed(Exception):
|
|
38
|
+
"""Raised by the mcp 1.x call handler for a failed call, so the SDK sets ``isError``;
|
|
39
|
+
its message is the tool's ``{"error": ...}`` JSON."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _mcp(module: str) -> ModuleType:
|
|
43
|
+
try:
|
|
44
|
+
return importlib.import_module(module)
|
|
45
|
+
except ModuleNotFoundError as exc:
|
|
46
|
+
if exc.name is not None and (exc.name == "mcp" or exc.name.startswith("mcp.")):
|
|
47
|
+
raise ImportError(INSTALL_HINT) from exc
|
|
48
|
+
raise
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def tool_registrations(pack: ContractPack | None = None) -> list[dict[str, Any]]:
|
|
52
|
+
"""The tools as MCP registers them: ``{"name", "description", "inputSchema"}``."""
|
|
53
|
+
return [
|
|
54
|
+
{"name": t["name"], "description": t["description"], "inputSchema": t["input_schema"]}
|
|
55
|
+
for t in tool_definitions(pack)
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _dispatch(checker: Checker, name: str, arguments: Any) -> tuple[str, bool]:
|
|
60
|
+
result = handle_tool_call(name, arguments, checker)
|
|
61
|
+
return json.dumps(result, indent=2), "error" in result
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def call_tool(checker: Checker, name: str, arguments: Any) -> str:
|
|
65
|
+
"""One tool call as the JSON text an MCP ``TextContent`` carries; never raises."""
|
|
66
|
+
return _dispatch(checker, name, arguments)[0]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def build_server(checker: Checker, *, name: str = SERVER_NAME) -> Any:
|
|
70
|
+
"""A low-level ``mcp`` server with the three tools registered (needs ``factlang[mcp]``).
|
|
71
|
+
|
|
72
|
+
Works with both ``mcp`` 1.x (decorator registration) and 2.x (``on_*`` handlers); a
|
|
73
|
+
failed call carries the ``{"error": ...}`` JSON with ``isError`` set (2.x: in the
|
|
74
|
+
result; 1.x: the handler raises :class:`ToolCallFailed`, which the SDK turns into an
|
|
75
|
+
error result with that JSON as its text).
|
|
76
|
+
"""
|
|
77
|
+
lowlevel = _mcp("mcp.server.lowlevel")
|
|
78
|
+
types = _mcp("mcp.types")
|
|
79
|
+
tools = [types.Tool.model_validate(r) for r in tool_registrations(checker.pack)]
|
|
80
|
+
|
|
81
|
+
async def run_tool(tool: str, arguments: Any) -> tuple[Any, bool]:
|
|
82
|
+
args = arguments if arguments is not None else {}
|
|
83
|
+
# checks block on the warehouse: keep the event loop free
|
|
84
|
+
text, failed = await asyncio.to_thread(_dispatch, checker, tool, args)
|
|
85
|
+
return types.TextContent(type="text", text=text), failed
|
|
86
|
+
|
|
87
|
+
if hasattr(lowlevel.Server, "list_tools"): # mcp 1.x
|
|
88
|
+
server = lowlevel.Server(name)
|
|
89
|
+
|
|
90
|
+
async def list_tools_v1() -> list[Any]:
|
|
91
|
+
return tools
|
|
92
|
+
|
|
93
|
+
async def call_tool_v1(tool: str, arguments: dict[str, Any] | None) -> list[Any]:
|
|
94
|
+
content, failed = await run_tool(tool, arguments)
|
|
95
|
+
if failed:
|
|
96
|
+
# mcp 1.x sets isError only for a handler that raises; the message is the
|
|
97
|
+
# same {"error": ...} JSON a 2.x client gets as content
|
|
98
|
+
raise ToolCallFailed(content.text)
|
|
99
|
+
return [content]
|
|
100
|
+
|
|
101
|
+
server.list_tools()(list_tools_v1)
|
|
102
|
+
server.call_tool()(call_tool_v1)
|
|
103
|
+
return server
|
|
104
|
+
|
|
105
|
+
async def list_tools(ctx: Any, params: Any) -> Any: # mcp 2.x
|
|
106
|
+
return types.ListToolsResult.model_validate({"tools": tools})
|
|
107
|
+
|
|
108
|
+
async def call(ctx: Any, params: Any) -> Any:
|
|
109
|
+
content, failed = await run_tool(params.name, params.arguments)
|
|
110
|
+
return types.CallToolResult.model_validate({"content": [content], "isError": failed})
|
|
111
|
+
|
|
112
|
+
return lowlevel.Server(name, on_list_tools=list_tools, on_call_tool=call)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def serve(checker: Checker, *, name: str = SERVER_NAME) -> None:
|
|
116
|
+
"""Serve the tools over stdio until the client disconnects (needs ``factlang[mcp]``)."""
|
|
117
|
+
server = build_server(checker, name=name)
|
|
118
|
+
stdio = _mcp("mcp.server.stdio")
|
|
119
|
+
|
|
120
|
+
async def run() -> None:
|
|
121
|
+
async with stdio.stdio_server() as (read, write):
|
|
122
|
+
await server.run(read, write, server.create_initialization_options())
|
|
123
|
+
|
|
124
|
+
asyncio.run(run())
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
# -- command line ----------------------------------------------------------------------------
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def configure_parser(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
|
|
131
|
+
"""Add the ``mcp`` options to ``parser`` (used by ``factlang mcp`` and :func:`main`)."""
|
|
132
|
+
parser.add_argument(
|
|
133
|
+
"--dsn",
|
|
134
|
+
help=(
|
|
135
|
+
f"SQLAlchemy URL of the warehouse to check against; default ${DSN_ENV} when "
|
|
136
|
+
"neither --dsn nor --dialect is given (prefer it: --dsn shows in the process list)"
|
|
137
|
+
),
|
|
138
|
+
)
|
|
139
|
+
parser.add_argument("--dialect", help="SQL dialect (default: the connection's)")
|
|
140
|
+
parser.add_argument(
|
|
141
|
+
"--timeout", type=float, default=60.0, help="per-probe timeout in seconds (default 60)"
|
|
142
|
+
)
|
|
143
|
+
parser.add_argument(
|
|
144
|
+
"--max-bytes", type=int, default=None, help="refuse probes priced above this (dry run)"
|
|
145
|
+
)
|
|
146
|
+
parser.add_argument("--name", default=SERVER_NAME, help="MCP server name")
|
|
147
|
+
return parser
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _dsn(args: argparse.Namespace) -> str | None:
|
|
151
|
+
"""``--dsn``, else ``$FACTLANG_DSN`` when neither ``--dsn`` nor ``--dialect`` is given."""
|
|
152
|
+
if args.dsn is not None or args.dialect is not None:
|
|
153
|
+
return args.dsn # type: ignore[no-any-return]
|
|
154
|
+
return os.environ.get(DSN_ENV) or None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def run(args: argparse.Namespace) -> int:
|
|
158
|
+
"""Build the Checker from parsed options and serve; 2 on a configuration error."""
|
|
159
|
+
dsn = _dsn(args)
|
|
160
|
+
if dsn is None and args.dialect is None:
|
|
161
|
+
print(f"factlang mcp: give --dsn URL, --dialect D or ${DSN_ENV}", file=sys.stderr)
|
|
162
|
+
return 2
|
|
163
|
+
try:
|
|
164
|
+
connector = connect(dsn) if dsn is not None else None
|
|
165
|
+
checker = Checker(
|
|
166
|
+
connector, dialect=args.dialect, timeout_s=args.timeout, max_bytes=args.max_bytes
|
|
167
|
+
)
|
|
168
|
+
except Exception as exc: # a bad URL, a missing driver: configuration, not a crash
|
|
169
|
+
print(f"factlang mcp: cannot connect: {exc}", file=sys.stderr)
|
|
170
|
+
return 2
|
|
171
|
+
try:
|
|
172
|
+
serve(checker, name=args.name)
|
|
173
|
+
except ImportError as exc:
|
|
174
|
+
print(f"factlang mcp: {exc}", file=sys.stderr)
|
|
175
|
+
return 2
|
|
176
|
+
return 0
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
180
|
+
parser = configure_parser(
|
|
181
|
+
argparse.ArgumentParser(
|
|
182
|
+
prog="factlang mcp", description="Serve the FactLang tools over MCP (stdio)."
|
|
183
|
+
)
|
|
184
|
+
)
|
|
185
|
+
args = parser.parse_args(argv)
|
|
186
|
+
if _dsn(args) is None and args.dialect is None:
|
|
187
|
+
parser.error(f"give --dsn URL, --dialect D or ${DSN_ENV}")
|
|
188
|
+
return run(args)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
if __name__ == "__main__": # pragma: no cover
|
|
192
|
+
raise SystemExit(main())
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
__all__ = [
|
|
196
|
+
"DSN_ENV",
|
|
197
|
+
"INSTALL_HINT",
|
|
198
|
+
"ToolCallFailed",
|
|
199
|
+
"build_server",
|
|
200
|
+
"call_tool",
|
|
201
|
+
"configure_parser",
|
|
202
|
+
"main",
|
|
203
|
+
"run",
|
|
204
|
+
"serve",
|
|
205
|
+
"tool_registrations",
|
|
206
|
+
]
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""The prompt-ready verb reference (spec 10, agent surface; layer 17).
|
|
2
|
+
|
|
3
|
+
Everything in it is generated from the pack: each contract's ``VerbSpec`` (name, summary,
|
|
4
|
+
operands, attributes, operators, constraints, ``WHERE`` support) and its *valid* examples
|
|
5
|
+
(which the contract-completeness tests execute). Nothing is written by hand, so the
|
|
6
|
+
reference cannot drift from what the analyser accepts.
|
|
7
|
+
|
|
8
|
+
``style="markdown"`` is a full reference for documentation and system prompts;
|
|
9
|
+
``style="compact"`` is a few lines per verb, small enough to sit in one tool description.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import Literal
|
|
15
|
+
|
|
16
|
+
from factlang.contract import Contract, ContractPack
|
|
17
|
+
from factlang.packs.standard import standard_pack
|
|
18
|
+
from factlang.semantics.signature import AttrSpec, OperandKind, OperandSpec, VerbSpec
|
|
19
|
+
|
|
20
|
+
Style = Literal["markdown", "compact"]
|
|
21
|
+
|
|
22
|
+
# examples per verb in the compact style (the markdown style lists every valid example)
|
|
23
|
+
COMPACT_EXAMPLES = 2
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _operand(o: OperandSpec) -> str:
|
|
27
|
+
if o.kind is OperandKind.TABLE:
|
|
28
|
+
return f"<{o.name}>"
|
|
29
|
+
if o.kind is OperandKind.COLUMN:
|
|
30
|
+
return f"<table.{o.name}>"
|
|
31
|
+
return "<table.column> -> <table.column>"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _attr(a: AttrSpec) -> str:
|
|
35
|
+
ops = f"{'|'.join(a.ops)} " if a.ops else ""
|
|
36
|
+
text = f"{a.name} {ops}<{a.type}>"
|
|
37
|
+
return text if a.required else f"[{text}]"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def syntax(spec: VerbSpec) -> str:
|
|
41
|
+
"""One line: ``VERB <operands> ATTR op <TYPE> [OPTIONAL <TYPE>] [WHERE <condition>]``."""
|
|
42
|
+
parts = [spec.name, *(_operand(o) for o in spec.operands), *(_attr(a) for a in spec.attrs)]
|
|
43
|
+
if spec.filterable:
|
|
44
|
+
parts.append("[WHERE <condition>]")
|
|
45
|
+
return " ".join(parts)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _constraints(spec: VerbSpec) -> list[str]:
|
|
49
|
+
out = [f"`{a}` requires `{b}`" for a, b in spec.requires]
|
|
50
|
+
out += [f"`{a}` and `{b}` are mutually exclusive" for a, b in spec.exclusive]
|
|
51
|
+
out += [f"`{a}` and `{b}` go together and list as many columns" for a, b in spec.paired]
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _valid_examples(contract: Contract) -> list[str]:
|
|
56
|
+
return [e.source for e in contract.examples if e.valid]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _header(pack: ContractPack) -> str:
|
|
60
|
+
return f"FactLang verbs (pack {pack.name} {pack.version})"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _compact(pack: ContractPack) -> str:
|
|
64
|
+
lines = [
|
|
65
|
+
_header(pack) + ". One claim per line; [..] is optional; <TYPE> is a value; "
|
|
66
|
+
"a|b are the allowed operators.",
|
|
67
|
+
]
|
|
68
|
+
for contract in pack.contracts():
|
|
69
|
+
spec = contract.spec
|
|
70
|
+
lines.append(syntax(spec))
|
|
71
|
+
if spec.summary:
|
|
72
|
+
lines.append(f" {spec.summary}")
|
|
73
|
+
lines.extend(f" e.g. {src}" for src in _valid_examples(contract)[:COMPACT_EXAMPLES])
|
|
74
|
+
return "\n".join(lines) + "\n"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _cell(text: str) -> str:
|
|
78
|
+
return text.replace("|", "\\|").replace("\n", " ")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _markdown(pack: ContractPack) -> str:
|
|
82
|
+
lines = [f"# {_header(pack)}", ""]
|
|
83
|
+
for contract in pack.contracts():
|
|
84
|
+
spec = contract.spec
|
|
85
|
+
lines += [f"## {spec.name}", ""]
|
|
86
|
+
if spec.summary:
|
|
87
|
+
lines += [spec.summary, ""]
|
|
88
|
+
lines += ["```", syntax(spec), "```", ""]
|
|
89
|
+
if spec.attrs:
|
|
90
|
+
lines += [
|
|
91
|
+
"| attribute | value type | operators | required | meaning |",
|
|
92
|
+
"|---|---|---|---|---|",
|
|
93
|
+
]
|
|
94
|
+
for a in spec.attrs:
|
|
95
|
+
ops = " ".join(f"`{_cell(op)}`" for op in a.ops) if a.ops else "none"
|
|
96
|
+
lines.append(
|
|
97
|
+
f"| `{a.name}` | `{a.type}` | {ops} | {'yes' if a.required else 'no'} "
|
|
98
|
+
f"| {_cell(a.doc)} |"
|
|
99
|
+
)
|
|
100
|
+
lines.append("")
|
|
101
|
+
notes = _constraints(spec)
|
|
102
|
+
notes.append(
|
|
103
|
+
"Accepts a `WHERE <condition>` filter."
|
|
104
|
+
if spec.filterable
|
|
105
|
+
else "Does not accept a `WHERE` filter."
|
|
106
|
+
)
|
|
107
|
+
lines += [f"- {n}" for n in notes] + [""]
|
|
108
|
+
examples = _valid_examples(contract)
|
|
109
|
+
if examples:
|
|
110
|
+
lines += ["Examples:", "", "```", *examples, "```", ""]
|
|
111
|
+
return "\n".join(lines).rstrip("\n") + "\n"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def verb_reference(pack: ContractPack | None = None, style: Style = "markdown") -> str:
|
|
115
|
+
"""The reference of every verb in ``pack`` (default: the standard pack)."""
|
|
116
|
+
if style not in ("markdown", "compact"):
|
|
117
|
+
raise ValueError(f"style must be 'markdown' or 'compact', got {style!r}")
|
|
118
|
+
pack = pack if pack is not None else standard_pack()
|
|
119
|
+
return _compact(pack) if style == "compact" else _markdown(pack)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
__all__ = ["Style", "syntax", "verb_reference"]
|