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.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
codecop/discover/java.py
ADDED
|
@@ -0,0 +1,1528 @@
|
|
|
1
|
+
"""Java call-site extractor.
|
|
2
|
+
|
|
3
|
+
Finds calls and annotations whose argument is a query and resolves that argument
|
|
4
|
+
statically: string literals and text blocks, `+` concatenation, `String.format` /
|
|
5
|
+
`.formatted`, `String.join`, `.concat`, `.replace("{{X}}", y)`, local variables
|
|
6
|
+
(including `sql += ...` and `StringBuilder.append` chains, also through same-class
|
|
7
|
+
helper methods that append to a builder they are given), fields of the same class,
|
|
8
|
+
`Other.NAME` constants in other files, and methods that return a query.
|
|
9
|
+
|
|
10
|
+
Queries that are not SQL are still inventoried, with an engine hint that says so:
|
|
11
|
+
"jpql" for JPQL/HQL sinks and "cypher" for Cypher text.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
from collections import defaultdict
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
import tree_sitter_java
|
|
21
|
+
from tree_sitter import Language, Node, Parser
|
|
22
|
+
|
|
23
|
+
from .base import PLACEHOLDER, LangRules, RawSite, Sink, is_test_path, looks_like_sql, read_text, trim
|
|
24
|
+
from .base import walk_tree
|
|
25
|
+
|
|
26
|
+
LANG = Language(tree_sitter_java.language())
|
|
27
|
+
CONST_NAME = re.compile(r"^_?[A-Z][A-Z0-9_]*$")
|
|
28
|
+
MAX_DEPTH = 10
|
|
29
|
+
CLASS_TYPES = ("class_declaration", "interface_declaration", "enum_declaration", "record_declaration",
|
|
30
|
+
"annotation_type_declaration")
|
|
31
|
+
METHOD_TYPES = ("method_declaration", "constructor_declaration", "compact_constructor_declaration")
|
|
32
|
+
LOOP_TYPES = ("for_statement", "enhanced_for_statement", "while_statement", "do_statement")
|
|
33
|
+
COND_TYPES = LOOP_TYPES + ("if_statement", "switch_expression", "switch_statement", "catch_clause",
|
|
34
|
+
"ternary_expression", "lambda_expression")
|
|
35
|
+
LOOP_LAMBDA_CALLS = {"forEach", "forEachOrdered", "map", "flatMap", "mapToObj", "peek", "filter", "anyMatch",
|
|
36
|
+
"allMatch", "noneMatch", "computeIfAbsent", "replaceAll", "removeIf"}
|
|
37
|
+
COMMENTS = ("line_comment", "block_comment")
|
|
38
|
+
BUILDER_TYPE = re.compile(r"\b(StringBuilder|StringBuffer)\b")
|
|
39
|
+
ST_TYPE = re.compile(r"^(?:org\.stringtemplate\.v4\.)?ST$")
|
|
40
|
+
ST_FACTORY = re.compile(r"(?:^|[a-z])ST(?:[A-Z]|$)|^newST")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _outer(text: str) -> str:
|
|
44
|
+
return re.sub(r"<.*", "", text or "", flags=re.S).split(".")[-1].strip()
|
|
45
|
+
BUILDER_READS = {"toString", "length", "isEmpty", "indexOf", "lastIndexOf", "charAt", "substring", "capacity",
|
|
46
|
+
"chars", "equals", "hashCode", "compareTo", "subSequence", "isBlank"}
|
|
47
|
+
PASSTHROUGH = {"trim", "strip", "stripIndent", "stripLeading", "stripTrailing", "intern", "toLowerCase",
|
|
48
|
+
"toUpperCase", "translateEscapes"}
|
|
49
|
+
LOGGERS = re.compile(r"^(log|logger|LOG|LOGGER|System\.out|System\.err)$")
|
|
50
|
+
# Sink names that are also everyday method names: an unresolved argument needs more evidence.
|
|
51
|
+
GENERIC_SINKS = {"query", "update", "execute", "fetch", "fetchOne", "fetchMany", "addBatch"}
|
|
52
|
+
RECEIVER = re.compile(r"(jdbc|template|conn|stmt|statement|client|db|dao|repo|session|entityManager|\bem\b|dsl|ctx|"
|
|
53
|
+
r"clickhouse|\bch\b|graph|neo4j|database|datasource|cursor)", re.I)
|
|
54
|
+
SQLISH_NAME = re.compile(r"(sql|query|stmt|statement|ddl|cypher|jpql|hql)", re.I)
|
|
55
|
+
NOT_SQL_ARG = re.compile(r"(criteria|\bcq\b|creator|callback|\bpsc\b)", re.I)
|
|
56
|
+
JPQL_START = re.compile(r"^\s*(select|from|update|delete|insert)\b", re.I)
|
|
57
|
+
CYPHER_START = re.compile(
|
|
58
|
+
r"^\s*(?://[^\n]*\n\s*)*(?:(?:OPTIONAL\s+)?MATCH\s*[(«]|MERGE\s*\(|UNWIND\s+\S+\s+AS\b|CREATE\s*\(\w*:|"
|
|
59
|
+
r"CALL\s+(?:db|apoc|dbms|gds)\.|CALL\s*\{|WITH\s+\$\w+\s+AS\b|WITH\s+[^\n]*\n?\s*(?:OPTIONAL\s+)?(?:MATCH|UNWIND|MERGE)\b)")
|
|
60
|
+
CYPHER_ANYCASE = re.compile(CYPHER_START.pattern, re.I)
|
|
61
|
+
TEST_FILE = re.compile(r"(^|/)src/(test|it|integration-?test)/|(Test|Tests|IT|TestCase)\.java$")
|
|
62
|
+
FORMAT_SPEC = re.compile(r"%(?:(\d+)\$)?[-#+ 0,(]*\d*(?:\.\d+)?([a-zA-Z%])")
|
|
63
|
+
SIMPLE_ESCAPES = {"n": "\n", "t": "\t", "r": "\r", "b": "\b", "f": "\f", "s": " ", "0": "\0", "\\": "\\",
|
|
64
|
+
'"': '"', "'": "'", "\n": ""}
|
|
65
|
+
ESCAPE_RE = re.compile(r"\\(u+[0-9a-fA-F]{4}|[0-3]?[0-7]{1,2}|[\s\S])")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Res:
|
|
69
|
+
"""A resolved string: text with «expr» placeholders, and how it was reached.
|
|
70
|
+
|
|
71
|
+
`src` lists the string literals the text was built from, as (file, node id): they are
|
|
72
|
+
marked as used only when a site is reported, so nothing vanishes because of a lookup
|
|
73
|
+
that led nowhere. `alts` holds other whole queries the same expression can be
|
|
74
|
+
(switch arms, several returns, implementations of an abstract method)."""
|
|
75
|
+
|
|
76
|
+
__slots__ = ("text", "dynamic", "via_name", "src", "alts", "arms")
|
|
77
|
+
|
|
78
|
+
def __init__(self, text: str, dynamic: bool = False, via_name: bool = False, src: tuple = (), alts: tuple = ()):
|
|
79
|
+
self.text = text
|
|
80
|
+
self.dynamic = dynamic
|
|
81
|
+
self.via_name = via_name
|
|
82
|
+
self.src = src
|
|
83
|
+
self.alts = alts
|
|
84
|
+
self.arms: tuple = () # the whole statement of each if / else arm, when `text` names them as «or: ...»
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def resolution(self) -> str:
|
|
88
|
+
if self.dynamic:
|
|
89
|
+
return "template"
|
|
90
|
+
return "constant" if self.via_name else "literal"
|
|
91
|
+
|
|
92
|
+
def but(self, dynamic: bool | None = None, via: bool | None = None, fn=None, src: tuple = ()) -> "Res":
|
|
93
|
+
out = Res(fn(self.text) if fn else self.text, self.dynamic if dynamic is None else dynamic,
|
|
94
|
+
self.via_name if via is None else via, self.src + src,
|
|
95
|
+
tuple(a.but(dynamic, via, fn, src) for a in self.alts))
|
|
96
|
+
out.arms = tuple(a.but(dynamic, via, fn, src) for a in self.arms)
|
|
97
|
+
return out
|
|
98
|
+
|
|
99
|
+
def flat(self) -> list["Res"]:
|
|
100
|
+
own = [Res(a.text, a.dynamic, a.via_name, self.src + a.src) for a in self.arms] if self.arms else \
|
|
101
|
+
[Res(self.text, self.dynamic, self.via_name, self.src)]
|
|
102
|
+
return own + [x for a in self.alts for x in a.flat()]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
MAX_ALTS = 16
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _choice(options: list[Res]) -> Res | None:
|
|
109
|
+
"""One of several values, picked at run time. Whole queries stay as alternatives;
|
|
110
|
+
anything else keeps only the first."""
|
|
111
|
+
flat: list[Res] = []
|
|
112
|
+
for o in options:
|
|
113
|
+
for x in o.flat():
|
|
114
|
+
same = next((y for y in flat if y.text == x.text), None)
|
|
115
|
+
if same is None:
|
|
116
|
+
flat.append(x)
|
|
117
|
+
else:
|
|
118
|
+
same.src += x.src # the same text from two places: both are used
|
|
119
|
+
if not flat:
|
|
120
|
+
return None
|
|
121
|
+
queries = [x for x in flat if _is_query(x.text)]
|
|
122
|
+
first = queries[0] if queries else flat[0]
|
|
123
|
+
rest = tuple(Res(x.text, True, x.via_name, x.src) for x in queries[1:MAX_ALTS])
|
|
124
|
+
return Res(first.text, len(flat) > 1 or first.dynamic, first.via_name, first.src, rest)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _txt(node: Node) -> str:
|
|
128
|
+
return node.text.decode("utf-8", "replace")
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _ph_text(text: str) -> Res:
|
|
132
|
+
return Res("«" + trim(text, 60).replace("»", ">").replace("«", "<") + "»", dynamic=True)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _ph(node: Node) -> Res:
|
|
136
|
+
return _ph_text(_txt(node))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _join(parts: list[Res], sep: str = "") -> Res:
|
|
140
|
+
src: tuple = ()
|
|
141
|
+
for p in parts:
|
|
142
|
+
src += p.src
|
|
143
|
+
out = Res(sep.join(p.text for p in parts), any(p.dynamic for p in parts), any(p.via_name for p in parts), src)
|
|
144
|
+
with_alts = [i for i, p in enumerate(parts) if p.alts]
|
|
145
|
+
if len(with_alts) == 1: # "A or B" + suffix is "A + suffix" or "B + suffix"
|
|
146
|
+
i = with_alts[0]
|
|
147
|
+
out.alts = tuple(_join(parts[:i] + [a] + parts[i + 1:], sep) for a in parts[i].alts)
|
|
148
|
+
with_arms = [i for i, p in enumerate(parts) if p.arms]
|
|
149
|
+
if len(with_arms) == 1: # the same for the arms of an if / else
|
|
150
|
+
i = with_arms[0]
|
|
151
|
+
out.arms = tuple(_join(parts[:i] + [Res(a.text, a.dynamic, a.via_name, a.src)] + parts[i + 1:], sep) for a in parts[i].arms)
|
|
152
|
+
return out
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _walk(node: Node, stop: tuple[str, ...] = ()):
|
|
156
|
+
"""Depth-first over descendants, not descending into node types in `stop`."""
|
|
157
|
+
return walk_tree(node, stop)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _args(node: Node | None) -> list[Node]:
|
|
161
|
+
return [c for c in node.named_children if c.type not in COMMENTS] if node is not None else []
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _unescape(s: str) -> str:
|
|
165
|
+
def sub(m: re.Match) -> str:
|
|
166
|
+
e = m.group(1)
|
|
167
|
+
if e[0] == "u":
|
|
168
|
+
return chr(int(e.lstrip("u"), 16))
|
|
169
|
+
if e[0] in "01234567" and e != "0":
|
|
170
|
+
return chr(int(e, 8))
|
|
171
|
+
return SIMPLE_ESCAPES.get(e, e)
|
|
172
|
+
return ESCAPE_RE.sub(sub, s) if "\\" in s else s
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _text_block(raw: str) -> str:
|
|
176
|
+
"""Value of a Java text block: drop the opening line, strip the common indentation
|
|
177
|
+
(the closing delimiter's line counts) and trailing blanks, then apply escapes."""
|
|
178
|
+
body = raw[3:-3]
|
|
179
|
+
nl = body.find("\n")
|
|
180
|
+
if nl < 0:
|
|
181
|
+
return _unescape(body)
|
|
182
|
+
lines = body[nl + 1:].split("\n")
|
|
183
|
+
significant = [ln for ln in lines[:-1] if ln.strip()] + [lines[-1]]
|
|
184
|
+
indent = min(len(ln) - len(ln.lstrip(" \t")) for ln in significant)
|
|
185
|
+
out = [ln[indent:].rstrip(" \t") if ln.strip() else "" for ln in lines]
|
|
186
|
+
return _unescape("\n".join(out))
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _string_value(node: Node) -> str:
|
|
190
|
+
raw = _txt(node)
|
|
191
|
+
if raw.startswith('"""'):
|
|
192
|
+
return _text_block(raw)
|
|
193
|
+
return _unescape(raw[1:-1])
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
MYSQL_FULLTEXT = re.compile(r"\bMATCH\s*\((?:[^()]|\([^()]*\))*\)\s*AGAINST\s*\(", re.I)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def is_cypher(text: str, any_case: bool = True) -> bool:
|
|
200
|
+
if MYSQL_FULLTEXT.search(text):
|
|
201
|
+
return False # MySQL full-text search, `MATCH (col, ...) AGAINST (...)`: SQL, not a Cypher pattern
|
|
202
|
+
return bool((CYPHER_ANYCASE if any_case else CYPHER_START).match(text))
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class Scope:
|
|
206
|
+
"""Assignments, builder calls and declarations inside one method body."""
|
|
207
|
+
|
|
208
|
+
__slots__ = ("events", "declared", "types", "params")
|
|
209
|
+
|
|
210
|
+
def __init__(self) -> None:
|
|
211
|
+
self.events: dict[str, list[tuple[str, Node, object]]] = defaultdict(list)
|
|
212
|
+
self.declared: set[str] = set()
|
|
213
|
+
self.types: dict[str, str] = {}
|
|
214
|
+
self.params: list[str] = []
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class Wrapper:
|
|
218
|
+
"""A method that hands one of its parameters to a sink, as is or with text added around it."""
|
|
219
|
+
|
|
220
|
+
__slots__ = ("jf", "method", "call", "arg", "index", "argc", "engine", "derived", "inner")
|
|
221
|
+
|
|
222
|
+
def __init__(self, jf: "JavaFile", method: Node, call: Node, arg: Node, index: int, argc: int, engine: str,
|
|
223
|
+
derived: bool, inner: "Wrapper | None"):
|
|
224
|
+
self.jf, self.method, self.call, self.arg = jf, method, call, arg
|
|
225
|
+
self.index, self.argc, self.engine, self.derived, self.inner = index, argc, engine, derived, inner
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class Repo:
|
|
229
|
+
"""Every parsed file, for constants and methods that live in another class."""
|
|
230
|
+
|
|
231
|
+
def __init__(self) -> None:
|
|
232
|
+
self.files: list[JavaFile] = []
|
|
233
|
+
self.classes: dict[str, list[tuple[JavaFile, Node]]] = defaultdict(list)
|
|
234
|
+
self.subclasses: dict[str, list[tuple[JavaFile, Node]]] = defaultdict(list)
|
|
235
|
+
self.statics: dict[str, list[tuple[JavaFile, Node]]] = defaultdict(list) # NAME -> value nodes
|
|
236
|
+
self.named_queries: dict[str, tuple[Res, bool]] = {} # name -> (query, native)
|
|
237
|
+
self.wrappers: dict[str, list[Wrapper]] = defaultdict(list)
|
|
238
|
+
self._unique: dict[str, Res | None] = {}
|
|
239
|
+
|
|
240
|
+
def add(self, jf: "JavaFile") -> None:
|
|
241
|
+
self.files.append(jf)
|
|
242
|
+
for name, nodes in jf.classes.items():
|
|
243
|
+
for n in nodes:
|
|
244
|
+
self.classes[name].append((jf, n))
|
|
245
|
+
for sup in jf.supers(n):
|
|
246
|
+
self.subclasses[sup].append((jf, n))
|
|
247
|
+
for name, value in jf.static_consts:
|
|
248
|
+
self.statics[name].append((jf, value))
|
|
249
|
+
|
|
250
|
+
def field(self, cls: str, name: str, depth: int = 0) -> Res | None:
|
|
251
|
+
"""`Cls.NAME`, following superclasses and interfaces. Needs one distinct value."""
|
|
252
|
+
found: dict[str, Res] = {}
|
|
253
|
+
for jf, node in self.classes.get(cls, ()):
|
|
254
|
+
value = jf.class_fields.get(node.id, {}).get(name)
|
|
255
|
+
r = jf.field_res(value) if value is not None else None
|
|
256
|
+
if r is None and value is None and depth < 4:
|
|
257
|
+
for sup in jf.supers(node):
|
|
258
|
+
r = self.field(sup, name, depth + 1)
|
|
259
|
+
if r is not None:
|
|
260
|
+
break
|
|
261
|
+
if r is not None:
|
|
262
|
+
found.setdefault(r.text, r)
|
|
263
|
+
return next(iter(found.values())) if len(found) == 1 else None
|
|
264
|
+
|
|
265
|
+
def unique(self, name: str) -> Res | None:
|
|
266
|
+
"""A static constant by bare name, when the whole repo has one distinct value for it."""
|
|
267
|
+
if name in self._unique:
|
|
268
|
+
return self._unique[name]
|
|
269
|
+
self._unique[name] = None
|
|
270
|
+
found: dict[str, Res] = {}
|
|
271
|
+
for jf, value in self.statics.get(name, ()):
|
|
272
|
+
r = jf.field_res(value)
|
|
273
|
+
if r is None:
|
|
274
|
+
found.clear()
|
|
275
|
+
break
|
|
276
|
+
found.setdefault(r.text, r)
|
|
277
|
+
out = next(iter(found.values())) if len(found) == 1 else None
|
|
278
|
+
self._unique[name] = out
|
|
279
|
+
return out
|
|
280
|
+
|
|
281
|
+
def methods(self, cls: str, name: str, argc: int, depth: int = 0) -> list[tuple["JavaFile", Node]]:
|
|
282
|
+
"""`cls.name(...)`: the method itself, an inherited one, or, when it is abstract,
|
|
283
|
+
every implementation in a subclass."""
|
|
284
|
+
owners = self.classes.get(cls, ())
|
|
285
|
+
if len(owners) != 1 or depth > 4:
|
|
286
|
+
return []
|
|
287
|
+
jf, node = owners[0]
|
|
288
|
+
hit = jf.own_method(node, name, argc)
|
|
289
|
+
if hit is not None:
|
|
290
|
+
if hit.child_by_field_name("body") is not None:
|
|
291
|
+
return [(jf, hit)]
|
|
292
|
+
return self.implementations(cls, name, argc)
|
|
293
|
+
for sup in jf.supers(node):
|
|
294
|
+
r = self.methods(sup, name, argc, depth + 1)
|
|
295
|
+
if r:
|
|
296
|
+
return r
|
|
297
|
+
return []
|
|
298
|
+
|
|
299
|
+
def implementations(self, cls: str, name: str, argc: int, depth: int = 0) -> list[tuple["JavaFile", Node]]:
|
|
300
|
+
out = []
|
|
301
|
+
for jf, node in self.subclasses.get(cls, ()):
|
|
302
|
+
hit = jf.own_method(node, name, argc)
|
|
303
|
+
if hit is not None and hit.child_by_field_name("body") is not None:
|
|
304
|
+
out.append((jf, hit))
|
|
305
|
+
elif depth < 3:
|
|
306
|
+
nm = node.child_by_field_name("name")
|
|
307
|
+
if nm is not None:
|
|
308
|
+
out.extend(self.implementations(_txt(nm), name, argc, depth + 1))
|
|
309
|
+
return out[:MAX_ALTS]
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class JavaFile:
|
|
313
|
+
def __init__(self, rel: str, src: bytes, repo: Repo):
|
|
314
|
+
self.rel = rel
|
|
315
|
+
self.repo = repo
|
|
316
|
+
self.tree = Parser(LANG).parse(src)
|
|
317
|
+
self.root = self.tree.root_node
|
|
318
|
+
self.imports: list[str] = []
|
|
319
|
+
self.static_imports: dict[str, str] = {} # member -> class
|
|
320
|
+
self.static_wildcards: list[str] = [] # classes imported with `import static X.*`
|
|
321
|
+
self.classes: dict[str, list[Node]] = defaultdict(list)
|
|
322
|
+
self.class_fields: dict[int, dict[str, Node]] = {}
|
|
323
|
+
self.field_types: dict[str, str] = {}
|
|
324
|
+
self.fields_flat: dict[str, Node] = {}
|
|
325
|
+
self.static_consts: list[tuple[str, Node]] = []
|
|
326
|
+
self.methods: dict[str, list[Node]] = defaultdict(list)
|
|
327
|
+
self.annotations: list[Node] = []
|
|
328
|
+
self.calls: list[Node] = []
|
|
329
|
+
self.strings: list[Node] = []
|
|
330
|
+
self.consumed: set[int] = set() # string nodes already attached to a reported site
|
|
331
|
+
self._resolving: set = set()
|
|
332
|
+
self._scope_cache: dict[int, Scope] = {}
|
|
333
|
+
self._field_cache: dict[int, Res | None] = {}
|
|
334
|
+
self._event_cache: dict[tuple, Res | None] = {}
|
|
335
|
+
self._helper_cache: dict[tuple, Res | None] = {}
|
|
336
|
+
self._override: dict[str, Res] = {} # parameter -> value bound by the caller being followed
|
|
337
|
+
self._local: dict[str, Res] = {} # variable -> value so far, while resolving `x = x + ...`
|
|
338
|
+
self._index()
|
|
339
|
+
|
|
340
|
+
# ---- indexing -------------------------------------------------------
|
|
341
|
+
def _index(self) -> None:
|
|
342
|
+
for n in _walk(self.root):
|
|
343
|
+
t = n.type
|
|
344
|
+
if t == "method_invocation":
|
|
345
|
+
self.calls.append(n)
|
|
346
|
+
elif t == "string_literal":
|
|
347
|
+
self.strings.append(n)
|
|
348
|
+
elif t == "annotation":
|
|
349
|
+
self.annotations.append(n)
|
|
350
|
+
elif t == "import_declaration":
|
|
351
|
+
m = re.match(r"import\s+(static\s+)?([\w.]+)(\.\*)?\s*;", _txt(n))
|
|
352
|
+
if not m:
|
|
353
|
+
continue
|
|
354
|
+
self.imports.append(m.group(2))
|
|
355
|
+
parts = m.group(2).split(".")
|
|
356
|
+
if m.group(1) and m.group(3):
|
|
357
|
+
self.static_wildcards.append(parts[-1])
|
|
358
|
+
elif m.group(1) and len(parts) >= 2:
|
|
359
|
+
self.static_imports[parts[-1]] = parts[-2]
|
|
360
|
+
elif t in CLASS_TYPES:
|
|
361
|
+
nm = n.child_by_field_name("name")
|
|
362
|
+
if nm is not None:
|
|
363
|
+
self.classes[_txt(nm)].append(n)
|
|
364
|
+
self._index_fields(n)
|
|
365
|
+
elif t in ("method_declaration", "constructor_declaration"):
|
|
366
|
+
nm = n.child_by_field_name("name")
|
|
367
|
+
if nm is not None:
|
|
368
|
+
self.methods[_txt(nm)].append(n)
|
|
369
|
+
|
|
370
|
+
def _index_fields(self, cls: Node) -> None:
|
|
371
|
+
fields: dict[str, Node] = {}
|
|
372
|
+
self.class_fields[cls.id] = fields
|
|
373
|
+
body = cls.child_by_field_name("body")
|
|
374
|
+
if body is None:
|
|
375
|
+
return
|
|
376
|
+
members = list(body.named_children)
|
|
377
|
+
for m in list(members):
|
|
378
|
+
if m.type == "enum_body_declarations":
|
|
379
|
+
members.extend(m.named_children)
|
|
380
|
+
for m in members:
|
|
381
|
+
if m.type not in ("field_declaration", "constant_declaration"):
|
|
382
|
+
continue
|
|
383
|
+
mods = next((_txt(c) for c in m.children if c.type == "modifiers"), "")
|
|
384
|
+
static = m.type == "constant_declaration" or cls.type == "interface_declaration" or \
|
|
385
|
+
bool(re.search(r"\bstatic\b", mods))
|
|
386
|
+
ftype = m.child_by_field_name("type")
|
|
387
|
+
for d in m.named_children:
|
|
388
|
+
if d.type != "variable_declarator":
|
|
389
|
+
continue
|
|
390
|
+
nm, value = d.child_by_field_name("name"), d.child_by_field_name("value")
|
|
391
|
+
if nm is None:
|
|
392
|
+
continue
|
|
393
|
+
name = _txt(nm)
|
|
394
|
+
if ftype is not None:
|
|
395
|
+
self.field_types.setdefault(name, _txt(ftype))
|
|
396
|
+
if value is None:
|
|
397
|
+
continue
|
|
398
|
+
fields[name] = value
|
|
399
|
+
self.fields_flat.setdefault(name, value)
|
|
400
|
+
if static:
|
|
401
|
+
self.static_consts.append((name, value))
|
|
402
|
+
|
|
403
|
+
def supers(self, cls: Node) -> list[str]:
|
|
404
|
+
out = []
|
|
405
|
+
for c in cls.children:
|
|
406
|
+
if c.type in ("superclass", "super_interfaces", "extends_interfaces"):
|
|
407
|
+
text = _txt(c)
|
|
408
|
+
while True:
|
|
409
|
+
stripped = re.sub(r"<[^<>]*>", "", text)
|
|
410
|
+
if stripped == text:
|
|
411
|
+
break
|
|
412
|
+
text = stripped
|
|
413
|
+
out.extend(w for w in re.findall(r"\b([A-Z]\w*)\b", text))
|
|
414
|
+
return out
|
|
415
|
+
|
|
416
|
+
def own_method(self, cls: Node | None, name: str, argc: int) -> Node | None:
|
|
417
|
+
cands = self.methods.get(name, ())
|
|
418
|
+
if cls is not None:
|
|
419
|
+
cands = [m for m in cands if cls.start_byte <= m.start_byte < cls.end_byte]
|
|
420
|
+
exact = [m for m in cands if len(_args(m.child_by_field_name("parameters"))) == argc]
|
|
421
|
+
return exact[0] if exact else None
|
|
422
|
+
|
|
423
|
+
def scope(self, func: Node) -> Scope:
|
|
424
|
+
sc = self._scope_cache.get(func.id)
|
|
425
|
+
if sc is not None:
|
|
426
|
+
return sc
|
|
427
|
+
sc = Scope()
|
|
428
|
+
self._scope_cache[func.id] = sc
|
|
429
|
+
self._params(func, sc, record=True)
|
|
430
|
+
for n in _walk(func):
|
|
431
|
+
t = n.type
|
|
432
|
+
if t == "variable_declarator":
|
|
433
|
+
nm, value = n.child_by_field_name("name"), n.child_by_field_name("value")
|
|
434
|
+
if nm is None or n.parent is None or n.parent.type != "local_variable_declaration":
|
|
435
|
+
continue
|
|
436
|
+
name = _txt(nm)
|
|
437
|
+
sc.declared.add(name)
|
|
438
|
+
ftype = n.parent.child_by_field_name("type")
|
|
439
|
+
if ftype is not None:
|
|
440
|
+
sc.types[name] = _txt(ftype)
|
|
441
|
+
if value is not None:
|
|
442
|
+
if value.type == "object_creation_expression" and BUILDER_TYPE.search(_txt(value.child_by_field_name("type") or value)[:40]):
|
|
443
|
+
sc.types[name] = "StringBuilder"
|
|
444
|
+
sc.events[name].append(("set", n, value))
|
|
445
|
+
elif t == "resource":
|
|
446
|
+
nm, value = n.child_by_field_name("name"), n.child_by_field_name("value")
|
|
447
|
+
if nm is not None:
|
|
448
|
+
sc.declared.add(_txt(nm))
|
|
449
|
+
if value is not None:
|
|
450
|
+
sc.events[_txt(nm)].append(("set", n, value))
|
|
451
|
+
elif t == "assignment_expression":
|
|
452
|
+
left, right, op = n.child_by_field_name("left"), n.child_by_field_name("right"), n.child_by_field_name("operator")
|
|
453
|
+
if left is not None and right is not None and left.type == "identifier" and op is not None:
|
|
454
|
+
o = _txt(op)
|
|
455
|
+
if o in ("=", "+="):
|
|
456
|
+
sc.events[_txt(left)].append(("set" if o == "=" else "aug", n, right))
|
|
457
|
+
elif t == "method_invocation":
|
|
458
|
+
obj = n.child_by_field_name("object")
|
|
459
|
+
p = n.parent
|
|
460
|
+
p_obj = p.child_by_field_name("object") if p is not None and p.type == "method_invocation" else None
|
|
461
|
+
outermost = p_obj is None or p_obj.id != n.id
|
|
462
|
+
if outermost and obj is not None:
|
|
463
|
+
chain, cur = [], n
|
|
464
|
+
while cur is not None and cur.type == "method_invocation":
|
|
465
|
+
chain.append((_txt(cur.child_by_field_name("name")), _args(cur.child_by_field_name("arguments"))))
|
|
466
|
+
cur = cur.child_by_field_name("object")
|
|
467
|
+
if cur is not None and cur.type == "identifier":
|
|
468
|
+
chain.reverse()
|
|
469
|
+
sc.events[_txt(cur)].append(("chain", n, chain))
|
|
470
|
+
for i, a in enumerate(_args(n.child_by_field_name("arguments"))):
|
|
471
|
+
if a.type == "identifier":
|
|
472
|
+
sc.events[_txt(a)].append(("opaque", n, i))
|
|
473
|
+
elif t == "lambda_expression" and n.id != func.id:
|
|
474
|
+
self._params(n, sc, record=False)
|
|
475
|
+
elif t in ("enhanced_for_statement", "catch_formal_parameter"):
|
|
476
|
+
nm = n.child_by_field_name("name")
|
|
477
|
+
if nm is not None:
|
|
478
|
+
sc.declared.add(_txt(nm))
|
|
479
|
+
return sc
|
|
480
|
+
|
|
481
|
+
@staticmethod
|
|
482
|
+
def _params(func: Node, sc: Scope, record: bool) -> None:
|
|
483
|
+
params = func.child_by_field_name("parameters")
|
|
484
|
+
if params is None:
|
|
485
|
+
return
|
|
486
|
+
if params.type == "identifier":
|
|
487
|
+
sc.declared.add(_txt(params))
|
|
488
|
+
return
|
|
489
|
+
for p in _args(params):
|
|
490
|
+
if p.type == "identifier":
|
|
491
|
+
name, ptype = _txt(p), None
|
|
492
|
+
else:
|
|
493
|
+
nm = p.child_by_field_name("name")
|
|
494
|
+
if nm is None:
|
|
495
|
+
d = next((c for c in p.named_children if c.type == "variable_declarator"), None)
|
|
496
|
+
nm = d.child_by_field_name("name") if d is not None else None
|
|
497
|
+
if nm is None:
|
|
498
|
+
if record:
|
|
499
|
+
sc.params.append("")
|
|
500
|
+
continue
|
|
501
|
+
name, ptype = _txt(nm), p.child_by_field_name("type")
|
|
502
|
+
sc.declared.add(name)
|
|
503
|
+
if record:
|
|
504
|
+
sc.params.append(name)
|
|
505
|
+
if ptype is not None:
|
|
506
|
+
sc.types[name] = _txt(ptype)
|
|
507
|
+
|
|
508
|
+
# ---- resolution -----------------------------------------------------
|
|
509
|
+
def _lit(self, node: Node) -> Res:
|
|
510
|
+
return Res(_string_value(node), src=((self, node.id),))
|
|
511
|
+
|
|
512
|
+
def resolve(self, node: Node | None, at: Node | None, depth: int) -> Res | None:
|
|
513
|
+
"""Resolve an expression to query text. `at` is the statement it feeds, used to
|
|
514
|
+
pick the assignments that precede it. Returns None when nothing is known."""
|
|
515
|
+
if node is None or depth > MAX_DEPTH:
|
|
516
|
+
return None
|
|
517
|
+
t = node.type
|
|
518
|
+
if t == "string_literal":
|
|
519
|
+
return self._lit(node)
|
|
520
|
+
if t == "binary_expression":
|
|
521
|
+
op = node.child_by_field_name("operator")
|
|
522
|
+
if op is None or _txt(op) != "+":
|
|
523
|
+
return None
|
|
524
|
+
# left-deep chains ("a" + b + "c" + ...) can be hundreds long: flatten instead of recursing
|
|
525
|
+
operands, cur = [], node
|
|
526
|
+
while cur.type == "binary_expression" and _txt(cur.child_by_field_name("operator")) == "+":
|
|
527
|
+
operands.append(cur.child_by_field_name("right"))
|
|
528
|
+
cur = cur.child_by_field_name("left")
|
|
529
|
+
operands.append(cur)
|
|
530
|
+
operands.reverse()
|
|
531
|
+
parts = [self.resolve(o, at, depth + 1) for o in operands]
|
|
532
|
+
if all(p is None for p in parts):
|
|
533
|
+
return None
|
|
534
|
+
return _join([p or self._literal_or_ph(o) for p, o in zip(parts, operands)])
|
|
535
|
+
if t == "parenthesized_expression":
|
|
536
|
+
return self.resolve(node.named_children[0], at, depth) if node.named_children else None
|
|
537
|
+
if t == "identifier":
|
|
538
|
+
return self._name(node, at, depth)
|
|
539
|
+
if t == "field_access":
|
|
540
|
+
obj, field = node.child_by_field_name("object"), node.child_by_field_name("field")
|
|
541
|
+
if obj is None or field is None:
|
|
542
|
+
return None
|
|
543
|
+
name = _txt(field)
|
|
544
|
+
if obj.type == "this":
|
|
545
|
+
return self._field(name, node, depth)
|
|
546
|
+
owner = _txt(obj).split(".")[-1]
|
|
547
|
+
r = self.repo.field(owner, name) if owner[:1].isupper() else None
|
|
548
|
+
if r is None and CONST_NAME.match(name):
|
|
549
|
+
r = self.repo.unique(name)
|
|
550
|
+
return r.but(via=True) if r is not None else None
|
|
551
|
+
if t == "ternary_expression":
|
|
552
|
+
options = [self.resolve(node.child_by_field_name(f), at, depth + 1) for f in ("consequence", "alternative")]
|
|
553
|
+
options = [o for o in options if o is not None and len(o.text) > 8]
|
|
554
|
+
r = _choice(options)
|
|
555
|
+
return r.but(dynamic=True) if r is not None else None
|
|
556
|
+
if t == "switch_expression":
|
|
557
|
+
options = []
|
|
558
|
+
body = node.child_by_field_name("body")
|
|
559
|
+
for rule in (body.named_children if body is not None else ()):
|
|
560
|
+
if rule.type != "switch_rule":
|
|
561
|
+
continue
|
|
562
|
+
value = rule.named_children[-1] if rule.named_children else None
|
|
563
|
+
if value is not None and value.type == "expression_statement" and value.named_children:
|
|
564
|
+
r = self.resolve(value.named_children[0], at, depth + 1)
|
|
565
|
+
if r is not None:
|
|
566
|
+
options.append(r)
|
|
567
|
+
r = _choice(options)
|
|
568
|
+
return r.but(dynamic=True) if r is not None else None
|
|
569
|
+
if t == "cast_expression":
|
|
570
|
+
return self.resolve(node.child_by_field_name("value"), at, depth)
|
|
571
|
+
if t == "object_creation_expression":
|
|
572
|
+
ctype = node.child_by_field_name("type")
|
|
573
|
+
if ctype is not None and ST_TYPE.match(_txt(ctype)):
|
|
574
|
+
# StringTemplate: `new ST(template)`, `new ST(group, template)`, `new ST(template, '<', '>')`
|
|
575
|
+
for a in _args(node.child_by_field_name("arguments")):
|
|
576
|
+
r = self.resolve(a, at, depth + 1)
|
|
577
|
+
if r is not None and r.text.strip():
|
|
578
|
+
return r
|
|
579
|
+
return None
|
|
580
|
+
if ctype is None or not BUILDER_TYPE.search(_txt(ctype)):
|
|
581
|
+
return None
|
|
582
|
+
args = _args(node.child_by_field_name("arguments"))
|
|
583
|
+
if not args or args[0].type == "decimal_integer_literal":
|
|
584
|
+
return Res("")
|
|
585
|
+
return self.resolve(args[0], at, depth + 1)
|
|
586
|
+
if t == "method_invocation":
|
|
587
|
+
return self._invocation(node, at, depth)
|
|
588
|
+
return None
|
|
589
|
+
|
|
590
|
+
def _st_project(self) -> bool:
|
|
591
|
+
"""Does any file of the repository import StringTemplate (a DAO may hold its templates through a helper)?"""
|
|
592
|
+
got = getattr(self.repo, "_st_project", None)
|
|
593
|
+
if got is None:
|
|
594
|
+
got = self.repo._st_project = any(i.startswith("org.stringtemplate") for f in self.repo.files for i in f.imports)
|
|
595
|
+
return got
|
|
596
|
+
|
|
597
|
+
def _template_obj(self, obj: Node, at: Node | None) -> bool:
|
|
598
|
+
"""Is this a StringTemplate object (declared `ST`, or made by `new ST(...)` / a call that returns one)?"""
|
|
599
|
+
if obj.type == "identifier":
|
|
600
|
+
declared = self._type_of(_txt(obj), at or obj)
|
|
601
|
+
if declared in ("", "var"):
|
|
602
|
+
return self._st_project()
|
|
603
|
+
return bool(ST_TYPE.match(_outer(declared)))
|
|
604
|
+
if obj.type == "object_creation_expression":
|
|
605
|
+
return bool(ST_TYPE.match(_txt(obj.child_by_field_name("type"))))
|
|
606
|
+
if obj.type == "method_invocation":
|
|
607
|
+
return _txt(obj.child_by_field_name("name")) in ("add", "render") and self._template_obj(obj.child_by_field_name("object"), at) \
|
|
608
|
+
or bool(ST_FACTORY.search(_txt(obj.child_by_field_name("name"))))
|
|
609
|
+
return False
|
|
610
|
+
|
|
611
|
+
@staticmethod
|
|
612
|
+
def _literal_or_ph(node: Node) -> Res:
|
|
613
|
+
if node.type == "character_literal":
|
|
614
|
+
return Res(_unescape(_txt(node)[1:-1]))
|
|
615
|
+
if node.type in ("decimal_integer_literal", "decimal_floating_point_literal"):
|
|
616
|
+
return Res(_txt(node).rstrip("lLfFdD"))
|
|
617
|
+
return _ph(node)
|
|
618
|
+
|
|
619
|
+
def _invocation(self, node: Node, at: Node | None, depth: int) -> Res | None:
|
|
620
|
+
name = _txt(node.child_by_field_name("name"))
|
|
621
|
+
obj = node.child_by_field_name("object")
|
|
622
|
+
args = _args(node.child_by_field_name("arguments"))
|
|
623
|
+
obj_text = _txt(obj) if obj is not None and obj.type in ("identifier", "this", "field_access") else ""
|
|
624
|
+
if name == "format" and obj_text in ("String", "MessageFormat") and args:
|
|
625
|
+
if len(args) > 1 and _txt(args[0]).startswith("Locale"):
|
|
626
|
+
args = args[1:]
|
|
627
|
+
return self._format(args[0], args[1:], at, depth, braces=obj_text == "MessageFormat")
|
|
628
|
+
if name == "formatted" and obj is not None:
|
|
629
|
+
return self._format(obj, args, at, depth)
|
|
630
|
+
if name == "join" and obj_text == "String" and len(args) >= 3:
|
|
631
|
+
sep = self.resolve(args[0], at, depth + 1)
|
|
632
|
+
if sep is None or sep.dynamic:
|
|
633
|
+
return None
|
|
634
|
+
return _join([self.resolve(a, at, depth + 1) or self._literal_or_ph(a) for a in args[1:]], sep.text)
|
|
635
|
+
if name in ("concat", "append") and obj is not None and args:
|
|
636
|
+
base = self.resolve(obj, at, depth)
|
|
637
|
+
if base is None:
|
|
638
|
+
return None
|
|
639
|
+
return _join([base, self.resolve(args[0], at, depth + 1) or self._literal_or_ph(args[0])])
|
|
640
|
+
if name == "toString" and obj is not None and not args:
|
|
641
|
+
return self.resolve(obj, at, depth)
|
|
642
|
+
if obj is not None and ((name == "render" and not args) or (name == "add" and len(args) == 2)) \
|
|
643
|
+
and self._template_obj(obj, at):
|
|
644
|
+
# StringTemplate: `template.render()` is the template's text; `.add(name, value)` sets an attribute.
|
|
645
|
+
# The text keeps its <...> syntax, which orm_jdbi renders into statements with run-time parts.
|
|
646
|
+
return self.resolve(obj, at, depth)
|
|
647
|
+
if name in PASSTHROUGH and obj is not None:
|
|
648
|
+
return self.resolve(obj, at, depth)
|
|
649
|
+
if name in ("replace", "replaceAll", "replaceFirst") and obj is not None and len(args) == 2:
|
|
650
|
+
base = self.resolve(obj, at, depth)
|
|
651
|
+
if base is None:
|
|
652
|
+
return None
|
|
653
|
+
if name == "replace" and args[0].type == "string_literal":
|
|
654
|
+
needle = _string_value(args[0])
|
|
655
|
+
if needle and needle in base.text:
|
|
656
|
+
value = self.resolve(args[1], at, depth + 1) or _ph(args[1])
|
|
657
|
+
return base.but(dynamic=True, fn=lambda s: s.replace(needle, value.text), src=value.src)
|
|
658
|
+
return base.but(dynamic=True)
|
|
659
|
+
if name == "valueOf" and obj_text == "String" and len(args) == 1:
|
|
660
|
+
return self.resolve(args[0], at, depth + 1)
|
|
661
|
+
if name in TUPLE_ACCESSORS and obj is not None and obj.type == "identifier" and not args:
|
|
662
|
+
return self._tuple_part(obj, TUPLE_ACCESSORS[name], at or node, depth)
|
|
663
|
+
|
|
664
|
+
if ST_FACTORY.search(name) and args and self._st_project():
|
|
665
|
+
# a helper that makes a StringTemplate from its query argument (`newST(SQL)`, `getSTWithLogComment(SQL, ...)`)
|
|
666
|
+
for a in args:
|
|
667
|
+
r = self.resolve(a, at, depth + 1)
|
|
668
|
+
if r is not None and _is_query(r.text):
|
|
669
|
+
return r.but(via=True)
|
|
670
|
+
# a method that returns the query: same class (or a superclass), `Other.build()`, or a typed helper field
|
|
671
|
+
targets = self._targets(node, name, obj, len(args))
|
|
672
|
+
if targets:
|
|
673
|
+
given = [self.resolve(a, at, depth + 1) for a in args]
|
|
674
|
+
shown = [g if g is not None else _ph(a) for g, a in zip(given, args)]
|
|
675
|
+
options = [r for jf, m in targets if (r := jf.method_return(m, shown, depth + 1)) is not None]
|
|
676
|
+
r = _choice(options)
|
|
677
|
+
if r is not None:
|
|
678
|
+
return r.but(dynamic=True if any(g is None for g in given) or len(targets) > 1 else None, via=True)
|
|
679
|
+
return None
|
|
680
|
+
if len(args) == 1:
|
|
681
|
+
inner = self.resolve(args[0], at, depth + 1)
|
|
682
|
+
if inner is not None and _is_query(inner.text):
|
|
683
|
+
return inner
|
|
684
|
+
return None
|
|
685
|
+
|
|
686
|
+
def _targets(self, node: Node, name: str, obj: Node | None, argc: int) -> list[tuple["JavaFile", Node]]:
|
|
687
|
+
if obj is None or obj.type == "this":
|
|
688
|
+
cls = self._enclosing(node, CLASS_TYPES)
|
|
689
|
+
hit = self.own_method(None, name, argc)
|
|
690
|
+
if hit is not None:
|
|
691
|
+
if hit.child_by_field_name("body") is not None:
|
|
692
|
+
return [(self, hit)]
|
|
693
|
+
owner = self._enclosing(hit, CLASS_TYPES)
|
|
694
|
+
nm = owner.child_by_field_name("name") if owner is not None else None
|
|
695
|
+
return self.repo.implementations(_txt(nm), name, argc) if nm is not None else []
|
|
696
|
+
while cls is not None:
|
|
697
|
+
for sup in self.supers(cls):
|
|
698
|
+
r = self.repo.methods(sup, name, argc)
|
|
699
|
+
if r:
|
|
700
|
+
return r
|
|
701
|
+
cls = self._enclosing(cls, CLASS_TYPES)
|
|
702
|
+
return []
|
|
703
|
+
if obj.type == "identifier":
|
|
704
|
+
owner = _txt(obj)
|
|
705
|
+
if not owner[:1].isupper():
|
|
706
|
+
owner = self._type_of(owner, node)
|
|
707
|
+
return self.repo.methods(owner, name, argc) if owner else []
|
|
708
|
+
return []
|
|
709
|
+
|
|
710
|
+
def _tuple_part(self, obj: Node, k: int, at: Node, depth: int) -> Res | None:
|
|
711
|
+
"""`pair.getT1()` where `pair` came from `Tuples.of(a, b)` here, or from a method that returns one."""
|
|
712
|
+
name = _txt(obj)
|
|
713
|
+
value = None
|
|
714
|
+
for func in self._scopes(at):
|
|
715
|
+
sets = [e for e in self.scope(func).events.get(name, ()) if e[0] == "set" and e[1].end_byte <= at.start_byte]
|
|
716
|
+
if sets:
|
|
717
|
+
value = sets[-1]
|
|
718
|
+
break
|
|
719
|
+
if value is None:
|
|
720
|
+
return None
|
|
721
|
+
made = self._tuple_make(value[2], k, value[1], depth)
|
|
722
|
+
if made is not None or value[2].type != "method_invocation":
|
|
723
|
+
return made
|
|
724
|
+
call = value[2]
|
|
725
|
+
cargs = _args(call.child_by_field_name("arguments"))
|
|
726
|
+
targets = self._targets(call, _txt(call.child_by_field_name("name")), call.child_by_field_name("object"), len(cargs))
|
|
727
|
+
given = [self.resolve(a, value[1], depth + 1) or _ph(a) for a in cargs] if targets else []
|
|
728
|
+
options = [r for jf, m in targets if (r := jf.method_return(m, given, depth + 1, part=k)) is not None]
|
|
729
|
+
r = _choice(options)
|
|
730
|
+
return r.but(dynamic=True, via=True) if r is not None else None
|
|
731
|
+
|
|
732
|
+
def _tuple_make(self, node: Node, k: int, at: Node, depth: int) -> Res | None:
|
|
733
|
+
if node.type == "method_invocation" and _txt(node.child_by_field_name("name")) in ("of", "with", "entry", "pair", "immutableEntry"):
|
|
734
|
+
args = _args(node.child_by_field_name("arguments"))
|
|
735
|
+
elif node.type == "object_creation_expression" and not BUILDER_TYPE.search(_txt(node.child_by_field_name("type") or node)[:40]):
|
|
736
|
+
args = _args(node.child_by_field_name("arguments"))
|
|
737
|
+
else:
|
|
738
|
+
return None
|
|
739
|
+
return self.resolve(args[k], at, depth + 1) if k < len(args) else None
|
|
740
|
+
|
|
741
|
+
def _format(self, fmt: Node, args: list[Node], at: Node | None, depth: int, braces: bool = False) -> Res | None:
|
|
742
|
+
base = self.resolve(fmt, at, depth + 1)
|
|
743
|
+
if base is None:
|
|
744
|
+
return None
|
|
745
|
+
state = {"i": 0, "dyn": base.dynamic, "via": base.via_name, "src": base.src}
|
|
746
|
+
|
|
747
|
+
def arg_value(index: int, inline: bool) -> str:
|
|
748
|
+
if index >= len(args):
|
|
749
|
+
state["dyn"] = True
|
|
750
|
+
return "«arg»"
|
|
751
|
+
r = self.resolve(args[index], at, depth + 1) if inline else None
|
|
752
|
+
if r is None:
|
|
753
|
+
lit = self._literal_or_ph(args[index])
|
|
754
|
+
state["dyn"] = state["dyn"] or lit.dynamic
|
|
755
|
+
return lit.text
|
|
756
|
+
state["dyn"] = state["dyn"] or r.dynamic
|
|
757
|
+
state["via"] = True
|
|
758
|
+
state["src"] = state["src"] + r.src
|
|
759
|
+
return r.text
|
|
760
|
+
|
|
761
|
+
if braces:
|
|
762
|
+
text = re.sub(r"\{(\d+)[^}]*\}", lambda m: arg_value(int(m.group(1)), True), base.text).replace("''", "'")
|
|
763
|
+
return Res(text, bool(state["dyn"]), bool(state["via"]), state["src"])
|
|
764
|
+
|
|
765
|
+
def spec(m: re.Match) -> str:
|
|
766
|
+
conv = m.group(2)
|
|
767
|
+
if conv == "%":
|
|
768
|
+
return "%"
|
|
769
|
+
if conv == "n":
|
|
770
|
+
return "\n"
|
|
771
|
+
if m.group(1):
|
|
772
|
+
index = int(m.group(1)) - 1
|
|
773
|
+
else:
|
|
774
|
+
index = state["i"]
|
|
775
|
+
state["i"] += 1
|
|
776
|
+
return arg_value(index, conv in "sS")
|
|
777
|
+
|
|
778
|
+
text = FORMAT_SPEC.sub(spec, base.text)
|
|
779
|
+
return Res(text, bool(state["dyn"]), bool(state["via"]), state["src"])
|
|
780
|
+
|
|
781
|
+
def _type_of(self, name: str, at: Node) -> str:
|
|
782
|
+
t = ""
|
|
783
|
+
for func in self._scopes(at):
|
|
784
|
+
t = self.scope(func).types.get(name, "")
|
|
785
|
+
if t:
|
|
786
|
+
break
|
|
787
|
+
t = t or self.field_types.get(name, "")
|
|
788
|
+
return re.sub(r"<.*", "", t, flags=re.S).split(".")[-1].strip()
|
|
789
|
+
|
|
790
|
+
def method_return(self, method: Node, given: list[Res | None], depth: int, part: int | None = None) -> Res | None:
|
|
791
|
+
"""The query a method returns, with the call's arguments bound to its parameters.
|
|
792
|
+
With `part`, the method returns a tuple and that component is wanted."""
|
|
793
|
+
key = ("ret", method.id, part)
|
|
794
|
+
body = method.child_by_field_name("body")
|
|
795
|
+
if key in self._resolving or body is None or depth > MAX_DEPTH:
|
|
796
|
+
return None
|
|
797
|
+
sc = self.scope(method)
|
|
798
|
+
saved, saved_local = self._override, self._local
|
|
799
|
+
self._override = {p: g for p, g in zip(sc.params, given) if p and g is not None}
|
|
800
|
+
self._local = {}
|
|
801
|
+
self._resolving.add(key)
|
|
802
|
+
try:
|
|
803
|
+
found, returns, unknown = [], 0, 0
|
|
804
|
+
for n in _walk(body, stop=("lambda_expression", "class_body")):
|
|
805
|
+
if n.type == "return_statement" and n.named_children:
|
|
806
|
+
returns += 1
|
|
807
|
+
value = n.named_children[0]
|
|
808
|
+
if value.type == "null_literal":
|
|
809
|
+
continue
|
|
810
|
+
if part is None:
|
|
811
|
+
r = self.resolve(value, n, depth + 1)
|
|
812
|
+
else:
|
|
813
|
+
r = self._tuple_make(value, part, n, depth)
|
|
814
|
+
if r is None:
|
|
815
|
+
unknown += 1
|
|
816
|
+
elif r.text:
|
|
817
|
+
found.append(r)
|
|
818
|
+
queries = [r for r in found if _is_query(r.text)] or [r for r in found if _leading_ph(r.text)]
|
|
819
|
+
if not queries:
|
|
820
|
+
# not a whole query: usable as a fragment (" AND x = :x") when every return is known
|
|
821
|
+
if found and not unknown and part is None:
|
|
822
|
+
return found[-1].but(dynamic=True if returns > 1 else None, via=True)
|
|
823
|
+
return None
|
|
824
|
+
r = _choice(list(reversed(queries))) # the last return is usually the main path
|
|
825
|
+
return r.but(dynamic=True if returns > 1 else None, via=True) if r is not None else None
|
|
826
|
+
finally:
|
|
827
|
+
self._resolving.discard(key)
|
|
828
|
+
self._override, self._local = saved, saved_local
|
|
829
|
+
|
|
830
|
+
def _scopes(self, node: Node) -> list[Node]:
|
|
831
|
+
out, lam = [], None
|
|
832
|
+
n = node.parent
|
|
833
|
+
while n is not None:
|
|
834
|
+
if n.type in METHOD_TYPES or n.type == "static_initializer":
|
|
835
|
+
out.append(n)
|
|
836
|
+
elif n.type == "lambda_expression":
|
|
837
|
+
lam = n
|
|
838
|
+
n = n.parent
|
|
839
|
+
if not out and lam is not None:
|
|
840
|
+
out.append(lam)
|
|
841
|
+
return out
|
|
842
|
+
|
|
843
|
+
def _name(self, node: Node, at: Node | None, depth: int) -> Res | None:
|
|
844
|
+
name = _txt(node)
|
|
845
|
+
if name in self._local:
|
|
846
|
+
return self._local[name]
|
|
847
|
+
anchor = at or node
|
|
848
|
+
for func in self._scopes(anchor):
|
|
849
|
+
sc = self.scope(func)
|
|
850
|
+
builder = bool(BUILDER_TYPE.search(sc.types.get(name, "")))
|
|
851
|
+
if any(e[1].end_byte <= anchor.start_byte and (builder or e[0] in ("set", "aug")) for e in sc.events.get(name, ())):
|
|
852
|
+
return self.run_events(func, name, anchor.start_byte, depth, self._override.get(name) if name in sc.params else None)
|
|
853
|
+
if name in sc.declared:
|
|
854
|
+
return self._override.get(name) if name in sc.params else None
|
|
855
|
+
return self._field(name, node, depth)
|
|
856
|
+
|
|
857
|
+
def _field(self, name: str, at: Node, depth: int) -> Res | None:
|
|
858
|
+
cls = self._enclosing(at, CLASS_TYPES)
|
|
859
|
+
first = cls
|
|
860
|
+
while cls is not None:
|
|
861
|
+
value = self.class_fields.get(cls.id, {}).get(name)
|
|
862
|
+
if value is not None:
|
|
863
|
+
return self.field_res(value)
|
|
864
|
+
cls = self._enclosing(cls, CLASS_TYPES)
|
|
865
|
+
value = self.fields_flat.get(name)
|
|
866
|
+
if value is not None and CONST_NAME.match(name):
|
|
867
|
+
return self.field_res(value)
|
|
868
|
+
cls = first
|
|
869
|
+
owners = []
|
|
870
|
+
while cls is not None:
|
|
871
|
+
owners.extend(self.supers(cls))
|
|
872
|
+
cls = self._enclosing(cls, CLASS_TYPES)
|
|
873
|
+
if name in self.static_imports:
|
|
874
|
+
owners.append(self.static_imports[name])
|
|
875
|
+
owners.extend(self.static_wildcards)
|
|
876
|
+
for owner in owners:
|
|
877
|
+
r = self.repo.field(owner, name)
|
|
878
|
+
if r is not None:
|
|
879
|
+
return r.but(via=True)
|
|
880
|
+
if CONST_NAME.match(name):
|
|
881
|
+
r = self.repo.unique(name)
|
|
882
|
+
if r is not None:
|
|
883
|
+
return r.but(via=True)
|
|
884
|
+
return None
|
|
885
|
+
|
|
886
|
+
def field_res(self, value: Node) -> Res | None:
|
|
887
|
+
"""A field initializer, resolved once."""
|
|
888
|
+
if value.id in self._field_cache:
|
|
889
|
+
return self._field_cache[value.id]
|
|
890
|
+
self._field_cache[value.id] = None
|
|
891
|
+
saved, saved_local = self._override, self._local
|
|
892
|
+
self._override, self._local = {}, {}
|
|
893
|
+
try:
|
|
894
|
+
r = self.resolve(value, value, 1)
|
|
895
|
+
finally:
|
|
896
|
+
self._override, self._local = saved, saved_local
|
|
897
|
+
if r is not None:
|
|
898
|
+
r = r.but(via=True)
|
|
899
|
+
self._field_cache[value.id] = r
|
|
900
|
+
return r
|
|
901
|
+
|
|
902
|
+
def _conditional(self, node: Node, func: Node, anchor: int) -> bool:
|
|
903
|
+
n = node.parent
|
|
904
|
+
while n is not None and n.id != func.id:
|
|
905
|
+
if n.type in COND_TYPES and not (n.start_byte <= anchor < n.end_byte):
|
|
906
|
+
return True
|
|
907
|
+
n = n.parent
|
|
908
|
+
return False
|
|
909
|
+
|
|
910
|
+
def _else_branch(self, node: Node, func: Node, anchor: int, events: list) -> bool:
|
|
911
|
+
"""True when `node` sits in the else-part of an if whose then-part already
|
|
912
|
+
contributed to the same variable: the two are alternatives, keep the first."""
|
|
913
|
+
child, n = node, node.parent
|
|
914
|
+
while n is not None and n.id != func.id:
|
|
915
|
+
if n.type == "if_statement" and not (n.start_byte <= anchor < n.end_byte):
|
|
916
|
+
alt, cons = n.child_by_field_name("alternative"), n.child_by_field_name("consequence")
|
|
917
|
+
if alt is not None and cons is not None and alt.id == child.id and any(
|
|
918
|
+
cons.start_byte <= e[1].start_byte < cons.end_byte and e[0] != "opaque" for e in events):
|
|
919
|
+
return True
|
|
920
|
+
child, n = n, n.parent
|
|
921
|
+
return False
|
|
922
|
+
|
|
923
|
+
def _strings_in(self, node: Node) -> tuple:
|
|
924
|
+
if node.type == "string_literal":
|
|
925
|
+
return ((self, node.id),)
|
|
926
|
+
return tuple((self, s.id) for s in _walk(node) if s.type == "string_literal")
|
|
927
|
+
|
|
928
|
+
def run_events(self, func: Node, name: str, anchor: int, depth: int, initial: Res | None) -> Res | None:
|
|
929
|
+
"""Replay what happens to a local variable before byte offset `anchor`."""
|
|
930
|
+
key = (func.id, name, anchor)
|
|
931
|
+
if key in self._resolving or depth > MAX_DEPTH:
|
|
932
|
+
return None
|
|
933
|
+
memo = key if initial is None and not self._override and not self._local else None
|
|
934
|
+
if memo is not None and memo in self._event_cache:
|
|
935
|
+
return self._event_cache[memo]
|
|
936
|
+
sc = self.scope(func)
|
|
937
|
+
events = [e for e in sc.events.get(name, ()) if e[1].end_byte <= anchor]
|
|
938
|
+
is_builder = bool(BUILDER_TYPE.search(sc.types.get(name, "")))
|
|
939
|
+
cur, dyn, pending = initial, False, None
|
|
940
|
+
skipped: tuple = () # strings on branches we did not follow: part of this value's story
|
|
941
|
+
|
|
942
|
+
def base() -> Res:
|
|
943
|
+
return cur if cur is not None else (pending or _ph_text(name))
|
|
944
|
+
|
|
945
|
+
from . import arms as arms_mod # one statement per if / else arm, beside the text with «or: ...»
|
|
946
|
+
arms = arms_mod.Arms(_join)
|
|
947
|
+
arms.reset(initial)
|
|
948
|
+
pend: list = []
|
|
949
|
+
|
|
950
|
+
def flush() -> None:
|
|
951
|
+
if not pend:
|
|
952
|
+
return
|
|
953
|
+
old, node, kind, other_branch, else_piece, cond = pend.pop()
|
|
954
|
+
if else_piece is not None:
|
|
955
|
+
arms.append_else(arms_mod.arm_key(node, func, anchor), else_piece)
|
|
956
|
+
elif other_branch:
|
|
957
|
+
arms.kill()
|
|
958
|
+
elif cur is not old:
|
|
959
|
+
if old is None or cur is None or arms.vs is None:
|
|
960
|
+
arms.reset(cur)
|
|
961
|
+
elif len(cur.text) > len(old.text) and cur.text.startswith(old.text):
|
|
962
|
+
arms.then(arms_mod.then_keys(node, func, anchor))
|
|
963
|
+
arms.append(Res(cur.text[len(old.text):], cur.dynamic, cur.via_name))
|
|
964
|
+
elif len(cur.text) > len(old.text) and cur.text.endswith(old.text):
|
|
965
|
+
arms.then(arms_mod.then_keys(node, func, anchor))
|
|
966
|
+
arms.append(Res(cur.text[: len(cur.text) - len(old.text)], cur.dynamic, cur.via_name), front=True)
|
|
967
|
+
elif cond:
|
|
968
|
+
arms.kill()
|
|
969
|
+
else:
|
|
970
|
+
arms.reset(cur)
|
|
971
|
+
|
|
972
|
+
self._resolving.add(key)
|
|
973
|
+
try:
|
|
974
|
+
for kind, node, payload in events:
|
|
975
|
+
if kind in ("opaque", "chain") and not is_builder:
|
|
976
|
+
continue
|
|
977
|
+
flush()
|
|
978
|
+
cond = self._conditional(node, func, anchor)
|
|
979
|
+
other_branch = cond and self._else_branch(node, func, anchor, events)
|
|
980
|
+
pend.append([cur, node, kind, other_branch, None, cond])
|
|
981
|
+
if kind == "set":
|
|
982
|
+
selfref = (payload.type == "identifier" and _txt(payload) == name) or \
|
|
983
|
+
any(c.type == "identifier" and _txt(c) == name for c in _walk(payload))
|
|
984
|
+
if selfref and not other_branch:
|
|
985
|
+
saved = self._local
|
|
986
|
+
self._local = {**saved, name: base()}
|
|
987
|
+
try:
|
|
988
|
+
r = self.resolve(payload, node, depth + 1)
|
|
989
|
+
finally:
|
|
990
|
+
self._local = saved
|
|
991
|
+
if r is None:
|
|
992
|
+
dyn = True
|
|
993
|
+
continue
|
|
994
|
+
cur = r
|
|
995
|
+
elif cond and cur is not None and cur.text:
|
|
996
|
+
# another value on some branch: a different whole query is an alternative
|
|
997
|
+
r = self.resolve(payload, node, depth + 1) if not selfref else None
|
|
998
|
+
if r is not None and _is_query(r.text) and _is_query(cur.text) and len(cur.alts) < MAX_ALTS:
|
|
999
|
+
cur = Res(cur.text, True, cur.via_name, cur.src, cur.alts + tuple(
|
|
1000
|
+
Res(x.text, True, True, x.src) for x in r.flat() if x.text != cur.text))
|
|
1001
|
+
else:
|
|
1002
|
+
skipped += self._strings_in(payload)
|
|
1003
|
+
dyn = True
|
|
1004
|
+
continue
|
|
1005
|
+
else:
|
|
1006
|
+
r = self.resolve(payload, node, depth + 1)
|
|
1007
|
+
if r is None:
|
|
1008
|
+
pending = None if payload.type == "null_literal" else _ph(payload)
|
|
1009
|
+
if not cond:
|
|
1010
|
+
cur = None
|
|
1011
|
+
continue
|
|
1012
|
+
cur = r
|
|
1013
|
+
dyn = dyn or cond
|
|
1014
|
+
elif other_branch:
|
|
1015
|
+
dyn = True
|
|
1016
|
+
skipped += self._strings_in(node)
|
|
1017
|
+
# The else-part appends something else: the statement keeps the then-part's text, and a
|
|
1018
|
+
# run-time part says there is an alternative, instead of dropping it without a trace.
|
|
1019
|
+
other = payload if kind == "aug" else next(
|
|
1020
|
+
(margs[0] for mname, margs in payload if mname == "append" and margs), None) if kind == "chain" else None
|
|
1021
|
+
if other is not None and cur is not None:
|
|
1022
|
+
r = self.resolve(other, node, depth + 1)
|
|
1023
|
+
text = " ".join((r.text if r is not None else _txt(other)).split())
|
|
1024
|
+
pend[-1][4] = r if r is not None else self._literal_or_ph(other)
|
|
1025
|
+
cur = _join([cur, Res(" "), _ph_text("or: " + text)])
|
|
1026
|
+
elif kind == "aug":
|
|
1027
|
+
cur = _join([base(), self.resolve(payload, node, depth + 1) or self._literal_or_ph(payload)])
|
|
1028
|
+
dyn = dyn or cond
|
|
1029
|
+
elif kind == "chain":
|
|
1030
|
+
for mname, margs in payload:
|
|
1031
|
+
if mname == "append" and margs:
|
|
1032
|
+
cur = _join([base(), self.resolve(margs[0], node, depth + 1) or self._literal_or_ph(margs[0])])
|
|
1033
|
+
dyn = dyn or cond
|
|
1034
|
+
elif mname == "insert" and len(margs) == 2 and _txt(margs[0]) == "0":
|
|
1035
|
+
cur = _join([self.resolve(margs[1], node, depth + 1) or self._literal_or_ph(margs[1]), base()])
|
|
1036
|
+
dyn = dyn or cond
|
|
1037
|
+
elif mname == "setLength" and margs and _txt(margs[0]) == "0":
|
|
1038
|
+
if cond:
|
|
1039
|
+
dyn = True
|
|
1040
|
+
else:
|
|
1041
|
+
cur = Res("")
|
|
1042
|
+
elif mname in BUILDER_READS:
|
|
1043
|
+
break
|
|
1044
|
+
else:
|
|
1045
|
+
dyn = True
|
|
1046
|
+
elif kind == "opaque":
|
|
1047
|
+
part = self._inline_helper(node, int(payload), depth)
|
|
1048
|
+
if part is not None:
|
|
1049
|
+
cur = _join([base(), part])
|
|
1050
|
+
dyn = True
|
|
1051
|
+
flush()
|
|
1052
|
+
out = cur.but(dynamic=True if dyn else None, via=True, src=skipped) if cur is not None else None
|
|
1053
|
+
if out is not None:
|
|
1054
|
+
out.arms = tuple(Res(a.text, True, True, a.src) for a in arms.result() if a is not None)
|
|
1055
|
+
if memo is not None and depth <= 2:
|
|
1056
|
+
self._event_cache[memo] = out
|
|
1057
|
+
return out
|
|
1058
|
+
finally:
|
|
1059
|
+
self._resolving.discard(key)
|
|
1060
|
+
|
|
1061
|
+
def _inline_helper(self, call: Node, index: int, depth: int) -> Res | None:
|
|
1062
|
+
"""A builder handed to another method. When that method is visible, replay what it
|
|
1063
|
+
appends; otherwise leave a placeholder so the template shows something was added here."""
|
|
1064
|
+
if call.type != "method_invocation":
|
|
1065
|
+
return None
|
|
1066
|
+
obj = call.child_by_field_name("object")
|
|
1067
|
+
cname = _txt(call.child_by_field_name("name"))
|
|
1068
|
+
if obj is not None and LOGGERS.match(_txt(obj)):
|
|
1069
|
+
return None
|
|
1070
|
+
if cname in ("valueOf", "println", "print", "isEmpty", "isBlank", "isNotBlank", "isNotEmpty", "length"):
|
|
1071
|
+
return None
|
|
1072
|
+
if obj is not None and cname in ("append", "format", "of", "add", "put", "equals"):
|
|
1073
|
+
return None
|
|
1074
|
+
args = _args(call.child_by_field_name("arguments"))
|
|
1075
|
+
targets = self._targets(call, cname, obj, len(args)) if depth < MAX_DEPTH else []
|
|
1076
|
+
parts = []
|
|
1077
|
+
for jf, method in targets[:1]:
|
|
1078
|
+
sc = jf.scope(method)
|
|
1079
|
+
if index >= len(sc.params) or not sc.params[index]:
|
|
1080
|
+
continue
|
|
1081
|
+
# bind the other arguments that are plain text (a clause, a column name); builders are not followed
|
|
1082
|
+
given = [(self.resolve(a, call, depth + 1) or _ph(a)) if i != index and self._cheap(a, call) else None
|
|
1083
|
+
for i, a in enumerate(args)]
|
|
1084
|
+
bound = {p: g for p, g in zip(sc.params, given) if p and g is not None}
|
|
1085
|
+
hkey = (method.id, index, tuple(sorted((p, g.text) for p, g in bound.items())))
|
|
1086
|
+
if hkey in jf._helper_cache:
|
|
1087
|
+
r = jf._helper_cache[hkey]
|
|
1088
|
+
else:
|
|
1089
|
+
saved, saved_local = jf._override, jf._local
|
|
1090
|
+
jf._override, jf._local = bound, {}
|
|
1091
|
+
try:
|
|
1092
|
+
r = jf.run_events(method, sc.params[index], method.end_byte, depth + 1, Res(""))
|
|
1093
|
+
finally:
|
|
1094
|
+
jf._override, jf._local = saved, saved_local
|
|
1095
|
+
if depth <= 3:
|
|
1096
|
+
jf._helper_cache[hkey] = r
|
|
1097
|
+
if r is not None and r.text:
|
|
1098
|
+
parts.append(Res(r.text, True, True, r.src))
|
|
1099
|
+
elif r is not None:
|
|
1100
|
+
return None # the helper adds nothing we can see (it only reads the builder)
|
|
1101
|
+
return parts[0] if parts else _ph_text(cname + "(…)")
|
|
1102
|
+
|
|
1103
|
+
def _cheap(self, node: Node, at: Node) -> bool:
|
|
1104
|
+
if node.type in ("string_literal", "field_access"):
|
|
1105
|
+
return True
|
|
1106
|
+
if node.type == "identifier":
|
|
1107
|
+
return not BUILDER_TYPE.search(self._type_of(_txt(node), at) or "")
|
|
1108
|
+
return node.type == "binary_expression" and len(node.text) < 400
|
|
1109
|
+
|
|
1110
|
+
def bound(self, w: Wrapper, given: list[Res | None], depth: int) -> Res | None:
|
|
1111
|
+
"""What a wrapper method sends to its sink when called with these arguments."""
|
|
1112
|
+
key = ("bound", w.call.id)
|
|
1113
|
+
if key in self._resolving or depth > 3:
|
|
1114
|
+
return None
|
|
1115
|
+
sc = self.scope(w.method)
|
|
1116
|
+
saved, saved_local = self._override, self._local
|
|
1117
|
+
self._override = {p: g for p, g in zip(sc.params, given) if p and g is not None}
|
|
1118
|
+
self._local = {}
|
|
1119
|
+
self._resolving.add(key)
|
|
1120
|
+
try:
|
|
1121
|
+
r = self.resolve(w.arg, w.call, depth + 1)
|
|
1122
|
+
if r is not None and w.inner is not None:
|
|
1123
|
+
inner_args = _args(w.call.child_by_field_name("arguments"))
|
|
1124
|
+
passed = [self.resolve(a, w.call, depth + 1) or _ph(a) for a in inner_args]
|
|
1125
|
+
passed[w.inner.index] = r
|
|
1126
|
+
r = w.inner.jf.bound(w.inner, passed, depth + 1) or r
|
|
1127
|
+
return r
|
|
1128
|
+
finally:
|
|
1129
|
+
self._resolving.discard(key)
|
|
1130
|
+
self._override, self._local = saved, saved_local
|
|
1131
|
+
|
|
1132
|
+
@staticmethod
|
|
1133
|
+
def _enclosing(node: Node, types: tuple[str, ...]) -> Node | None:
|
|
1134
|
+
n = node.parent
|
|
1135
|
+
while n is not None:
|
|
1136
|
+
if n.type in types:
|
|
1137
|
+
return n
|
|
1138
|
+
n = n.parent
|
|
1139
|
+
return None
|
|
1140
|
+
|
|
1141
|
+
# ---- call sites -----------------------------------------------------
|
|
1142
|
+
def symbol(self, node: Node) -> str:
|
|
1143
|
+
names = []
|
|
1144
|
+
n = node.parent
|
|
1145
|
+
while n is not None:
|
|
1146
|
+
if n.type in CLASS_TYPES or n.type in ("method_declaration", "constructor_declaration"):
|
|
1147
|
+
nm = n.child_by_field_name("name")
|
|
1148
|
+
if nm is not None:
|
|
1149
|
+
names.append(_txt(nm))
|
|
1150
|
+
n = n.parent
|
|
1151
|
+
return ".".join(reversed(names))
|
|
1152
|
+
|
|
1153
|
+
def in_loop(self, node: Node) -> bool:
|
|
1154
|
+
n = node.parent
|
|
1155
|
+
while n is not None and n.type not in METHOD_TYPES and n.type not in CLASS_TYPES:
|
|
1156
|
+
if n.type in LOOP_TYPES:
|
|
1157
|
+
return True
|
|
1158
|
+
if n.type == "lambda_expression":
|
|
1159
|
+
p = n.parent
|
|
1160
|
+
if p is not None and p.type == "argument_list" and p.parent is not None and p.parent.type == "method_invocation" \
|
|
1161
|
+
and _txt(p.parent.child_by_field_name("name")) in LOOP_LAMBDA_CALLS:
|
|
1162
|
+
return True
|
|
1163
|
+
n = n.parent
|
|
1164
|
+
return False
|
|
1165
|
+
|
|
1166
|
+
def file_engine(self, rules: LangRules) -> tuple[str, bool]:
|
|
1167
|
+
"""(engine implied by the imports, whether the file imports any database API)."""
|
|
1168
|
+
engines, db = set(), False
|
|
1169
|
+
for imp in self.imports:
|
|
1170
|
+
for prefix, engine in rules.imports.items():
|
|
1171
|
+
if imp == prefix or imp.startswith(prefix + "."):
|
|
1172
|
+
db = True
|
|
1173
|
+
if engine:
|
|
1174
|
+
engines.add(engine)
|
|
1175
|
+
return (next(iter(engines)) if len(engines) == 1 else ""), db
|
|
1176
|
+
|
|
1177
|
+
def _param_of(self, call: Node, arg: Node) -> tuple[str, int] | None:
|
|
1178
|
+
"""When `arg` is a parameter of the enclosing method, that method is a wrapper
|
|
1179
|
+
around the driver. Returns (method name, positional index)."""
|
|
1180
|
+
if arg.type != "identifier":
|
|
1181
|
+
return None
|
|
1182
|
+
func = self._enclosing(call, ("method_declaration", "constructor_declaration"))
|
|
1183
|
+
if func is None:
|
|
1184
|
+
return None
|
|
1185
|
+
name = _txt(arg)
|
|
1186
|
+
sc = self.scope(func)
|
|
1187
|
+
if any(e[0] in ("set", "aug") for e in sc.events.get(name, ())) or name not in sc.params:
|
|
1188
|
+
return None
|
|
1189
|
+
fname = func.child_by_field_name("name")
|
|
1190
|
+
return (_txt(fname), sc.params.index(name)) if fname is not None else None
|
|
1191
|
+
|
|
1192
|
+
def find_wrappers(self, rules: LangRules) -> list[tuple[str, Wrapper]]:
|
|
1193
|
+
"""Methods in this file that pass one of their own parameters to a sink, as is
|
|
1194
|
+
(`run(String sql) { jdbc.query(sql) }`) or with text added (`jdbc.query(sql + where)`)."""
|
|
1195
|
+
out = []
|
|
1196
|
+
engine = self.file_engine(rules)[0]
|
|
1197
|
+
for call in self.calls:
|
|
1198
|
+
name = _txt(call.child_by_field_name("name"))
|
|
1199
|
+
sink = rules.sink_for(name)
|
|
1200
|
+
args = _args(call.child_by_field_name("arguments"))
|
|
1201
|
+
inner = [] if sink is not None else [w for w in self.repo.wrappers.get(name, ()) if w.argc == len(args)]
|
|
1202
|
+
if sink is None and not inner:
|
|
1203
|
+
continue
|
|
1204
|
+
func = self._enclosing(call, ("method_declaration", "constructor_declaration"))
|
|
1205
|
+
fname = func.child_by_field_name("name") if func is not None else None
|
|
1206
|
+
if fname is None:
|
|
1207
|
+
continue
|
|
1208
|
+
sc = self.scope(func)
|
|
1209
|
+
argc = len(sc.params)
|
|
1210
|
+
for i, w in ([(i, None) for i in sink.args] if sink is not None else [(w.index, w) for w in inner]):
|
|
1211
|
+
if i >= len(args):
|
|
1212
|
+
continue
|
|
1213
|
+
arg = args[i]
|
|
1214
|
+
eng = (sink.engine if sink is not None else w.engine) or engine
|
|
1215
|
+
hit = self._param_of(call, arg)
|
|
1216
|
+
if hit:
|
|
1217
|
+
if SQLISH_NAME.search(_txt(arg)) or w is not None:
|
|
1218
|
+
out.append((hit[0], Wrapper(self, func, call, arg, hit[1], argc, eng, False, w)))
|
|
1219
|
+
continue
|
|
1220
|
+
texts = [p for p in sc.params if p and STRING_TYPE.match(sc.types.get(p, ""))]
|
|
1221
|
+
if not texts or arg.type in ("string_literal", "lambda_expression"):
|
|
1222
|
+
continue
|
|
1223
|
+
saved, saved_local = self._override, self._local
|
|
1224
|
+
self._override, self._local = {p: Res(f"«§{p}§»", True) for p in texts}, {}
|
|
1225
|
+
try:
|
|
1226
|
+
r = self.resolve(arg, call, 0)
|
|
1227
|
+
finally:
|
|
1228
|
+
self._override, self._local = saved, saved_local
|
|
1229
|
+
m = re.match(r"\s*«§(\w+)§»", r.text) if r is not None else None
|
|
1230
|
+
if m:
|
|
1231
|
+
out.append((_txt(fname), Wrapper(self, func, call, arg, sc.params.index(m.group(1)), argc, eng, True, w)))
|
|
1232
|
+
return out
|
|
1233
|
+
|
|
1234
|
+
def _plausible(self, generic: bool, obj: Node | None, arg: Node, db_file: bool) -> bool:
|
|
1235
|
+
"""Keep an argument we could not read only when the call plausibly reaches a database."""
|
|
1236
|
+
if obj is not None and _txt(obj) == "super":
|
|
1237
|
+
return False # `super.execute(x)` hands its argument to the parent's method: no SQL is sent here
|
|
1238
|
+
if arg.type in ("lambda_expression", "true", "false", "null_literal", "decimal_integer_literal",
|
|
1239
|
+
"method_reference", "class_literal", "array_creation_expression", "string_literal"):
|
|
1240
|
+
return False
|
|
1241
|
+
text = _txt(arg)[:80]
|
|
1242
|
+
if arg.type == "object_creation_expression" and not BUILDER_TYPE.search(text):
|
|
1243
|
+
return False
|
|
1244
|
+
if NOT_SQL_ARG.search(text) and not SQLISH_NAME.search(text):
|
|
1245
|
+
return False
|
|
1246
|
+
if arg.type == "identifier":
|
|
1247
|
+
declared = self._type_of(text, arg)
|
|
1248
|
+
if declared and declared != "var" and not STRING_TYPE.match(declared) and declared != "Object":
|
|
1249
|
+
return False # a Map, a DTO, a PreparedStatementCreator: not query text
|
|
1250
|
+
arg_ok = bool(SQLISH_NAME.search(text))
|
|
1251
|
+
receiver_ok = obj is not None and bool(RECEIVER.search(_txt(obj)[-40:]))
|
|
1252
|
+
if not generic:
|
|
1253
|
+
return arg_ok or receiver_ok or db_file
|
|
1254
|
+
return (receiver_ok and (arg_ok or db_file)) or (arg_ok and db_file)
|
|
1255
|
+
|
|
1256
|
+
def _use(self, res: Res | None) -> None:
|
|
1257
|
+
for jf, node_id in (res.src if res is not None else ()):
|
|
1258
|
+
jf.consumed.add(node_id)
|
|
1259
|
+
|
|
1260
|
+
def _site(self, node: Node, line_node: Node, arg: Node, sink_text: str, engine: str, res: Res | None,
|
|
1261
|
+
known: bool = True, kind: str = "call") -> RawSite:
|
|
1262
|
+
if res is not None and is_cypher(res.text):
|
|
1263
|
+
engine = "cypher"
|
|
1264
|
+
self._use(res)
|
|
1265
|
+
return RawSite(
|
|
1266
|
+
file=self.rel, line=line_node.start_point[0] + 1, end_line=node.end_point[0] + 1, language="java",
|
|
1267
|
+
kind=kind, sink=trim(sink_text, 80), symbol=self.symbol(node),
|
|
1268
|
+
sql=res.text if res is not None else None,
|
|
1269
|
+
resolution=res.resolution if res is not None else ("parameter" if self._param_of(node, arg) else "unresolved"),
|
|
1270
|
+
expr=trim(_txt(arg)), in_loop=self.in_loop(node), engine_hint=engine,
|
|
1271
|
+
is_test=is_test_path(self.rel) or bool(TEST_FILE.search(self.rel)), known_sink=known,
|
|
1272
|
+
)
|
|
1273
|
+
|
|
1274
|
+
def sites(self, rules: LangRules) -> list[RawSite]:
|
|
1275
|
+
out: list[RawSite] = []
|
|
1276
|
+
file_engine, db_file = self.file_engine(rules)
|
|
1277
|
+
|
|
1278
|
+
for call in self.calls:
|
|
1279
|
+
name_node = call.child_by_field_name("name")
|
|
1280
|
+
name = _txt(name_node)
|
|
1281
|
+
sink = rules.sink_for(name)
|
|
1282
|
+
args = _args(call.child_by_field_name("arguments"))
|
|
1283
|
+
wraps = [] if sink is not None else [w for w in self.repo.wrappers.get(name, ()) if w.argc == len(args)]
|
|
1284
|
+
if sink is None and not wraps:
|
|
1285
|
+
continue
|
|
1286
|
+
obj = call.child_by_field_name("object")
|
|
1287
|
+
jpql = sink is not None and sink.engine == "jpql"
|
|
1288
|
+
generic = sink is None or name in GENERIC_SINKS
|
|
1289
|
+
sink_text = (_txt(obj) + "." if obj is not None else "") + name
|
|
1290
|
+
resolved: dict[int, Res | None] = {}
|
|
1291
|
+
seen: set[str | None] = set()
|
|
1292
|
+
for i, w in ([(i, None) for i in sink.args] if sink is not None else [(w.index, w) for w in wraps]):
|
|
1293
|
+
if i >= len(args):
|
|
1294
|
+
continue
|
|
1295
|
+
arg = args[i]
|
|
1296
|
+
if i not in resolved:
|
|
1297
|
+
r = self.resolve(arg, call, 0)
|
|
1298
|
+
resolved[i] = None if r is not None and not PLACEHOLDER.sub("", r.text).strip() else r
|
|
1299
|
+
res = resolved[i]
|
|
1300
|
+
engine = (sink.engine if sink is not None else w.engine) or file_engine
|
|
1301
|
+
is_param = self._param_of(call, arg) is not None
|
|
1302
|
+
if res is not None and not res.dynamic and name == "createNamedQuery" and res.text in self.repo.named_queries:
|
|
1303
|
+
named, native = self.repo.named_queries[res.text]
|
|
1304
|
+
res, engine = named.but(via=True), ("" if native else "jpql")
|
|
1305
|
+
elif res is not None and not (_is_query(res.text) or (jpql and JPQL_START.match(res.text))):
|
|
1306
|
+
# resolved and not a query (Map.get("query"), HTTP clients, ...). A template whose
|
|
1307
|
+
# start is only known at run time cannot be judged by its text: judge the call.
|
|
1308
|
+
if not _leading_ph(res.text) or not self._plausible(generic, obj, arg, db_file):
|
|
1309
|
+
continue
|
|
1310
|
+
elif res is None and is_param:
|
|
1311
|
+
if not (SQLISH_NAME.search(_txt(arg)) or self._plausible(generic, obj, arg, db_file)):
|
|
1312
|
+
continue
|
|
1313
|
+
elif res is None and not self._plausible(generic, obj, arg, db_file):
|
|
1314
|
+
continue
|
|
1315
|
+
if w is not None and res is not None and (w.derived or w.inner is not None):
|
|
1316
|
+
given = [res if j == i else (self.resolve(a, call, 1) or _ph(a)) for j, a in enumerate(args)]
|
|
1317
|
+
full = w.jf.bound(w, given, 0)
|
|
1318
|
+
if full is not None and _is_query(full.text):
|
|
1319
|
+
res = full.but(dynamic=True if full.text != res.text else None, via=True, src=res.src)
|
|
1320
|
+
for v in (res.flat() if res is not None else [None]):
|
|
1321
|
+
key = v.text if v is not None else None
|
|
1322
|
+
if key in seen:
|
|
1323
|
+
continue
|
|
1324
|
+
seen.add(key)
|
|
1325
|
+
out.append(self._site(call, name_node, arg, sink_text, engine, v))
|
|
1326
|
+
if sink is not None:
|
|
1327
|
+
break
|
|
1328
|
+
|
|
1329
|
+
for ann in self.annotations:
|
|
1330
|
+
sink = rules.sink_for("@" + _txt(ann.child_by_field_name("name")).split(".")[-1])
|
|
1331
|
+
arglist = ann.child_by_field_name("arguments")
|
|
1332
|
+
if sink is None or arglist is None:
|
|
1333
|
+
continue
|
|
1334
|
+
native = False
|
|
1335
|
+
candidates: list[Node] = []
|
|
1336
|
+
for a in _args(arglist):
|
|
1337
|
+
if a.type == "element_value_pair":
|
|
1338
|
+
key, value = _txt(a.child_by_field_name("key")), a.child_by_field_name("value")
|
|
1339
|
+
if key == "nativeQuery" and value is not None and _txt(value) == "true":
|
|
1340
|
+
native = True
|
|
1341
|
+
elif key in sink.kwargs and value is not None:
|
|
1342
|
+
candidates.append(value)
|
|
1343
|
+
elif 0 in sink.args:
|
|
1344
|
+
candidates.append(a)
|
|
1345
|
+
engine = sink.engine
|
|
1346
|
+
if engine == "jpql" and native:
|
|
1347
|
+
engine = ""
|
|
1348
|
+
for arg in candidates:
|
|
1349
|
+
res = self._annotation_value(arg)
|
|
1350
|
+
if res is None or not res.text.strip():
|
|
1351
|
+
continue
|
|
1352
|
+
if not (_is_query(res.text) or JPQL_START.match(res.text)):
|
|
1353
|
+
continue
|
|
1354
|
+
out.append(self._site(ann, ann, arg, "@" + _txt(ann.child_by_field_name("name")), engine or file_engine, res))
|
|
1355
|
+
return out
|
|
1356
|
+
|
|
1357
|
+
def _annotation_value(self, arg: Node) -> Res | None:
|
|
1358
|
+
if arg.type == "element_value_array_initializer": # MyBatis: {"SELECT *", "FROM t"} is joined with spaces
|
|
1359
|
+
parts = [self.resolve(c, c, 0) or _ph(c) for c in _args(arg)]
|
|
1360
|
+
return _join(parts, " ") if parts else None
|
|
1361
|
+
return self.resolve(arg, arg, 0)
|
|
1362
|
+
|
|
1363
|
+
def named_queries(self) -> dict[str, tuple[Res, bool]]:
|
|
1364
|
+
out = {}
|
|
1365
|
+
for ann in self.annotations:
|
|
1366
|
+
aname = _txt(ann.child_by_field_name("name")).split(".")[-1]
|
|
1367
|
+
if aname not in ("NamedQuery", "NamedNativeQuery"):
|
|
1368
|
+
continue
|
|
1369
|
+
pairs = {_txt(a.child_by_field_name("key")): a.child_by_field_name("value")
|
|
1370
|
+
for a in _args(ann.child_by_field_name("arguments")) if a.type == "element_value_pair"}
|
|
1371
|
+
name = self.resolve(pairs.get("name"), None, 0)
|
|
1372
|
+
query = self.resolve(pairs.get("query"), None, 0)
|
|
1373
|
+
if name is not None and query is not None and not name.dynamic:
|
|
1374
|
+
out[name.text] = (query, aname == "NamedNativeQuery")
|
|
1375
|
+
return out
|
|
1376
|
+
|
|
1377
|
+
def orphan_candidates(self) -> list[tuple["JavaFile", Node, Node, Res, Node | None]]:
|
|
1378
|
+
"""Query strings not attached to a known sink: wrapper calls, builders that are
|
|
1379
|
+
returned to a caller, and constants nothing in the repo refers to."""
|
|
1380
|
+
found = []
|
|
1381
|
+
for s in self.strings:
|
|
1382
|
+
if s.id in self.consumed:
|
|
1383
|
+
continue
|
|
1384
|
+
top = s
|
|
1385
|
+
while top.parent is not None and (
|
|
1386
|
+
(top.parent.type == "binary_expression" and _txt(top.parent.child_by_field_name("operator")) == "+")
|
|
1387
|
+
or top.parent.type == "parenthesized_expression"):
|
|
1388
|
+
top = top.parent
|
|
1389
|
+
first = top
|
|
1390
|
+
while first.type in ("binary_expression", "parenthesized_expression"):
|
|
1391
|
+
first = first.child_by_field_name("left") if first.type == "binary_expression" else first.named_children[0]
|
|
1392
|
+
if first.id != s.id:
|
|
1393
|
+
continue
|
|
1394
|
+
value = _string_value(s)
|
|
1395
|
+
if not (looks_like_sql(value) or is_cypher(value, any_case=False) or ORPHAN_LEAD.match(value)):
|
|
1396
|
+
continue # cheap check on the first literal; the whole expression is resolved below
|
|
1397
|
+
res: Res | None = None
|
|
1398
|
+
call: Node | None = None
|
|
1399
|
+
holder = top.parent
|
|
1400
|
+
ctor = None
|
|
1401
|
+
if holder is not None and holder.type == "argument_list" and holder.parent is not None:
|
|
1402
|
+
owner = holder.parent
|
|
1403
|
+
if owner.type == "object_creation_expression" and BUILDER_TYPE.search(_txt(owner.child_by_field_name("type") or owner)[:40]):
|
|
1404
|
+
ctor = owner
|
|
1405
|
+
holder = owner.parent
|
|
1406
|
+
elif owner.type == "method_invocation" and _txt(owner.child_by_field_name("name")) == "append":
|
|
1407
|
+
root = owner
|
|
1408
|
+
while root is not None and root.type == "method_invocation":
|
|
1409
|
+
root = root.child_by_field_name("object")
|
|
1410
|
+
if root is not None and root.type == "identifier":
|
|
1411
|
+
res = self._at_scope_end(_txt(root), owner)
|
|
1412
|
+
elif owner.type in ("method_invocation", "object_creation_expression"):
|
|
1413
|
+
call = owner
|
|
1414
|
+
if res is None and holder is not None and holder.type == "variable_declarator" and holder.parent is not None \
|
|
1415
|
+
and holder.parent.type == "local_variable_declaration":
|
|
1416
|
+
nm = holder.child_by_field_name("name")
|
|
1417
|
+
if nm is not None:
|
|
1418
|
+
res = self._at_scope_end(_txt(nm), holder)
|
|
1419
|
+
if res is None or (self, s.id) not in res.src:
|
|
1420
|
+
res = self.resolve(ctor or top, top, 0)
|
|
1421
|
+
if res is None or not (looks_like_sql(res.text) or is_cypher(res.text, any_case=False)):
|
|
1422
|
+
continue
|
|
1423
|
+
if len(res.text.split()) < 3:
|
|
1424
|
+
continue # "CREATE TABLE" in a keyword list is not a statement
|
|
1425
|
+
found.append((self, s, top, Res(res.text, res.dynamic, res.via_name, res.src), call))
|
|
1426
|
+
return found
|
|
1427
|
+
|
|
1428
|
+
def orphan_site(self, rules: LangRules, top: Node, res: Res, call: Node | None) -> RawSite:
|
|
1429
|
+
sink_text = ""
|
|
1430
|
+
if call is not None:
|
|
1431
|
+
obj = call.child_by_field_name("object")
|
|
1432
|
+
if call.type == "method_invocation":
|
|
1433
|
+
sink_text = (_txt(obj) + "." if obj is not None else "") + _txt(call.child_by_field_name("name"))
|
|
1434
|
+
else:
|
|
1435
|
+
sink_text = "new " + _txt(call.child_by_field_name("type") or call)
|
|
1436
|
+
return self._site(top, top, top, sink_text, self.file_engine(rules)[0], res, known=False,
|
|
1437
|
+
kind="call" if call is not None else "sql_string")
|
|
1438
|
+
|
|
1439
|
+
def _at_scope_end(self, name: str, at: Node) -> Res | None:
|
|
1440
|
+
"""What a local variable holds when its method ends (for a builder that is returned)."""
|
|
1441
|
+
scopes = self._scopes(at)
|
|
1442
|
+
if not scopes:
|
|
1443
|
+
return None
|
|
1444
|
+
func = scopes[0]
|
|
1445
|
+
if name not in self.scope(func).events:
|
|
1446
|
+
return None
|
|
1447
|
+
return self.run_events(func, name, func.end_byte, 0, None)
|
|
1448
|
+
|
|
1449
|
+
|
|
1450
|
+
STRING_TYPE = re.compile(r"^(?:final\s+)?(?:java\.lang\.)?(String|CharSequence|StringBuilder|StringBuffer)$")
|
|
1451
|
+
ORPHAN_LEAD = re.compile(r"\s*(?:--|/\*|\(|//)")
|
|
1452
|
+
TUPLE_ACCESSORS = {**{f"getT{i}": i - 1 for i in range(1, 9)}, "getLeft": 0, "getKey": 0, "getFirst": 0,
|
|
1453
|
+
"getRight": 1, "getValue": 1, "getSecond": 1}
|
|
1454
|
+
|
|
1455
|
+
|
|
1456
|
+
def _is_query(text: str) -> bool:
|
|
1457
|
+
return looks_like_sql(text, any_case=True) or is_cypher(text)
|
|
1458
|
+
|
|
1459
|
+
|
|
1460
|
+
def _leading_ph(text: str) -> bool:
|
|
1461
|
+
return text.lstrip().startswith("«")
|
|
1462
|
+
|
|
1463
|
+
|
|
1464
|
+
def extract(root: Path, files: list[str], rules: LangRules) -> list[RawSite]:
|
|
1465
|
+
"""Parse every file, find wrapper methods, then report sink calls and annotations,
|
|
1466
|
+
and last the query strings nothing claimed."""
|
|
1467
|
+
repo = Repo()
|
|
1468
|
+
for rel in files:
|
|
1469
|
+
text = read_text(root / rel)
|
|
1470
|
+
if text is None:
|
|
1471
|
+
continue
|
|
1472
|
+
try:
|
|
1473
|
+
repo.add(JavaFile(rel, text.encode("utf-8"), repo))
|
|
1474
|
+
except Exception: # one unreadable file must not stop the inventory
|
|
1475
|
+
continue
|
|
1476
|
+
for jf in repo.files:
|
|
1477
|
+
try:
|
|
1478
|
+
repo.named_queries.update(jf.named_queries())
|
|
1479
|
+
except Exception:
|
|
1480
|
+
continue
|
|
1481
|
+
# a method that hands its parameter to a sink is a sink for its callers; repeat for wrappers of wrappers
|
|
1482
|
+
known: set[tuple] = set()
|
|
1483
|
+
for _ in range(3):
|
|
1484
|
+
fresh: list[tuple[str, Wrapper]] = []
|
|
1485
|
+
for jf in repo.files:
|
|
1486
|
+
try:
|
|
1487
|
+
fresh.extend(jf.find_wrappers(rules))
|
|
1488
|
+
except Exception:
|
|
1489
|
+
continue
|
|
1490
|
+
added = False
|
|
1491
|
+
for fname, w in fresh:
|
|
1492
|
+
key = (w.call.id, w.index, w.inner.call.id if w.inner is not None else 0)
|
|
1493
|
+
if key in known or rules.sink_for(fname) is not None:
|
|
1494
|
+
continue
|
|
1495
|
+
known.add(key)
|
|
1496
|
+
repo.wrappers[fname].append(w)
|
|
1497
|
+
added = True
|
|
1498
|
+
if not added:
|
|
1499
|
+
break
|
|
1500
|
+
out: list[RawSite] = []
|
|
1501
|
+
for jf in repo.files:
|
|
1502
|
+
try:
|
|
1503
|
+
out.extend(jf.sites(rules))
|
|
1504
|
+
except Exception:
|
|
1505
|
+
continue
|
|
1506
|
+
# After every file's sites, so a constant used from another file is reported at its use
|
|
1507
|
+
# sites only. Largest first: a query built from smaller query strings claims them.
|
|
1508
|
+
candidates = []
|
|
1509
|
+
for jf in repo.files:
|
|
1510
|
+
try:
|
|
1511
|
+
candidates.extend(jf.orphan_candidates())
|
|
1512
|
+
except Exception:
|
|
1513
|
+
continue
|
|
1514
|
+
candidates.sort(key=lambda c: -len(c[3].src))
|
|
1515
|
+
for jf, s, top, res, call in candidates:
|
|
1516
|
+
if s.id in jf.consumed:
|
|
1517
|
+
continue
|
|
1518
|
+
try:
|
|
1519
|
+
out.append(jf.orphan_site(rules, top, res, call))
|
|
1520
|
+
except Exception:
|
|
1521
|
+
continue
|
|
1522
|
+
from . import orm_java # JPA / Spring Data / jOOQ / JDBI: JPQL to SQL, and sites for calls without a SQL string
|
|
1523
|
+
return orm_java.extend(root, repo, rules, out, files)
|
|
1524
|
+
|
|
1525
|
+
|
|
1526
|
+
def summary_extras() -> dict:
|
|
1527
|
+
from . import orm_java
|
|
1528
|
+
return orm_java.summary_extras()
|