codecop 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.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
codecop/discover/go.py ADDED
@@ -0,0 +1,1947 @@
1
+ """Go call-site extractor.
2
+
3
+ Finds calls whose argument is SQL and resolves that argument statically:
4
+ interpreted and raw string literals, `+` concatenation, `fmt.Sprintf`, local
5
+ variables (`:=`, `=`, `var`, `q += ...`), `strings.Builder` / `bytes.Buffer`
6
+ writes, `strings.Join` over a slice, `strings.ReplaceAll`, package constants
7
+ (same package first, then repo-wide when a name has one value), `//go:embed`
8
+ files, `embed.FS.ReadFile`, and same-package helpers that return the SQL.
9
+
10
+ Go drivers take the context first, so a sink rule lists several positional
11
+ indexes: the first one that resolves to SQL wins.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import re
18
+ from collections import defaultdict
19
+ from pathlib import Path
20
+
21
+ import tree_sitter_go
22
+ from tree_sitter import Language, Node, Parser, Query, QueryCursor
23
+
24
+ from .base import LangRules, RawSite, is_test_path, looks_like_sql, read_text, trim
25
+ from .base import walk_tree
26
+
27
+ LANG = Language(tree_sitter_go.language())
28
+ # How many steps of indirection (variables, helpers, constants) one SQL argument is followed through, and the
29
+ # longest package constant kept for use from other packages. Settings: `[discover] go_resolve_depth`,
30
+ # `max_const_chars`.
31
+ DEFAULT_MAX_DEPTH = 8
32
+ MAX_DEPTH = DEFAULT_MAX_DEPTH
33
+ DEFAULT_MAX_CONST_CHARS = 20_000
34
+ MAX_CONST_CHARS = DEFAULT_MAX_CONST_CHARS
35
+ # The most complete statements one call site is split into when its SQL is assembled from mutually
36
+ # exclusive branches. Past it the branches become one run-time part. A setting: `[discover] max_variants`.
37
+ DEFAULT_MAX_VARIANTS = 12
38
+ MAX_VARIANTS = DEFAULT_MAX_VARIANTS
39
+ # The most statements a `stmt.field` argument may stand for (one per struct literal that sets the field).
40
+ DEFAULT_MAX_FIELD_VALUES = 60
41
+ MAX_FIELD_VALUES = DEFAULT_MAX_FIELD_VALUES
42
+ FUNC_DECL = ("function_declaration", "method_declaration")
43
+ FUNC_TYPES = FUNC_DECL + ("func_literal",)
44
+ CASE_TYPES = ("expression_case", "default_case", "type_case", "communication_case")
45
+ SCOPE_TYPES = ("block", "if_statement", "for_statement", "expression_switch_statement", "type_switch_statement",
46
+ "select_statement") + CASE_TYPES + FUNC_TYPES
47
+ COND_TYPES = ("block", "func_literal") + CASE_TYPES
48
+ STRING_TYPES = ("interpreted_string_literal", "raw_string_literal")
49
+
50
+ SCAN = Query(LANG, """
51
+ (call_expression) @call
52
+ [(interpreted_string_literal) (raw_string_literal)] @str
53
+ """)
54
+
55
+ KEYED = QueryCursor(Query(LANG, "(keyed_element) @k"))
56
+
57
+ SIMPLE_ESC = {"n": "\n", "t": "\t", "r": "\r", "\\": "\\", '"': '"', "'": "'", "a": "\a", "b": "\b", "f": "\f", "v": "\v"}
58
+ ESC_RE = re.compile(r"\\(?:[abfnrtv\\'\"]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|[0-7]{3})")
59
+ VERB_RE = re.compile(r"%(?:\[(\d+)\])?[-+# 0]*(?:\d+|\*)?(?:\.(?:\d+|\*))?([a-zA-Z%])")
60
+ SQLISH_NAME = re.compile(r"(sql|query|stmt|statement|ddl|dml|cypher)", re.I)
61
+ CTX_NAME = re.compile(r"^\w*(?:[cC]tx|[cC]ontext)\w*$")
62
+ CTX_CALL = re.compile(r"(?:\bcontext\.(?:Background|TODO)|\.Context|\b\w*[cC]tx)\(\)$")
63
+
64
+ # What a string must start with to count as SQL when it is the argument of a database call. Looser than
65
+ # base.looks_like_sql, which also has to reject prose in free-standing strings.
66
+ STATEMENT_START = re.compile(
67
+ r"^\s*(?:--[^\n]*\n\s*|/\*.*?\*/\s*)*\(?\s*(?:SELECT|INSERT|UPDATE|DELETE|WITH|CREATE|DROP|ALTER|TRUNCATE|BEGIN|COMMIT|"
68
+ r"ROLLBACK|START\s+TRANSACTION|SAVEPOINT|RELEASE|SET|RESET|SHOW|EXPLAIN|DESCRIBE|DESC|OPTIMIZE|SYSTEM|EXISTS|GRANT|"
69
+ r"REVOKE|LOCK|VACUUM|ANALYZE|CALL|COPY|MERGE|REFRESH|ATTACH|DETACH|RENAME|KILL|USE|UPSERT|REPLACE|VALUES|LISTEN|"
70
+ r"NOTIFY|UNLISTEN|DO|REINDEX|CLUSTER|DISCARD|DEALLOCATE|PREPARE|EXECUTE|DECLARE|FETCH|COMMENT\s+ON|CHECK|EXCHANGE|"
71
+ r"UNDROP|PRAGMA|BACKUP|RESTORE)(?:\s+[\w(\"'`*$«@-]|\s*;|\s*$)", re.I | re.S)
72
+ SQL_INSIDE = re.compile(
73
+ r"\bSELECT\b[\s\S]+?\bFROM\b|\bINSERT\s+INTO\b|\bUPDATE\s+\S+\s+SET\b|\bDELETE\s+FROM\b|\b(?:CREATE|ALTER|DROP)\s+TABLE\b", re.I)
74
+ CYPHER_START = re.compile(r"^\s*(?:MATCH|OPTIONAL\s+MATCH|MERGE|UNWIND|CREATE|CALL|RETURN|WITH)\b[\s\S]*[(\[]", re.I)
75
+ LEAD_HOLES = re.compile(r"^(?:\s*«[^»]*»)+")
76
+ PKG_ENGINES = {"clickhouse": "clickhouse", "ch": "clickhouse", "postgres": "postgres", "pg": "postgres",
77
+ "postgresql": "postgres", "sqlite": "sqlite", "mysql": "mysql", "neo4j": "cypher"}
78
+ # Calls that only shape a string: a SQL literal inside one belongs to whatever the result is passed to.
79
+ PASS_CALLS = {"fmt.Sprintf", "strings.TrimSpace", "strings.Join", "strings.ReplaceAll", "strings.Replace", "strings.Trim",
80
+ "strings.TrimLeft", "strings.TrimRight", "strings.TrimPrefix", "strings.TrimSuffix", "string", "fmt.Sprint"}
81
+ UNWRAP_CALLS = {"strings.TrimSpace", "strings.Trim", "strings.TrimLeft", "strings.TrimRight", "strings.TrimPrefix",
82
+ "strings.TrimSuffix", "strings.ToValidUTF8", "string", "strings.Clone"}
83
+ NOT_A_SINK = re.compile(
84
+ r"^(?:strings\.(?:Has\w+|Contains\w*|Index\w*|LastIndex\w*|Cut\w*|Count|EqualFold|Split\w*|Fields\w*)|regexp\.\w+|"
85
+ r"errors\.\w+|fmt\.(?:Errorf|Print\w*|Fprint\w*)|log\.\w+|slog\.\w+|(?:require|assert)\.\w+|t\.\w+|panic)$|"
86
+ r"(?:^|\.)(?:Errorf|Fatalf|Logf|Infof|Debugf|Warnf|Contains|NotContains|Equal|NotEqual|HasPrefix)$")
87
+ SEPARATORS = {",", "AND", "OR", "UNION ALL", "UNION"}
88
+ BUILDER_WRITES = {"WriteString", "WriteByte", "WriteRune", "Write", "Reset"}
89
+ FPRINT = {"Fprintf", "Fprint", "Fprintln"}
90
+ STRONG_SKIP_ARG = ("composite_literal", "int_literal", "float_literal", "nil", "true", "false", "func_literal", "unary_expression",
91
+ "rune_literal")
92
+
93
+
94
+ class Res:
95
+ """A resolved string: text with «expr» placeholders, and how it was reached."""
96
+
97
+ __slots__ = ("text", "dynamic", "via_name", "from_file", "alts")
98
+
99
+ def __init__(self, text: str, dynamic: bool = False, via_name: bool = False, from_file: bool = False,
100
+ alts: list[str] | None = None):
101
+ self.text = text
102
+ self.dynamic = dynamic
103
+ self.via_name = via_name
104
+ self.from_file = from_file
105
+ # Complete alternative texts of this same value, one per mutually exclusive branch (if / else,
106
+ # switch cases). `text` then holds a run-time part where the branches differ.
107
+ self.alts = alts
108
+
109
+ @property
110
+ def resolution(self) -> str:
111
+ if self.dynamic:
112
+ return "template"
113
+ if self.from_file:
114
+ return "file"
115
+ return "constant" if self.via_name else "literal"
116
+
117
+ def named(self) -> "Res":
118
+ return Res(self.text, self.dynamic, True, self.from_file, self.alts)
119
+
120
+ def dyn(self) -> "Res":
121
+ return Res(self.text, True, self.via_name, self.from_file, self.alts)
122
+
123
+
124
+ def _join(parts: list[Res]) -> Res:
125
+ """Concatenate. Alternatives of a part carry over: each combination is one alternative of the whole,
126
+ up to MAX_VARIANTS; past that only the text with run-time parts is kept."""
127
+ alts: list[str] | None = None
128
+ if any(p.alts for p in parts):
129
+ alts = [""]
130
+ for p in parts:
131
+ options = p.alts or [p.text]
132
+ if len(alts) * len(options) > MAX_VARIANTS:
133
+ alts = None
134
+ break
135
+ alts = [a + o for a in alts for o in options]
136
+ return Res("".join(p.text for p in parts), any(p.dynamic for p in parts), any(p.via_name for p in parts),
137
+ any(p.from_file for p in parts), alts)
138
+
139
+
140
+ def _txt(node: Node) -> str:
141
+ return node.text.decode("utf-8", "replace")
142
+
143
+
144
+ def _ph_text(text: str) -> Res:
145
+ return Res("«" + trim(text, 60).replace("»", ">") + "»", dynamic=True)
146
+
147
+
148
+ def _ph(node: Node) -> Res:
149
+ return _ph_text(_txt(node))
150
+
151
+
152
+ def _walk(node: Node, stop: tuple[str, ...] = ()):
153
+ """Depth-first over descendants, not descending into node types in `stop`."""
154
+ return walk_tree(node, stop)
155
+
156
+
157
+ def _within(inner: Node, outer: Node) -> bool:
158
+ return outer.start_byte <= inner.start_byte and inner.end_byte <= outer.end_byte
159
+
160
+
161
+ def _unescape(m: re.Match) -> str:
162
+ s = m.group(0)[1:]
163
+ if s in SIMPLE_ESC:
164
+ return SIMPLE_ESC[s]
165
+ try:
166
+ return chr(int(s[1:], 16)) if s[0] in "xuU" else chr(int(s, 8))
167
+ except ValueError:
168
+ return m.group(0)
169
+
170
+
171
+ def decode_string(node: Node) -> str:
172
+ text = _txt(node)
173
+ if node.type == "raw_string_literal":
174
+ return text[1:-1].replace("\r", "")
175
+ return ESC_RE.sub(_unescape, text[1:-1])
176
+
177
+
178
+ def _strip_parens(node: Node | None) -> Node | None:
179
+ while node is not None and node.type == "parenthesized_expression" and node.named_children:
180
+ node = node.named_children[0]
181
+ return node
182
+
183
+
184
+ def callee_name(fn: Node | None) -> tuple[str, Node | None, str]:
185
+ """(last segment, receiver node, dotted text) of a call's function; generic instantiation ignored."""
186
+ while fn is not None and fn.type in ("index_expression", "type_instantiation_expression", "parenthesized_expression"):
187
+ fn = fn.child_by_field_name("operand") or (fn.named_children[0] if fn.named_children else None)
188
+ if fn is None:
189
+ return "", None, ""
190
+ if fn.type == "identifier":
191
+ name = _txt(fn)
192
+ return name, None, name
193
+ if fn.type == "selector_expression":
194
+ field, operand = fn.child_by_field_name("field"), fn.child_by_field_name("operand")
195
+ if field is None:
196
+ return "", None, ""
197
+ name = _txt(field)
198
+ dotted = (_txt(operand) + "." + name) if operand is not None and operand.type == "identifier" else name
199
+ return name, operand, dotted
200
+ return "", None, ""
201
+
202
+
203
+ def call_args(call: Node) -> list[Node]:
204
+ args = call.child_by_field_name("arguments")
205
+ return [a for a in args.named_children if a.type != "comment"] if args is not None else []
206
+
207
+
208
+ def param_names(func: Node) -> list[str]:
209
+ """Flattened parameter names in positional order ("" for an unnamed one)."""
210
+ out: list[str] = []
211
+ params = func.child_by_field_name("parameters")
212
+ if params is None:
213
+ return out
214
+ for p in params.named_children:
215
+ if p.type not in ("parameter_declaration", "variadic_parameter_declaration"):
216
+ continue
217
+ names = [_txt(c) for c in p.children_by_field_name("name")]
218
+ out.extend(names or [""])
219
+ return out
220
+
221
+
222
+ def is_ctx(arg: Node) -> bool: # noqa: C901
223
+ """A context.Context argument, judged by its text."""
224
+ if arg.type == "identifier":
225
+ return bool(CTX_NAME.match(_txt(arg)))
226
+ if arg.type == "selector_expression":
227
+ field = arg.child_by_field_name("field")
228
+ return field is not None and bool(CTX_NAME.match(_txt(field)))
229
+ if arg.type != "call_expression":
230
+ return False
231
+ name = callee_name(arg.child_by_field_name("function"))[0]
232
+ return bool(CTX_NAME.match(name)) or bool(CTX_CALL.search(_txt(arg))) or \
233
+ (name.startswith("With") and any(is_ctx(a) for a in call_args(arg)[:1]))
234
+
235
+
236
+ def leading_ctx(arg: Node) -> bool:
237
+ """A first argument that is a context, or derives one: `ctx`, `withTimeout(ctx)`, `clickhouse.Context(ctx, ...)`."""
238
+ if is_ctx(arg):
239
+ return True
240
+ if arg.type != "call_expression":
241
+ return False
242
+ inner = call_args(arg)
243
+ return bool(inner) and is_ctx(inner[0])
244
+
245
+
246
+ def param_type(func: Node, name: str) -> str:
247
+ params = func.child_by_field_name("parameters")
248
+ for p in (params.named_children if params is not None else ()):
249
+ if p.type in ("parameter_declaration", "variadic_parameter_declaration") \
250
+ and any(_txt(c) == name for c in p.children_by_field_name("name")):
251
+ typ = p.child_by_field_name("type")
252
+ return ("..." if p.type.startswith("variadic") else "") + (_txt(typ) if typ is not None else "")
253
+ return ""
254
+
255
+
256
+ def bare_type(text: str) -> str:
257
+ """`*pkg.Store[T]` -> `Store`."""
258
+ text = text.lstrip("*.").split("[")[0]
259
+ return text.rsplit(".", 1)[-1]
260
+
261
+
262
+ def recv_type(func: Node) -> str:
263
+ recv = func.child_by_field_name("receiver")
264
+ if recv is None:
265
+ return ""
266
+ for p in recv.named_children:
267
+ typ = p.child_by_field_name("type")
268
+ if typ is not None:
269
+ return bare_type(_txt(typ))
270
+ return ""
271
+
272
+
273
+ def sinkish_sql(text: str, engine: str = "", strict: bool = False) -> bool:
274
+ """Is this resolved sink argument SQL?"""
275
+ if not text or len(text.strip()) < 5:
276
+ return False
277
+ if looks_like_sql(text, any_case=True):
278
+ return True
279
+ body = LEAD_HOLES.sub("", text)
280
+ if body != text and (looks_like_sql(body, any_case=True) or SQL_INSIDE.search(body)):
281
+ return True
282
+ if engine == "cypher" and CYPHER_START.match(text):
283
+ return True
284
+ if strict:
285
+ return False
286
+ return bool(STATEMENT_START.match(body))
287
+
288
+
289
+ class Event:
290
+ __slots__ = ("kind", "node", "value", "index", "scope")
291
+
292
+ def __init__(self, kind: str, node: Node, value: Node | None, index: int, scope: Node):
293
+ self.kind = kind # decl | assign | append | param | range | write
294
+ self.node = node # the statement (or the declaring function / range clause)
295
+ self.value = value # right-hand expression, range operand or write call
296
+ self.index = index # which result of a multi-value right-hand side; -1 for one-to-one
297
+ self.scope = scope # where a declaration is visible
298
+
299
+
300
+ class Wrapper:
301
+ __slots__ = ("name", "index", "engine", "dir", "method", "param", "nparams", "variadic", "recv", "test")
302
+
303
+ def __init__(self, name: str, index: int, engine: str, dir: str, method: bool, param: str, nparams: int, variadic: bool,
304
+ recv: str = "", test: bool = False):
305
+ self.name, self.index, self.engine, self.dir, self.method, self.param = name, index, engine, dir, method, param
306
+ self.nparams, self.variadic, self.recv, self.test = nparams, variadic, recv, test
307
+
308
+
309
+ class Ctx:
310
+ """State shared by every file of one run."""
311
+
312
+ def __init__(self, root: Path, rules: LangRules):
313
+ self.root = root
314
+ self.rules = rules
315
+ self.files: dict[str, GoFile] = {}
316
+ self.dir_files: dict[str, list[GoFile]] = defaultdict(list)
317
+ self.pkg_decls: dict[str, dict[str, tuple[GoFile, str]]] = defaultdict(dict)
318
+ self.pkg_funcs: dict[str, dict[str, list[tuple[GoFile, Node]]]] = defaultdict(lambda: defaultdict(list))
319
+ self.pkg_engines: dict[str, set[str]] = defaultdict(set)
320
+ self.pkg_db: set[str] = set()
321
+ self.global_consts: dict[str, set[str]] = defaultdict(set)
322
+ self.used_globals: set[str] = set()
323
+ self.wrappers: dict[str, list[Wrapper]] = defaultdict(list)
324
+ self.env: dict[int, dict[str, Res | None]] = {}
325
+ self.resolving: set[tuple] = set()
326
+ self.file_cache: dict[str, str | None] = {}
327
+ self.modules: dict[str, tuple[str, str] | None] = {}
328
+ self.sink_args: dict[str, list[int]] = {}
329
+ self.sink_engine: dict[str, str] = {}
330
+ self._repo_modules: dict[str, str] | None = None
331
+ self._modules_for = -1
332
+ self._handles = None
333
+ self.weak: set[str] = set()
334
+ self.passthrough: set[str] = set()
335
+ for s in rules.sinks:
336
+ for name in s.names:
337
+ if "passthrough" in s.kwargs:
338
+ self.passthrough.add(name)
339
+ elif "weak" in s.kwargs:
340
+ self.weak.add(name)
341
+ self.sink_args.setdefault(name, s.args)
342
+ self.sink_engine.setdefault(name, s.engine)
343
+
344
+ def import_engine(self, path: str) -> str | None:
345
+ """Engine for an import path by longest rule prefix; None when the path is not a database package."""
346
+ best = None
347
+ for prefix, engine in self.rules.imports.items():
348
+ if (path == prefix or path.startswith(prefix + "/")) and (best is None or len(prefix) > len(best[0])):
349
+ best = (prefix, engine)
350
+ return best[1] if best is not None else None
351
+
352
+ def module_of(self, dir: str) -> tuple[str, str] | None:
353
+ """(module path, module dir) from the nearest go.mod at or above `dir`."""
354
+ if dir in self.modules:
355
+ return self.modules[dir]
356
+ found = None
357
+ text = read_text(self.root / dir / "go.mod")
358
+ if text is not None:
359
+ m = re.search(r"^module\s+(\S+)", text, re.M)
360
+ if m:
361
+ found = (m.group(1).strip('"'), dir)
362
+ if found is None and dir:
363
+ found = self.module_of(os.path.dirname(dir))
364
+ self.modules[dir] = found
365
+ return found
366
+
367
+ def import_dir(self, from_dir: str, path: str) -> str | None:
368
+ mod = self.module_of(from_dir)
369
+ if mod is not None:
370
+ module, mdir = mod
371
+ if path == module:
372
+ return mdir
373
+ if path.startswith(module + "/"):
374
+ return os.path.normpath(os.path.join(mdir, path[len(module) + 1:]))
375
+ # another module of the same repository (a go.work workspace, or a `replace` to a sibling directory):
376
+ # the module whose path is the longest prefix of the import path
377
+ best = None
378
+ for module, mdir in self.repo_modules().items():
379
+ if (path == module or path.startswith(module + "/")) and (best is None or len(module) > len(best[0])):
380
+ best = (module, mdir)
381
+ if best is None or (mod is not None and best[0] == mod[0]):
382
+ return None
383
+ rest = path[len(best[0]) + 1:] if path != best[0] else ""
384
+ found = os.path.normpath(os.path.join(best[1], rest)) if rest else best[1]
385
+ return found if found in self.dir_files else None
386
+
387
+ def repo_modules(self) -> dict[str, str]:
388
+ """Module path -> directory of every go.mod above a directory with Go files."""
389
+ if self._repo_modules is None or self._modules_for != len(self.dir_files):
390
+ self._repo_modules, self._modules_for = {}, len(self.dir_files)
391
+ for d in list(self.dir_files):
392
+ mod = self.module_of(d)
393
+ if mod is not None:
394
+ self._repo_modules.setdefault(mod[0], mod[1])
395
+ return self._repo_modules
396
+
397
+ @property
398
+ def handles(self):
399
+ """Where each call's handle comes from (engine_go.Handles), built on first use."""
400
+ if self._handles is None:
401
+ from .engine_go import Handles
402
+ self._handles = Handles(self)
403
+ return self._handles
404
+
405
+ def read_file(self, rel: str) -> str | None:
406
+ if rel not in self.file_cache:
407
+ p = (self.root / rel)
408
+ try:
409
+ inside = p.resolve().is_relative_to(self.root) and p.is_file()
410
+ except OSError:
411
+ inside = False
412
+ self.file_cache[rel] = read_text(p) if inside else None
413
+ return self.file_cache[rel]
414
+
415
+
416
+ class GoFile:
417
+ def __init__(self, rel: str, src: bytes, ctx: Ctx):
418
+ self.rel = rel
419
+ self.dir = os.path.dirname(rel)
420
+ self.ctx = ctx
421
+ self.tree = Parser(LANG).parse(src)
422
+ self.root = self.tree.root_node
423
+ self.imports: dict[str, str] = {} # alias -> import path
424
+ self.side_imports: list[str] = [] # every `_` and `.` import (one alias, several paths)
425
+ self.decls: dict[str, tuple[Node | None, str, int]] = {} # package-level name -> (value, embed path, result index)
426
+ self.embed_fs: set[str] = set()
427
+ self.package = ""
428
+ self.consumed: set[int] = set() # string nodes already attached to a reported site
429
+ self._events_cache: dict[int, dict[str, list[Event]]] = {}
430
+ self._decl_cache: dict[str, Res | None] = {}
431
+ self._decl_used: set[str] = set()
432
+ self._ovr: dict[tuple[int, str], Res | None] = {}
433
+ self._keyed: dict[str, list[tuple[Node, str]]] | None = None
434
+ self.test = is_test_path(rel)
435
+ self.closures: dict[tuple[int, str], int] = {} # (enclosing function, local name) -> SQL index of a closure
436
+ self.src = src
437
+ caps = QueryCursor(SCAN).captures(self.root)
438
+ self.calls: list[Node] = sorted(caps.get("call", []), key=lambda n: n.start_byte)
439
+ self.strings: list[Node] = sorted(caps.get("str", []), key=lambda n: n.start_byte)
440
+ self._index()
441
+ engines = {e for e in (ctx.import_engine(p) for p in [*self.imports.values(), *self.side_imports]) if e is not None}
442
+ self.has_db = bool(engines)
443
+ self.engines = {e for e in engines if e}
444
+ if self.has_db:
445
+ ctx.pkg_db.add(self.dir)
446
+ ctx.pkg_engines[self.dir] |= self.engines
447
+
448
+ # ---- indexing -------------------------------------------------------
449
+ def _index(self) -> None:
450
+ prev = None
451
+ for n in self.root.named_children:
452
+ t = n.type
453
+ if t == "package_clause":
454
+ self.package = _txt(n.named_children[0]) if n.named_children else ""
455
+ elif t == "import_declaration":
456
+ for spec in _walk(n):
457
+ if spec.type != "import_spec":
458
+ continue
459
+ path = spec.child_by_field_name("path")
460
+ if path is None:
461
+ continue
462
+ p = _txt(path).strip('"`')
463
+ name = spec.child_by_field_name("name")
464
+ alias = _txt(name) if name is not None else re.sub(r"^go-|\.go$|-go$", "", self._last_seg(p))
465
+ if alias in ("_", "."):
466
+ self.side_imports.append(p) # several driver registrations share the alias `_`
467
+ self.imports[alias] = p
468
+ elif t in ("const_declaration", "var_declaration"):
469
+ embed = ""
470
+ if prev is not None and prev.type == "comment" and prev.end_point[0] + 1 == n.start_point[0]:
471
+ m = re.match(r"//go:embed\s+(\S+)", _txt(prev))
472
+ embed = m.group(1).strip('"`') if m else ""
473
+ group_embed = embed
474
+ for spec in _walk(n, stop=("const_spec", "var_spec")):
475
+ if spec.type not in ("const_spec", "var_spec"):
476
+ continue
477
+ embed = group_embed
478
+ before = spec.prev_named_sibling # //go:embed inside a `var ( ... )` block
479
+ if before is not None and before.type == "comment" and before.end_point[0] + 1 == spec.start_point[0]:
480
+ m = re.match(r"//go:embed\s+(\S+)", _txt(before))
481
+ embed = m.group(1).strip('"`') if m else ""
482
+ names = spec.children_by_field_name("name")
483
+ value = spec.child_by_field_name("value")
484
+ values = value.named_children if value is not None else []
485
+ typ = spec.child_by_field_name("type")
486
+ for i, nm in enumerate(names):
487
+ name = _txt(nm)
488
+ if embed and typ is not None and _txt(typ).endswith("FS"):
489
+ self.embed_fs.add(name)
490
+ continue
491
+ if len(values) == len(names):
492
+ self.decls.setdefault(name, (values[i], "", -1))
493
+ elif len(values) == 1:
494
+ self.decls.setdefault(name, (values[0], "", i))
495
+ else:
496
+ self.decls.setdefault(name, (None, embed, -1))
497
+ self.ctx.pkg_decls[self.dir].setdefault(name, (self, name))
498
+ elif t in FUNC_DECL:
499
+ nm = n.child_by_field_name("name")
500
+ if nm is not None:
501
+ self.ctx.pkg_funcs[self.dir][_txt(nm)].append((self, n))
502
+ prev = n
503
+
504
+ @staticmethod
505
+ def _last_seg(path: str) -> str:
506
+ segs = path.split("/")
507
+ if len(segs) > 1 and re.fullmatch(r"v\d+", segs[-1]):
508
+ return segs[-2]
509
+ return segs[-1]
510
+
511
+ def file_engine(self) -> str:
512
+ return self.engine_source()[0]
513
+
514
+ def engine_source(self) -> tuple[str, str, str]:
515
+ """(engine, basis, unsure) the file's own imports or its package give its calls: basis `file` for the file's
516
+ driver imports, `package` for the package's (engine_go.Handles.package), `package_name` for a package
517
+ named after an engine. `unsure` says why there is none when the evidence names two engines."""
518
+ if len(self.engines) == 1:
519
+ return next(iter(self.engines)), "file", ""
520
+ if self.engines:
521
+ return "", "", f"the file imports drivers for {' and '.join(sorted(self.engines))}"
522
+ try:
523
+ eng, unsure = self.ctx.handles.package(self.dir)
524
+ except Exception: # the package evidence is an aid: without it, the file says nothing
525
+ eng, unsure = "", ""
526
+ if eng:
527
+ return eng, "package", ""
528
+ if unsure:
529
+ return "", "", unsure
530
+ named = PKG_ENGINES.get(self.package, "")
531
+ return named, "package_name" if named else "", ""
532
+
533
+ def reset(self) -> None:
534
+ """Forget which strings were used: the passes before call-site extraction only collect."""
535
+ self.consumed.clear()
536
+ self._decl_used.clear()
537
+ self.closures.clear()
538
+
539
+ # ---- scopes ---------------------------------------------------------
540
+ @staticmethod
541
+ def _enclosing(node: Node, types: tuple[str, ...]) -> Node | None:
542
+ n = node.parent
543
+ while n is not None:
544
+ if n.type in types:
545
+ return n
546
+ n = n.parent
547
+ return None
548
+
549
+ @staticmethod
550
+ def _top_func(node: Node) -> Node | None:
551
+ top, n = None, node.parent
552
+ while n is not None:
553
+ if n.type in FUNC_TYPES:
554
+ top = n
555
+ n = n.parent
556
+ return top
557
+
558
+ def _events(self, top: Node) -> dict[str, list[Event]]:
559
+ cached = self._events_cache.get(top.id)
560
+ if cached is not None:
561
+ return cached
562
+ ev: dict[str, list[Event]] = defaultdict(list)
563
+
564
+ def scope_of(n: Node) -> Node:
565
+ return self._enclosing(n, SCOPE_TYPES) or top
566
+
567
+ def add_params(func: Node) -> None:
568
+ for name in param_names(func):
569
+ if name and name != "_":
570
+ ev[name].append(Event("param", func, None, -1, func))
571
+ recv = func.child_by_field_name("receiver")
572
+ if recv is not None:
573
+ for p in recv.named_children:
574
+ for c in p.children_by_field_name("name"):
575
+ ev[_txt(c)].append(Event("param", func, None, -1, func))
576
+
577
+ def pairs(lefts: list[Node], rights: list[Node]):
578
+ for i, left in enumerate(lefts):
579
+ if left.type != "identifier" or _txt(left) == "_":
580
+ continue
581
+ if len(rights) == len(lefts):
582
+ yield _txt(left), rights[i], -1
583
+ elif len(rights) == 1:
584
+ yield _txt(left), rights[0], i
585
+ else:
586
+ yield _txt(left), None, -1
587
+
588
+ add_params(top)
589
+ for n in _walk(top):
590
+ t = n.type
591
+ if t == "short_var_declaration" or t == "assignment_statement":
592
+ left, right = n.child_by_field_name("left"), n.child_by_field_name("right")
593
+ if left is None:
594
+ continue
595
+ rights = right.named_children if right is not None else []
596
+ if t == "short_var_declaration":
597
+ kind = "decl"
598
+ else:
599
+ op = n.child_by_field_name("operator")
600
+ optxt = _txt(op) if op is not None else "="
601
+ kind = "assign" if optxt == "=" else "append" if optxt == "+=" else ""
602
+ if not kind:
603
+ continue
604
+ for name, value, index in pairs(left.named_children, rights):
605
+ ev[name].append(Event(kind, n, value, index, scope_of(n)))
606
+ elif t in ("var_spec", "const_spec"):
607
+ value = n.child_by_field_name("value")
608
+ rights = value.named_children if value is not None else []
609
+ names = n.children_by_field_name("name")
610
+ for i, nm in enumerate(names):
611
+ v, index = (rights[i], -1) if len(rights) == len(names) else (rights[0], i) if len(rights) == 1 else (None, -1)
612
+ ev[_txt(nm)].append(Event("decl", n, v, index, scope_of(n)))
613
+ elif t == "range_clause":
614
+ left, right = n.child_by_field_name("left"), n.child_by_field_name("right")
615
+ loop = n.parent if n.parent is not None else n
616
+ declares = any(c.type == ":=" for c in n.children)
617
+ if left is not None and declares:
618
+ idents = [c for c in left.named_children if c.type == "identifier"]
619
+ for i, c in enumerate(idents):
620
+ if _txt(c) != "_":
621
+ ev[_txt(c)].append(Event("range", n, right if i == len(left.named_children) - 1 and i > 0 else None, i, loop))
622
+ elif t == "func_literal":
623
+ add_params(n)
624
+ elif t == "call_expression":
625
+ name, recv, _ = callee_name(n.child_by_field_name("function"))
626
+ if name in BUILDER_WRITES and recv is not None and recv.type == "identifier":
627
+ ev[_txt(recv)].append(Event("write", n, n, -1, scope_of(n)))
628
+ elif name in FPRINT and recv is not None and _txt(recv) == "fmt":
629
+ args = call_args(n)
630
+ target = args[0] if args else None
631
+ if target is not None and target.type == "unary_expression" and target.named_children:
632
+ target = target.named_children[0]
633
+ if target is not None and target.type == "identifier":
634
+ ev[_txt(target)].append(Event("write", n, n, -1, scope_of(n)))
635
+ for lst in ev.values():
636
+ lst.sort(key=lambda e: (e.node.start_byte, e.kind != "param"))
637
+ self._events_cache[top.id] = ev
638
+ return ev
639
+
640
+ def _conditional(self, node: Node, anchor: Node, top: Node) -> bool:
641
+ """True when `node` sits in a branch or loop body that `anchor` is not part of."""
642
+ n = node.parent
643
+ while n is not None and n.id != top.id:
644
+ if n.type in COND_TYPES and not _within(anchor, n):
645
+ return True
646
+ n = n.parent
647
+ return False
648
+
649
+ def _local(self, name: str, anchor: Node) -> tuple[Node, Event, list[Event]] | None:
650
+ """The declaration of `name` visible at `anchor`, and the later events that precede the anchor."""
651
+ top = self._top_func(anchor)
652
+ if top is None:
653
+ return None
654
+ events = self._events(top).get(name)
655
+ if not events:
656
+ return None
657
+ decl_at = None
658
+ for i, e in enumerate(events):
659
+ if e.kind in ("param", "range"):
660
+ if _within(anchor, e.scope):
661
+ decl_at = i
662
+ elif e.kind == "decl" and e.node.end_byte <= anchor.start_byte and _within(anchor, e.scope):
663
+ decl_at = i
664
+ if decl_at is None:
665
+ return None
666
+ later = [e for e in events[decl_at + 1:] if e.node.end_byte <= anchor.start_byte and e.kind not in ("param", "range", "decl")]
667
+ return top, events[decl_at], later
668
+
669
+ # ---- resolution -----------------------------------------------------
670
+ def resolve(self, node: Node | None, at: Node | None, depth: int = 0) -> Res | None:
671
+ """Resolve an expression to SQL text. `at` is the statement it feeds, used to
672
+ pick the assignments that precede it. Returns None when nothing is known."""
673
+ if node is None or depth > MAX_DEPTH:
674
+ return None
675
+ t = node.type
676
+ if t in STRING_TYPES:
677
+ return Res(decode_string(node))
678
+ if t == "parenthesized_expression":
679
+ return self.resolve(node.named_children[0], at, depth) if node.named_children else None
680
+ if t == "binary_expression":
681
+ op = node.child_by_field_name("operator")
682
+ if op is None or _txt(op) != "+":
683
+ return None
684
+ left, right = node.child_by_field_name("left"), node.child_by_field_name("right")
685
+ l, r = self.resolve(left, at, depth), self.resolve(right, at, depth)
686
+ if l is None and r is None:
687
+ return None
688
+ return _join([l or _ph(left), r or _ph(right)])
689
+ if t == "identifier":
690
+ return self._name(node, at, depth)
691
+ if t == "selector_expression":
692
+ return self._selector(node, depth)
693
+ if t == "type_conversion_expression":
694
+ return self.resolve(node.child_by_field_name("operand"), at, depth)
695
+ if t == "call_expression":
696
+ return self._call(node, at, depth)
697
+ if t == "index_expression":
698
+ index = node.child_by_field_name("index")
699
+ if index is not None and index.type == "int_literal" and _txt(index).isdigit():
700
+ items = self._list(node.child_by_field_name("operand"), at, depth + 1)
701
+ if items is not None and int(_txt(index)) < len(items[0]):
702
+ return items[0][int(_txt(index))].named()
703
+ return None
704
+
705
+ def _selector(self, node: Node, depth: int) -> Res | None:
706
+ operand, field = node.child_by_field_name("operand"), node.child_by_field_name("field")
707
+ if operand is None or field is None or operand.type != "identifier":
708
+ return None
709
+ path = self.imports.get(_txt(operand))
710
+ if path is None:
711
+ return None
712
+ name = _txt(field)
713
+ target = self.ctx.import_dir(self.dir, path)
714
+ if target is not None:
715
+ hit = self.ctx.pkg_decls.get(target, {}).get(name)
716
+ if hit is not None:
717
+ return hit[0].decl_value(name, depth + 1)
718
+ return None
719
+ return self._global(name)
720
+
721
+ def _global(self, name: str) -> Res | None:
722
+ values = self.ctx.global_consts.get(name)
723
+ if values and len(values) == 1:
724
+ value = next(iter(values))
725
+ self.ctx.used_globals.add(value)
726
+ return Res(value, False, True)
727
+ return None
728
+
729
+ def decl_value(self, name: str, depth: int = 0) -> Res | None:
730
+ """Value of a package-level const or var of this file."""
731
+ if name in self._decl_cache:
732
+ res = self._decl_cache[name]
733
+ if res is not None and name not in self._decl_used:
734
+ self._decl_used.add(name)
735
+ value = self.decls[name][0]
736
+ if value is not None:
737
+ self._consume(value)
738
+ return res
739
+ entry = self.decls.get(name)
740
+ if entry is None:
741
+ return None
742
+ key = ("decl", self.rel, name)
743
+ if key in self.ctx.resolving:
744
+ return None
745
+ self.ctx.resolving.add(key)
746
+ try:
747
+ value, embed, index = entry
748
+ res = None
749
+ if embed:
750
+ text = self.ctx.read_file(os.path.normpath(os.path.join(self.dir, embed)))
751
+ res = Res(text, False, True, True) if text is not None else None
752
+ elif value is not None:
753
+ v = _strip_parens(value)
754
+ if index >= 0:
755
+ r = self._call(v, None, depth, index) if v is not None and v.type == "call_expression" else None
756
+ else:
757
+ r = self.resolve(value, None, depth)
758
+ if r is not None:
759
+ self._consume(value)
760
+ res = r.named()
761
+ finally:
762
+ self.ctx.resolving.discard(key)
763
+ if depth <= 2:
764
+ self._decl_cache[name] = res
765
+ if res is not None:
766
+ self._decl_used.add(name)
767
+ return res
768
+
769
+ def _name(self, node: Node, at: Node | None, depth: int) -> Res | None:
770
+ name = _txt(node)
771
+ anchor = at or node
772
+ if (anchor.id, name) in self._ovr:
773
+ return self._ovr[(anchor.id, name)]
774
+ local = self._local(name, anchor)
775
+ if local is not None:
776
+ top, decl, later = local
777
+ if decl.kind == "param":
778
+ env = self.ctx.env.get(decl.node.id)
779
+ return env.get(name) if env else None
780
+ if decl.kind == "range":
781
+ return None
782
+ key = ("name", decl.node.id, name, anchor.id)
783
+ if key in self.ctx.resolving:
784
+ return None
785
+ self.ctx.resolving.add(key)
786
+ try:
787
+ return self._fold(name, anchor, top, decl, later, depth)
788
+ finally:
789
+ self.ctx.resolving.discard(key)
790
+ return self._package_name(name, depth)
791
+
792
+ def _package_name(self, name: str, depth: int) -> Res | None:
793
+ if name in self.decls:
794
+ return self.decl_value(name, depth + 1)
795
+ hit = self.ctx.pkg_decls.get(self.dir, {}).get(name)
796
+ if hit is not None:
797
+ return hit[0].decl_value(name, depth + 1)
798
+ if name in ("nil", "true", "false", "err"):
799
+ return None
800
+ return self._global(name)
801
+
802
+ def _event_value(self, e: Event, depth: int) -> Res | None:
803
+ if e.value is None:
804
+ return None
805
+ if e.index >= 0:
806
+ v = _strip_parens(e.value)
807
+ return self._call(v, e.node, depth + 1, e.index) if v is not None and v.type == "call_expression" else None
808
+ return self.resolve(e.value, e.node, depth + 1)
809
+
810
+ def _arm(self, node: Node, anchor: Node, top: Node) -> tuple[int, int] | None:
811
+ """(branching statement, arm) when `node` sits directly in one arm of an if / else chain or of a
812
+ switch that `anchor` is not part of: two events in different arms of one statement never both run."""
813
+ n = node.parent
814
+ while n is not None and n.id != top.id:
815
+ if n.type in COND_TYPES and not _within(anchor, n):
816
+ parent = n.parent
817
+ if n.type == "block" and parent is not None and parent.type == "if_statement":
818
+ root = parent # `else if` chains hang off the first `if`
819
+ while root.parent is not None and root.parent.type == "if_statement":
820
+ alt = root.parent.child_by_field_name("alternative")
821
+ if alt is None or alt.id != root.id:
822
+ break
823
+ root = root.parent
824
+ return (root.id, n.id) if not _within(anchor, root) else None
825
+ if n.type in ("expression_case", "default_case", "type_case") and parent is not None:
826
+ return (parent.id, n.id) if not _within(anchor, parent) else None
827
+ return None # a loop body or a closure: not an alternative
828
+ n = n.parent
829
+ return None
830
+
831
+ def _fold(self, name: str, anchor: Node, top: Node, decl: Event, later: list[Event], depth: int) -> Res | None:
832
+ """Value of a local string at `anchor`: its declaration, then `=` and `+=` in order.
833
+
834
+ `+=` in different arms of one if / else or switch are alternatives, never one text: the value
835
+ gets one complete variant per arm (`alts`), and a run-time part in their place in `text`."""
836
+ arms: dict[int, tuple[int, int]] = {}
837
+ for e in later:
838
+ if e.kind == "append":
839
+ arm = self._arm(e.node, anchor, top)
840
+ if arm is not None:
841
+ arms[e.node.id] = arm
842
+ groups: dict[int, list[int]] = {} # branching statement -> its arms that append, in order
843
+ for e in later:
844
+ arm = arms.get(e.node.id)
845
+ if arm is not None and arm[1] not in groups.setdefault(arm[0], []):
846
+ groups[arm[0]].append(arm[1])
847
+ groups = {g: a for g, a in groups.items() if len(a) > 1}
848
+ if not groups:
849
+ return self._fold_once(name, anchor, top, decl, later, depth, arms, None)
850
+ merged = self._fold_once(name, anchor, top, decl, later, depth, arms, {g: -1 for g in groups})
851
+ if merged is None:
852
+ return None
853
+ total = 1
854
+ for a in groups.values():
855
+ total *= len(a)
856
+ if total > MAX_VARIANTS:
857
+ return merged
858
+ choices: list[dict[int, int]] = [{}]
859
+ for g, a in groups.items():
860
+ choices = [{**c, g: arm} for c in choices for arm in a]
861
+ alts: list[str] = []
862
+ for choice in choices:
863
+ r = self._fold_once(name, anchor, top, decl, later, depth, arms, choice)
864
+ for text in ((r.alts or [r.text]) if r is not None else ()):
865
+ if text not in alts:
866
+ alts.append(text)
867
+ merged.alts = alts if 1 < len(alts) <= MAX_VARIANTS else None
868
+ return merged
869
+
870
+ def _fold_once(self, name: str, anchor: Node, top: Node, decl: Event, later: list[Event], depth: int,
871
+ arms: dict[int, tuple[int, int]], choice: dict[int, int] | None) -> Res | None:
872
+ """One reading of the events. `choice` picks an arm per branching statement with alternatives
873
+ (-1: a run-time part stands for all of its arms); None means there are none."""
874
+ if decl.value is None and decl.node.type == "var_spec":
875
+ typ = decl.node.child_by_field_name("type")
876
+ state: Res | None = Res("") if typ is not None and _txt(typ) == "string" else None
877
+ else:
878
+ state = self._event_value(decl, depth)
879
+ used = [decl]
880
+ branched = False
881
+ held: set[int] = set()
882
+ for e in later:
883
+ if e.kind == "write":
884
+ continue
885
+ arm = arms.get(e.node.id) if choice else None
886
+ if arm is not None and arm[0] in choice:
887
+ picked = choice[arm[0]]
888
+ used.append(e)
889
+ if picked == -1:
890
+ if arm[0] not in held and state is not None:
891
+ held.add(arm[0])
892
+ gap = "" if not state.text or state.text[-1].isspace() else " "
893
+ state = _join([state, Res(gap), _ph_text("one of the branches at line %d" % (e.node.start_point[0] + 1))])
894
+ branched = True
895
+ continue
896
+ if picked != arm[1]:
897
+ continue
898
+ branched = True
899
+ cond = self._conditional(e.node, anchor, top)
900
+ self._ovr[(e.node.id, name)] = state
901
+ try:
902
+ if e.kind == "assign":
903
+ value = self._event_value(e, depth)
904
+ if cond:
905
+ branched = True
906
+ if state is None or (not state.text and value is not None):
907
+ state = value
908
+ else:
909
+ state, branched = value, False
910
+ else:
911
+ piece = self._event_value(e, depth) or (_ph(e.value) if e.value is not None else _ph_text("…"))
912
+ if cond and piece.text.strip().upper() in SEPARATORS:
913
+ branched = True
914
+ elif state is not None:
915
+ state = _join([state, piece])
916
+ branched = branched or cond
917
+ finally:
918
+ self._ovr.pop((e.node.id, name), None)
919
+ used.append(e)
920
+ if state is None:
921
+ return None
922
+ for e in used:
923
+ if e.value is not None:
924
+ self._consume(e.value)
925
+ return Res(state.text, state.dynamic or branched, True, state.from_file, state.alts)
926
+
927
+ def _builder(self, name: str, at: Node, depth: int) -> Res | None:
928
+ """Text written to a strings.Builder / bytes.Buffer before `at`."""
929
+ local = self._local(name, at)
930
+ if local is None:
931
+ return None
932
+ top, decl, later = local
933
+ if decl.kind != "decl":
934
+ return None
935
+ parts: list[Res] = []
936
+ dynamic = False
937
+ if decl.value is not None:
938
+ v = _strip_parens(decl.value)
939
+ if v is not None and v.type == "call_expression":
940
+ cname, _, dotted = callee_name(v.child_by_field_name("function"))
941
+ args = call_args(v)
942
+ if dotted in ("bytes.NewBufferString", "bytes.NewBuffer") and args:
943
+ parts.append(self.resolve(args[0], decl.node, depth + 1) or _ph(args[0]))
944
+ elif cname != "new":
945
+ return None
946
+ seen_write = False
947
+ for e in later:
948
+ if e.kind != "write":
949
+ if e.kind == "assign":
950
+ return None
951
+ continue
952
+ call = e.node
953
+ cname, recv, _ = callee_name(call.child_by_field_name("function"))
954
+ args = call_args(call)
955
+ cond = self._conditional(call, at, top)
956
+ piece: Res | None = None
957
+ if cname == "Reset":
958
+ if not cond:
959
+ parts, dynamic = [], False
960
+ continue
961
+ if cname in FPRINT:
962
+ rest = args[1:]
963
+ if cname == "Fprintf":
964
+ piece = self._sprintf(rest, call, depth + 1) if rest else None
965
+ else:
966
+ piece = _join([self.resolve(a, call, depth + 1) or _ph(a) for a in rest]) if rest else Res("")
967
+ if cname == "Fprintln":
968
+ piece = _join([piece, Res("\n")])
969
+ elif cname == "WriteString" or cname == "Write":
970
+ piece = self.resolve(args[0], call, depth + 1) if args else None
971
+ elif cname in ("WriteByte", "WriteRune") and args and args[0].type == "rune_literal":
972
+ piece = Res(ESC_RE.sub(_unescape, _txt(args[0])[1:-1]))
973
+ if piece is None:
974
+ piece = _ph(args[-1]) if args else _ph_text("…")
975
+ for a in args:
976
+ self._consume(a)
977
+ seen_write = True
978
+ dynamic = dynamic or cond
979
+ if cond and piece.text.strip().upper() in SEPARATORS:
980
+ continue # `if i > 0 { b.WriteString(", ") }`: joins repeated parts, not part of one statement
981
+ parts.append(piece)
982
+ if not seen_write and not parts:
983
+ return None
984
+ r = _join(parts)
985
+ return Res(r.text, r.dynamic or dynamic, True, r.from_file)
986
+
987
+ def _list(self, node: Node | None, at: Node | None, depth: int) -> tuple[list[Res], bool] | None:
988
+ """Elements of a []string expression, and whether the list depends on run-time branches."""
989
+ node = _strip_parens(node)
990
+ if node is None or depth > MAX_DEPTH:
991
+ return None
992
+ if node.type == "composite_literal":
993
+ typ, body = node.child_by_field_name("type"), node.child_by_field_name("body")
994
+ if typ is None or body is None or typ.type not in ("slice_type", "array_type", "implicit_length_array_type", "map_type"):
995
+ return None
996
+ items = []
997
+ for el in body.named_children:
998
+ if el.type == "keyed_element": # map[string]string{"name": `SELECT ...`}: the values
999
+ el = el.child_by_field_name("value") or el
1000
+ if el.type != "literal_element" or not el.named_children:
1001
+ return None
1002
+ items.append(self.resolve(el.named_children[0], at or node, depth + 1) or _ph(el.named_children[0]))
1003
+ return items, False
1004
+ if node.type == "call_expression":
1005
+ name, recv, dotted = callee_name(node.child_by_field_name("function"))
1006
+ args = call_args(node)
1007
+ if dotted == "slices.Concat" and args:
1008
+ out: list[Res] = []
1009
+ dyn = False
1010
+ for a in args:
1011
+ part = self._list(a, at, depth + 1)
1012
+ if part is None:
1013
+ return None
1014
+ out.extend(part[0])
1015
+ dyn = dyn or part[1]
1016
+ return out, dyn
1017
+ if name == "append" and recv is None and args:
1018
+ base = self._list(args[0], at, depth + 1)
1019
+ if base is None:
1020
+ return None
1021
+ items, dyn = list(base[0]), base[1]
1022
+ for a in args[1:]:
1023
+ if a.type == "variadic_argument":
1024
+ more = self._list(a.named_children[0], at, depth + 1) if a.named_children else None
1025
+ if more is None:
1026
+ items.append(_ph(a))
1027
+ dyn = True
1028
+ else:
1029
+ items.extend(more[0])
1030
+ dyn = dyn or more[1]
1031
+ else:
1032
+ items.append(self.resolve(a, at, depth + 1) or _ph(a))
1033
+ return items, dyn
1034
+ return None
1035
+ if node.type != "identifier":
1036
+ return None
1037
+ name = _txt(node)
1038
+ anchor = at or node
1039
+ if (anchor.id, "[]" + name) in self._ovr:
1040
+ return self._ovr[(anchor.id, "[]" + name)] # type: ignore[return-value]
1041
+ local = self._local(name, anchor)
1042
+ if local is None:
1043
+ entry = self.decls.get(name)
1044
+ owner = self
1045
+ if entry is None:
1046
+ hit = self.ctx.pkg_decls.get(self.dir, {}).get(name)
1047
+ if hit is None:
1048
+ return None
1049
+ owner, entry = hit[0], hit[0].decls.get(name)
1050
+ if entry is None or entry[0] is None or entry[2] >= 0:
1051
+ return None
1052
+ found = owner._list(entry[0], None, depth + 1)
1053
+ if found is not None:
1054
+ owner._consume(entry[0])
1055
+ return found
1056
+ top, decl, later = local
1057
+ if decl.kind != "decl":
1058
+ return None
1059
+ if decl.value is None:
1060
+ state: tuple[list[Res], bool] | None = ([], False) if decl.node.type == "var_spec" else None
1061
+ else:
1062
+ v = _strip_parens(decl.value)
1063
+ if v is not None and v.type == "nil":
1064
+ state = ([], False)
1065
+ elif v is not None and v.type == "call_expression" and callee_name(v.child_by_field_name("function"))[0] == "make":
1066
+ size = call_args(v)[1:2] # make([]string, n) is filled by index: not followed
1067
+ state = ([], False) if not size or _txt(size[0]) == "0" else None
1068
+ else:
1069
+ state = self._list(decl.value, decl.node, depth + 1)
1070
+ if decl.value is not None:
1071
+ self._consume(decl.value)
1072
+ for e in later:
1073
+ if e.kind != "assign" or e.value is None:
1074
+ continue
1075
+ cond = self._conditional(e.node, anchor, top)
1076
+ self._ovr[(e.node.id, "[]" + name)] = state # type: ignore[assignment]
1077
+ try:
1078
+ value = self._list(e.value, e.node, depth + 1)
1079
+ finally:
1080
+ self._ovr.pop((e.node.id, "[]" + name), None)
1081
+ self._consume(e.value)
1082
+ if value is None:
1083
+ state = (state[0] + [_ph(e.value)], True) if state is not None and cond else None
1084
+ elif cond:
1085
+ state = (value[0], True)
1086
+ else:
1087
+ state = value
1088
+ return state
1089
+
1090
+ def _sprintf(self, args: list[Node], at: Node | None, depth: int) -> Res | None:
1091
+ """fmt.Sprintf: inline arguments that resolve, leave «arg» for the rest."""
1092
+ if not args:
1093
+ return None
1094
+ base = self.resolve(args[0], at, depth)
1095
+ if base is None:
1096
+ return None
1097
+ rest = args[1:]
1098
+ out: list[Res] = []
1099
+ pos, nxt = 0, 0
1100
+ for m in VERB_RE.finditer(base.text):
1101
+ out.append(Res(base.text[pos:m.start()]))
1102
+ pos = m.end()
1103
+ verb = m.group(2)
1104
+ if verb == "%":
1105
+ out.append(Res("%"))
1106
+ continue
1107
+ if m.group(1):
1108
+ nxt = int(m.group(1)) - 1
1109
+ nxt += m.group(0).count("*")
1110
+ arg = rest[nxt] if 0 <= nxt < len(rest) else None
1111
+ nxt += 1
1112
+ if arg is None:
1113
+ out.append(_ph_text("arg"))
1114
+ continue
1115
+ r = self.resolve(arg, at, depth + 1) if verb in "svq" else None
1116
+ if r is None and verb == "d" and arg.type == "int_literal":
1117
+ r = Res(_txt(arg))
1118
+ if r is None:
1119
+ out.append(_ph(arg))
1120
+ elif verb == "q":
1121
+ out.append(_join([Res('"'), r, Res('"')]).named())
1122
+ else:
1123
+ out.append(r.named() if arg.type not in STRING_TYPES else r)
1124
+ out.append(Res(base.text[pos:]))
1125
+ joined = _join(out)
1126
+ return Res(joined.text, joined.dynamic or base.dynamic, joined.via_name or base.via_name, base.from_file, joined.alts)
1127
+
1128
+ def _call(self, node: Node, at: Node | None, depth: int, ret_index: int = 0) -> Res | None:
1129
+ fn = _strip_parens(node.child_by_field_name("function"))
1130
+ if fn is not None and fn.type == "func_literal": # func() string { ... }()
1131
+ key = ("fn", fn.id)
1132
+ if key in self.ctx.resolving:
1133
+ return None
1134
+ self.ctx.resolving.add(key)
1135
+ try:
1136
+ return self._fn_return(fn, depth + 1, ret_index)
1137
+ finally:
1138
+ self.ctx.resolving.discard(key)
1139
+ name, recv, dotted = callee_name(fn)
1140
+ args = call_args(node)
1141
+ if not name:
1142
+ return None
1143
+ if ret_index == 0:
1144
+ if dotted == "fmt.Sprintf":
1145
+ return self._sprintf(args, at, depth)
1146
+ if dotted == "fmt.Sprint" and args:
1147
+ return _join([self.resolve(a, at, depth + 1) or _ph(a) for a in args])
1148
+ if dotted in UNWRAP_CALLS and args:
1149
+ return self.resolve(args[0], at, depth + 1)
1150
+ if dotted == "strings.Join" and len(args) == 2:
1151
+ items = self._list(args[0], at, depth + 1)
1152
+ sep = self.resolve(args[1], at, depth + 1)
1153
+ if items is None or sep is None:
1154
+ return None
1155
+ parts: list[Res] = []
1156
+ for i, it in enumerate(items[0]):
1157
+ if i:
1158
+ parts.append(sep)
1159
+ parts.append(it)
1160
+ r = _join(parts) if parts else Res("")
1161
+ return Res(r.text, r.dynamic or items[1], r.via_name, r.from_file)
1162
+ if dotted in ("strings.ReplaceAll", "strings.Replace") and len(args) >= 3:
1163
+ base = self.resolve(args[0], at, depth + 1)
1164
+ if base is None:
1165
+ return None
1166
+ old, new = self.resolve(args[1], at, depth + 1), self.resolve(args[2], at, depth + 1)
1167
+ if old is not None and not old.dynamic and old.text and old.text in base.text:
1168
+ sub = new if new is not None else _ph(args[2])
1169
+ return Res(base.text.replace(old.text, sub.text), base.dynamic or sub.dynamic, True,
1170
+ base.from_file and not sub.dynamic)
1171
+ return base.dyn()
1172
+ if name == "String" and not args and recv is not None and recv.type == "identifier":
1173
+ return self._builder(_txt(recv), at or node, depth + 1)
1174
+ if name == "Replace" and len(args) == 1 and recv is not None:
1175
+ base = self.resolve(args[0], at, depth + 1)
1176
+ return base.dyn() if base is not None else None
1177
+ if name == "ReadFile" and len(args) == 1 and recv is not None and recv.type == "identifier":
1178
+ owner = _txt(recv)
1179
+ if owner in ("os", "ioutil") or owner in self.embed_fs or self._pkg_embed_fs(owner):
1180
+ path = self.resolve(args[0], at, depth + 1)
1181
+ if path is not None and not path.dynamic and path.text:
1182
+ text = self.ctx.read_file(os.path.normpath(os.path.join(self.dir, path.text)))
1183
+ if text is not None:
1184
+ return Res(text, False, True, True)
1185
+ return None
1186
+ through = self._through_fn(node, name, recv, args, at, depth, ret_index)
1187
+ if through is not None:
1188
+ # a helper that computes its result (quote(x), escape(x)) is a run-time part, not a template
1189
+ if not through.dynamic or sinkish_sql(through.text):
1190
+ return through
1191
+ # a helper that appends filters, each under its own condition (buildFilterSQL(f): `if f.From != "" { AND
1192
+ # created_at >= ... }`): an optional part. Its text is kept, so a rule can tell what it may add
1193
+ if ret_index == 0 and re.match(r"\s*(?:AND|OR|WHERE)\b", through.text, re.I) and self._all_writes_conditional(name, recv):
1194
+ from .orm_jdbi import MARKER_CHARS
1195
+ text = trim(through.text.replace("«", "‹").replace("»", "›"), MARKER_CHARS)
1196
+ return Res("«if(" + trim(_txt(node), 40).replace(")", "]").replace("(", "[") + "): " + text + "»", dynamic=True)
1197
+ return None
1198
+ # rebind(sql), dedent(sql), ...: a call whose only argument is SQL passes it on
1199
+ if ret_index == 0 and len(args) == 1 and self._find_fn(name, recv) is None:
1200
+ inner = self.resolve(args[0], at, depth + 1)
1201
+ if inner is not None and looks_like_sql(inner.text, any_case=True):
1202
+ return inner
1203
+ return None
1204
+
1205
+ def _all_writes_conditional(self, name: str, recv: Node | None) -> bool:
1206
+ """True when the helper `name` builds its result only from writes and appends that each sit in an if: called with
1207
+ nothing set, it returns nothing."""
1208
+ hit = self._find_fn(name, recv)
1209
+ if hit is None:
1210
+ return False
1211
+ _, func = hit
1212
+ body = func.child_by_field_name("body")
1213
+ if body is None:
1214
+ return False
1215
+ writes = 0
1216
+ for n in _walk(body, stop=("func_literal",)):
1217
+ grows = (n.type == "call_expression" and callee_name(n.child_by_field_name("function"))[0] in ("WriteString", "Fprintf", "Write")) \
1218
+ or (n.type == "assignment_statement" and _txt(n).split("=", 1)[0].rstrip().endswith("+")) \
1219
+ or (n.type == "call_expression" and callee_name(n.child_by_field_name("function"))[0] == "append")
1220
+ if not grows:
1221
+ continue
1222
+ writes += 1
1223
+ up = n.parent
1224
+ while up is not None and up.id != body.id and up.type != "if_statement":
1225
+ up = up.parent
1226
+ if up is None or up.id == body.id:
1227
+ return False
1228
+ return writes > 0
1229
+
1230
+ def _pkg_embed_fs(self, name: str) -> bool:
1231
+ return any(name in f.embed_fs for f in self.ctx.files.values() if f.dir == self.dir) if name not in self.imports else False
1232
+
1233
+ def _find_fn(self, name: str, recv: Node | None) -> tuple["GoFile", Node] | None:
1234
+ """The one function or method this call can mean, looked up by name in the package it names."""
1235
+ target = self.dir
1236
+ want_method = recv is not None
1237
+ if recv is not None and recv.type == "identifier" and _txt(recv) in self.imports:
1238
+ found = self.ctx.import_dir(self.dir, self.imports[_txt(recv)])
1239
+ if found is None:
1240
+ return None
1241
+ target, want_method = found, False
1242
+ cands = [(f, n) for f, n in self.ctx.pkg_funcs.get(target, {}).get(name, ())
1243
+ if (n.type == "method_declaration") == want_method]
1244
+ return cands[0] if len(cands) == 1 else None
1245
+
1246
+ def _through_fn(self, call: Node, name: str, recv: Node | None, args: list[Node], at: Node | None, depth: int,
1247
+ ret_index: int) -> Res | None:
1248
+ """A helper in this repo that returns the SQL: resolve its return value with the arguments bound."""
1249
+ hit = self._find_fn(name, recv)
1250
+ if recv is None and at is not None:
1251
+ local = self._local(name, at) # child := func(table string) string { return `SELECT ...` + table }
1252
+ if local is not None:
1253
+ v = _strip_parens(local[1].value) if local[1].kind == "decl" and local[1].value is not None else None
1254
+ hit = (self, v) if v is not None and v.type == "func_literal" else None
1255
+ if hit is None or depth + 1 > MAX_DEPTH:
1256
+ return None
1257
+ owner, func = hit
1258
+ key = ("fn", func.id)
1259
+ if key in self.ctx.resolving:
1260
+ return None
1261
+ names = param_names(func)
1262
+ env: dict[str, Res | None] = {}
1263
+ for i, pname in enumerate(names):
1264
+ if pname and i < len(args) and args[i].type != "variadic_argument":
1265
+ env[pname] = self.resolve(args[i], at, depth + 1) or _ph(args[i])
1266
+ self.ctx.resolving.add(key)
1267
+ saved = self.ctx.env.get(func.id)
1268
+ self.ctx.env[func.id] = env
1269
+ try:
1270
+ return owner._fn_return(func, depth + 1, ret_index)
1271
+ finally:
1272
+ self.ctx.resolving.discard(key)
1273
+ if saved is None:
1274
+ self.ctx.env.pop(func.id, None)
1275
+ else:
1276
+ self.ctx.env[func.id] = saved
1277
+
1278
+ def _fn_return(self, func: Node, depth: int, ret_index: int) -> Res | None:
1279
+ body = func.child_by_field_name("body")
1280
+ if body is None:
1281
+ return None
1282
+ found: list[Res] = []
1283
+ missing = False
1284
+ nodes = []
1285
+ for n in _walk(body, stop=("func_literal",)):
1286
+ if n.type != "return_statement" or not n.named_children:
1287
+ continue
1288
+ exprs = n.named_children[0].named_children if n.named_children[0].type == "expression_list" else n.named_children
1289
+ if ret_index >= len(exprs):
1290
+ continue
1291
+ r = self.resolve(exprs[ret_index], n, depth)
1292
+ if r is None:
1293
+ missing = True
1294
+ elif r.text:
1295
+ found.append(r)
1296
+ nodes.append(exprs[ret_index])
1297
+ if not found:
1298
+ return None
1299
+ sqlish = [r for r in found if sinkish_sql(r.text)]
1300
+ pick = (sqlish or found)[-1]
1301
+ for n in nodes:
1302
+ self._consume(n)
1303
+ several = len({r.text for r in found}) > 1 or missing
1304
+ return Res(pick.text, pick.dynamic or several, True, pick.from_file, pick.alts)
1305
+
1306
+ def _consume(self, node: Node) -> None:
1307
+ if node.type in STRING_TYPES:
1308
+ self.consumed.add(node.id)
1309
+ return
1310
+ if node.child_count == 0:
1311
+ return
1312
+ for s in _walk(node):
1313
+ if s.type in STRING_TYPES:
1314
+ self.consumed.add(s.id)
1315
+
1316
+ # ---- call sites -----------------------------------------------------
1317
+ def symbol(self, node: Node) -> str:
1318
+ """`(*Store).FetchPage` for a pointer receiver, `Store.FetchPage` for a value receiver, `FetchPage` for a function."""
1319
+ func = node if node.type in FUNC_DECL else self._enclosing(node, FUNC_DECL)
1320
+ if func is None:
1321
+ return ""
1322
+ nm = func.child_by_field_name("name")
1323
+ name = _txt(nm) if nm is not None else ""
1324
+ recv = func.child_by_field_name("receiver")
1325
+ if recv is None:
1326
+ return name
1327
+ typ = None
1328
+ for p in recv.named_children:
1329
+ typ = p.child_by_field_name("type") or typ
1330
+ if typ is None:
1331
+ return name
1332
+ pointer = typ.type == "pointer_type"
1333
+ if pointer and typ.named_children:
1334
+ typ = typ.named_children[0]
1335
+ if typ.type == "generic_type":
1336
+ typ = typ.child_by_field_name("type") or typ
1337
+ base = _txt(typ)
1338
+ return f"(*{base}).{name}" if pointer else f"{base}.{name}"
1339
+
1340
+ def in_loop(self, node: Node) -> bool:
1341
+ n = node.parent
1342
+ while n is not None and n.type not in FUNC_DECL:
1343
+ if n.type == "for_statement":
1344
+ return True
1345
+ n = n.parent
1346
+ return False
1347
+
1348
+ def _param_root(self, arg: Node | None, at: Node, depth: int = 0) -> tuple[Node, str] | None:
1349
+ """When `arg` is (a light rewrite of) a parameter of the enclosing named function,
1350
+ that function is a wrapper around the driver. Returns (function, parameter name)."""
1351
+ arg = _strip_parens(arg)
1352
+ if arg is None or depth > 4:
1353
+ return None
1354
+ t = arg.type
1355
+ if t == "identifier":
1356
+ name = _txt(arg)
1357
+ local = self._local(name, at)
1358
+ if local is None:
1359
+ return None
1360
+ _, decl, later = local
1361
+ if decl.kind == "param":
1362
+ if decl.node.type not in FUNC_DECL or any(e.kind == "assign" and not self._self_ref(e, name) for e in later):
1363
+ return None
1364
+ if param_type(decl.node, name) not in ("string", "[]byte"):
1365
+ return None
1366
+ return decl.node, name
1367
+ if decl.kind == "decl" and decl.value is not None and decl.index < 0 and not any(e.kind == "assign" for e in later):
1368
+ return self._param_root(decl.value, decl.node, depth + 1)
1369
+ return None
1370
+ if t == "binary_expression":
1371
+ # `sql + " FORMAT JSON"`: the parameter leads. `"... FROM " + table` only counts when named like SQL.
1372
+ hit = self._param_root(arg.child_by_field_name("left"), at, depth + 1)
1373
+ if hit is None:
1374
+ hit = self._param_root(arg.child_by_field_name("right"), at, depth + 1)
1375
+ if hit is not None and not SQLISH_NAME.search(hit[1]):
1376
+ return None
1377
+ return hit
1378
+ if t == "type_conversion_expression":
1379
+ return self._param_root(arg.child_by_field_name("operand"), at, depth + 1)
1380
+ if t == "call_expression":
1381
+ _, _, dotted = callee_name(arg.child_by_field_name("function"))
1382
+ args = call_args(arg)
1383
+ if dotted in UNWRAP_CALLS and args:
1384
+ return self._param_root(args[0], at, depth + 1)
1385
+ return None
1386
+
1387
+ @staticmethod
1388
+ def _self_ref(e: Event, name: str) -> bool:
1389
+ return e.value is not None and bool(re.search(rf"(?<![\w.]){re.escape(name)}(?!\w)", _txt(e.value)))
1390
+
1391
+ def _ident_type(self, node: Node) -> str:
1392
+ """Declared type of a parameter or method receiver used as a call's receiver; "" when unknown."""
1393
+ if node.type != "identifier":
1394
+ return ""
1395
+ name = _txt(node)
1396
+ local = self._local(name, node)
1397
+ if local is None or local[1].kind != "param":
1398
+ return ""
1399
+ func = local[1].node
1400
+ typ = param_type(func, name)
1401
+ if typ:
1402
+ return bare_type(typ)
1403
+ recv = func.child_by_field_name("receiver")
1404
+ if recv is not None and any(_txt(c) == name for p in recv.named_children for c in p.children_by_field_name("name")):
1405
+ return recv_type(func)
1406
+ return ""
1407
+
1408
+ def _closure_root(self, arg: Node, at: Node) -> tuple[int, str, int] | None:
1409
+ """`run := func(sql string) { db.Exec(ctx, sql) }`: (enclosing function id, "run", index of sql)."""
1410
+ if arg.type != "identifier":
1411
+ return None
1412
+ name = _txt(arg)
1413
+ local = self._local(name, at)
1414
+ if local is None or local[1].kind != "param" or local[1].node.type != "func_literal":
1415
+ return None
1416
+ lit = local[1].node
1417
+ if any(e.kind == "assign" for e in local[2]) or param_type(lit, name) != "string":
1418
+ return None
1419
+ holder = lit.parent
1420
+ if holder is not None and holder.type == "expression_list":
1421
+ holder = holder.parent
1422
+ if holder is None or holder.type not in ("short_var_declaration", "var_spec", "assignment_statement"):
1423
+ return None
1424
+ left = holder.child_by_field_name("left") or holder.child_by_field_name("name")
1425
+ target = left.named_children[0] if left is not None and left.type == "expression_list" and left.named_children else left
1426
+ if target is None or target.type != "identifier":
1427
+ return None
1428
+ return local[0].id, _txt(target), param_names(lit).index(name)
1429
+
1430
+ def _ctx_first(self, args: list[Node]) -> bool:
1431
+ """Is the first argument a context.Context? By its text, else by how the variable was declared."""
1432
+ if not args:
1433
+ return False
1434
+ arg = args[0]
1435
+ if leading_ctx(arg):
1436
+ return True
1437
+ if arg.type != "identifier":
1438
+ return False
1439
+ local = self._local(_txt(arg), arg)
1440
+ if local is None:
1441
+ return False
1442
+ decl = local[1]
1443
+ if decl.kind == "param":
1444
+ return "Context" in param_type(decl.node, _txt(arg))
1445
+ v = _strip_parens(decl.value) if decl.kind == "decl" else None
1446
+ if v is None or v.type != "call_expression":
1447
+ return False
1448
+ _, _, dotted = callee_name(v.child_by_field_name("function"))
1449
+ return dotted.startswith("context.") or leading_ctx(v)
1450
+
1451
+ def _candidates(self, args: list[Node], name: str, recv: Node | None) -> tuple[list[tuple[int, bool]], str, bool] | None:
1452
+ """Positional indexes that may hold SQL for this callee, each with whether it is certain (a wrapper of the
1453
+ package the call names, or a rule for a name that is not "weak"), the engine the callee implies, and
1454
+ whether that engine is certain: False when it is only what same-named methods of other packages talk
1455
+ to (`Exec` of the MySQL plugin says nothing sure about `Exec` called in the SQLite one).
1456
+ Rule indexes are counted after a leading context argument; wrapper indexes are absolute."""
1457
+ ctx = self.ctx
1458
+ indexes: list[tuple[int, bool]] = []
1459
+ engine = ""
1460
+ engine_sure = True
1461
+ wrappers = ctx.wrappers.get(name)
1462
+ if wrappers:
1463
+ target = self.dir
1464
+ qualified = recv is not None and recv.type == "identifier" and _txt(recv) in self.imports
1465
+ if qualified:
1466
+ target = ctx.import_dir(self.dir, self.imports[_txt(recv)]) or ""
1467
+ rtype = self._ident_type(recv) if recv is not None and not qualified else ""
1468
+ fits = [w for w in wrappers if (w.nparams == len(args) or (w.variadic and len(args) >= w.nparams - 1))
1469
+ and (self.test or not w.test) and not (rtype and w.recv and rtype != w.recv)]
1470
+ near = [w for w in fits if w.dir == target and w.method == (recv is not None and not qualified)]
1471
+ sure = bool(near)
1472
+ if not near and recv is not None and not qualified and name[:1].isupper():
1473
+ near = [w for w in fits if w.method] # an exported method of another package: receiver type unknown
1474
+ for w in near:
1475
+ if not any(i == w.index for i, _ in indexes):
1476
+ indexes.append((w.index, sure))
1477
+ engines = {w.engine for w in near if w.engine}
1478
+ engine = next(iter(engines)) if len(engines) == 1 else ""
1479
+ engine_sure = sure or not engine
1480
+ ruled = name in ctx.sink_args and name not in ctx.passthrough
1481
+ if ruled:
1482
+ rule_engine = ctx.sink_engine.get(name, "")
1483
+ if rule_engine == "cypher" and "cypher" not in self.engines and "cypher" not in ctx.pkg_engines.get(self.dir, ()):
1484
+ ruled = False
1485
+ else:
1486
+ skip = 1 if self._ctx_first(args) else 0
1487
+ strong = name not in ctx.weak and len(ctx.sink_args[name]) == 1
1488
+ for i in ctx.sink_args[name]:
1489
+ at = next((k for k, (j, _) in enumerate(indexes) if j == i + skip), None)
1490
+ if at is None:
1491
+ indexes.append((i + skip, strong))
1492
+ elif strong:
1493
+ indexes[at] = (i + skip, True)
1494
+ if not engine or (rule_engine and not engine_sure):
1495
+ engine, engine_sure = rule_engine, True
1496
+ if not indexes:
1497
+ return None
1498
+ return indexes, engine, engine_sure
1499
+
1500
+ def wrappers(self, names: set[str] | None) -> list[Wrapper]:
1501
+ """Functions in this file that pass one of their own parameters to a sink."""
1502
+ out = []
1503
+ ctx = self.ctx
1504
+ for call in self.calls:
1505
+ name, recv, dotted = callee_name(call.child_by_field_name("function"))
1506
+ if not name or (names is not None and name not in names):
1507
+ continue
1508
+ passthrough = name in ctx.passthrough
1509
+ args = call_args(call)
1510
+ if passthrough:
1511
+ indexes, engine = [(i, False) for i in ctx.sink_args[name]], ""
1512
+ else:
1513
+ cand = self._candidates(args, name, recv)
1514
+ if cand is None:
1515
+ continue
1516
+ indexes, engine, engine_sure = cand
1517
+ if not engine_sure:
1518
+ # a wrapper does not inherit the engine of a same-named method somewhere else: with three
1519
+ # database plugins that each define `Exec`, the first one found would name all three
1520
+ engine = ""
1521
+ for i, sure in indexes:
1522
+ if i >= len(args):
1523
+ continue
1524
+ hit = self._param_root(args[i], call)
1525
+ if hit is None:
1526
+ continue
1527
+ func, pname = hit
1528
+ if not sure and not SQLISH_NAME.search(pname):
1529
+ continue
1530
+ if not SQLISH_NAME.search(pname) and not (self.has_db or self.dir in ctx.pkg_db):
1531
+ continue
1532
+ fname = func.child_by_field_name("name")
1533
+ params = param_names(func)
1534
+ if fname is None or pname not in params:
1535
+ continue
1536
+ plist = func.child_by_field_name("parameters")
1537
+ variadic = plist is not None and any(c.type == "variadic_parameter_declaration" for c in plist.named_children)
1538
+ out.append(Wrapper(_txt(fname), params.index(pname), engine or self.file_engine(), self.dir,
1539
+ func.type == "method_declaration", pname, len(params), variadic, recv_type(func),
1540
+ self.test))
1541
+ break
1542
+ return out
1543
+
1544
+ def _range_items(self, arg: Node, call: Node) -> list[Res] | None:
1545
+ """`for _, stmt := range statements { db.Exec(ctx, stmt) }`: the statements."""
1546
+ def indexed(node: Node | None) -> Node | None:
1547
+ node = _strip_parens(node)
1548
+ if node is None or node.type != "index_expression":
1549
+ return None
1550
+ index = node.child_by_field_name("index")
1551
+ return node.child_by_field_name("operand") if index is not None and index.type != "int_literal" else None
1552
+
1553
+ source, at = indexed(arg), call # queries[name]: any of the map's values
1554
+ if source is None and arg.type == "identifier":
1555
+ local = self._local(_txt(arg), call)
1556
+ if local is None or local[1].value is None:
1557
+ return None
1558
+ decl = local[1]
1559
+ if decl.kind == "range":
1560
+ source, at = decl.value, decl.node
1561
+ elif decl.kind == "decl" and not any(e.kind == "assign" for e in local[2]):
1562
+ source, at = indexed(decl.value), decl.node # query, ok := queries[name]
1563
+ if source is None:
1564
+ return None
1565
+ found = self._list(source, at, 1)
1566
+ if found is None:
1567
+ return None
1568
+ self._consume(source)
1569
+ return found[0]
1570
+
1571
+ def _field_values(self, arg: Node) -> list[Res] | None:
1572
+ """`stmt.insert` where the package builds structs with `insert: "INSERT ..."`: every such value.
1573
+ The struct type is not checked, only the field name within the package."""
1574
+ if arg.type != "selector_expression":
1575
+ return None
1576
+ operand, field = arg.child_by_field_name("operand"), arg.child_by_field_name("field")
1577
+ if operand is None or field is None or (operand.type == "identifier" and _txt(operand) in self.imports):
1578
+ return None
1579
+ name = _txt(field)
1580
+ want = self._expr_type(operand, arg)
1581
+ out: list[Res] = []
1582
+ seen: set[str] = set()
1583
+ pool = self.ctx.dir_files.get(self.dir, ())
1584
+ # Without the variable's type, the field name alone decides. That is only safe when the package
1585
+ # gives that field name to one struct type: `Query:` in three unrelated literals is three things.
1586
+ known = {typ for f in pool if self.test or not f.test for _, typ in f.keyed_values().get(name, ())}
1587
+ if not want and len(known) != 1:
1588
+ return None
1589
+ for f in pool:
1590
+ if f.test and not self.test:
1591
+ continue # a literal that exists only in test code never explains an application call
1592
+ for value, typ in f.keyed_values().get(name, ()):
1593
+ if want and typ and want != typ:
1594
+ continue
1595
+ r = f.resolve(value, value, 1)
1596
+ if r is not None and r.text not in seen and looks_like_sql(r.text, any_case=True):
1597
+ seen.add(r.text)
1598
+ f._consume(value)
1599
+ out.append(r.named())
1600
+ return out if 0 < len(out) <= MAX_FIELD_VALUES else None
1601
+
1602
+ def _value_type(self, value: Node | None, at: Node | None, depth: int = 0) -> str:
1603
+ value = _strip_parens(value)
1604
+ if value is None or depth > 3:
1605
+ return ""
1606
+ if value.type == "unary_expression" and value.named_children:
1607
+ value = value.named_children[0]
1608
+ if value.type == "composite_literal":
1609
+ typ = value.child_by_field_name("type")
1610
+ return bare_type(_txt(typ)) if typ is not None and typ.type in ("type_identifier", "qualified_type", "generic_type") else ""
1611
+ if value.type == "call_expression":
1612
+ name, recv, _ = callee_name(value.child_by_field_name("function"))
1613
+ hit = self._find_fn(name, recv) if name else None
1614
+ if hit is not None:
1615
+ result = hit[1].child_by_field_name("result")
1616
+ if result is not None and result.type != "parameter_list":
1617
+ return bare_type(_txt(result))
1618
+ if value.type == "identifier" and at is not None:
1619
+ return self._expr_type(value, at, depth + 1)
1620
+ return ""
1621
+
1622
+ def _expr_type(self, node: Node, at: Node, depth: int = 0) -> str:
1623
+ """Struct type of an identifier, as far as its declaration says; "" when unknown."""
1624
+ if node.type != "identifier":
1625
+ return ""
1626
+ name = _txt(node)
1627
+ local = self._local(name, at)
1628
+ if local is not None:
1629
+ decl = local[1]
1630
+ if decl.kind == "param":
1631
+ return self._ident_type(node)
1632
+ if decl.kind == "decl" and decl.index < 0:
1633
+ return self._value_type(decl.value, decl.node, depth)
1634
+ return ""
1635
+ owner = self if name in self.decls else (self.ctx.pkg_decls.get(self.dir, {}).get(name) or (None,))[0]
1636
+ if owner is None:
1637
+ return ""
1638
+ value, _, index = owner.decls[name]
1639
+ return owner._value_type(value, None, depth) if index < 0 else ""
1640
+
1641
+ @staticmethod
1642
+ def _literal_type(keyed: Node) -> str:
1643
+ """Type name of the struct literal a `name: value` element belongs to; "" for an elided type."""
1644
+ lit = keyed.parent
1645
+ comp = lit.parent if lit is not None else None
1646
+ if comp is None:
1647
+ return ""
1648
+ if comp.type == "composite_literal":
1649
+ typ = comp.child_by_field_name("type")
1650
+ return bare_type(_txt(typ)) if typ is not None and typ.type in ("type_identifier", "qualified_type", "generic_type") else ""
1651
+ n = comp # an element of []T{{...}} or map[K]T{k: {...}}
1652
+ while n is not None and n.type != "composite_literal":
1653
+ n = n.parent
1654
+ typ = n.child_by_field_name("type") if n is not None else None
1655
+ if typ is None:
1656
+ return ""
1657
+ inner = typ.child_by_field_name("element") or typ.child_by_field_name("value")
1658
+ return bare_type(_txt(inner)) if inner is not None and inner.type in ("type_identifier", "qualified_type", "pointer_type") else ""
1659
+
1660
+ def keyed_values(self) -> dict[str, list[tuple[Node, str]]]:
1661
+ """Field name -> (value expression, struct type) of `name: value` elements in struct literals of this file."""
1662
+ if self._keyed is None:
1663
+ self._keyed = defaultdict(list)
1664
+ if b"`" in self.src or b'"' in self.src:
1665
+ for n in KEYED.captures(self.root).get("k", []):
1666
+ key, value = n.child_by_field_name("key"), n.child_by_field_name("value")
1667
+ if key is None or value is None or not key.named_children or not value.named_children:
1668
+ continue
1669
+ k = key.named_children[0]
1670
+ if k.type == "identifier":
1671
+ self._keyed[_txt(k)].append((value.named_children[0], self._literal_type(n)))
1672
+ return self._keyed
1673
+
1674
+ def call_engine(self, call: Node, rule_engine: str, file_engine: str, file_basis: str, file_unsure: str,
1675
+ sql: str | None) -> tuple[str, dict | None]:
1676
+ """(engine hint, evidence) of one database call: the sink rule's engine, else the handle's (engine_go), else
1677
+ the file's or its package's. A statement written with `?` placeholders is never sent to PostgreSQL on the
1678
+ file's or the package's word alone: no database/sql driver for it takes `?` (unless the package uses a
1679
+ library that rewrites them)."""
1680
+ from .engine_go import qmark_binds
1681
+ if rule_engine:
1682
+ return rule_engine, None
1683
+ try:
1684
+ eng, how = self.ctx.handles.site(self, call)
1685
+ except Exception: # a handle that can not be followed says nothing
1686
+ eng, how = "", ""
1687
+ if eng:
1688
+ return eng, {"basis": "handle", "detail": how}
1689
+ qmark = qmark_binds(sql) and not self.ctx.handles.rebinds(self)
1690
+ evidence: dict = {"binds": "qmark"} if qmark else {}
1691
+ if file_engine == "postgres" and qmark:
1692
+ return "", {**evidence, "unsure": f"the statement takes `?` placeholders, which no PostgreSQL driver for database/sql "
1693
+ f"accepts; the {'file' if file_basis == 'file' else 'package'} also opens postgres"}
1694
+ if file_engine:
1695
+ if file_basis in ("package", "package_name"):
1696
+ evidence["basis"] = "package"
1697
+ return file_engine, evidence or None
1698
+ if qmark:
1699
+ # a package that opens PostgreSQL and one other engine: `?` placeholders leave the other one
1700
+ left = (self.engines or self.ctx.handles.package_engines(self.dir)) - {"postgres"}
1701
+ if len(left) == 1 and "postgres" in (self.engines or self.ctx.handles.package_engines(self.dir)):
1702
+ eng = next(iter(left))
1703
+ return eng, {**evidence, "basis": "package",
1704
+ "detail": f"{file_unsure}; the statement's `?` placeholders rule out postgres"}
1705
+ if file_unsure:
1706
+ evidence["unsure"] = file_unsure
1707
+ evidence["engines"] = sorted(self.engines or self.ctx.handles.package_engines(self.dir))
1708
+ return "", evidence or None
1709
+
1710
+ def _db_package(self, name: str) -> bool:
1711
+ """Does this package talk to a database: a driver import, or its own wrapper around one."""
1712
+ return self.has_db or self.dir in self.ctx.pkg_db or name in self.ctx.wrappers
1713
+
1714
+ def _plausible_unresolved(self, name: str, recv: Node | None, arg: Node, sure: bool) -> bool:
1715
+ """Keep an unresolved call only when it plausibly is a database call."""
1716
+ if arg.type in STRONG_SKIP_ARG or arg.type in STRING_TYPES:
1717
+ return False
1718
+ text = _txt(arg)
1719
+ if is_ctx(arg):
1720
+ return False
1721
+ db = self._db_package(name) if sure else (self.has_db or self.dir in self.ctx.pkg_db)
1722
+ named = bool(SQLISH_NAME.search(text[:80]))
1723
+ if not sure:
1724
+ return named and db and recv is not None
1725
+ return db and (named or arg.type in ("identifier", "call_expression", "selector_expression", "binary_expression"))
1726
+
1727
+ def sites(self) -> list[RawSite]:
1728
+ out: list[RawSite] = []
1729
+ ctx = self.ctx
1730
+ test = self.test
1731
+ file_engine, file_basis, file_unsure = self.engine_source()
1732
+
1733
+ def emit(call: Node, arg: Node, sink_text: str, engine: str, res: Res | None, resolution: str) -> None:
1734
+ hint, evidence = self.call_engine(call, engine, file_engine, file_basis, file_unsure, res.text if res is not None else None)
1735
+ out.append(RawSite(
1736
+ file=self.rel, line=call.start_point[0] + 1, end_line=call.end_point[0] + 1, language="go",
1737
+ kind="call", sink=trim(sink_text, 80), symbol=self.symbol(call),
1738
+ sql=res.text if res is not None else None, resolution=resolution,
1739
+ expr=trim(_txt(arg)), in_loop=self.in_loop(call), engine_hint=hint,
1740
+ is_test=test, known_sink=True, engine_evidence=evidence,
1741
+ ))
1742
+
1743
+ for call in self.calls:
1744
+ fn = call.child_by_field_name("function")
1745
+ name, recv, dotted = callee_name(fn)
1746
+ if not name:
1747
+ continue
1748
+ args = call_args(call)
1749
+ closure = None
1750
+ if recv is None and self.closures:
1751
+ top = self._top_func(call)
1752
+ closure = self.closures.get((top.id, name)) if top is not None else None
1753
+ if closure is not None:
1754
+ cand = ([(closure, True)], "", True)
1755
+ elif name not in ctx.sink_args and name not in ctx.wrappers:
1756
+ continue
1757
+ else:
1758
+ cand = self._candidates(args, name, recv)
1759
+ if cand is None:
1760
+ continue
1761
+ indexes, engine, engine_sure = cand
1762
+ if not engine_sure and file_engine:
1763
+ engine = "" # what this file's own imports and package say beats a same-named method elsewhere
1764
+ sink_text = _txt(fn).split("[")[0] if fn is not None else name
1765
+ fallback: tuple[Node, str] | None = None
1766
+ done = False
1767
+ for i, sure in indexes:
1768
+ strict = not sure
1769
+ if i >= len(args):
1770
+ continue
1771
+ arg = args[i]
1772
+ if arg.type in STRONG_SKIP_ARG or is_ctx(arg) or (i == 0 and self._ctx_first(args)):
1773
+ continue
1774
+ items = self._range_items(arg, call)
1775
+ if items is not None:
1776
+ hits = [r for r in items if sinkish_sql(r.text, engine, strict)]
1777
+ for r in hits:
1778
+ emit(call, arg, sink_text, engine, r, "template" if r.dynamic else "constant")
1779
+ if hits:
1780
+ done = True
1781
+ break
1782
+ continue
1783
+ res = self.resolve(arg, call, 0)
1784
+ root = self._param_root(arg, call)
1785
+ if res is not None and sinkish_sql(res.text, engine, strict):
1786
+ variants = [a for a in (res.alts or ()) if sinkish_sql(a, engine, strict)]
1787
+ if len(variants) > 1: # one complete statement per mutually exclusive branch
1788
+ for text in variants:
1789
+ emit(call, arg, sink_text, engine, Res(text, True, res.via_name, res.from_file), "template")
1790
+ else:
1791
+ emit(call, arg, sink_text, engine, res, res.resolution)
1792
+ self._consume(arg)
1793
+ done = True
1794
+ break
1795
+ if res is not None and not (root is not None and res.dynamic):
1796
+ continue # resolved, and it is not SQL
1797
+ fields = self._field_values(arg) if res is None else None
1798
+ if fields:
1799
+ hits = [r for r in fields if sinkish_sql(r.text, engine, True)]
1800
+ for r in hits:
1801
+ emit(call, arg, sink_text, engine, r, "template" if r.dynamic else "constant")
1802
+ if hits:
1803
+ done = True
1804
+ break
1805
+ if fallback is None:
1806
+ local_fn = self._closure_root(arg, call) if root is None and sure else None
1807
+ if local_fn is not None:
1808
+ self.closures[(local_fn[0], local_fn[1])] = local_fn[2]
1809
+ fallback = (arg, "parameter")
1810
+ elif root is not None and (SQLISH_NAME.search(root[1]) or (sure and self._db_package(name))):
1811
+ fallback = (arg, "parameter")
1812
+ elif res is None and self._plausible_unresolved(name, recv, arg, sure):
1813
+ fallback = (arg, "unresolved")
1814
+ if not done and fallback is not None:
1815
+ emit(call, fallback[0], sink_text, engine, None, fallback[1])
1816
+ return out
1817
+
1818
+ def loose_strings(self) -> list[RawSite]:
1819
+ """SQL strings not attached to a known sink: wrapper calls, fragments, constants."""
1820
+ out: list[RawSite] = []
1821
+ test = is_test_path(self.rel)
1822
+ file_engine = self.file_engine()
1823
+ found: list[tuple[Node, Node, Res]] = []
1824
+ for s in self.strings:
1825
+ if s.id in self.consumed or s.end_byte - s.start_byte < 14:
1826
+ continue
1827
+ parent = s.parent
1828
+ if parent is None or parent.type in ("import_spec", "field_declaration"):
1829
+ continue
1830
+ top = s
1831
+ while top.parent is not None and top.parent.type in ("binary_expression", "parenthesized_expression"):
1832
+ top = top.parent
1833
+ if top.id != s.id:
1834
+ first = next((n for n in _walk(top) if n.type in STRING_TYPES), None)
1835
+ if first is None or first.id != s.id:
1836
+ continue
1837
+ res = self.resolve(top, top, 0)
1838
+ if res is None or not looks_like_sql(res.text):
1839
+ continue
1840
+ found.append((s, top, res))
1841
+ for s, top, res in found:
1842
+ if s.id in self.consumed:
1843
+ continue # a larger SQL string was built from this one
1844
+ # fmt.Sprintf(`SELECT ... %s`, table) and friends: report the built string
1845
+ while top.parent is not None and top.parent.type == "argument_list" and top.parent.parent is not None:
1846
+ outer = top.parent.parent
1847
+ _, _, dotted = callee_name(outer.child_by_field_name("function"))
1848
+ if dotted not in PASS_CALLS or call_args(outer)[0].id != top.id:
1849
+ break
1850
+ r2 = self.resolve(outer, outer, 0)
1851
+ if r2 is None or not looks_like_sql(r2.text):
1852
+ break
1853
+ top, res = outer, r2
1854
+ while top.parent is not None and top.parent.type in ("binary_expression", "parenthesized_expression"):
1855
+ top = top.parent
1856
+ res = self.resolve(top, top, 0) or res
1857
+ call = None
1858
+ if top.parent is not None and top.parent.type == "argument_list" and top.parent.parent is not None \
1859
+ and top.parent.parent.type == "call_expression":
1860
+ call = top.parent.parent
1861
+ sink_text = ""
1862
+ if call is not None:
1863
+ fn = call.child_by_field_name("function")
1864
+ sink_text = _txt(fn).split("[")[0] if fn is not None else ""
1865
+ if NOT_A_SINK.search(sink_text):
1866
+ continue # a test on the text, a log line or an error message, not a query
1867
+ self._consume(top)
1868
+ variants = [a for a in (res.alts or ()) if looks_like_sql(a)]
1869
+ for text in (variants if len(variants) > 1 else [res.text]): # one statement per exclusive branch
1870
+ out.append(RawSite(
1871
+ file=self.rel, line=top.start_point[0] + 1, end_line=top.end_point[0] + 1, language="go",
1872
+ kind="call" if call is not None else "sql_string", sink=trim(sink_text, 80), symbol=self.symbol(top),
1873
+ sql=text, resolution="template" if len(variants) > 1 else res.resolution, expr=trim(_txt(top)),
1874
+ in_loop=self.in_loop(top), engine_hint=file_engine, is_test=test, known_sink=False,
1875
+ ))
1876
+ return out
1877
+
1878
+
1879
+ def extract(root: Path, files: list[str], rules: LangRules) -> list[RawSite]:
1880
+ """Index every file, find wrapper functions, then find call sites and loose SQL strings."""
1881
+ ctx = Ctx(root, rules)
1882
+ for rel in files:
1883
+ text = read_text(root / rel)
1884
+ if text is None:
1885
+ continue
1886
+ try:
1887
+ ctx.files[rel] = gf = GoFile(rel, text.encode("utf-8"), ctx)
1888
+ ctx.dir_files[gf.dir].append(gf)
1889
+ except Exception: # one odd file must not stop the inventory
1890
+ continue
1891
+
1892
+ def guarded(fn, default):
1893
+ try:
1894
+ return fn()
1895
+ except Exception: # one odd file must not stop the inventory
1896
+ return default
1897
+
1898
+ # package-level string constants, for names used from a package we cannot map to a directory
1899
+ for f in ctx.files.values():
1900
+ for name in list(f.decls):
1901
+ r = guarded(lambda: f.decl_value(name), None)
1902
+ if r is not None and not r.dynamic and not r.from_file and r.text and len(r.text) < MAX_CONST_CHARS:
1903
+ ctx.global_consts[name].add(r.text)
1904
+ f.reset()
1905
+ ctx.used_globals.clear()
1906
+
1907
+ # wrappers, to a fixed point: a function that passes its parameter to a wrapper is a wrapper too
1908
+ names: set[str] | None = None
1909
+ for _ in range(6):
1910
+ fresh: set[str] = set()
1911
+ for f in ctx.files.values():
1912
+ for w in guarded(lambda: f.wrappers(names), []):
1913
+ known = ctx.wrappers[w.name]
1914
+ if not any(k.dir == w.dir and k.index == w.index and k.method == w.method for k in known):
1915
+ known.append(w)
1916
+ fresh.add(w.name)
1917
+ if not fresh:
1918
+ break
1919
+ names = fresh
1920
+ for f in ctx.files.values():
1921
+ f.reset()
1922
+ ctx.used_globals.clear()
1923
+
1924
+ out: list[RawSite] = []
1925
+ for f in ctx.files.values():
1926
+ out.extend(guarded(f.sites, []))
1927
+ for f in ctx.files.values():
1928
+ out.extend(guarded(f.loose_strings, []))
1929
+ from . import orm_go_run # ORMs and query builders: statements with no SQL string (orm_go.py)
1930
+ out = guarded(lambda: orm_go_run.extract(ctx, out), out)
1931
+ from . import named_go # queries loaded from .sql files by name (named_go.py)
1932
+ out = guarded(lambda: named_go.extract(ctx, out), out)
1933
+ # a constant used from another package is reported at its use sites, not again at its definition
1934
+ return [s for s in out if not (s.kind == "sql_string" and s.sql in ctx.used_globals)]
1935
+
1936
+
1937
+ def replaced_sites() -> list:
1938
+ """(raw site, the builder's site that replaced it) of the last `extract`: the raw site stays in the list
1939
+ so that discover can give its id to the replacement (`previous_ids`) without renumbering its neighbours."""
1940
+ from . import orm_go_run
1941
+ return list(orm_go_run.LAST.get("replaced") or ())
1942
+
1943
+
1944
+ def summary_extras() -> dict:
1945
+ """Counts the ORM pass reports beside its sites (`summary.orm_calls`, `summary.orm`)."""
1946
+ from . import orm_go_run
1947
+ return orm_go_run.summary_extras()