prograph 1.3.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.
Files changed (237) hide show
  1. prograph/__init__.py +36 -0
  2. prograph/__main__.py +5 -0
  3. prograph/_version.py +375 -0
  4. prograph/cli/__init__.py +1 -0
  5. prograph/cli/_iri_utils.py +124 -0
  6. prograph/cli/emit_genie_space.py +107 -0
  7. prograph/cli/generate_views.py +140 -0
  8. prograph/cli/main.py +420 -0
  9. prograph/cli/schema_inferrer.py +746 -0
  10. prograph/cli/ttl_loader.py +289 -0
  11. prograph/cli/upload_genie_space.py +84 -0
  12. prograph/config/__init__.py +27 -0
  13. prograph/config/yaml_config.py +848 -0
  14. prograph/demos/__init__.py +14 -0
  15. prograph/demos/turbofan/README.md +74 -0
  16. prograph/demos/turbofan/SCENARIO.md +209 -0
  17. prograph/demos/turbofan/__init__.py +75 -0
  18. prograph/demos/turbofan/create_tables.sql +206 -0
  19. prograph/demos/turbofan/data/engine-instances.ttl +1123 -0
  20. prograph/demos/turbofan/data/sensor-timeseries.csv +90 -0
  21. prograph/demos/turbofan/demo.py +162 -0
  22. prograph/demos/turbofan/genie_qa_notebook.py +434 -0
  23. prograph/demos/turbofan/graph.yaml +1098 -0
  24. prograph/demos/turbofan/instance_graph_demo.py +32 -0
  25. prograph/demos/turbofan/load.py +223 -0
  26. prograph/demos/turbofan/mapping.r2rml.ttl +991 -0
  27. prograph/demos/turbofan/ontology/engine-maintenance.ttl +606 -0
  28. prograph/demos/turbofan/payload-shapes.ttl +33 -0
  29. prograph/demos/turbofan/queries/example-queries.sparql +215 -0
  30. prograph/demos/turbofan/shapes.ttl +75 -0
  31. prograph/demos/turbofan/tables.py +106 -0
  32. prograph/demos/turbofan/turbofan_schema.py +393 -0
  33. prograph/demos/turbofan/validation_demo.py +153 -0
  34. prograph/describe.py +231 -0
  35. prograph/endpoint/__init__.py +12 -0
  36. prograph/endpoint/app.py +722 -0
  37. prograph/endpoint/cli.py +280 -0
  38. prograph/endpoint/credentials.py +240 -0
  39. prograph/endpoint/engines.py +418 -0
  40. prograph/endpoint/negotiate.py +101 -0
  41. prograph/endpoint/results.py +181 -0
  42. prograph/endpoint/service.py +31 -0
  43. prograph/engine.py +2718 -0
  44. prograph/execution.py +455 -0
  45. prograph/executors/__init__.py +6 -0
  46. prograph/executors/base.py +11 -0
  47. prograph/executors/databricks_sql_executor.py +51 -0
  48. prograph/executors/duckdb_executor.py +24 -0
  49. prograph/executors/mysql_executor.py +20 -0
  50. prograph/executors/oracle_executor.py +24 -0
  51. prograph/executors/pandas_executor.py +72 -0
  52. prograph/executors/postgresql_executor.py +35 -0
  53. prograph/executors/spark_executor.py +88 -0
  54. prograph/executors/sqlserver_executor.py +35 -0
  55. prograph/extras/__init__.py +1 -0
  56. prograph/extras/graphql/__init__.py +33 -0
  57. prograph/extras/graphql/execute.py +25 -0
  58. prograph/extras/graphql/schema.py +314 -0
  59. prograph/extras/instance_graph.py +559 -0
  60. prograph/genie/__init__.py +83 -0
  61. prograph/genie/databricks_uploader.py +306 -0
  62. prograph/genie/deploy.py +393 -0
  63. prograph/genie/formats.py +414 -0
  64. prograph/genie/instruction_generator.py +375 -0
  65. prograph/genie/sample_query_generator.py +256 -0
  66. prograph/genie/shacl_views.py +318 -0
  67. prograph/genie/space_emitter.py +329 -0
  68. prograph/genie/view_generator.py +628 -0
  69. prograph/genie/view_writer.py +172 -0
  70. prograph/graph/__init__.py +1 -0
  71. prograph/graph/ansi_session.py +348 -0
  72. prograph/graph/databricks_sql_graph.py +300 -0
  73. prograph/graph/drivers.py +143 -0
  74. prograph/graph/duckdb_graph.py +68 -0
  75. prograph/graph/mysql_graph.py +38 -0
  76. prograph/graph/oracle_graph.py +285 -0
  77. prograph/graph/pandas_graph.py +343 -0
  78. prograph/graph/postgresql_graph.py +644 -0
  79. prograph/graph/spark_graph.py +556 -0
  80. prograph/graph/sql_graph.py +83 -0
  81. prograph/graph/sqlserver_graph.py +72 -0
  82. prograph/hints.py +95 -0
  83. prograph/logging.py +550 -0
  84. prograph/mcp/__init__.py +29 -0
  85. prograph/mcp/__main__.py +180 -0
  86. prograph/mcp/bootstrap.py +98 -0
  87. prograph/mcp/server.py +601 -0
  88. prograph/mcp/sparql.py +397 -0
  89. prograph/mcp/tools.py +504 -0
  90. prograph/nlp/__init__.py +79 -0
  91. prograph/nlp/client.py +305 -0
  92. prograph/nlp/databricks_tools.py +369 -0
  93. prograph/nlp/graph_context.py +313 -0
  94. prograph/nlp/interface.py +652 -0
  95. prograph/nlp/prompts/__init__.py +19 -0
  96. prograph/nlp/prompts/examples.py +258 -0
  97. prograph/nlp/prompts/system.py +239 -0
  98. prograph/nlp/providers/__init__.py +14 -0
  99. prograph/nlp/providers/anthropic.py +274 -0
  100. prograph/nlp/providers/databricks.py +312 -0
  101. prograph/nlp/providers/openai.py +203 -0
  102. prograph/nlp/schema_context.py +78 -0
  103. prograph/ontology/__init__.py +53 -0
  104. prograph/ontology/alignment.py +542 -0
  105. prograph/ontology/hierarchy.py +310 -0
  106. prograph/ontology/imports.py +587 -0
  107. prograph/ontology/layer.py +991 -0
  108. prograph/ontology/skos.py +61 -0
  109. prograph/owl/__init__.py +27 -0
  110. prograph/owl/defined_classes.py +323 -0
  111. prograph/parameters.py +242 -0
  112. prograph/parser/__init__.py +1 -0
  113. prograph/parser/cypher/CypherLexer.py +836 -0
  114. prograph/parser/cypher/CypherListener.py +966 -0
  115. prograph/parser/cypher/CypherParser.py +10854 -0
  116. prograph/parser/cypher/CypherVisitor.py +543 -0
  117. prograph/parser/cypher/__init__.py +1 -0
  118. prograph/parser/sparql/SparqlLexer.py +801 -0
  119. prograph/parser/sparql/SparqlParser.py +10146 -0
  120. prograph/parser/sparql/SparqlParserListener.py +1056 -0
  121. prograph/parser/sparql/SparqlParserVisitor.py +593 -0
  122. prograph/parser/sparql/__init__.py +8 -0
  123. prograph/plan/__init__.py +3 -0
  124. prograph/plan/ir/__init__.py +1 -0
  125. prograph/plan/ir/casts.py +338 -0
  126. prograph/plan/ir/consistency.py +397 -0
  127. prograph/plan/ir/construct.py +90 -0
  128. prograph/plan/ir/cost.py +234 -0
  129. prograph/plan/ir/cypher_answer.py +1081 -0
  130. prograph/plan/ir/cypher_apoc.py +717 -0
  131. prograph/plan/ir/cypher_apoc_convert.py +505 -0
  132. prograph/plan/ir/cypher_apoc_date.py +845 -0
  133. prograph/plan/ir/cypher_apoc_map.py +496 -0
  134. prograph/plan/ir/cypher_apoc_meta.py +384 -0
  135. prograph/plan/ir/cypher_apoc_path.py +597 -0
  136. prograph/plan/ir/cypher_apoc_procedures.py +163 -0
  137. prograph/plan/ir/cypher_apoc_text.py +785 -0
  138. prograph/plan/ir/cypher_front.py +5474 -0
  139. prograph/plan/ir/cypher_functions.py +565 -0
  140. prograph/plan/ir/cypher_lists.py +935 -0
  141. prograph/plan/ir/cypher_maps.py +370 -0
  142. prograph/plan/ir/cypher_mixed.py +604 -0
  143. prograph/plan/ir/cypher_ontology.py +226 -0
  144. prograph/plan/ir/cypher_procedures.py +191 -0
  145. prograph/plan/ir/cypher_runtime_errors.py +107 -0
  146. prograph/plan/ir/cypher_temporal.py +1357 -0
  147. prograph/plan/ir/cypher_temporal_arith.py +339 -0
  148. prograph/plan/ir/cypher_values.py +546 -0
  149. prograph/plan/ir/cypher_write.py +612 -0
  150. prograph/plan/ir/dataset.py +643 -0
  151. prograph/plan/ir/dates.py +102 -0
  152. prograph/plan/ir/entry.py +992 -0
  153. prograph/plan/ir/expr.py +260 -0
  154. prograph/plan/ir/facts.py +1171 -0
  155. prograph/plan/ir/fresh.py +291 -0
  156. prograph/plan/ir/freshness.py +625 -0
  157. prograph/plan/ir/identity.py +797 -0
  158. prograph/plan/ir/java_datetime.py +265 -0
  159. prograph/plan/ir/java_regex.py +391 -0
  160. prograph/plan/ir/join_order.py +39 -0
  161. prograph/plan/ir/key_checks.py +433 -0
  162. prograph/plan/ir/keys.py +454 -0
  163. prograph/plan/ir/lower.py +5323 -0
  164. prograph/plan/ir/ops.py +619 -0
  165. prograph/plan/ir/owl_rl.py +1119 -0
  166. prograph/plan/ir/owl_rl_rules.py +725 -0
  167. prograph/plan/ir/profiles.py +694 -0
  168. prograph/plan/ir/ql.py +987 -0
  169. prograph/plan/ir/rdfs.py +342 -0
  170. prograph/plan/ir/rewrite.py +1782 -0
  171. prograph/plan/ir/saturate.py +339 -0
  172. prograph/plan/ir/semantics.py +103 -0
  173. prograph/plan/ir/slot.py +509 -0
  174. prograph/plan/ir/sparql_front.py +3418 -0
  175. prograph/plan/ir/strings.py +534 -0
  176. prograph/plan/ir/term_functions.py +274 -0
  177. prograph/plan/ir/terms.py +84 -0
  178. prograph/plan/ir/xpath_regex.py +264 -0
  179. prograph/plan/run_record.py +65 -0
  180. prograph/plan/sql/__init__.py +21 -0
  181. prograph/plan/sql/dialect.py +3726 -0
  182. prograph/plan/sql/mysql_serializer.py +103 -0
  183. prograph/plan/sql/names.py +65 -0
  184. prograph/plan/sql/oracle_serializer.py +306 -0
  185. prograph/plan/sql/pg_serializer.py +501 -0
  186. prograph/plan/sql/rel_algebra.py +781 -0
  187. prograph/plan/sql/sql_serializer.py +1419 -0
  188. prograph/plan/sql/sqlserver_serializer.py +603 -0
  189. prograph/provenance.py +222 -0
  190. prograph/r2rml/__init__.py +48 -0
  191. prograph/r2rml/catalog.py +259 -0
  192. prograph/r2rml/compile.py +372 -0
  193. prograph/r2rml/direct.py +140 -0
  194. prograph/r2rml/export.py +495 -0
  195. prograph/r2rml/model.py +180 -0
  196. prograph/r2rml/parser.py +546 -0
  197. prograph/r2rml/schema.py +120 -0
  198. prograph/read_only.py +122 -0
  199. prograph/results.py +157 -0
  200. prograph/rules/__init__.py +168 -0
  201. prograph/rules/__main__.py +32 -0
  202. prograph/schema/__init__.py +60 -0
  203. prograph/schema/change_set.py +50 -0
  204. prograph/schema/collations.py +198 -0
  205. prograph/schema/compile_schema.py +388 -0
  206. prograph/schema/context.py +845 -0
  207. prograph/schema/examples.py +234 -0
  208. prograph/schema/iri.py +817 -0
  209. prograph/schema/literals.py +94 -0
  210. prograph/schema/lpg_view.py +617 -0
  211. prograph/schema/mapping.py +1803 -0
  212. prograph/schema/maps_schema.py +40 -0
  213. prograph/schema/naming.py +77 -0
  214. prograph/schema/query_sources.py +59 -0
  215. prograph/schema/rows.py +215 -0
  216. prograph/schema/source_map.py +1103 -0
  217. prograph/schema/store_view.py +459 -0
  218. prograph/schema/types.py +569 -0
  219. prograph/schema/xsd.py +569 -0
  220. prograph/shacl/__init__.py +30 -0
  221. prograph/shacl/dqv.py +58 -0
  222. prograph/shacl/generate.py +255 -0
  223. prograph/shacl/report.py +138 -0
  224. prograph/shacl/validator.py +164 -0
  225. prograph/store.py +1737 -0
  226. prograph/utils/__init__.py +6 -0
  227. prograph/utils/exceptions.py +308 -0
  228. prograph/utils/helpers.py +126 -0
  229. prograph/warnings.py +46 -0
  230. prograph/writes.py +369 -0
  231. prograph-1.3.3.dist-info/METADATA +281 -0
  232. prograph-1.3.3.dist-info/RECORD +237 -0
  233. prograph-1.3.3.dist-info/WHEEL +5 -0
  234. prograph-1.3.3.dist-info/entry_points.txt +3 -0
  235. prograph-1.3.3.dist-info/licenses/LICENSE +201 -0
  236. prograph-1.3.3.dist-info/licenses/NOTICE +10 -0
  237. prograph-1.3.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,565 @@
1
+ """Cypher's scalar functions on the one plan (rules cypher-conversions, cypher-scalar-functions; Cypher
2
+ inventory row 14): toString, toInteger, toFloat, toBoolean, coalesce, abs, sign, toUpper, toLower, sqrt,
3
+ ceil, floor, round, substring and split. All literal arguments are worked out at planning; a column's in SQL. Null
4
+ in, null out.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import re
11
+ from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional
12
+
13
+ from prograph.plan.ir import expr as E
14
+ from prograph.plan.ir.cypher_runtime_errors import RuntimeTypeError
15
+ from prograph.plan.ir.facts import NotBuilt, expr_slot
16
+ from prograph.plan.ir.slot import LIST, MAP, MIXED, NOTHING, UNKNOWN, VALUE, Bound, Slot, value_slot
17
+ from prograph.rules import home, module_home
18
+ from prograph.schema import xsd
19
+
20
+ if TYPE_CHECKING:
21
+ from prograph.plan.ir import lower as L
22
+ from prograph.plan.sql import rel_algebra as R
23
+
24
+ module_home("cypher-scalar-functions", "Cypher's scalar functions, in SQL",
25
+ terms=("coalesce", "abs", "sign", "toUpper", "toLower", "sqrt", "ceil", "floor", "round", "rounding", "substring",
26
+ "split", "scalar function"))
27
+
28
+ FUNCTIONS = frozenset({"TOSTRING", "TOINTEGER", "TOFLOAT", "TOBOOLEAN", "COALESCE", "ABS", "SIGN", "TOUPPER",
29
+ "TOLOWER", "SQRT", "CEIL", "FLOOR", "ROUND", "SUBSTRING", "SPLIT"})
30
+ _STRING_ARGS = {"SUBSTRING": (2, 3), "SPLIT": (2,)} # the functions of several arguments, their counts
31
+ _TWO_52 = 4503599627370496.0 # a double this large or larger is whole already
32
+ _TWO_63 = 9223372036854775808.0 # past every 64-bit integer: round()'s clamp
33
+ _INTEGERS = frozenset({xsd.INTEGER}) | xsd.INTEGER_DATATYPES
34
+ _FLOATS = (xsd.DOUBLE, xsd.FLOAT)
35
+ from prograph.plan.ir.cypher_temporal import TEMPORAL, text as temporal_text # noqa: E402
36
+
37
+
38
+ def _type(s: Slot) -> Optional[str]:
39
+ if s.present is Bound.NEVER:
40
+ return None
41
+ from prograph.plan.ir.cypher_lists import value_type
42
+ t = value_type(s) if not s.kinds & {LIST, MAP, MIXED} else None # a condition's boolean among the plain types
43
+ if t is None:
44
+ raise NotBuilt("a function of a value that is not one plain type (a list, map, node or mixed)")
45
+ return t
46
+
47
+
48
+ def _kind(dt: Optional[str]) -> Optional[str]:
49
+ if dt is None:
50
+ return None
51
+ if dt in _INTEGERS:
52
+ return "integer"
53
+ if dt in _FLOATS:
54
+ return "float"
55
+ return {xsd.STRING: "string", xsd.BOOLEAN: "boolean", xsd.DECIMAL: "decimal"}.get(dt, "other")
56
+
57
+
58
+ def java_double(x: float) -> str:
59
+ """Java's Double.toString, as openCypher's toString of a float prints it."""
60
+ if not math.isfinite(x): # NaN or an infinity: Java's text of each (a value, not a missing one)
61
+ return "NaN" if repr(x) == "nan" else ("Infinity" if x > 0 else "-Infinity")
62
+ if x == 0:
63
+ return "-0.0" if math.copysign(1.0, x) < 0 else "0.0"
64
+ if abs(x) < 2.2250738585072014e-308:
65
+ raise NotBuilt("toString() of a subnormal float (Java's digits differ from the shortest ones)")
66
+ if 1e-3 <= abs(x) < 1e7:
67
+ text = repr(x)
68
+ if "e" in text: # repr of a plain-range value in exponent form: write it out
69
+ text = f"{x:.17f}".rstrip("0")
70
+ return text if "." in text else text + ".0"
71
+ # Scientific: the shortest digits and their exponent, both from repr (one rounding).
72
+ digits_part, _, exp_part = repr(abs(x)).partition("e")
73
+ whole, _, frac = digits_part.partition(".")
74
+ digits = (whole + frac).lstrip("0")
75
+ exponent = (int(exp_part) if exp_part else 0) + len(whole.lstrip("0")) - 1 if whole.strip("0") else \
76
+ (int(exp_part) if exp_part else 0) - (len(frac) - len(frac.lstrip("0"))) - 1
77
+ digits = digits.rstrip("0") or "0"
78
+ sign = "-" if x < 0 else ""
79
+ return f"{sign}{digits[0]}.{digits[1:] or '0'}E{exponent}"
80
+
81
+
82
+ _INTEGER_TEXT = r"[+-]?[0-9]+"
83
+ _FLOAT_TEXT = r"[+-]?([0-9]+[.]?[0-9]*|[.][0-9]+)([eE][+-]?[0-9]+)?"
84
+ _SPECIAL_TEXT = r"[+-]?(NaN|Infinity)" # Java's parseDouble spellings, exactly
85
+
86
+
87
+ @home("cypher-conversions", "Cypher's toString, toInteger, toFloat and toBoolean",
88
+ terms=("toString", "toInteger", "toFloat", "toBoolean", "conversion", "Double.toString"))
89
+ def fold(name: str, values: list) -> Any:
90
+ """A conversion or scalar function of literal values (openCypher 9): toString (a float as Java's
91
+ Double.toString), toInteger (a float truncated toward zero; a string of an integer or a float, else
92
+ null), toFloat (a number or a string of one, else null), toBoolean ('true'/'false' in any case, else
93
+ null); coalesce, abs, sign, toUpper, toLower."""
94
+ if name == "COALESCE":
95
+ return next((v for v in values if v is not None), None)
96
+ if name == "SUBSTRING":
97
+ return _substring(*values)
98
+ if name == "SPLIT":
99
+ s, d = values
100
+ _split_args(s, d)
101
+ return None if s is None or d is None else s.split(d)
102
+ (v,) = values
103
+ if v is None:
104
+ return None
105
+ if name == "TOSTRING":
106
+ if isinstance(v, bool):
107
+ return "true" if v else "false"
108
+ if isinstance(v, int):
109
+ return str(v)
110
+ if isinstance(v, float):
111
+ return java_double(v)
112
+ if isinstance(v, str):
113
+ return v
114
+ from prograph.plan.ir.cypher_temporal import iso_text
115
+ try:
116
+ return iso_text(v)
117
+ except NotBuilt:
118
+ raise NotBuilt("toString() of a list, map or node literal")
119
+ if name == "TOINTEGER":
120
+ if isinstance(v, bool):
121
+ raise RuntimeTypeError(0, "InvalidArgumentValue", "toInteger() of a boolean")
122
+ if isinstance(v, int):
123
+ return v
124
+ if isinstance(v, float):
125
+ if not math.isfinite(v) or not -2 ** 63 <= int(v) < 2 ** 63:
126
+ raise NotBuilt("toInteger() of NaN, Infinity or a float past 64 bits (an error)")
127
+ return int(v)
128
+ if isinstance(v, str):
129
+ t = v.strip(" ")
130
+ if re.fullmatch(_INTEGER_TEXT, t):
131
+ n = int(t)
132
+ if not -2 ** 63 <= n < 2 ** 63:
133
+ raise NotBuilt("toInteger() of a string past 64 bits (an error)")
134
+ return n
135
+ if re.fullmatch(_FLOAT_TEXT, t):
136
+ f = float(t)
137
+ if not math.isfinite(f) or not -2 ** 63 <= int(f) < 2 ** 63:
138
+ raise NotBuilt("toInteger() of a string past 64 bits (an error)")
139
+ return int(f)
140
+ return None
141
+ raise NotBuilt("toInteger() of a list, map or node")
142
+ if name == "TOFLOAT":
143
+ if isinstance(v, bool):
144
+ raise RuntimeTypeError(0, "InvalidArgumentValue", "toFloat() of a boolean")
145
+ if isinstance(v, (int, float)):
146
+ return float(v)
147
+ if isinstance(v, str):
148
+ t = v.strip(" ")
149
+ return float(t) if re.fullmatch(_FLOAT_TEXT, t) or re.fullmatch(_SPECIAL_TEXT, t) else None
150
+ raise NotBuilt("toFloat() of a list, map or node")
151
+ if name == "TOBOOLEAN":
152
+ if isinstance(v, bool):
153
+ return v
154
+ if isinstance(v, str):
155
+ return {"true": True, "false": False}.get(v.strip(" ").lower())
156
+ raise RuntimeTypeError(0, "InvalidArgumentValue", "toBoolean() of a value that is no boolean or string")
157
+ if name == "ABS" and isinstance(v, (int, float)) and not isinstance(v, bool):
158
+ return abs(v)
159
+ if name == "SIGN" and isinstance(v, (int, float)) and not isinstance(v, bool):
160
+ if isinstance(v, float) and not math.isfinite(v) and repr(v) == "nan":
161
+ raise NotBuilt("sign() of NaN")
162
+ return 0 if v == 0 else (1 if v > 0 else -1)
163
+ if name in ("TOUPPER", "TOLOWER") and isinstance(v, str):
164
+ return v.upper() if name == "TOUPPER" else v.lower()
165
+ if name == "SQRT" and isinstance(v, (int, float)) and not isinstance(v, bool):
166
+ return float("nan") if v < 0 else math.sqrt(v) # Java's Math.sqrt: NaN below zero
167
+ if name in ("CEIL", "FLOOR") and isinstance(v, (int, float)) and not isinstance(v, bool):
168
+ x = float(v)
169
+ if not math.isfinite(x):
170
+ return x
171
+ r = float(math.ceil(x) if name == "CEIL" else math.floor(x))
172
+ return math.copysign(r, x) if r == 0 else r # Java's Math.ceil(-0.5) is -0.0
173
+ if name == "ROUND" and isinstance(v, (int, float)) and not isinstance(v, bool):
174
+ x = float(v)
175
+ if abs(x) >= _TWO_63: # past the long range: clamped to it, as Neo4j's (the infinities too)
176
+ return math.copysign(_TWO_63, x)
177
+ if not abs(x) < _TWO_52: # whole already; NaN (no comparison holds) itself
178
+ return x
179
+ f = float(math.floor(x))
180
+ return (f + 1.0 if x - f >= 0.5 else f) + 0.0 # the nearest integer, a tie up, no -0.0 (`round_cell`)
181
+ raise NotBuilt(f"{name.lower()}() of that value")
182
+
183
+
184
+ _ALL = object() # substring() with no length: to the end
185
+
186
+
187
+ def _substring(s: Any, start: Any, length: Any = _ALL) -> Any:
188
+ """openCypher 9's substring(original, start [, length]): `length` characters (code points) from the
189
+ zero-based `start`, to the end where none is given or fewer are left; '' from a start past the end; null
190
+ for a null original. A null or negative start or length is an error, refused here."""
191
+ for n in (start,) if length is _ALL else (start, length):
192
+ if n is None or isinstance(n, bool) or not isinstance(n, int) or n < 0:
193
+ raise NotBuilt("substring() of a start or length that is null, negative or not an integer (an error)")
194
+ if s is None:
195
+ return None
196
+ if not isinstance(s, str):
197
+ raise NotBuilt("substring() of a value that is not a string (an error)")
198
+ return s[start:] if length is _ALL else s[start:start + length]
199
+
200
+
201
+ def _split_args(s: Any, d: Any) -> None:
202
+ """split(s, d)'s arguments built: strings or null, d a literal (`function_slot`) that is not ''."""
203
+ if any(v is not None and not isinstance(v, str) for v in (s, d)):
204
+ raise NotBuilt("split() of a value that is not a string (an error)")
205
+ if d == "":
206
+ raise NotBuilt("split() at the empty string")
207
+ if d is not None and "\\E" in d:
208
+ raise NotBuilt("split() at a delimiter holding \\E")
209
+
210
+
211
+ def _folded(e: E.Call) -> Optional[E.Const]:
212
+ """The function of constant arguments, worked out at planning (a lambda's element substituted)."""
213
+ if e.name == "SPLIT" or e.name == "ROUND" and len(e.args) == 2:
214
+ # A list: built as one in SQL (the front end folds a literal one into a LIST); round(x, places)
215
+ # only of a decimal, never a literal.
216
+ return None
217
+ if all(isinstance(a, E.Const) for a in e.args):
218
+ return E.Const(fold(e.name, [a.value for a in e.args]))
219
+ return None
220
+
221
+
222
+ def function_slot(e: E.Call, slots: Mapping[str, Slot]) -> Slot:
223
+ folded = _folded(e)
224
+ if folded is not None:
225
+ return expr_slot(folded, slots)
226
+ args = [expr_slot(a, slots) for a in e.args]
227
+ if len(args) == 1 and args[0].kinds == {MIXED} and e.name != "COALESCE":
228
+ return mixed_function(e, slots)
229
+ if e.name == "COALESCE" and any(a.kinds & {LIST, MAP} for a in args if a.present is not Bound.NEVER):
230
+ # Lists or maps of one type (a CASE's rule, `cypher_lists.element_type`); a list of no element type
231
+ # yet (`[]`) beside a typed one only as a literal (`cypher_values._case_value`).
232
+ from prograph.plan.ir.cypher_lists import element_type, typed_slot
233
+ dt = element_type(args, "coalesce()")
234
+ present = Bound.NEVER if any(a.present is Bound.ALWAYS for a in args) else Bound.MAYBE
235
+ return NOTHING if dt is None else typed_slot(dt, present)
236
+ if e.name == "COALESCE":
237
+ types = {t for t in (_type(a) for a in args) if t is not None}
238
+ if len(types) > 1:
239
+ raise NotBuilt("coalesce() of values of several types")
240
+ if not types:
241
+ return NOTHING
242
+ present = Bound.NEVER if any(a.present is Bound.ALWAYS for a in args) else Bound.MAYBE
243
+ return value_slot(next(iter(types)), present)
244
+ if e.name in _STRING_ARGS:
245
+ return _string_args_slot(e, args)
246
+ if e.name == "ROUND" and len(args) == 2:
247
+ return _round_places_slot(e, args)
248
+ (a,) = args
249
+ _wrong_conversion(e.name, a)
250
+ k = _kind(_type(a))
251
+ if k is None:
252
+ return NOTHING
253
+ null = Bound.MAYBE
254
+ if e.name == "TOSTRING":
255
+ if k == "float" or (k == "other" and _type(a) not in TEMPORAL):
256
+ raise NotBuilt("toString() of a float column (Java's text of a double)")
257
+ return value_slot(xsd.STRING, Bound.MAYBE)
258
+ if e.name == "TOINTEGER":
259
+ if k not in ("integer", "float", "string", "decimal"):
260
+ raise NotBuilt("toInteger() of that value")
261
+ return value_slot(xsd.INTEGER, null)
262
+ if e.name == "TOFLOAT":
263
+ if k not in ("integer", "float", "string", "decimal"):
264
+ raise NotBuilt("toFloat() of that value")
265
+ return value_slot(xsd.DOUBLE, null)
266
+ if e.name == "TOBOOLEAN":
267
+ if k not in ("boolean", "string"):
268
+ raise NotBuilt("toBoolean() of that value")
269
+ return replace_bool()
270
+ if k == "decimal" and e.name in ("CEIL", "FLOOR", "ROUND", "ABS"):
271
+ # A decimal keeps its type (rule cypher-decimal-functions): its digits by the decimal home.
272
+ from prograph.plan.ir.facts import rounded_digits
273
+ return value_slot(xsd.DECIMAL, null, digits=a.digits if e.name == "ABS" else rounded_digits(a.digits))
274
+ if e.name in ("SQRT", "CEIL", "FLOOR", "ROUND"): # a float, of an integer too (Java's double functions)
275
+ if k not in ("integer", "float", "decimal"):
276
+ raise NotBuilt(f"{e.name.lower()}() of a value that is not a number")
277
+ return value_slot(xsd.DOUBLE, null)
278
+ if e.name in ("ABS", "SIGN"):
279
+ if k not in ("integer", "float", "decimal"):
280
+ raise NotBuilt(f"{e.name.lower()}() of a value that is not a number")
281
+ return value_slot(xsd.INTEGER if e.name == "SIGN" or k == "integer" else xsd.DOUBLE, null)
282
+ if e.name in ("TOUPPER", "TOLOWER"):
283
+ if k != "string":
284
+ raise NotBuilt(f"{e.name.lower()}() of a value that is not a string")
285
+ return value_slot(xsd.STRING, null)
286
+ raise NotBuilt(f"the function {e.name.lower()}()")
287
+
288
+
289
+ _NOT_CONVERTED = {"TOINTEGER": {"boolean", "list", "map"}, "TOFLOAT": {"boolean", "list", "map"},
290
+ "TOBOOLEAN": {"integer", "float", "list", "map"}, "TOSTRING": {"list", "map"}}
291
+
292
+
293
+ _NAMES = {"TOINTEGER": "toInteger", "TOFLOAT": "toFloat", "TOBOOLEAN": "toBoolean", "TOSTRING": "toString"}
294
+
295
+
296
+ def _wrong_conversion(name: str, a: Slot) -> None:
297
+ """toInteger(), toFloat(), toBoolean() and toString() of a value of a kind openCypher raises an error
298
+ for (a boolean, a number, a list or a map, by function), where a row holds it: an InvalidArgumentValue."""
299
+ bad = _NOT_CONVERTED.get(name)
300
+ if bad is None or a.present is Bound.NEVER:
301
+ return
302
+ kind = "list" if a.kinds == {LIST} else "map" if a.kinds == {MAP} else \
303
+ _kind(a.datatype) if a.kinds == {VALUE} and a.datatype in (*_INTEGERS, *_FLOATS, xsd.BOOLEAN) else None
304
+ if kind in bad:
305
+ raise RuntimeTypeError(0, "InvalidArgumentValue", f"{_NAMES[name]}() of a value of kind {kind}")
306
+
307
+
308
+ def _round_places_slot(e: E.Call, args: list) -> Slot:
309
+ """round(x, places) of a decimal (Neo4j's form; rule cypher-decimal-functions): `places` a non-negative
310
+ integer written in the query, the result a decimal of that scale (`facts.rounded_digits`). Of another
311
+ value, or of places read from a column, refused by name."""
312
+ from prograph.plan.ir.facts import rounded_digits
313
+ places = e.args[1]
314
+ if not isinstance(places, E.Const) or isinstance(places.value, bool) or not isinstance(places.value, int) \
315
+ or places.value < 0:
316
+ raise NotBuilt("round() of a precision that is not a non-negative integer written in the query")
317
+ k = _kind(_type(args[0]))
318
+ if k is None:
319
+ return NOTHING
320
+ if k != "decimal":
321
+ raise NotBuilt("round() of a precision or a rounding mode (Neo4j's forms, not openCypher 9's) "
322
+ "of a value that is not a decimal")
323
+ return value_slot(xsd.DECIMAL, Bound.MAYBE, digits=rounded_digits(args[0].digits, places.value))
324
+
325
+
326
+ def _string_args_slot(e: E.Call, args: list) -> Slot:
327
+ """substring()'s and split()'s slot: a string, or a list of strings; each argument's type checked, a
328
+ literal start or length checked (`_substring`), split()'s delimiter a literal (`_split_args`)."""
329
+ from prograph.plan.ir.slot import list_slot
330
+ if len(e.args) not in _STRING_ARGS[e.name]:
331
+ raise NotBuilt(f"{e.name.lower()}() of {len(e.args)} arguments")
332
+ if e.name == "SUBSTRING":
333
+ consts = [a.value if isinstance(a, E.Const) else 0 for a in e.args[1:]]
334
+ _substring("", *consts) # a literal start or length that is an error: refused
335
+ for a in args[1:]:
336
+ if _kind(_type(a)) != "integer":
337
+ raise NotBuilt("substring() of a start or length that is not an integer")
338
+ else:
339
+ if not isinstance(e.args[1], E.Const):
340
+ raise NotBuilt("split() at a delimiter read from a column")
341
+ _split_args(None, e.args[1].value)
342
+ if e.args[1].value is None:
343
+ return NOTHING
344
+ k = _kind(_type(args[0]))
345
+ if k is None:
346
+ return NOTHING
347
+ if k != "string":
348
+ raise NotBuilt(f"{e.name.lower()}() of a value that is not a string (an error)")
349
+ return value_slot(xsd.STRING, Bound.MAYBE) if e.name == "SUBSTRING" else list_slot(xsd.STRING, Bound.MAYBE)
350
+
351
+
352
+ def _string_args_cell(e: E.Call, slot: Slot, cells: Dict[str, "L.Cell"]) -> "L.Cell":
353
+ """substring() and split() in SQL. substring: '' from a start at or past the string's length, the rest
354
+ from a length reaching past it (so the engines' 32-bit positions never overflow), else SUBSTR_CP, by code
355
+ points; a start or length a column holds that is null or negative an error the statement raises."""
356
+ from prograph.plan.ir import lower as L
357
+ from prograph.plan.sql import rel_algebra as R
358
+ args = [L.expr_cell(a, cells) for a in e.args]
359
+ s = args[0].value
360
+ if e.name == "SPLIT":
361
+ return L.Cell(slot, L.fn("CYPHER_SPLIT", s, args[1].value))
362
+ start = args[1].value
363
+ length = args[2].value if len(args) == 3 else None
364
+ size = L.fn("STR_LEN", s)
365
+ parts = [L.is_null(s), L.NULL_TEXT]
366
+ for x, a in zip(e.args[1:], args[1:]):
367
+ if not isinstance(x, E.Const): # a literal one is checked at planning
368
+ bad = L.any_of([L.is_null(a.value), R.CompareExpr(left=a.value, op="<", right=L.integer(0))])
369
+ parts += [bad, L.fn("CAST_STRING", L.fn("DATA_ERROR", L.text(
370
+ "ProGraph: substring() of a null or negative start or length: "),
371
+ L.fn("COALESCE", L.fn("CAST_STRING", a.value), L.text("null"))))]
372
+ # A literal start or length is read through the string's size, so no constant part is left for
373
+ # PostgreSQL's planner to fold (it would cast or add a literal past 32 or 64 bits in a branch never taken).
374
+ first = L.fn("+", L.fn("-", size, L.fn("-", size, start)) if isinstance(e.args[1], E.Const) else start,
375
+ L.integer(1))
376
+ parts += [R.CompareExpr(left=start, op=">=", right=size), L.text("")]
377
+ if length is not None:
378
+ taken = L.fn("-", L.fn("+", length, size), size) if isinstance(e.args[2], E.Const) else length
379
+ parts += [R.CompareExpr(left=length, op="<", right=L.fn("-", size, start)), L.fn("SUBSTR_CP", s, first, taken)]
380
+ parts += [L.fn("SUBSTR_FROM", s, first)]
381
+ return L.Cell(slot, L.case(*parts))
382
+
383
+
384
+ def replace_bool() -> Slot:
385
+ return value_slot(xsd.BOOLEAN, Bound.MAYBE)
386
+
387
+
388
+ def function_cell(e: E.Call, cells: Dict[str, "L.Cell"]) -> "L.Cell":
389
+ from prograph.plan.ir import lower as L
390
+ from prograph.plan.sql import rel_algebra as R
391
+ folded = _folded(e)
392
+ if folded is not None:
393
+ return L.expr_cell(folded, cells)
394
+ slot = function_slot(e, {n: c.slot for n, c in cells.items()})
395
+ if slot.present is Bound.NEVER:
396
+ return L.nothing()
397
+ args = [L.expr_cell(a, cells) for a in e.args]
398
+ if len(args) == 1 and args[0].slot.kinds == {MIXED} and e.name != "COALESCE":
399
+ return mixed_function(e, {n: c.slot for n, c in cells.items()}, cells)
400
+ if e.name == "COALESCE" and slot.kinds & {LIST, MAP}:
401
+ from prograph.plan.ir.cypher_values import _case_value
402
+ return L.Cell(slot, L.fn("COALESCE", *(_case_value(x, cells, slot, L) for x, a in zip(e.args, args)
403
+ if a.slot.present is not Bound.NEVER)))
404
+ if e.name == "COALESCE":
405
+ return L.Cell(slot, L.fn("COALESCE", *(a.value for a in args if a.slot.present is not Bound.NEVER)))
406
+ if e.name in _STRING_ARGS:
407
+ return _string_args_cell(e, slot, cells)
408
+ if e.name == "ROUND" and len(args) == 2:
409
+ return decimal_function_cell(e.name, args[0].value, slot, L, places=e.args[1].value)
410
+ (a,) = args
411
+ k = _kind(_type(a.slot))
412
+ v = a.value
413
+ if k == "decimal" and e.name in ("CEIL", "FLOOR", "ROUND", "ABS", "TOINTEGER"):
414
+ return decimal_function_cell(e.name, v, slot, L)
415
+ if e.name == "TOSTRING":
416
+ if k == "boolean":
417
+ return L.Cell(slot, L.case(L.is_null(v), L.NULL, v, L.text("true"), L.text("false")))
418
+ if _type(a.slot) in TEMPORAL: # the answer's ISO text, from its one home
419
+ return L.Cell(slot, temporal_text(_type(a.slot), v, L))
420
+ return L.Cell(slot, L.fn("CAST_STRING", v))
421
+ if e.name == "TOINTEGER":
422
+ if k == "integer":
423
+ return L.Cell(slot, v)
424
+ number = v if k == "float" else _parsed_float(v, L)
425
+ whole = L.case(R.CompareExpr(left=number, op=">=", right=L.integer(0)), L.fn("FLOOR", number),
426
+ L.fn("CEIL", number))
427
+ # Past 64 bits (or NaN) an error, raised by the statement (Spark's FLOOR of a double saturates).
428
+ inside = R.CompareExpr(left=L.fn("ABS", number), op="<", right=L.fn("CAST_DOUBLE", L.text("9.223372036854775807E18")))
429
+ out = L.case(L.is_null(number), L.NULL, inside, L.fn("DOUBLE_TO_BIGINT", whole),
430
+ L.fn("CAST_LONG", L.fn("DATA_ERROR", L.text("ProGraph: toInteger() past 64 bits: "), number)))
431
+ if k == "string": # an integer's text read exactly (an engine's cast of '1.9' rounds), else a
432
+ # float's text truncated, else null
433
+ integer_text = R.CompareExpr(left=L.fn("TRIM", v), op="RLIKE", right=L.text("^[+-]?[0-9]+$"))
434
+ out = L.case(integer_text, L.fn("CAST_LONG", L.fn("TRIM", v)), out) # an integer's text: castable
435
+ return L.Cell(slot, out)
436
+ if e.name == "TOFLOAT":
437
+ if k == "string": # also Java's NaN and Infinity, exactly as it spells them
438
+ t = L.fn("TRIM", v)
439
+ special = R.CompareExpr(left=t, op="RLIKE", right=L.text("^" + _SPECIAL_TEXT + "$"))
440
+ return L.Cell(slot, L.case(special, L.fn("CAST_DOUBLE", t), _parsed_float(v, L)))
441
+ return L.Cell(slot, L.fn("CAST_DOUBLE", v) if k in ("integer", "decimal") else v)
442
+ if e.name == "TOBOOLEAN":
443
+ if k == "boolean":
444
+ return L.Cell(slot, v)
445
+ low = L.fn("LOWER", L.fn("TRIM", v))
446
+ return L.Cell(slot, L.case(R.CompareExpr(left=low, op="=", right=L.text("true")), L.TRUE,
447
+ R.CompareExpr(left=low, op="=", right=L.text("false")), L.FALSE, L.NULL_BOOLEAN))
448
+ if e.name == "SQRT": # NaN below zero, as Java's (PostgreSQL and DuckDB raise)
449
+ x = L.fn("CAST_DOUBLE", v) if k in ("integer", "decimal") else v
450
+ return L.Cell(slot, L.case(R.CompareExpr(left=x, op="<", right=L.integer(0)),
451
+ L.fn("CAST_DOUBLE", L.text("NaN")), L.fn("SQRT", x)))
452
+ if e.name == "ROUND":
453
+ return round_cell(v, k, slot, L)
454
+ if e.name in ("CEIL", "FLOOR"):
455
+ if k == "integer":
456
+ return L.Cell(slot, L.fn("CAST_DOUBLE", v))
457
+ # A double of 2^52 or more is whole (and Spark's CEIL of one past 64 bits saturates): itself, as
458
+ # are the infinities and NaN (NaN compares above every number on these engines). A zero result
459
+ # keeps the argument's sign, as Java's (ceil(-0.5) is -0.0): v * 0.0.
460
+ r = L.fn("CAST_DOUBLE", L.fn(e.name, v))
461
+ return L.Cell(slot, L.case(
462
+ R.CompareExpr(left=L.fn("ABS", v), op=">=", right=L.fn("CAST_DOUBLE", L.text(repr(_TWO_52)))), v,
463
+ R.CompareExpr(left=r, op="=", right=L.fn("CAST_DOUBLE", L.integer(0))),
464
+ L.fn("*", v, L.fn("CAST_DOUBLE", L.integer(0))), r))
465
+ if e.name == "ABS":
466
+ return L.Cell(slot, L.fn("ABS", v))
467
+ if e.name == "SIGN":
468
+ return L.Cell(slot, L.fn("CAST_LONG", L.fn("SIGN", v)))
469
+ return L.Cell(slot, L.fn("UPPER" if e.name == "TOUPPER" else "LOWER", v))
470
+
471
+
472
+ @home("cypher-decimal-functions", "Cypher's functions of a decimal, in SQL",
473
+ terms=("decimal", "DECIMAL", "round(x, places)", "toInteger of a decimal", "ceil of a decimal",
474
+ "exact decimal", "Cypher decimal"))
475
+ def decimal_function_cell(name: str, v: "R.Expr", slot: Slot, L, places: Optional[int] = None) -> "L.Cell":
476
+ """A mapped DECIMAL column's value under abs, ceil, floor, round and toInteger (openCypher has no
477
+ decimal; ProGraph's choice, as SQL computes it): abs, ceil, floor and round keep the decimal, at the
478
+ digits of the decimal home (`facts.rounded_digits`); round(x) a tie toward positive infinity, as
479
+ round() of a float (`term_functions.decimal_round`, fn:round's); round(x, places) Neo4j's form, half
480
+ away from zero (Neo4j's HALF_UP, each engine's ROUND of a decimal); toInteger truncates toward zero, an
481
+ error past 64 bits. toFloat, sqrt and the other float functions read it as a FLOAT; sign() is an
482
+ integer, as of any number."""
483
+ from prograph.plan.sql import rel_algebra as R
484
+ if name == "TOINTEGER":
485
+ whole = L.case(R.CompareExpr(left=v, op=">=", right=L.integer(0)), L.fn("FLOOR", v), L.fn("CEIL", v))
486
+ return L.Cell(slot, L.fn("CAST_LONG", whole))
487
+ if name == "ABS":
488
+ value = L.fn("ABS", v)
489
+ elif name in ("CEIL", "FLOOR"):
490
+ value = L.fn(name, v)
491
+ elif places is None:
492
+ from prograph.plan.ir.term_functions import decimal_round
493
+ value = decimal_round(v, L)
494
+ else:
495
+ value = L.fn("ROUND", v, L.integer(places))
496
+ if slot.digits is not None:
497
+ value = L.fn("DECIMAL_SIZED", value, L.integer(slot.digits[0]), L.integer(slot.digits[1]))
498
+ return L.Cell(slot, value)
499
+
500
+
501
+ @home("cypher-round", "Cypher's round(), in SQL",
502
+ terms=("round()", "round half up", "tie toward positive infinity", "nearest integer", "Math.round"))
503
+ def round_cell(v: "R.Expr", k: str, slot: Slot, L) -> "L.Cell":
504
+ """openCypher 9's round(x): the nearest integer, as a float. A tie (x.5) goes toward positive infinity,
505
+ as Java's Math.round, which openCypher 9's reference implementation used (round(-2.5) is -2.0); the spec
506
+ does not say. Worked out from floor(x), whose difference from x is exact for |x| < 2^52 (adding 0.5 first
507
+ rounds 0.49999999999999994 up); a double of 2^52 or more is whole, itself, up to the long range: at
508
+ 2^63 or more (the infinities too) clamped to it, ±9.223372036854776E18, as Neo4j 5's; NaN itself; a zero is 0.0, as Math.round's (round(-0.4) is 0.0). The precision and mode forms are Neo4j's, not openCypher 9's
509
+ (refused by the front end)."""
510
+ from prograph.plan.sql import rel_algebra as R
511
+ if k == "integer":
512
+ return L.Cell(slot, L.fn("CAST_DOUBLE", v))
513
+ f = L.fn("CAST_DOUBLE", L.fn("FLOOR", v))
514
+ half = L.fn("CAST_DOUBLE", L.text("0.5"))
515
+ r = L.case(R.CompareExpr(left=L.fn("-", v, f), op=">=", right=half), L.fn("+", f, L.fn("CAST_DOUBLE", L.integer(1))), f)
516
+ big = L.fn("CAST_DOUBLE", L.text(repr(_TWO_63)))
517
+ return L.Cell(slot, L.case(
518
+ L.fn("IS_NAN", v), v,
519
+ R.CompareExpr(left=v, op=">=", right=big), big,
520
+ R.CompareExpr(left=v, op="<=", right=L.fn("-", L.fn("CAST_DOUBLE", L.integer(0)), big)),
521
+ L.fn("-", L.fn("CAST_DOUBLE", L.integer(0)), big),
522
+ R.CompareExpr(left=L.fn("ABS", v), op=">=", right=L.fn("CAST_DOUBLE", L.text(repr(_TWO_52)))), v,
523
+ L.fn("+", r, L.fn("CAST_DOUBLE", L.integer(0)))))
524
+
525
+
526
+ def _parsed_float(v: "R.Expr", L) -> "R.Expr":
527
+ """A string's float as openCypher reads one (Java's parseDouble of ASCII digits, spaces trimmed),
528
+ null for any other text; the same pattern the literal fold reads."""
529
+ from prograph.plan.sql import rel_algebra as R
530
+ t = L.fn("TRIM", v)
531
+ return L.case(R.CompareExpr(left=t, op="RLIKE", right=L.text("^" + _FLOAT_TEXT + "$")), L.fn("CAST_DOUBLE_TRY", t))
532
+
533
+
534
+ def mixed_function(e: E.Call, slots: Mapping[str, Slot], cells: Optional[Dict[str, "L.Cell"]] = None):
535
+ """A one-argument function of a value of several types (`toInteger(x)` of an integer, a float or a
536
+ string): worked out for each kind the value may be (its slot's tags), each its own call over that
537
+ kind's plain value, and chosen by the value's tag. Built where every kind's result is one type (a kind
538
+ the function refuses is refused); `slots` gives the result's slot, `cells` also its value."""
539
+ from prograph.plan.ir import cypher_mixed as M
540
+ tags = M.slot_tags(expr_slot(e.args[0], slots))
541
+ types = {"i": xsd.INTEGER, "f": xsd.DOUBLE, "s": xsd.STRING, "b": xsd.BOOLEAN}
542
+ out = []
543
+ for tag in tags:
544
+ name = f"#mixed_{tag}"
545
+ branch = E.Call(e.name, (E.Col(name),) + tuple(e.args[1:]), e.semantics)
546
+ inner = {**slots, name: value_slot(types[tag], Bound.NEVER)}
547
+ out.append((tag, name, branch, function_slot(branch, inner)))
548
+ results = {s.datatype for _, _, _, s in out if s.present is not Bound.NEVER}
549
+ if len(results) > 1 or any(s.kinds != {VALUE} and s.present is not Bound.NEVER for *_, s in out):
550
+ raise NotBuilt(f"{e.name.lower()}() of values of several types whose results differ in type")
551
+ slot = value_slot(next(iter(results)), Bound.MAYBE) if results else NOTHING
552
+ if cells is None:
553
+ return slot
554
+ from prograph.plan.ir import lower as L
555
+ value = L.expr_cell(e.args[0], cells)
556
+ struct = M.wrap(value, L)
557
+ parts = []
558
+ for tag, name, branch, s in out:
559
+ if s.present is Bound.NEVER:
560
+ continue
561
+ field = {"i": M.INT, "f": M.FLOAT, "s": M.STR, "b": M.BOOL}[tag]
562
+ typed = L.Cell(value_slot(types[tag], Bound.NEVER), M.field(struct, field, L))
563
+ parts += [L.eq(M.field(struct, M.KIND, L), L.text(tag)),
564
+ L.expr_cell(branch, {**cells, name: typed}).value]
565
+ return L.Cell(slot, L.case(*parts, L.NULL) if parts else L.NULL)