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/rust.py
ADDED
|
@@ -0,0 +1,2378 @@
|
|
|
1
|
+
"""Rust call-site extractor.
|
|
2
|
+
|
|
3
|
+
Finds calls whose argument is SQL and resolves that argument statically:
|
|
4
|
+
string and raw-string literals, `concat!`, `format!` (positional, indexed,
|
|
5
|
+
named and inline-captured arguments), `include_str!`, local `let` bindings
|
|
6
|
+
with later `push_str` / `+=` / `write!`, `const` and `static` items in this
|
|
7
|
+
file and in other files, `.replace("{k}", v)` chains, and calls to functions
|
|
8
|
+
that return a string (arguments are bound to the callee's parameters).
|
|
9
|
+
|
|
10
|
+
A function that passes one of its own parameters to a sink is a wrapper: its
|
|
11
|
+
call site is recorded with resolution "parameter" and the function becomes a
|
|
12
|
+
sink for its callers.
|
|
13
|
+
|
|
14
|
+
Sink names in the rules: a bare name ("query") is a method call
|
|
15
|
+
(`client.query(sql)`); a name with `::` ("sqlx::query_as") is a path call
|
|
16
|
+
matched on its trailing segments with any turbofish removed, after the first
|
|
17
|
+
segment is expanded through the file's `use` lines.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
from collections import defaultdict
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
import tree_sitter_rust
|
|
28
|
+
from tree_sitter import Language, Node, Parser, Query, QueryCursor
|
|
29
|
+
|
|
30
|
+
from .base import LangRules, RawSite, is_test_path, looks_like_sql, read_text, trim
|
|
31
|
+
from .base import walk_tree
|
|
32
|
+
|
|
33
|
+
LANG = Language(tree_sitter_rust.language())
|
|
34
|
+
MAX_DEPTH = 48
|
|
35
|
+
CONST_NAME = re.compile(r"^_{0,2}[A-Z][A-Z0-9_]*$")
|
|
36
|
+
FUNC_STOP = ("function_item",)
|
|
37
|
+
LOOP_TYPES = ("for_expression", "while_expression", "loop_expression")
|
|
38
|
+
ITER_METHODS = {"map", "for_each", "filter_map", "flat_map", "try_for_each", "fold", "filter", "then", "and_then"}
|
|
39
|
+
ITER_RECEIVER = re.compile(r"\b(iter|iter_mut|into_iter|chunks|windows|drain|stream|buffer_unordered|buffered|enumerate|zip|keys|values|lines)\b")
|
|
40
|
+
# Methods that return the same text (or a view of it).
|
|
41
|
+
PASS_METHODS = {
|
|
42
|
+
"as_str", "to_string", "to_owned", "into", "clone", "as_ref", "borrow", "as_deref", "into_owned", "to_str",
|
|
43
|
+
"into_boxed_str", "trim", "trim_start", "trim_end", "trim_matches", "trim_end_matches", "trim_start_matches",
|
|
44
|
+
"unwrap", "expect", "unwrap_or_default", "into_string", "deref", "as_mut_str", "cloned", "copied", "leak",
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _PassMethods(set):
|
|
49
|
+
"""PASS_METHODS, plus the text conversions crates add (`sql.into_sql_str()`, `q.as_sql()`, `s.to_sql_string()`)."""
|
|
50
|
+
|
|
51
|
+
def __contains__(self, name: object) -> bool:
|
|
52
|
+
return set.__contains__(self, name) or (isinstance(name, str) and bool(PASS_CONVERSION.match(name)))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
PASS_CONVERSION = re.compile(r"^(?:into|as|to)_\w*(?:str|string|sql)$")
|
|
56
|
+
PASS_METHODS = _PassMethods(PASS_METHODS)
|
|
57
|
+
PASS_PATHS = {
|
|
58
|
+
"String::from", "str::to_string", "str::to_owned", "ToString::to_string", "ToOwned::to_owned", "Into::into",
|
|
59
|
+
"From::from", "Cow::Borrowed", "Cow::Owned", "Cow::from", "Arc::from", "Box::from", "Rc::from", "Arc::new",
|
|
60
|
+
"Box::new", "Some", "Ok", "std::convert::identity", "format_args", "String::from_str", "Into::<String>::into",
|
|
61
|
+
}
|
|
62
|
+
LAZY_PATHS = {"LazyLock::new", "Lazy::new", "LazyCell::new", "OnceLock::from", "OnceCell::from"}
|
|
63
|
+
FORMAT_MACROS = {"format", "formatdoc", "format_args", "indoc", "concat", "include_str", "concatcp", "formatcp",
|
|
64
|
+
"const_format::concatcp", "const_format::formatcp", "std::format", "std::concat", "std::include_str",
|
|
65
|
+
"indoc::indoc", "indoc::formatdoc", "write", "writeln"}
|
|
66
|
+
# A macro whose arguments contain something like a database call. Its `!` is blanked and the
|
|
67
|
+
# file parsed again, so `tokio::try_join!(a.query(..), ..)` is parsed as calls, not left as tokens.
|
|
68
|
+
SINKY = re.compile(rb"\bquery\w*\s*(?:::\s*<[^()]*>\s*)?\(|\bsqlx\s*::|QueryBuilder|\b\w*(?:sql|query|execute|fetch)\w*\s*\(", re.I)
|
|
69
|
+
KEEP_MACROS = {"format", "formatdoc", "format_args", "indoc", "concat", "include_str", "concatcp", "formatcp", "write",
|
|
70
|
+
"writeln", "matches", "json", "println", "eprintln", "print", "eprint", "info", "debug", "warn", "error",
|
|
71
|
+
"trace", "panic", "unreachable", "todo", "unimplemented", "macro_rules", "assert", "assert_eq",
|
|
72
|
+
"assert_ne", "debug_assert", "debug_assert_eq", "debug_assert_ne", "stringify", "env", "cfg", "line",
|
|
73
|
+
"file", "column", "module_path", "compile_error", "include", "include_bytes", "lazy_static",
|
|
74
|
+
"thread_local", "task_local", "select", "html", "quote"}
|
|
75
|
+
# Calls whose string arguments are comparisons, not SQL that reaches a database.
|
|
76
|
+
NOT_A_SINK = re.compile(
|
|
77
|
+
r"(^|[.:\s])(contains|starts_with|ends_with|find|rfind|matches|strip_prefix|strip_suffix|eq|ne|split|split_once|"
|
|
78
|
+
r"assert|assert_eq|assert_ne|debug_assert|debug_assert_eq|eq_ignore_ascii_case|trim_start_matches|expect|"
|
|
79
|
+
r"trim_end_matches|rsplit|position|any|all|count|is_match|insert|get|remove|contains_key|unwrap_or|"
|
|
80
|
+
r"context|with_context|println|eprintln|panic|unreachable|info|debug|warn|error|trace|ensure|bail|anyhow)\s*$"
|
|
81
|
+
)
|
|
82
|
+
STR_TYPE = re.compile(r"\b(str|String|Cow|Into|AsRef|Display|ToString|Arguments)\b")
|
|
83
|
+
RECEIVER = re.compile(r"(^|_)(client|clickhouse|ch|conn|connection|db|pool|tx|txn|transaction|session|pg|postgres|database|executor)$", re.I)
|
|
84
|
+
BUILDER_APPEND = re.compile(r"^(push|append|add|write|and_where|or_where|where_|and|or)")
|
|
85
|
+
SQLISH_NAME = re.compile(r"(sql|query|stmt|statement|ddl|template)", re.I)
|
|
86
|
+
DISTINCT_METHOD = re.compile(r"(sql|query|stmt|statement|ddl|exec|fetch|select|scalar|command)", re.I)
|
|
87
|
+
HTTP_CHAIN = re.compile(r"\.(get|post|put|patch|delete|head|request|uri|url|builder|form|json|header|bearer_auth)\s*\(")
|
|
88
|
+
STRING_ESC = re.compile(r"\\(?:\r?\n\s*|x[0-9a-fA-F]{2}|u\{[0-9a-fA-F_]{1,8}\}|[\s\S])")
|
|
89
|
+
SIMPLE_ESC = {"n": "\n", "r": "\r", "t": "\t", "0": "\0", "\\": "\\", '"': '"', "'": "'"}
|
|
90
|
+
FMT_FIELD = re.compile(r"\{\{|\}\}|\{([^{}]*)\}")
|
|
91
|
+
TOKEN_PATH = re.compile(
|
|
92
|
+
r"^[&*\s]*((?:[A-Za-z_]\w*\s*::\s*)*[A-Za-z_]\w*)"
|
|
93
|
+
r"((?:\s*\.\s*(?:as_str|to_string|to_owned|clone|into|as_ref|trim|to_str)\s*\(\s*\))*)$"
|
|
94
|
+
)
|
|
95
|
+
NUMBER = re.compile(r"^-?[0-9][0-9_]*(?:\.[0-9_]+)?")
|
|
96
|
+
# For the argument of a sink: any statement verb, any case. Wider than base.looks_like_sql,
|
|
97
|
+
# which also has to reject prose in strings that are not attached to a database call.
|
|
98
|
+
SINK_SQL = re.compile(
|
|
99
|
+
r"^\s*(?:--[^\n]*\n\s*|/\*[\s\S]*?\*/\s*)*\(*\s*(?:SELECT|WITH|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|TRUNCATE|SET|SHOW|"
|
|
100
|
+
r"EXPLAIN|DESCRIBE|DESC|OPTIMIZE|SYSTEM|GRANT|REVOKE|BEGIN|COMMIT|ROLLBACK|LOCK|ANALYZE|VACUUM|MERGE|REPLACE|"
|
|
101
|
+
r"EXISTS|ATTACH|DETACH|RENAME|KILL|USE|CALL|DO|COPY|LISTEN|NOTIFY|UNLISTEN|REFRESH|REINDEX|SAVEPOINT|RELEASE|"
|
|
102
|
+
r"PRAGMA|DECLARE|FETCH|CHECK|EXCHANGE|UNDROP|WATCH|VALUES|START|END|ABORT|RESET|DISCARD|CLUSTER|COMMENT|"
|
|
103
|
+
r"PREPARE|EXECUTE|DEALLOCATE)\b", re.I)
|
|
104
|
+
SQL_WORDS = re.compile(r"\b(?:SELECT|FROM|WHERE|INSERT\s+INTO|UPDATE|DELETE|JOIN|GROUP\s+BY|ORDER\s+BY|LIMIT|SETTINGS|VALUES)\b")
|
|
105
|
+
# sqlx's database type named at one call (turbofish, the pool or connection handed to it) or in a whole file
|
|
106
|
+
SQLX_DB_CALL = (("sqlite", re.compile(r"<\s*(?:_\s*,\s*)?Sqlite\b|\bsqlite\w*(?:\.|\(\))|\bSqlite(?:Pool|Connection)\b")),
|
|
107
|
+
("postgres", re.compile(r"<\s*(?:_\s*,\s*)?Postgres\b|\bpg_?pool\b|\bPg(?:Pool|Connection)\b|\bpostgres\w*(?:\.|\(\))")),
|
|
108
|
+
("mysql", re.compile(r"<\s*(?:_\s*,\s*)?MySql\b|\bMySql(?:Pool|Connection)\b|\bmysql\w*(?:\.|\(\))")))
|
|
109
|
+
SQLX_DB_FILE = (("sqlite", re.compile(r"\bsqlx::sqlite\b|\bSqlite(?:Pool|Connection|Row|ConnectOptions|QueryResult|Arguments)?\b")),
|
|
110
|
+
("postgres", re.compile(r"\bsqlx::postgres\b|\bPg(?:Pool|Connection|Row|ConnectOptions|QueryResult|Arguments|Database)\b|\bPostgres\b")),
|
|
111
|
+
("mysql", re.compile(r"\bsqlx::mysql\b|\bMySql(?:Pool|Connection|Row|ConnectOptions|QueryResult|Arguments)?\b")))
|
|
112
|
+
TEXT_PARAM = re.compile(
|
|
113
|
+
r"^(&('\w+)?(mut)?(str|String)|String|(std::borrow::)?Cow<('\w+,)?str>|impl(Into<String>|AsRef<str>|Into<Cow<('\w+,)?str>>|\w*Sql\w*Str\w*|Into<\w*Sql\w*>)"
|
|
114
|
+
r"|Arc<str>|Box<str>|&Arc<str>|[A-Z]\w?)$"
|
|
115
|
+
)
|
|
116
|
+
TEST_FILE = re.compile(r"(^|/)(tests?|[^/]*_tests?|test_[^/]*|testing|test_support|test_helpers|bench[^/]*)\.rs$|(^|/)benches/")
|
|
117
|
+
TEST_ATTR = re.compile(r"#\[\s*(?:cfg\s*\(\s*(?:test\b|all\s*\(\s*test\b)|(?:\w+::)*test\b|rstest\b|test_case\b)")
|
|
118
|
+
|
|
119
|
+
INDEX_QUERY = Query(LANG, """
|
|
120
|
+
(const_item) @const
|
|
121
|
+
(static_item) @const
|
|
122
|
+
(function_item) @fn
|
|
123
|
+
(function_signature_item) @sig
|
|
124
|
+
(use_declaration) @use
|
|
125
|
+
(mod_item) @mod
|
|
126
|
+
(macro_definition) @macro
|
|
127
|
+
(inner_attribute_item) @inner
|
|
128
|
+
""")
|
|
129
|
+
STRING_QUERY = Query(LANG, "(string_literal) @s (raw_string_literal) @s")
|
|
130
|
+
MACRO_QUERY = Query(LANG, "(macro_invocation) @m")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
STRING_MACRO_DEF = re.compile(rb"macro_rules!\s+(\w+)\s*\{\s*\([^)]*\)\s*=>\s*\{\s*(\w+)\s*!")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def string_macros(sources: list[bytes]) -> set[str]:
|
|
137
|
+
"""Names of `macro_rules!` macros that expand to `concat!` / `format!` (directly or through each other)."""
|
|
138
|
+
inner: dict[str, str] = {}
|
|
139
|
+
for src in sources:
|
|
140
|
+
if b"macro_rules!" in src:
|
|
141
|
+
for m in STRING_MACRO_DEF.finditer(src):
|
|
142
|
+
inner[m.group(1).decode()] = m.group(2).decode()
|
|
143
|
+
out = {"concat", "format", "concatcp", "formatcp", "indoc", "formatdoc", "include_str"}
|
|
144
|
+
changed = True
|
|
145
|
+
while changed:
|
|
146
|
+
changed = False
|
|
147
|
+
for name, first in inner.items():
|
|
148
|
+
if first in out and name not in out:
|
|
149
|
+
out.add(name)
|
|
150
|
+
changed = True
|
|
151
|
+
return out
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def parse_rust(src: bytes, keep: set[str] | frozenset = frozenset()):
|
|
155
|
+
"""Parse, turning macros that hold database calls into plain calls (same byte offsets)."""
|
|
156
|
+
parser = Parser(LANG)
|
|
157
|
+
tree = parser.parse(src)
|
|
158
|
+
if not SINKY.search(src) or b"!" not in src:
|
|
159
|
+
return tree
|
|
160
|
+
for _ in range(4):
|
|
161
|
+
offsets = []
|
|
162
|
+
for m in QueryCursor(MACRO_QUERY).captures(tree.root_node).get("m", []):
|
|
163
|
+
mac = m.child_by_field_name("macro")
|
|
164
|
+
name = mac.text.split(b"::")[-1].strip().decode("utf-8", "replace") if mac is not None else ""
|
|
165
|
+
if not name or name in KEEP_MACROS or name in keep:
|
|
166
|
+
continue
|
|
167
|
+
kids = m.children
|
|
168
|
+
tt = kids[-1] if kids else None
|
|
169
|
+
if tt is None or tt.type != "token_tree" or not tt.children or tt.children[0].type != "(":
|
|
170
|
+
continue
|
|
171
|
+
if not SINKY.search(tt.text):
|
|
172
|
+
continue
|
|
173
|
+
bang = next((c for c in kids if c.type == "!"), None)
|
|
174
|
+
if bang is not None:
|
|
175
|
+
offsets.append(bang.start_byte)
|
|
176
|
+
if not offsets:
|
|
177
|
+
break
|
|
178
|
+
buf = bytearray(src)
|
|
179
|
+
for o in offsets:
|
|
180
|
+
buf[o] = 0x20
|
|
181
|
+
src = bytes(buf)
|
|
182
|
+
tree = parser.parse(src)
|
|
183
|
+
return tree
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class Res:
|
|
187
|
+
"""A resolved string: text with «expr» placeholders, and how it was reached."""
|
|
188
|
+
|
|
189
|
+
__slots__ = ("text", "dynamic", "via_name", "from_file", "param", "binder", "alts")
|
|
190
|
+
|
|
191
|
+
def __init__(self, text: str, dynamic: bool = False, via_name: bool = False, from_file: bool = False,
|
|
192
|
+
param: str = "", binder: Node | None = None):
|
|
193
|
+
self.alts: tuple = () # the whole statement of each if / else arm, when `text` names them as «or: ...»
|
|
194
|
+
self.text = text
|
|
195
|
+
self.dynamic = dynamic
|
|
196
|
+
self.via_name = via_name
|
|
197
|
+
self.from_file = from_file
|
|
198
|
+
self.param = param # set when the value is exactly a parameter of the enclosing function
|
|
199
|
+
self.binder = binder # the closure parameter list, when the parameter is a closure's
|
|
200
|
+
|
|
201
|
+
@property
|
|
202
|
+
def resolution(self) -> str:
|
|
203
|
+
if self.param:
|
|
204
|
+
return "parameter"
|
|
205
|
+
if self.dynamic:
|
|
206
|
+
return "template"
|
|
207
|
+
if self.from_file:
|
|
208
|
+
return "file"
|
|
209
|
+
return "constant" if self.via_name else "literal"
|
|
210
|
+
|
|
211
|
+
def named(self) -> "Res":
|
|
212
|
+
out = Res(self.text, self.dynamic, True, self.from_file, self.param, self.binder)
|
|
213
|
+
out.alts = self.alts
|
|
214
|
+
return out
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _join(parts: list[Res]) -> Res:
|
|
218
|
+
if len(parts) == 1:
|
|
219
|
+
return parts[0]
|
|
220
|
+
return Res("".join(p.text for p in parts), any(p.dynamic for p in parts), any(p.via_name for p in parts),
|
|
221
|
+
any(p.from_file for p in parts))
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _txt(node: Node) -> str:
|
|
225
|
+
return node.text.decode("utf-8", "replace")
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _ph_text(text: str) -> Res:
|
|
229
|
+
return Res("«" + trim(text, 60).replace("»", ">") + "»", dynamic=True)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _ph(node: Node) -> Res:
|
|
233
|
+
return _ph_text(_txt(node))
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _walk(node: Node, stop: tuple[str, ...] = ()):
|
|
237
|
+
"""Depth-first over descendants, not descending into node types in `stop`."""
|
|
238
|
+
return walk_tree(node, stop)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _unescape(m: re.Match) -> str:
|
|
242
|
+
s = m.group(0)
|
|
243
|
+
c = s[1]
|
|
244
|
+
if c in SIMPLE_ESC:
|
|
245
|
+
return SIMPLE_ESC[c]
|
|
246
|
+
if c in "\r\n":
|
|
247
|
+
return "" # line continuation: the newline and the indent after it are dropped
|
|
248
|
+
try:
|
|
249
|
+
if c == "x":
|
|
250
|
+
return chr(int(s[2:], 16))
|
|
251
|
+
if c == "u":
|
|
252
|
+
return chr(int(s[3:-1].replace("_", ""), 16))
|
|
253
|
+
except ValueError:
|
|
254
|
+
pass
|
|
255
|
+
return s
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def decode_literal(text: str) -> str | None:
|
|
259
|
+
"""The value of a Rust string, raw string, byte string or char literal."""
|
|
260
|
+
m = re.match(r'^b?r(#*)"', text)
|
|
261
|
+
if m:
|
|
262
|
+
end = len(text) - 1 - len(m.group(1))
|
|
263
|
+
return text[m.end():end] if end >= m.end() else None
|
|
264
|
+
if text.startswith("b"):
|
|
265
|
+
text = text[1:]
|
|
266
|
+
if len(text) >= 2 and text[0] == text[-1] and text[0] in "\"'":
|
|
267
|
+
return STRING_ESC.sub(_unescape, text[1:-1])
|
|
268
|
+
return None
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _split_top(text: str, sep: str = ",") -> list[str]:
|
|
272
|
+
"""Split on `sep` outside brackets."""
|
|
273
|
+
out, depth, cur = [], 0, []
|
|
274
|
+
for ch in text:
|
|
275
|
+
if ch in "({[<":
|
|
276
|
+
depth += 1
|
|
277
|
+
elif ch in ")}]>":
|
|
278
|
+
depth -= 1
|
|
279
|
+
if ch == sep and depth == 0:
|
|
280
|
+
out.append("".join(cur))
|
|
281
|
+
cur = []
|
|
282
|
+
else:
|
|
283
|
+
cur.append(ch)
|
|
284
|
+
out.append("".join(cur))
|
|
285
|
+
return out
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def expand_use(text: str) -> dict[str, list[str]]:
|
|
289
|
+
"""`use a::{b, c::d as e};` -> {"b": [a, b], "e": [a, c, d]}."""
|
|
290
|
+
text = re.sub(r"//[^\n]*", "", text)
|
|
291
|
+
m = re.search(r"\buse\s+([\s\S]*?);?\s*$", text)
|
|
292
|
+
out: dict[str, list[str]] = {}
|
|
293
|
+
if not m:
|
|
294
|
+
return out
|
|
295
|
+
|
|
296
|
+
def go(prefix: list[str], body: str) -> None:
|
|
297
|
+
body = body.strip()
|
|
298
|
+
if not body:
|
|
299
|
+
return
|
|
300
|
+
brace = body.find("{")
|
|
301
|
+
if brace >= 0 and body.endswith("}"):
|
|
302
|
+
head = [s.strip() for s in body[:brace].split("::") if s.strip()]
|
|
303
|
+
for part in _split_top(body[brace + 1:-1]):
|
|
304
|
+
go(prefix + head, part)
|
|
305
|
+
return
|
|
306
|
+
alias = None
|
|
307
|
+
if " as " in body:
|
|
308
|
+
body, alias = (s.strip() for s in body.rsplit(" as ", 1))
|
|
309
|
+
segs = [s.strip() for s in body.split("::") if s.strip()]
|
|
310
|
+
if segs and segs[-1] == "*":
|
|
311
|
+
out.setdefault("*", []).append(prefix + segs[:-1]) # glob imports, under the key "*"
|
|
312
|
+
return
|
|
313
|
+
if not segs:
|
|
314
|
+
return
|
|
315
|
+
full = prefix + segs
|
|
316
|
+
if segs[-1] == "self":
|
|
317
|
+
full = full[:-1]
|
|
318
|
+
if full:
|
|
319
|
+
out[alias or full[-1]] = full
|
|
320
|
+
go([], m.group(1))
|
|
321
|
+
return out
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _mod_path(rel: str) -> tuple[list[str], int]:
|
|
325
|
+
"""Module path of a file, and how many leading segments are the crate root.
|
|
326
|
+
|
|
327
|
+
crates/my-crate/src/a/b.rs -> ([crates, my_crate, a, b], 2)"""
|
|
328
|
+
parts = rel[:-3].replace("-", "_").split("/") if rel.endswith(".rs") else rel.split("/")
|
|
329
|
+
root = parts.index("src") if "src" in parts else 0
|
|
330
|
+
return [p for p in parts if p not in ("src", "mod", "lib", "main")], root
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _type_name(node: Node | None) -> str:
|
|
334
|
+
"""`Bar<T>` -> Bar, `a::Bar` -> Bar, `&mut Bar` -> Bar."""
|
|
335
|
+
if node is None:
|
|
336
|
+
return ""
|
|
337
|
+
m = re.findall(r"[A-Za-z_]\w*", re.sub(r"<[\s\S]*$", "", _txt(node)))
|
|
338
|
+
m = [x for x in m if x not in ("mut", "dyn", "impl")]
|
|
339
|
+
return m[-1] if m else ""
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
class Callee:
|
|
343
|
+
__slots__ = ("name", "is_method", "segs", "receiver", "text")
|
|
344
|
+
|
|
345
|
+
def __init__(self, name: str, is_method: bool, segs: list[str], receiver: Node | None, text: str):
|
|
346
|
+
self.name = name
|
|
347
|
+
self.is_method = is_method
|
|
348
|
+
self.segs = segs
|
|
349
|
+
self.receiver = receiver
|
|
350
|
+
self.text = text
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def callee_of(call: Node) -> Callee | None:
|
|
354
|
+
fn = call.child_by_field_name("function")
|
|
355
|
+
if fn is None:
|
|
356
|
+
return None
|
|
357
|
+
text = _txt(fn)
|
|
358
|
+
if fn.type == "generic_function":
|
|
359
|
+
fn = fn.child_by_field_name("function")
|
|
360
|
+
if fn is None:
|
|
361
|
+
return None
|
|
362
|
+
if fn.type == "field_expression":
|
|
363
|
+
field = fn.child_by_field_name("field")
|
|
364
|
+
if field is None or field.type != "field_identifier":
|
|
365
|
+
return None
|
|
366
|
+
return Callee(_txt(field), True, [_txt(field)], fn.child_by_field_name("value"), text)
|
|
367
|
+
if fn.type in ("identifier", "scoped_identifier"):
|
|
368
|
+
raw = re.sub(r"\s+", "", _txt(fn))
|
|
369
|
+
prev = None
|
|
370
|
+
while prev != raw: # drop turbofish and generic arguments, innermost first
|
|
371
|
+
prev = raw
|
|
372
|
+
raw = re.sub(r"(::)?<[^<>]*>", "", raw)
|
|
373
|
+
segs = [s for s in raw.split("::") if s]
|
|
374
|
+
if not segs or not all(re.match(r"^\w+$", s) for s in segs):
|
|
375
|
+
return None
|
|
376
|
+
return Callee(segs[-1], False, segs, None, text)
|
|
377
|
+
return None
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
class Wrapper:
|
|
381
|
+
__slots__ = ("name", "is_method", "index", "engine", "impl_type", "rel", "mod")
|
|
382
|
+
|
|
383
|
+
def __init__(self, name: str, is_method: bool, index: int, engine: str, impl_type: str, rel: str):
|
|
384
|
+
self.name, self.is_method, self.index = name, is_method, index
|
|
385
|
+
self.engine, self.impl_type, self.rel = engine, impl_type, rel
|
|
386
|
+
self.mod = _mod_path(rel)[0]
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
class Ctx:
|
|
390
|
+
"""State shared by every file of one run."""
|
|
391
|
+
|
|
392
|
+
def __init__(self, root: Path, rules: LangRules):
|
|
393
|
+
self.root = root
|
|
394
|
+
self.rules = rules
|
|
395
|
+
self.files: dict[str, "RsFile"] = {}
|
|
396
|
+
self.consts: dict[str, list[tuple["RsFile", Node]]] = defaultdict(list)
|
|
397
|
+
self.fns: dict[str, list[tuple["RsFile", Node]]] = defaultdict(list)
|
|
398
|
+
self.macros: dict[str, list[tuple["RsFile", Node]]] = defaultdict(list)
|
|
399
|
+
self.string_macros: set[str] = set()
|
|
400
|
+
self.macro_binds: list[dict] = []
|
|
401
|
+
self.wrappers: dict[str, list[Wrapper]] = defaultdict(list)
|
|
402
|
+
self.field_sinks: set[tuple[str, str, str]] = set() # (file, impl type, field) passed to a sink
|
|
403
|
+
self.field_ctors: set[tuple[str, str]] = set() # (type, constructor) that fills such a field
|
|
404
|
+
self.test_prefixes: set[str] = set()
|
|
405
|
+
self.memo: dict[tuple[int, int], Res | None] = {}
|
|
406
|
+
self.resolving: set[tuple[int, int]] = set()
|
|
407
|
+
self.touched: list[tuple[str, int]] | None = None
|
|
408
|
+
self.consumed: set[tuple[str, int]] = set()
|
|
409
|
+
self.include_cache: dict[str, str | None] = {}
|
|
410
|
+
self.budget = 0
|
|
411
|
+
self._queries: dict[frozenset, tuple[re.Pattern, Query]] = {}
|
|
412
|
+
self.method_sinks: dict[str, str] = {}
|
|
413
|
+
self.path_sinks: list[tuple[list[str], str]] = []
|
|
414
|
+
for s in rules.sinks:
|
|
415
|
+
for name in s.names:
|
|
416
|
+
if "::" in name:
|
|
417
|
+
self.path_sinks.append((name.split("::"), s.engine))
|
|
418
|
+
else:
|
|
419
|
+
self.method_sinks.setdefault(name, s.engine)
|
|
420
|
+
self.sink_args = {name: s.args for s in rules.sinks for name in s.names}
|
|
421
|
+
|
|
422
|
+
def call_query(self, names: set[str]) -> tuple[re.Pattern, Query]:
|
|
423
|
+
"""A byte pre-filter and a tree query for calls whose callee ends in one of `names`."""
|
|
424
|
+
key = frozenset(names)
|
|
425
|
+
hit = self._queries.get(key)
|
|
426
|
+
if hit is None:
|
|
427
|
+
ordered = sorted(names)
|
|
428
|
+
pre = re.compile(rb"\b(?:" + b"|".join(re.escape(n.encode()) for n in ordered) + rb")\b")
|
|
429
|
+
alts = " ".join('"' + n + '"' for n in ordered)
|
|
430
|
+
query = Query(LANG, f"""
|
|
431
|
+
(call_expression function: (field_expression field: (field_identifier) @n (#any-of? @n {alts}))) @c
|
|
432
|
+
(call_expression function: (generic_function function: (field_expression field: (field_identifier) @n (#any-of? @n {alts})))) @c
|
|
433
|
+
(call_expression function: (identifier) @n (#any-of? @n {alts})) @c
|
|
434
|
+
(call_expression function: (scoped_identifier name: (identifier) @n (#any-of? @n {alts}))) @c
|
|
435
|
+
(call_expression function: (generic_function function: (identifier) @n (#any-of? @n {alts}))) @c
|
|
436
|
+
(call_expression function: (generic_function function: (scoped_identifier name: (identifier) @n (#any-of? @n {alts})))) @c
|
|
437
|
+
""")
|
|
438
|
+
hit = self._queries[key] = (pre, query)
|
|
439
|
+
return hit
|
|
440
|
+
|
|
441
|
+
def is_test_file(self, rel: str) -> bool:
|
|
442
|
+
if is_test_path(rel) or TEST_FILE.search(rel):
|
|
443
|
+
return True
|
|
444
|
+
return any(rel == p + ".rs" or rel.startswith(p + "/") for p in self.test_prefixes)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
class RsFile:
|
|
448
|
+
def __init__(self, rel: str, src: bytes, ctx: Ctx):
|
|
449
|
+
self.rel = rel
|
|
450
|
+
self.ctx = ctx
|
|
451
|
+
self.src = src
|
|
452
|
+
self.tree = parse_rust(src, ctx.string_macros)
|
|
453
|
+
self.root = self.tree.root_node
|
|
454
|
+
self.mod_path, self.crate_len = _mod_path(rel)
|
|
455
|
+
# `super` is relative to the module this file is: a/b.rs and a/b/mod.rs are both module a::b
|
|
456
|
+
self.is_dir_mod = os.path.basename(rel) in ("mod.rs", "lib.rs", "main.rs")
|
|
457
|
+
self.consts: dict[str, list[Node]] = defaultdict(list)
|
|
458
|
+
self.fns: dict[str, list[Node]] = defaultdict(list)
|
|
459
|
+
self.macros: dict[str, Node] = {}
|
|
460
|
+
self.uses: dict[str, list[str]] = {}
|
|
461
|
+
self.globs: list[list[str]] = []
|
|
462
|
+
self._tuple_idx: dict[tuple[int, str], int] = {}
|
|
463
|
+
self.crates: set[str] = set()
|
|
464
|
+
self._sqlx_file: str | None = None
|
|
465
|
+
self.cfg_test = False
|
|
466
|
+
self._scope_cache: dict[int, tuple[dict, dict]] = {}
|
|
467
|
+
self._test_cache: dict[int, bool] = {}
|
|
468
|
+
self._index()
|
|
469
|
+
|
|
470
|
+
# ---- indexing -------------------------------------------------------
|
|
471
|
+
def _index(self) -> None:
|
|
472
|
+
caps = QueryCursor(INDEX_QUERY).captures(self.root)
|
|
473
|
+
for n in caps.get("const", []):
|
|
474
|
+
name = n.child_by_field_name("name")
|
|
475
|
+
if name is not None and n.child_by_field_name("value") is not None:
|
|
476
|
+
self.consts[_txt(name)].append(n)
|
|
477
|
+
for n in caps.get("fn", []):
|
|
478
|
+
name = n.child_by_field_name("name")
|
|
479
|
+
if name is not None:
|
|
480
|
+
self.fns[_txt(name)].append(n)
|
|
481
|
+
for n in caps.get("macro", []):
|
|
482
|
+
name = n.child_by_field_name("name")
|
|
483
|
+
if name is not None:
|
|
484
|
+
self.macros.setdefault(_txt(name), n)
|
|
485
|
+
for n in caps.get("use", []):
|
|
486
|
+
for local, full in expand_use(_txt(n)).items():
|
|
487
|
+
if local == "*":
|
|
488
|
+
self.globs.extend(g for g in full if g)
|
|
489
|
+
continue
|
|
490
|
+
self.uses.setdefault(local, full)
|
|
491
|
+
self.crates.add(full[0])
|
|
492
|
+
for n in caps.get("inner", []):
|
|
493
|
+
if n.parent is self.root and re.search(r"cfg\s*\(\s*test\b", _txt(n)):
|
|
494
|
+
self.cfg_test = True
|
|
495
|
+
base = os.path.dirname(self.rel)
|
|
496
|
+
stem = os.path.basename(self.rel)[:-3]
|
|
497
|
+
here = base if stem in ("mod", "lib", "main") else (base + "/" + stem if base else stem)
|
|
498
|
+
for n in caps.get("mod", []):
|
|
499
|
+
if n.child_by_field_name("body") is None and self._has_test_attr(n):
|
|
500
|
+
name = n.child_by_field_name("name")
|
|
501
|
+
if name is not None:
|
|
502
|
+
self.ctx.test_prefixes.add((here + "/" if here else "") + _txt(name))
|
|
503
|
+
for m in re.finditer(rb"\b([a-z_][a-z0-9_]*)::", self.src):
|
|
504
|
+
self.crates.add(m.group(1).decode())
|
|
505
|
+
|
|
506
|
+
@staticmethod
|
|
507
|
+
def _has_test_attr(item: Node) -> bool:
|
|
508
|
+
p = item.prev_named_sibling
|
|
509
|
+
while p is not None and p.type in ("attribute_item", "line_comment", "block_comment"):
|
|
510
|
+
if p.type == "attribute_item" and TEST_ATTR.search(_txt(p)):
|
|
511
|
+
return True
|
|
512
|
+
p = p.prev_named_sibling
|
|
513
|
+
return False
|
|
514
|
+
|
|
515
|
+
def file_engine(self) -> str:
|
|
516
|
+
imports = self.ctx.rules.imports
|
|
517
|
+
engines = {imports[c] for c in self.crates if c in imports}
|
|
518
|
+
one = next(iter(engines)) if len(engines) == 1 else ""
|
|
519
|
+
return self.sqlx_engine(None, one)
|
|
520
|
+
|
|
521
|
+
def sqlx_engine(self, node: Node | None, engine: str) -> str:
|
|
522
|
+
"""sqlx is generic over its database: `query::<Sqlite>(..)`, `.execute(db.sqlite.pool())`, or a file that only
|
|
523
|
+
names SQLite (`SqlitePool`, `sqlx::sqlite`) or MySQL types decides instead of the sink's Postgres default."""
|
|
524
|
+
if engine not in ("postgres", "") or b"sqlx" not in self.src and "sqlx" not in self.crates:
|
|
525
|
+
return engine
|
|
526
|
+
if node is not None:
|
|
527
|
+
stmt = node
|
|
528
|
+
while stmt.parent is not None and stmt.type not in ("expression_statement", "let_declaration", "block"):
|
|
529
|
+
stmt = stmt.parent
|
|
530
|
+
m = {e for e, rx in SQLX_DB_CALL if rx.search(_txt(stmt)[:2000])}
|
|
531
|
+
if len(m) == 1:
|
|
532
|
+
return m.pop()
|
|
533
|
+
if self._sqlx_file is None:
|
|
534
|
+
text = self.src.decode("utf-8", "replace")
|
|
535
|
+
found = {e for e, rx in SQLX_DB_FILE if rx.search(text)}
|
|
536
|
+
self._sqlx_file = found.pop() if len(found) == 1 else ""
|
|
537
|
+
return self._sqlx_file or engine
|
|
538
|
+
|
|
539
|
+
# ---- tree helpers ---------------------------------------------------
|
|
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
|
+
def _impl_type(self, node: Node) -> str:
|
|
550
|
+
impl = self._enclosing(node, ("impl_item", "trait_item"))
|
|
551
|
+
if impl is None:
|
|
552
|
+
return ""
|
|
553
|
+
return _type_name(impl.child_by_field_name("type") or impl.child_by_field_name("name"))
|
|
554
|
+
|
|
555
|
+
def symbol(self, node: Node) -> str:
|
|
556
|
+
names: list[str] = []
|
|
557
|
+
n = node.parent
|
|
558
|
+
while n is not None:
|
|
559
|
+
if n.type == "function_item":
|
|
560
|
+
nm = n.child_by_field_name("name")
|
|
561
|
+
if nm is not None:
|
|
562
|
+
names.append(_txt(nm))
|
|
563
|
+
elif n.type in ("impl_item", "trait_item"):
|
|
564
|
+
t = _type_name(n.child_by_field_name("type") or n.child_by_field_name("name"))
|
|
565
|
+
if t:
|
|
566
|
+
names.append(t)
|
|
567
|
+
elif n.type in ("const_item", "static_item") and not names:
|
|
568
|
+
nm = n.child_by_field_name("name")
|
|
569
|
+
if nm is not None:
|
|
570
|
+
names.append(_txt(nm))
|
|
571
|
+
n = n.parent
|
|
572
|
+
return "::".join(reversed(names))
|
|
573
|
+
|
|
574
|
+
def in_loop(self, node: Node) -> bool:
|
|
575
|
+
child, n = node, node.parent
|
|
576
|
+
while n is not None and n.type != "function_item":
|
|
577
|
+
if n.type in LOOP_TYPES:
|
|
578
|
+
body = n.child_by_field_name("body")
|
|
579
|
+
if body is not None and body.start_byte <= node.start_byte and node.end_byte <= body.end_byte:
|
|
580
|
+
return True
|
|
581
|
+
elif n.type == "closure_expression":
|
|
582
|
+
args = n.parent
|
|
583
|
+
call = args.parent if args is not None else None
|
|
584
|
+
if args is not None and args.type == "arguments" and call is not None:
|
|
585
|
+
c = callee_of(call)
|
|
586
|
+
if c is not None and c.is_method and c.name in ITER_METHODS and c.receiver is not None:
|
|
587
|
+
if c.name in ("for_each", "try_for_each", "flat_map", "filter_map", "fold") or \
|
|
588
|
+
ITER_RECEIVER.search(_txt(c.receiver)[-200:]):
|
|
589
|
+
return True
|
|
590
|
+
child, n = n, n.parent
|
|
591
|
+
return False
|
|
592
|
+
|
|
593
|
+
def is_test_node(self, node: Node) -> bool:
|
|
594
|
+
n = node.parent
|
|
595
|
+
chain = []
|
|
596
|
+
result = False
|
|
597
|
+
while n is not None:
|
|
598
|
+
if n.type in ("function_item", "mod_item"):
|
|
599
|
+
cached = self._test_cache.get(n.id)
|
|
600
|
+
if cached is not None:
|
|
601
|
+
result = cached
|
|
602
|
+
break
|
|
603
|
+
chain.append(n)
|
|
604
|
+
if self._has_test_attr(n):
|
|
605
|
+
result = True
|
|
606
|
+
break
|
|
607
|
+
n = n.parent
|
|
608
|
+
for c in chain:
|
|
609
|
+
self._test_cache[c.id] = result
|
|
610
|
+
return result
|
|
611
|
+
|
|
612
|
+
# ---- scopes ---------------------------------------------------------
|
|
613
|
+
def _scope(self, func: Node) -> tuple[dict[str, list[Node]], dict[str, list[tuple[Node, str, object]]]]:
|
|
614
|
+
"""Bindings and mutations inside one function body, by variable name.
|
|
615
|
+
|
|
616
|
+
lets[name] let declarations (and other binders, value unknown) in source order
|
|
617
|
+
muts[name] (node, kind, payload): push | bind | assign | write | opaque | clear
|
|
618
|
+
"""
|
|
619
|
+
cached = self._scope_cache.get(func.id)
|
|
620
|
+
if cached is not None:
|
|
621
|
+
return cached
|
|
622
|
+
lets: dict[str, list[Node]] = defaultdict(list)
|
|
623
|
+
muts: dict[str, list[tuple[Node, str, object]]] = defaultdict(list)
|
|
624
|
+
body = func.child_by_field_name("body") or func
|
|
625
|
+
for n in _walk(body, stop=FUNC_STOP):
|
|
626
|
+
t = n.type
|
|
627
|
+
if t == "let_declaration":
|
|
628
|
+
pat = n.child_by_field_name("pattern")
|
|
629
|
+
if pat is None:
|
|
630
|
+
continue
|
|
631
|
+
if pat.type == "identifier":
|
|
632
|
+
lets[_txt(pat)].append(n)
|
|
633
|
+
elif pat.type == "tuple_pattern":
|
|
634
|
+
for idx, el in enumerate(pat.named_children):
|
|
635
|
+
if el.type == "mut_pattern" and el.named_children:
|
|
636
|
+
el = el.named_children[-1]
|
|
637
|
+
if el.type == "identifier": # let (a, b) = (x, y): element idx of the value
|
|
638
|
+
lets[_txt(el)].append(n)
|
|
639
|
+
self._tuple_idx[(n.id, _txt(el))] = idx
|
|
640
|
+
else:
|
|
641
|
+
for i in _walk(el):
|
|
642
|
+
if i.type == "identifier":
|
|
643
|
+
lets[_txt(i)].append(pat)
|
|
644
|
+
else:
|
|
645
|
+
for i in _walk(pat):
|
|
646
|
+
if i.type == "identifier":
|
|
647
|
+
lets[_txt(i)].append(pat) # a destructuring: bound, value unknown
|
|
648
|
+
elif t in ("closure_parameters", "match_pattern", "for_expression", "let_condition"):
|
|
649
|
+
pat = n if t in ("closure_parameters", "match_pattern") else n.child_by_field_name("pattern")
|
|
650
|
+
if pat is not None:
|
|
651
|
+
if pat.type == "identifier":
|
|
652
|
+
lets[_txt(pat)].append(pat)
|
|
653
|
+
for i in _walk(pat):
|
|
654
|
+
if i.type == "identifier" and (i.parent is None or i.parent.type not in ("scoped_identifier", "field_expression")):
|
|
655
|
+
lets[_txt(i)].append(pat)
|
|
656
|
+
elif t == "call_expression":
|
|
657
|
+
c = callee_of(n)
|
|
658
|
+
if c is None:
|
|
659
|
+
continue
|
|
660
|
+
args = n.child_by_field_name("arguments")
|
|
661
|
+
argv = args.named_children if args is not None else []
|
|
662
|
+
if c.is_method:
|
|
663
|
+
root = c.receiver
|
|
664
|
+
while root is not None and root.type in ("call_expression", "field_expression", "reference_expression",
|
|
665
|
+
"parenthesized_expression", "try_expression", "await_expression"):
|
|
666
|
+
if root.type == "call_expression":
|
|
667
|
+
inner = callee_of(root)
|
|
668
|
+
root = inner.receiver if inner is not None and inner.is_method else None
|
|
669
|
+
elif root.type == "field_expression":
|
|
670
|
+
root = None # a.b.push(..) mutates a field, not the variable
|
|
671
|
+
else:
|
|
672
|
+
root = root.named_children[0] if root.named_children else None
|
|
673
|
+
if root is not None and root.type == "identifier":
|
|
674
|
+
name = _txt(root)
|
|
675
|
+
m = c.name
|
|
676
|
+
if m in ("push_str", "push") and argv:
|
|
677
|
+
muts[name].append((n, "push", argv[0]))
|
|
678
|
+
elif m in ("push_bind", "push_bind_unseparated") and argv:
|
|
679
|
+
muts[name].append((n, "bind", argv[0]))
|
|
680
|
+
elif m in ("push_values", "push_tuples", "separated", "extend", "insert_str", "insert",
|
|
681
|
+
"truncate", "replace_range", "pop", "retain", "drain", "push_fmt", "write_fmt"):
|
|
682
|
+
muts[name].append((n, "opaque", m))
|
|
683
|
+
elif m in ("clear", "reset"):
|
|
684
|
+
muts[name].append((n, "clear", None))
|
|
685
|
+
elif BUILDER_APPEND.match(m) and argv:
|
|
686
|
+
muts[name].append((n, "bpush", argv[0])) # only read for builder objects
|
|
687
|
+
for a in argv: # f(&mut sql, ...): the callee may append to it
|
|
688
|
+
if a.type == "reference_expression" and any(ch.type == "mutable_specifier" for ch in a.children):
|
|
689
|
+
v = a.child_by_field_name("value")
|
|
690
|
+
if v is not None and v.type == "identifier":
|
|
691
|
+
muts[_txt(v)].append((n, "opaque", c.text))
|
|
692
|
+
elif t == "compound_assignment_expr":
|
|
693
|
+
left, op, right = n.child_by_field_name("left"), n.child_by_field_name("operator"), n.child_by_field_name("right")
|
|
694
|
+
if left is not None and left.type == "identifier" and op is not None and _txt(op) == "+=" and right is not None:
|
|
695
|
+
muts[_txt(left)].append((n, "push", right))
|
|
696
|
+
elif t == "assignment_expression":
|
|
697
|
+
left, right = n.child_by_field_name("left"), n.child_by_field_name("right")
|
|
698
|
+
if left is not None and left.type == "identifier" and right is not None:
|
|
699
|
+
muts[_txt(left)].append((n, "assign", right))
|
|
700
|
+
elif t == "macro_invocation":
|
|
701
|
+
mac = n.child_by_field_name("macro")
|
|
702
|
+
if mac is not None and _txt(mac) in ("write", "writeln"):
|
|
703
|
+
tt = self._token_tree(n)
|
|
704
|
+
if tt is not None:
|
|
705
|
+
first = [c for c in tt.children[1:-1] if c.type not in ("&", "mutable_specifier")]
|
|
706
|
+
if first and first[0].type == "identifier":
|
|
707
|
+
muts[_txt(first[0])].append((n, "write", _txt(mac)))
|
|
708
|
+
for v in muts.values():
|
|
709
|
+
v.sort(key=lambda e: (e[0].start_byte, e[0].end_byte))
|
|
710
|
+
self._scope_cache[func.id] = (lets, muts)
|
|
711
|
+
return lets, muts
|
|
712
|
+
|
|
713
|
+
@staticmethod
|
|
714
|
+
def _token_tree(macro: Node) -> Node | None:
|
|
715
|
+
for c in macro.children:
|
|
716
|
+
if c.type == "token_tree":
|
|
717
|
+
return c
|
|
718
|
+
return None
|
|
719
|
+
|
|
720
|
+
@staticmethod
|
|
721
|
+
def _is_ancestor(anc: Node, node: Node) -> bool:
|
|
722
|
+
return anc.start_byte <= node.start_byte and node.end_byte <= anc.end_byte
|
|
723
|
+
|
|
724
|
+
def _branch_state(self, node: Node, top: Node | None) -> tuple[bool, bool]:
|
|
725
|
+
"""(conditional, skipped) for a statement relative to the block `top`.
|
|
726
|
+
|
|
727
|
+
conditional: inside an if / match / loop / closure below `top`.
|
|
728
|
+
skipped: inside an `else` branch or a match arm that is not the first,
|
|
729
|
+
so appending it as well would join two alternatives."""
|
|
730
|
+
cond = skip = False
|
|
731
|
+
child, n = node, node.parent
|
|
732
|
+
while n is not None and (top is None or n.id != top.id) and n.type != "function_item":
|
|
733
|
+
t = n.type
|
|
734
|
+
if t == "if_expression":
|
|
735
|
+
c = n.child_by_field_name("condition")
|
|
736
|
+
if c is None or child.id != c.id:
|
|
737
|
+
cond = True
|
|
738
|
+
elif t == "else_clause":
|
|
739
|
+
cond = skip = True
|
|
740
|
+
elif t == "match_arm":
|
|
741
|
+
cond = True
|
|
742
|
+
block = n.parent
|
|
743
|
+
if block is not None and block.named_children and block.named_children[0].id != n.id:
|
|
744
|
+
skip = True
|
|
745
|
+
elif t in LOOP_TYPES or t == "closure_expression":
|
|
746
|
+
cond = True
|
|
747
|
+
child, n = n, n.parent
|
|
748
|
+
return cond, skip
|
|
749
|
+
|
|
750
|
+
# ---- resolution -----------------------------------------------------
|
|
751
|
+
def resolve(self, node: Node | None, env: dict | None = None, depth: int = 0) -> Res | None:
|
|
752
|
+
"""Resolve an expression to SQL text, or None when nothing is known.
|
|
753
|
+
|
|
754
|
+
env binds the parameters of a function being resolved through:
|
|
755
|
+
{"fn": function node id, "args": {name: (file, node, env)}}."""
|
|
756
|
+
if node is None or depth > MAX_DEPTH:
|
|
757
|
+
return None
|
|
758
|
+
ctx = self.ctx
|
|
759
|
+
ctx.budget -= 1
|
|
760
|
+
if ctx.budget < 0:
|
|
761
|
+
return None
|
|
762
|
+
t = node.type
|
|
763
|
+
if t in ("string_literal", "raw_string_literal", "char_literal"):
|
|
764
|
+
s = decode_literal(_txt(node))
|
|
765
|
+
if s is None:
|
|
766
|
+
return None
|
|
767
|
+
if ctx.touched is not None:
|
|
768
|
+
ctx.touched.append((self.rel, node.id))
|
|
769
|
+
return Res(s)
|
|
770
|
+
if t == "identifier":
|
|
771
|
+
return self._name(_txt(node), node, env, depth)
|
|
772
|
+
if t == "metavariable":
|
|
773
|
+
binds = ctx.macro_binds
|
|
774
|
+
if not binds or _txt(node) not in binds[-1]:
|
|
775
|
+
return None
|
|
776
|
+
bfile, btoks, bat, benv = binds[-1][_txt(node)]
|
|
777
|
+
saved = binds.pop()
|
|
778
|
+
try:
|
|
779
|
+
return bfile._tokens_opt(btoks, bat, benv, depth + 1)
|
|
780
|
+
finally:
|
|
781
|
+
binds.append(saved)
|
|
782
|
+
if t == "scoped_identifier":
|
|
783
|
+
segs = [s for s in re.sub(r"\s+", "", _txt(node)).split("::") if s]
|
|
784
|
+
if segs and CONST_NAME.match(segs[-1]):
|
|
785
|
+
return self._const(segs[-1], segs[:-1], node, depth)
|
|
786
|
+
return None
|
|
787
|
+
if t in ("reference_expression", "parenthesized_expression", "await_expression", "try_expression",
|
|
788
|
+
"type_cast_expression", "unary_expression"):
|
|
789
|
+
if t == "unary_expression" and not _txt(node).startswith("*"):
|
|
790
|
+
return None
|
|
791
|
+
inner = node.child_by_field_name("value") or (node.named_children[0] if node.named_children else None)
|
|
792
|
+
return self.resolve(inner, env, depth)
|
|
793
|
+
if t == "macro_invocation":
|
|
794
|
+
return self._macro(node, env, depth)
|
|
795
|
+
if t == "call_expression":
|
|
796
|
+
return self._call(node, env, depth)
|
|
797
|
+
if t == "binary_expression":
|
|
798
|
+
op = node.child_by_field_name("operator")
|
|
799
|
+
if op is None or _txt(op) != "+":
|
|
800
|
+
return None
|
|
801
|
+
left, right = node.child_by_field_name("left"), node.child_by_field_name("right")
|
|
802
|
+
l, r = self.resolve(left, env, depth + 1), self.resolve(right, env, depth + 1)
|
|
803
|
+
if l is None and r is None:
|
|
804
|
+
return None
|
|
805
|
+
return _join([self._inline(l, left), self._inline(r, right)])
|
|
806
|
+
if t in ("block", "unsafe_block", "async_block"):
|
|
807
|
+
return self._block(node, env, depth)
|
|
808
|
+
if t == "if_expression":
|
|
809
|
+
for branch in (node.child_by_field_name("consequence"), node.child_by_field_name("alternative")):
|
|
810
|
+
if branch is not None and branch.type == "else_clause":
|
|
811
|
+
branch = branch.named_children[0] if branch.named_children else None
|
|
812
|
+
r = self.resolve(branch, env, depth + 1)
|
|
813
|
+
if r is not None and not r.param:
|
|
814
|
+
return Res(r.text, True, r.via_name)
|
|
815
|
+
return None
|
|
816
|
+
if t == "match_expression":
|
|
817
|
+
body = node.child_by_field_name("body")
|
|
818
|
+
for arm in (body.named_children if body is not None else []):
|
|
819
|
+
if arm.type != "match_arm":
|
|
820
|
+
continue
|
|
821
|
+
r = self.resolve(arm.child_by_field_name("value"), env, depth + 1)
|
|
822
|
+
if r is not None and not r.param:
|
|
823
|
+
return Res(r.text, True, r.via_name)
|
|
824
|
+
return None
|
|
825
|
+
if t == "closure_expression":
|
|
826
|
+
return self.resolve(node.child_by_field_name("body"), env, depth + 1)
|
|
827
|
+
if t in ("integer_literal", "float_literal"):
|
|
828
|
+
m = NUMBER.match(_txt(node))
|
|
829
|
+
return Res(m.group(0).replace("_", "")) if m else None
|
|
830
|
+
if t == "return_expression":
|
|
831
|
+
return self.resolve(node.named_children[0], env, depth) if node.named_children else None
|
|
832
|
+
return None
|
|
833
|
+
|
|
834
|
+
@staticmethod
|
|
835
|
+
def _inline(r: Res | None, node: Node | None) -> Res:
|
|
836
|
+
"""A resolved part, or a placeholder for it. A bare parameter stays a placeholder."""
|
|
837
|
+
if r is None:
|
|
838
|
+
return _ph(node) if node is not None else Res("«?»", True)
|
|
839
|
+
if r.param:
|
|
840
|
+
return Res(r.text, True)
|
|
841
|
+
return r
|
|
842
|
+
|
|
843
|
+
@staticmethod
|
|
844
|
+
def _tail(node: Node) -> Node | None:
|
|
845
|
+
"""The value of a block: its tail expression, or a final `return x;`."""
|
|
846
|
+
kids = node.named_children
|
|
847
|
+
while kids and kids[-1].type in ("line_comment", "block_comment"):
|
|
848
|
+
kids = kids[:-1]
|
|
849
|
+
if not kids:
|
|
850
|
+
return None
|
|
851
|
+
last = kids[-1]
|
|
852
|
+
if last.type == "expression_statement":
|
|
853
|
+
closed = _txt(last).rstrip().endswith(";")
|
|
854
|
+
last = last.named_children[0] if last.named_children else None
|
|
855
|
+
# `if c { a } else { b }` as the last line has no semicolon and is the block's value
|
|
856
|
+
if last is None or (closed and last.type != "return_expression"):
|
|
857
|
+
return None
|
|
858
|
+
if not closed and last.type not in ("if_expression", "match_expression", "block", "unsafe_block", "return_expression"):
|
|
859
|
+
return None
|
|
860
|
+
elif last.type.endswith("_declaration") or last.type.endswith("_item"):
|
|
861
|
+
return None
|
|
862
|
+
return last
|
|
863
|
+
|
|
864
|
+
def _block(self, node: Node, env: dict | None, depth: int) -> Res | None:
|
|
865
|
+
last = self._tail(node)
|
|
866
|
+
return self.resolve(last, env, depth + 1) if last is not None else None
|
|
867
|
+
|
|
868
|
+
def _elem(self, node: Node | None, idx: int, env: dict | None, depth: int) -> Res | None:
|
|
869
|
+
"""Element `idx` of a tuple-valued expression: `(a, b)`, a branch, or a function returning a tuple."""
|
|
870
|
+
if node is None or depth > MAX_DEPTH:
|
|
871
|
+
return None
|
|
872
|
+
t = node.type
|
|
873
|
+
if t == "tuple_expression":
|
|
874
|
+
kids = [k for k in node.named_children if k.type not in ("line_comment", "block_comment")]
|
|
875
|
+
return self.resolve(kids[idx], env, depth + 1) if idx < len(kids) else None
|
|
876
|
+
if t in ("parenthesized_expression", "await_expression", "try_expression", "reference_expression", "return_expression"):
|
|
877
|
+
return self._elem(node.named_children[0], idx, env, depth) if node.named_children else None
|
|
878
|
+
if t in ("block", "unsafe_block", "async_block"):
|
|
879
|
+
return self._elem(self._tail(node), idx, env, depth + 1)
|
|
880
|
+
if t == "if_expression":
|
|
881
|
+
for branch in (node.child_by_field_name("consequence"), node.child_by_field_name("alternative")):
|
|
882
|
+
if branch is not None and branch.type == "else_clause":
|
|
883
|
+
branch = branch.named_children[0] if branch.named_children else None
|
|
884
|
+
r = self._elem(branch, idx, env, depth + 1)
|
|
885
|
+
if r is not None and not r.param:
|
|
886
|
+
return Res(r.text, True, r.via_name)
|
|
887
|
+
return None
|
|
888
|
+
if t == "match_expression":
|
|
889
|
+
body = node.child_by_field_name("body")
|
|
890
|
+
for arm in (body.named_children if body is not None else []):
|
|
891
|
+
if arm.type == "match_arm":
|
|
892
|
+
r = self._elem(arm.child_by_field_name("value"), idx, env, depth + 1)
|
|
893
|
+
if r is not None and not r.param:
|
|
894
|
+
return Res(r.text, True, r.via_name)
|
|
895
|
+
return None
|
|
896
|
+
if t == "call_expression":
|
|
897
|
+
c = callee_of(node)
|
|
898
|
+
if c is None:
|
|
899
|
+
return None
|
|
900
|
+
if c.is_method and c.name in ("unwrap", "expect", "unwrap_or_default", "clone"):
|
|
901
|
+
return self._elem(c.receiver, idx, env, depth)
|
|
902
|
+
if c.is_method and c.name in ("unwrap_or", "unwrap_or_else", "map_or"):
|
|
903
|
+
for a in self._args(node): # the default value: one of the possibilities
|
|
904
|
+
r = self._elem(a, idx, env, depth + 1)
|
|
905
|
+
if r is not None and not r.param:
|
|
906
|
+
return Res(r.text, True, r.via_name)
|
|
907
|
+
return None
|
|
908
|
+
if not c.is_method and "::".join(c.segs[-2:]) in ("Ok", "Some") and len(self._args(node)) == 1:
|
|
909
|
+
return self._elem(self._args(node)[0], idx, env, depth)
|
|
910
|
+
target = self._target(c, self._args(node), node, env)
|
|
911
|
+
if target is None:
|
|
912
|
+
return None
|
|
913
|
+
tfile, tfunc, fenv = target
|
|
914
|
+
key = (id(tfile), tfunc.id, idx)
|
|
915
|
+
if key in self.ctx.resolving or tfunc.child_by_field_name("body") is None:
|
|
916
|
+
return None
|
|
917
|
+
self.ctx.resolving.add(key)
|
|
918
|
+
try:
|
|
919
|
+
r = tfile._elem(tfunc.child_by_field_name("body"), idx, fenv, depth + 1)
|
|
920
|
+
finally:
|
|
921
|
+
self.ctx.resolving.discard(key)
|
|
922
|
+
if r is None:
|
|
923
|
+
return None
|
|
924
|
+
return Res(r.text, r.dynamic, True, r.from_file) if r.param else r.named()
|
|
925
|
+
return None
|
|
926
|
+
|
|
927
|
+
def _list(self, node: Node | None, env: dict | None, depth: int) -> tuple[list[Res], bool] | None:
|
|
928
|
+
"""The string elements of an array, `vec![..]`, a const array, or a local Vec built with push."""
|
|
929
|
+
if node is None or depth > MAX_DEPTH:
|
|
930
|
+
return None
|
|
931
|
+
t = node.type
|
|
932
|
+
if t in ("reference_expression", "parenthesized_expression"):
|
|
933
|
+
return self._list(node.named_children[-1], env, depth) if node.named_children else None
|
|
934
|
+
if t == "array_expression":
|
|
935
|
+
return [self._inline(self.resolve(el, env, depth + 1), el) for el in node.named_children
|
|
936
|
+
if el.type not in ("line_comment", "block_comment")], False
|
|
937
|
+
if t == "macro_invocation":
|
|
938
|
+
mac, tt = node.child_by_field_name("macro"), self._token_tree(node)
|
|
939
|
+
if mac is not None and _txt(mac) == "vec" and tt is not None:
|
|
940
|
+
return [self._tokens(a, node, env, depth + 1) for a in self._tt_args(tt)], False
|
|
941
|
+
return None
|
|
942
|
+
if t == "call_expression":
|
|
943
|
+
c = callee_of(node)
|
|
944
|
+
if c is None:
|
|
945
|
+
return None
|
|
946
|
+
if c.is_method and c.name in ("iter", "into_iter", "to_vec", "clone", "as_slice", "copied", "cloned", "iter_mut"):
|
|
947
|
+
return self._list(c.receiver, env, depth)
|
|
948
|
+
if c.is_method and c.name == "chain" and len(self._args(node)) == 1:
|
|
949
|
+
head = self._list(c.receiver, env, depth + 1)
|
|
950
|
+
tail = self._list(self._args(node)[0], env, depth + 1)
|
|
951
|
+
if head is None or tail is None:
|
|
952
|
+
return None
|
|
953
|
+
return head[0] + tail[0], head[1] or tail[1]
|
|
954
|
+
if not c.is_method and "::".join(c.segs[-2:]) in ("Vec::new", "Vec::with_capacity", "Vec::default"):
|
|
955
|
+
return [], False
|
|
956
|
+
return None
|
|
957
|
+
if t in ("identifier", "scoped_identifier"):
|
|
958
|
+
segs = [x for x in re.sub(r"\s+", "", _txt(node)).split("::") if x]
|
|
959
|
+
name = segs[-1]
|
|
960
|
+
if t == "identifier":
|
|
961
|
+
func = self._scope_root(node)
|
|
962
|
+
if func is not None:
|
|
963
|
+
lets, muts = self._scope(func)
|
|
964
|
+
best = None
|
|
965
|
+
for d in lets.get(name, ()):
|
|
966
|
+
if d.end_byte > node.start_byte:
|
|
967
|
+
break
|
|
968
|
+
if d.type == "let_declaration" and d.parent is not None and self._is_ancestor(d.parent, node):
|
|
969
|
+
best = d
|
|
970
|
+
if best is not None:
|
|
971
|
+
got = self._list(best.child_by_field_name("value"), env, depth + 1)
|
|
972
|
+
if got is None:
|
|
973
|
+
return None
|
|
974
|
+
items, dynamic = list(got[0]), got[1]
|
|
975
|
+
for n, kind, payload in muts.get(name, ()):
|
|
976
|
+
if n.start_byte < best.end_byte or n.end_byte > node.start_byte:
|
|
977
|
+
continue
|
|
978
|
+
if kind != "push":
|
|
979
|
+
return None
|
|
980
|
+
cond, _ = self._branch_state(n, best.parent)
|
|
981
|
+
dynamic = dynamic or cond
|
|
982
|
+
items.append(self._inline(self.resolve(payload, env, depth + 1), payload))
|
|
983
|
+
return items, dynamic
|
|
984
|
+
if not CONST_NAME.match(name):
|
|
985
|
+
return None
|
|
986
|
+
local = self.consts.get(name)
|
|
987
|
+
if local and len(segs) == 1:
|
|
988
|
+
return self._list(local[0].child_by_field_name("value"), None, depth + 1)
|
|
989
|
+
cands = self._narrow(self.ctx.consts.get(name, []), segs[:-1] or self.uses.get(name, [name])[:-1])
|
|
990
|
+
if len(cands) == 1:
|
|
991
|
+
return cands[0][0]._list(cands[0][1].child_by_field_name("value"), None, depth + 1)
|
|
992
|
+
return None
|
|
993
|
+
|
|
994
|
+
def _scope_root(self, node: Node) -> Node | None:
|
|
995
|
+
"""The enclosing function, or outside any function the outermost closure
|
|
996
|
+
(`static X: LazyLock<String> = LazyLock::new(|| { let a = ..; a })`)."""
|
|
997
|
+
n = node.parent
|
|
998
|
+
top = None
|
|
999
|
+
while n is not None:
|
|
1000
|
+
if n.type == "function_item":
|
|
1001
|
+
return n
|
|
1002
|
+
if n.type == "closure_expression":
|
|
1003
|
+
top = n
|
|
1004
|
+
n = n.parent
|
|
1005
|
+
return top
|
|
1006
|
+
|
|
1007
|
+
@staticmethod
|
|
1008
|
+
def _lookup(env: dict | None, scope_id: int, name: str):
|
|
1009
|
+
while env is not None:
|
|
1010
|
+
if env["fn"] == scope_id and name in env["args"]:
|
|
1011
|
+
return env["args"][name]
|
|
1012
|
+
env = env.get("parent")
|
|
1013
|
+
return None
|
|
1014
|
+
|
|
1015
|
+
def _bound(self, binding, depth: int) -> Res:
|
|
1016
|
+
if isinstance(binding, Res): # an argument given as macro tokens, resolved at the call
|
|
1017
|
+
return binding
|
|
1018
|
+
bfile, bnode, benv = binding
|
|
1019
|
+
r = bfile.resolve(bnode, benv, depth + 1)
|
|
1020
|
+
if r is not None:
|
|
1021
|
+
return Res(r.text, r.dynamic, r.via_name, r.from_file) if r.param else r
|
|
1022
|
+
return _ph_text(_txt(bnode))
|
|
1023
|
+
|
|
1024
|
+
def _name(self, name: str, at: Node, env: dict | None, depth: int) -> Res | None:
|
|
1025
|
+
func = self._scope_root(at)
|
|
1026
|
+
if func is not None:
|
|
1027
|
+
lets, muts = self._scope(func)
|
|
1028
|
+
best = None
|
|
1029
|
+
for d in lets.get(name, ()):
|
|
1030
|
+
if d.end_byte > at.start_byte:
|
|
1031
|
+
break
|
|
1032
|
+
scope = d.parent if d.type == "let_declaration" else self._binder_scope(d)
|
|
1033
|
+
if scope is not None and self._is_ancestor(scope, at):
|
|
1034
|
+
best = d
|
|
1035
|
+
if best is not None:
|
|
1036
|
+
if best.type == "closure_parameters":
|
|
1037
|
+
binding = self._lookup(env, best.id, name)
|
|
1038
|
+
if binding is not None:
|
|
1039
|
+
return self._bound(binding, depth)
|
|
1040
|
+
return Res("«" + name + "»", True, param=name, binder=best)
|
|
1041
|
+
if best.type != "let_declaration":
|
|
1042
|
+
loop = best.parent
|
|
1043
|
+
if loop is not None and loop.type == "for_expression" and loop.child_by_field_name("pattern") is not None \
|
|
1044
|
+
and loop.child_by_field_name("pattern").id == best.id:
|
|
1045
|
+
items = self._list(loop.child_by_field_name("value"), env, depth + 1)
|
|
1046
|
+
if items: # `for statement in STATEMENTS`: every statement the loop runs
|
|
1047
|
+
parts: list[Res] = []
|
|
1048
|
+
for i, it in enumerate(items[0]):
|
|
1049
|
+
if i:
|
|
1050
|
+
parts.append(Res(";\n"))
|
|
1051
|
+
parts.append(it)
|
|
1052
|
+
r = _join(parts)
|
|
1053
|
+
return Res(r.text, True, True)
|
|
1054
|
+
return None
|
|
1055
|
+
key = (id(self), best.id)
|
|
1056
|
+
if key in self.ctx.resolving:
|
|
1057
|
+
return None
|
|
1058
|
+
self.ctx.resolving.add(key)
|
|
1059
|
+
try:
|
|
1060
|
+
value = best.child_by_field_name("value")
|
|
1061
|
+
idx = self._tuple_idx.get((best.id, name))
|
|
1062
|
+
if idx is not None:
|
|
1063
|
+
base = self._elem(value, idx, env, depth + 1)
|
|
1064
|
+
else:
|
|
1065
|
+
base = self.resolve(value, env, depth + 1) if value is not None else Res("")
|
|
1066
|
+
if base is not None and base.param:
|
|
1067
|
+
if any(best.end_byte <= e[0].start_byte and e[0].end_byte <= at.start_byte for e in muts.get(name, ())):
|
|
1068
|
+
base = Res(base.text, True)
|
|
1069
|
+
else:
|
|
1070
|
+
return base
|
|
1071
|
+
r = self._apply_muts(name, base, value, func, best, at.start_byte, env, depth)
|
|
1072
|
+
return r.named() if r is not None else None
|
|
1073
|
+
finally:
|
|
1074
|
+
self.ctx.resolving.discard(key)
|
|
1075
|
+
if self._is_param(func, name):
|
|
1076
|
+
binding = self._lookup(env, func.id, name)
|
|
1077
|
+
if binding is not None:
|
|
1078
|
+
return self._bound(binding, depth)
|
|
1079
|
+
return Res("«" + name + "»", True, param=name)
|
|
1080
|
+
if not CONST_NAME.match(name):
|
|
1081
|
+
return None
|
|
1082
|
+
return self._const(name, [], at, depth)
|
|
1083
|
+
|
|
1084
|
+
def _binder_scope(self, d: Node) -> Node | None:
|
|
1085
|
+
"""The region in which a non-`let` binding (closure, match arm, for, if-let) is visible."""
|
|
1086
|
+
n = d
|
|
1087
|
+
while n is not None:
|
|
1088
|
+
if n.type in ("closure_expression", "match_arm", "for_expression", "if_expression", "while_expression",
|
|
1089
|
+
"let_declaration"):
|
|
1090
|
+
return n.parent if n.type == "let_declaration" else n
|
|
1091
|
+
n = n.parent
|
|
1092
|
+
return None
|
|
1093
|
+
|
|
1094
|
+
def _apply_muts(self, name: str, base: Res | None, value: Node | None, func: Node, decl: Node, before: int,
|
|
1095
|
+
env: dict | None, depth: int, after: int | None = None, builder: bool = False) -> Res | None:
|
|
1096
|
+
"""Append `name.push_str(..)`, `name += ..`, `write!(name, ..)` between a binding and a use."""
|
|
1097
|
+
_, muts = self._scope(func)
|
|
1098
|
+
start = decl.end_byte if after is None else after
|
|
1099
|
+
events = [e for e in muts.get(name, ()) if e[0].start_byte >= start and e[0].end_byte <= before
|
|
1100
|
+
and (builder or e[1] != "bpush")]
|
|
1101
|
+
if not events:
|
|
1102
|
+
return base
|
|
1103
|
+
top = decl.parent
|
|
1104
|
+
parts: list[Res] = [base] if base is not None else [_ph(value) if value is not None else Res("«?»", True)]
|
|
1105
|
+
dynamic = False
|
|
1106
|
+
from . import arms as arms_mod # one statement per if / else arm, beside the text with «or: ...»
|
|
1107
|
+
arms = arms_mod.Arms(_join)
|
|
1108
|
+
arms.reset(_join(list(parts)))
|
|
1109
|
+
pend: list = []
|
|
1110
|
+
|
|
1111
|
+
def flush() -> None:
|
|
1112
|
+
if not pend:
|
|
1113
|
+
return
|
|
1114
|
+
n0, pid, node, skip, else_piece, cond = pend.pop()
|
|
1115
|
+
if else_piece is not None:
|
|
1116
|
+
arms.append_else(arms_mod.arm_key(node, top, before), else_piece)
|
|
1117
|
+
elif skip:
|
|
1118
|
+
arms.kill()
|
|
1119
|
+
elif id(parts) != pid or len(parts) < n0:
|
|
1120
|
+
if cond:
|
|
1121
|
+
arms.kill()
|
|
1122
|
+
else:
|
|
1123
|
+
arms.reset(_join(list(parts)))
|
|
1124
|
+
elif len(parts) > n0:
|
|
1125
|
+
arms.then(arms_mod.then_keys(node, top, before))
|
|
1126
|
+
arms.append(_join(parts[n0:]))
|
|
1127
|
+
|
|
1128
|
+
for node, kind, payload in events:
|
|
1129
|
+
flush()
|
|
1130
|
+
cond, skip = self._branch_state(node, top)
|
|
1131
|
+
dynamic = dynamic or cond
|
|
1132
|
+
pend.append([len(parts), id(parts), node, skip, None, cond])
|
|
1133
|
+
if skip:
|
|
1134
|
+
# An else branch or a later match arm appends something else: the statement keeps the first
|
|
1135
|
+
# arm's text, and a run-time part says there is an alternative, instead of dropping it silently.
|
|
1136
|
+
if kind in ("push", "bpush"):
|
|
1137
|
+
r = self.resolve(payload, env, depth + 1)
|
|
1138
|
+
text = " ".join((r.text if r is not None else _txt(payload)).split())
|
|
1139
|
+
pend[-1][4] = self._inline(r, payload)
|
|
1140
|
+
parts.append(Res(" «or: " + trim(text, 60).replace("»", ">") + "»", True))
|
|
1141
|
+
continue
|
|
1142
|
+
if kind in ("push", "bpush"):
|
|
1143
|
+
r = self.resolve(payload, env, depth + 1)
|
|
1144
|
+
parts.append(self._inline(r, payload))
|
|
1145
|
+
elif kind == "bind":
|
|
1146
|
+
n_binds = sum(1 for p in parts if p.text.startswith("$") and p.text[1:].isdigit()) + 1
|
|
1147
|
+
parts.append(Res(f"${n_binds}", False))
|
|
1148
|
+
elif kind == "write":
|
|
1149
|
+
r = self._format(self._token_tree(node), node, env, depth + 1, skip_first=True)
|
|
1150
|
+
parts.append(r if r is not None else _ph(node))
|
|
1151
|
+
if payload == "writeln":
|
|
1152
|
+
parts.append(Res("\n"))
|
|
1153
|
+
elif kind == "assign":
|
|
1154
|
+
r = self.resolve(payload, env, depth + 1)
|
|
1155
|
+
if cond:
|
|
1156
|
+
if len(parts) == 1 and not parts[0].text and r is not None:
|
|
1157
|
+
parts = [r] # `let sql; if c { sql = a } else { sql = b }`: keep the first
|
|
1158
|
+
continue
|
|
1159
|
+
parts = [self._inline(r, payload)]
|
|
1160
|
+
elif kind == "clear":
|
|
1161
|
+
if not cond:
|
|
1162
|
+
parts = [Res("")]
|
|
1163
|
+
else:
|
|
1164
|
+
dynamic = True
|
|
1165
|
+
if payload in ("push_values", "push_tuples"):
|
|
1166
|
+
parts.append(Res("«values»", True))
|
|
1167
|
+
elif payload not in ("separated", "truncate", "pop", "retain", "drain", "insert", "insert_str",
|
|
1168
|
+
"replace_range", "extend", "push_fmt", "write_fmt"):
|
|
1169
|
+
parts.append(Res("«" + trim(str(payload), 50) + "(…)»", True))
|
|
1170
|
+
flush()
|
|
1171
|
+
r = _join(parts)
|
|
1172
|
+
out = Res(r.text, r.dynamic or dynamic, r.via_name, r.from_file)
|
|
1173
|
+
out.alts = tuple(a.text for a in arms.result())
|
|
1174
|
+
return out
|
|
1175
|
+
|
|
1176
|
+
@staticmethod
|
|
1177
|
+
def _params(func: Node) -> tuple[list[str], bool]:
|
|
1178
|
+
"""Parameter names in order (None-pattern ones as ""), and whether there is a self parameter."""
|
|
1179
|
+
params = func.child_by_field_name("parameters")
|
|
1180
|
+
names, has_self = [], False
|
|
1181
|
+
if params is None:
|
|
1182
|
+
return names, has_self
|
|
1183
|
+
for p in params.named_children:
|
|
1184
|
+
if p.type == "self_parameter":
|
|
1185
|
+
has_self = True
|
|
1186
|
+
elif p.type == "parameter":
|
|
1187
|
+
pat = p.child_by_field_name("pattern")
|
|
1188
|
+
if pat is not None and pat.type == "mut_pattern" and pat.named_children:
|
|
1189
|
+
pat = pat.named_children[-1]
|
|
1190
|
+
names.append(_txt(pat) if pat is not None and pat.type == "identifier" else "")
|
|
1191
|
+
return names, has_self
|
|
1192
|
+
|
|
1193
|
+
@staticmethod
|
|
1194
|
+
def _param_is_text(func: Node, name: str) -> bool:
|
|
1195
|
+
"""Whether a parameter has a string type (`&str`, `String`, `impl Into<String>`, `Cow<str>`, ...)."""
|
|
1196
|
+
params = func.child_by_field_name("parameters")
|
|
1197
|
+
for p in (params.named_children if params is not None else []):
|
|
1198
|
+
if p.type != "parameter":
|
|
1199
|
+
continue
|
|
1200
|
+
pat = p.child_by_field_name("pattern")
|
|
1201
|
+
if pat is not None and _txt(pat).split()[-1] == name:
|
|
1202
|
+
ty = p.child_by_field_name("type")
|
|
1203
|
+
if ty is None:
|
|
1204
|
+
return False
|
|
1205
|
+
t = re.sub(r"\s+", "", _txt(ty))
|
|
1206
|
+
if re.match(r"^[A-Z]\w?$", t): # a generic: text only when bounded like `S: Into<String>`
|
|
1207
|
+
body = func.child_by_field_name("body")
|
|
1208
|
+
head = _txt(func)[: (body.start_byte - func.start_byte) if body is not None else None]
|
|
1209
|
+
return bool(re.search(rf"\b{t}\s*:\s*[^,{{]*(Into<String>|AsRef<str>|ToString|Display|Into<Cow)", head))
|
|
1210
|
+
return bool(TEXT_PARAM.match(t))
|
|
1211
|
+
return False
|
|
1212
|
+
|
|
1213
|
+
def _is_param(self, func: Node, name: str) -> bool:
|
|
1214
|
+
return name in self._params(func)[0]
|
|
1215
|
+
|
|
1216
|
+
# ---- constants ------------------------------------------------------
|
|
1217
|
+
def _const_value(self, item: Node, depth: int) -> Res | None:
|
|
1218
|
+
key = (id(self), item.id)
|
|
1219
|
+
memo = self.ctx.memo
|
|
1220
|
+
if key in memo:
|
|
1221
|
+
r = memo[key]
|
|
1222
|
+
if r is not None and self.ctx.touched is not None:
|
|
1223
|
+
self.ctx.touched.append((self.rel, -item.id))
|
|
1224
|
+
return r
|
|
1225
|
+
if key in self.ctx.resolving:
|
|
1226
|
+
return None
|
|
1227
|
+
self.ctx.resolving.add(key)
|
|
1228
|
+
saved = self.ctx.touched
|
|
1229
|
+
self.ctx.touched = []
|
|
1230
|
+
try:
|
|
1231
|
+
r = self.resolve(item.child_by_field_name("value"), None, depth + 1)
|
|
1232
|
+
if r is not None and r.param:
|
|
1233
|
+
r = None
|
|
1234
|
+
if r is not None:
|
|
1235
|
+
r = r.named()
|
|
1236
|
+
# only cache results that did not hit the depth limit on the way
|
|
1237
|
+
if depth <= 2 and self.ctx.budget > 0:
|
|
1238
|
+
memo[key] = r
|
|
1239
|
+
self._const_strings = getattr(self, "_const_strings", {})
|
|
1240
|
+
self._const_strings[item.id] = list(self.ctx.touched)
|
|
1241
|
+
touched_here = self.ctx.touched
|
|
1242
|
+
finally:
|
|
1243
|
+
self.ctx.resolving.discard(key)
|
|
1244
|
+
self.ctx.touched = saved
|
|
1245
|
+
if saved is not None and r is not None:
|
|
1246
|
+
saved.extend(touched_here)
|
|
1247
|
+
return r
|
|
1248
|
+
|
|
1249
|
+
def _absolute(self, qual: list[str]) -> list[str] | None:
|
|
1250
|
+
"""`super::sql` / `crate::a::sql` / `self::sql` as a full module path, or None for other paths."""
|
|
1251
|
+
if not qual or qual[0] not in ("crate", "self", "super"):
|
|
1252
|
+
return None
|
|
1253
|
+
if qual[0] == "crate":
|
|
1254
|
+
base = self.mod_path[:self.crate_len]
|
|
1255
|
+
rest = qual[1:]
|
|
1256
|
+
else:
|
|
1257
|
+
base = list(self.mod_path)
|
|
1258
|
+
rest = list(qual)
|
|
1259
|
+
if rest[0] == "self":
|
|
1260
|
+
rest = rest[1:]
|
|
1261
|
+
while rest and rest[0] == "super":
|
|
1262
|
+
base = base[:-1]
|
|
1263
|
+
rest = rest[1:]
|
|
1264
|
+
return base + [r for r in rest if r not in ("self", "super", "crate")]
|
|
1265
|
+
|
|
1266
|
+
def _narrow(self, cands: list, qual: list[str]) -> list:
|
|
1267
|
+
"""Candidates (file, item) that a qualifying path can refer to; all of them when it says nothing."""
|
|
1268
|
+
if not qual:
|
|
1269
|
+
return cands
|
|
1270
|
+
if qual[0] in self.uses and qual[0] not in ("crate", "self", "super"):
|
|
1271
|
+
qual = self.uses[qual[0]] + qual[1:]
|
|
1272
|
+
absolute = self._absolute(qual)
|
|
1273
|
+
if absolute is not None:
|
|
1274
|
+
exact = [(f, n) for f, n in cands if self._item_path(f, n) == absolute]
|
|
1275
|
+
if exact:
|
|
1276
|
+
return exact
|
|
1277
|
+
else:
|
|
1278
|
+
child = self.mod_path + qual # a child module of this file's module
|
|
1279
|
+
exact = [(f, n) for f, n in cands if self._item_path(f, n) == child]
|
|
1280
|
+
if exact:
|
|
1281
|
+
return exact
|
|
1282
|
+
plain = [q for q in qual if q not in ("crate", "self", "super")]
|
|
1283
|
+
if not plain:
|
|
1284
|
+
return cands
|
|
1285
|
+
matched = [(f, n) for f, n in cands if self._item_path(f, n)[-len(plain):] == plain]
|
|
1286
|
+
return matched or cands
|
|
1287
|
+
|
|
1288
|
+
def _via_glob(self, cands: list) -> list:
|
|
1289
|
+
"""Candidates reachable through `use path::*`, else the only candidate in this crate."""
|
|
1290
|
+
for g in self.globs:
|
|
1291
|
+
absolute = self._absolute(g)
|
|
1292
|
+
if absolute is None:
|
|
1293
|
+
continue
|
|
1294
|
+
exact = [(f, n) for f, n in cands if self._item_path(f, n) == absolute]
|
|
1295
|
+
if exact:
|
|
1296
|
+
return exact
|
|
1297
|
+
crate = self.mod_path[:self.crate_len]
|
|
1298
|
+
same = [(f, n) for f, n in cands if f.mod_path[:f.crate_len] == crate]
|
|
1299
|
+
return same if len(same) == 1 else []
|
|
1300
|
+
|
|
1301
|
+
@staticmethod
|
|
1302
|
+
def _item_path(f: "RsFile", item: Node) -> list[str]:
|
|
1303
|
+
inner: list[str] = []
|
|
1304
|
+
n = item.parent
|
|
1305
|
+
while n is not None:
|
|
1306
|
+
if n.type == "mod_item":
|
|
1307
|
+
inner.append(_txt(n.child_by_field_name("name")))
|
|
1308
|
+
elif n.type in ("impl_item", "trait_item"):
|
|
1309
|
+
inner.append(_type_name(n.child_by_field_name("type") or n.child_by_field_name("name")))
|
|
1310
|
+
n = n.parent
|
|
1311
|
+
return f.mod_path + list(reversed(inner))
|
|
1312
|
+
|
|
1313
|
+
def _const(self, name: str, qual: list[str], at: Node, depth: int) -> Res | None:
|
|
1314
|
+
full_qual = list(qual)
|
|
1315
|
+
qual = [q for q in qual if q not in ("crate", "self", "super")]
|
|
1316
|
+
if qual and qual[0] in self.uses:
|
|
1317
|
+
qual = [q for q in self.uses[qual[0]] if q not in ("crate", "self", "super")] + qual[1:]
|
|
1318
|
+
local = self.consts.get(name)
|
|
1319
|
+
if local and not (qual and qual[-1] != "Self" and self._qual_is_foreign(qual, local)):
|
|
1320
|
+
item = local[0]
|
|
1321
|
+
if len(local) > 1:
|
|
1322
|
+
# nearest definition: the one whose scope encloses the use, innermost first
|
|
1323
|
+
best_span = None
|
|
1324
|
+
for c in local:
|
|
1325
|
+
scope = c.parent
|
|
1326
|
+
if scope is not None and self._is_ancestor(scope, at):
|
|
1327
|
+
span = scope.end_byte - scope.start_byte
|
|
1328
|
+
if best_span is None or span < best_span:
|
|
1329
|
+
best_span, item = span, c
|
|
1330
|
+
if best_span is None and qual:
|
|
1331
|
+
for c in local:
|
|
1332
|
+
if self._impl_type(c) == qual[-1]:
|
|
1333
|
+
item = c
|
|
1334
|
+
break
|
|
1335
|
+
r = self._const_value(item, depth)
|
|
1336
|
+
self._touch_const(self, item)
|
|
1337
|
+
return r
|
|
1338
|
+
if not full_qual and name in self.uses:
|
|
1339
|
+
full_qual = self.uses[name][:-1]
|
|
1340
|
+
cands = self.ctx.consts.get(name)
|
|
1341
|
+
if not cands:
|
|
1342
|
+
return None
|
|
1343
|
+
cands = self._narrow(cands, full_qual)
|
|
1344
|
+
if not full_qual and self.globs and len(cands) > 1:
|
|
1345
|
+
cands = self._via_glob(cands) or cands
|
|
1346
|
+
if len(cands) > 12:
|
|
1347
|
+
return None
|
|
1348
|
+
values: dict[str, tuple[Res, "RsFile", Node]] = {}
|
|
1349
|
+
for f, n in cands:
|
|
1350
|
+
r = f._const_value(n, depth)
|
|
1351
|
+
if r is None:
|
|
1352
|
+
return None if len(cands) == 1 else None
|
|
1353
|
+
values.setdefault(r.text, (r, f, n))
|
|
1354
|
+
if len(values) == 1:
|
|
1355
|
+
r, f, n = next(iter(values.values()))
|
|
1356
|
+
self._touch_const(f, n)
|
|
1357
|
+
return r
|
|
1358
|
+
# several values: prefer the definition nearest in the directory tree, when unique
|
|
1359
|
+
scored = sorted(((self._closeness(f.rel), f, n) for f, n in cands), key=lambda x: -x[0])
|
|
1360
|
+
if len(scored) >= 2 and scored[0][0] > scored[1][0]:
|
|
1361
|
+
_, f, n = scored[0]
|
|
1362
|
+
self._touch_const(f, n)
|
|
1363
|
+
return f._const_value(n, depth)
|
|
1364
|
+
return None
|
|
1365
|
+
|
|
1366
|
+
def _touch_const(self, f: "RsFile", item: Node) -> None:
|
|
1367
|
+
if self.ctx.touched is not None:
|
|
1368
|
+
for t in getattr(f, "_const_strings", {}).get(item.id, ()):
|
|
1369
|
+
self.ctx.touched.append(t)
|
|
1370
|
+
|
|
1371
|
+
def _qual_is_foreign(self, qual: list[str], local: list[Node]) -> bool:
|
|
1372
|
+
"""`other_mod::NAME` where this file also defines NAME: use the other module's."""
|
|
1373
|
+
last = qual[-1]
|
|
1374
|
+
if last == "Self" or (self.mod_path and self.mod_path[-1] == last):
|
|
1375
|
+
return False
|
|
1376
|
+
if any(self._impl_type(c) == last for c in local):
|
|
1377
|
+
return False
|
|
1378
|
+
for c in local: # an inline `mod last { const NAME }`
|
|
1379
|
+
m = self._enclosing(c, ("mod_item",))
|
|
1380
|
+
if m is not None and _txt(m.child_by_field_name("name")) == last:
|
|
1381
|
+
return False
|
|
1382
|
+
return any(self._suffix_match(f, n, qual) for f, n in self.ctx.consts.get(_txt(local[0].child_by_field_name("name")), ()) if f is not self)
|
|
1383
|
+
|
|
1384
|
+
@staticmethod
|
|
1385
|
+
def _suffix_match(f: "RsFile", item: Node, qual: list[str]) -> bool:
|
|
1386
|
+
path = RsFile._item_path(f, item)
|
|
1387
|
+
k = len(qual)
|
|
1388
|
+
return path[-k:] == qual if k <= len(path) else False
|
|
1389
|
+
|
|
1390
|
+
def _closeness(self, other: str) -> int:
|
|
1391
|
+
a, b = self.rel.split("/"), other.split("/")
|
|
1392
|
+
n = 0
|
|
1393
|
+
for x, y in zip(a, b):
|
|
1394
|
+
if x != y:
|
|
1395
|
+
break
|
|
1396
|
+
n += 1
|
|
1397
|
+
return n
|
|
1398
|
+
|
|
1399
|
+
# ---- macros ---------------------------------------------------------
|
|
1400
|
+
def _macro(self, node: Node, env: dict | None, depth: int) -> Res | None:
|
|
1401
|
+
mac = node.child_by_field_name("macro")
|
|
1402
|
+
tt = self._token_tree(node)
|
|
1403
|
+
if mac is None or tt is None:
|
|
1404
|
+
return None
|
|
1405
|
+
return self._macro_named(re.sub(r"\s+", "", _txt(mac)).split("::")[-1], tt, node, env, depth)
|
|
1406
|
+
|
|
1407
|
+
def _macro_named(self, name: str, tt: Node, at: Node, env: dict | None, depth: int) -> Res | None:
|
|
1408
|
+
if name in ("format", "formatdoc", "format_args", "formatcp"):
|
|
1409
|
+
return self._format(tt, at, env, depth)
|
|
1410
|
+
if name in ("concat", "concatcp"):
|
|
1411
|
+
parts = []
|
|
1412
|
+
for toks in self._tt_args(tt):
|
|
1413
|
+
parts.append(self._tokens(toks, at, env, depth + 1))
|
|
1414
|
+
return _join(parts) if parts else Res("")
|
|
1415
|
+
if name == "indoc":
|
|
1416
|
+
args = self._tt_args(tt)
|
|
1417
|
+
if len(args) == 1 and len(args[0]) == 1:
|
|
1418
|
+
r = self.resolve(args[0][0], env, depth + 1)
|
|
1419
|
+
return Res(_dedent(r.text), r.dynamic, r.via_name) if r is not None else None
|
|
1420
|
+
return None
|
|
1421
|
+
if name == "include_str":
|
|
1422
|
+
args = self._tt_args(tt)
|
|
1423
|
+
if len(args) == 1 and len(args[0]) == 1:
|
|
1424
|
+
p = decode_literal(_txt(args[0][0]))
|
|
1425
|
+
if p is not None:
|
|
1426
|
+
text = self._include(p)
|
|
1427
|
+
if text is not None:
|
|
1428
|
+
return Res(text, False, False, True)
|
|
1429
|
+
return None
|
|
1430
|
+
return self._user_macro(name, tt, at, env, depth)
|
|
1431
|
+
|
|
1432
|
+
def _user_macro(self, name: str, tt: Node, at: Node, env: dict | None, depth: int) -> Res | None:
|
|
1433
|
+
"""A `macro_rules!` macro whose rule is `($a:literal, ..) => { concat!(.., $a, ..) }`."""
|
|
1434
|
+
if depth > MAX_DEPTH - 2:
|
|
1435
|
+
return None
|
|
1436
|
+
if name in self.macros:
|
|
1437
|
+
tfile, definition = self, self.macros[name]
|
|
1438
|
+
else:
|
|
1439
|
+
cands = self.ctx.macros.get(name, ())
|
|
1440
|
+
if len(cands) != 1:
|
|
1441
|
+
return None
|
|
1442
|
+
tfile, definition = cands[0]
|
|
1443
|
+
args = self._tt_args(tt)
|
|
1444
|
+
for rule in definition.named_children:
|
|
1445
|
+
if rule.type != "macro_rule":
|
|
1446
|
+
continue
|
|
1447
|
+
left, right = rule.child_by_field_name("left"), rule.child_by_field_name("right")
|
|
1448
|
+
if left is None or right is None:
|
|
1449
|
+
continue
|
|
1450
|
+
metas = [_txt(b.child_by_field_name("name")) for b in left.named_children
|
|
1451
|
+
if b.type == "token_binding_pattern" and b.child_by_field_name("name") is not None]
|
|
1452
|
+
if len(metas) != len(args) or len(left.named_children) != len(metas):
|
|
1453
|
+
continue
|
|
1454
|
+
body = [c for c in right.children[1:-1] if c.type not in ("line_comment", "block_comment", ";")]
|
|
1455
|
+
self.ctx.macro_binds.append({m: (self, toks, at, env) for m, toks in zip(metas, args)})
|
|
1456
|
+
try:
|
|
1457
|
+
r = tfile._tokens_opt(body, right, None, depth + 1)
|
|
1458
|
+
finally:
|
|
1459
|
+
self.ctx.macro_binds.pop()
|
|
1460
|
+
return r.named() if r is not None else None
|
|
1461
|
+
return None
|
|
1462
|
+
|
|
1463
|
+
def _include(self, path: str) -> str | None:
|
|
1464
|
+
full = os.path.normpath(os.path.join(os.path.dirname(self.rel), path))
|
|
1465
|
+
cache = self.ctx.include_cache
|
|
1466
|
+
if full not in cache:
|
|
1467
|
+
cache[full] = None if full.startswith("..") else read_text(self.ctx.root / full)
|
|
1468
|
+
return cache[full]
|
|
1469
|
+
|
|
1470
|
+
@staticmethod
|
|
1471
|
+
def _tt_args(tt: Node) -> list[list[Node]]:
|
|
1472
|
+
"""The comma-separated arguments of a macro, each a list of token nodes."""
|
|
1473
|
+
out: list[list[Node]] = [[]]
|
|
1474
|
+
for c in tt.children[1:-1]:
|
|
1475
|
+
if c.type == ",":
|
|
1476
|
+
out.append([])
|
|
1477
|
+
elif c.type not in ("line_comment", "block_comment"):
|
|
1478
|
+
out[-1].append(c)
|
|
1479
|
+
if out and not out[-1]:
|
|
1480
|
+
out.pop()
|
|
1481
|
+
return out
|
|
1482
|
+
|
|
1483
|
+
def _tokens(self, toks: list[Node], at: Node, env: dict | None, depth: int) -> Res:
|
|
1484
|
+
"""Resolve one macro argument given as tokens; a placeholder when it is not a simple value."""
|
|
1485
|
+
if not toks:
|
|
1486
|
+
return Res("")
|
|
1487
|
+
r = self._tokens_opt(toks, at, env, depth)
|
|
1488
|
+
return self._inline(r, None) if r is not None else _ph_text(self.src_text(toks[0].start_byte, toks[-1].end_byte))
|
|
1489
|
+
|
|
1490
|
+
def _tokens_opt(self, toks: list[Node], at: Node, env: dict | None, depth: int) -> Res | None:
|
|
1491
|
+
if not toks:
|
|
1492
|
+
return None
|
|
1493
|
+
text = self.src_text(toks[0].start_byte, toks[-1].end_byte)
|
|
1494
|
+
while len(toks) > 1 and toks[0].type in ("&", "*", "mutable_specifier"):
|
|
1495
|
+
toks = toks[1:]
|
|
1496
|
+
r: Res | None = None
|
|
1497
|
+
if len(toks) == 1 and toks[0].type != "token_tree":
|
|
1498
|
+
r = self.resolve(toks[0], env, depth)
|
|
1499
|
+
elif len(toks) == 3 and toks[1].type == "!" and toks[2].type == "token_tree":
|
|
1500
|
+
r = self._macro_named(_txt(toks[0]), toks[2], at, env, depth)
|
|
1501
|
+
elif len(toks) >= 4 and toks[-2].type == "!" and toks[-1].type == "token_tree" and toks[-3].type == "identifier":
|
|
1502
|
+
r = self._macro_named(_txt(toks[-3]), toks[-1], at, env, depth)
|
|
1503
|
+
else:
|
|
1504
|
+
m = TOKEN_PATH.match(text)
|
|
1505
|
+
if m:
|
|
1506
|
+
segs = [s.strip() for s in m.group(1).split("::")]
|
|
1507
|
+
if len(segs) == 1:
|
|
1508
|
+
r = self._name(segs[0], toks[0], env, depth)
|
|
1509
|
+
elif CONST_NAME.match(segs[-1]):
|
|
1510
|
+
r = self._const(segs[-1], segs[:-1], toks[0], depth)
|
|
1511
|
+
else:
|
|
1512
|
+
r = self._token_call(toks, at, env, depth)
|
|
1513
|
+
return r
|
|
1514
|
+
|
|
1515
|
+
def _token_call(self, toks: list[Node], at: Node, env: dict | None, depth: int) -> Res | None:
|
|
1516
|
+
"""A macro argument that is a call, `table_name(kind)` or `self.columns()`: resolve the function,
|
|
1517
|
+
binding its parameters to the arguments (which are tokens too)."""
|
|
1518
|
+
if depth > MAX_DEPTH - 2:
|
|
1519
|
+
return None
|
|
1520
|
+
toks = list(toks)
|
|
1521
|
+
# trailing .as_str() / .to_string() / ...
|
|
1522
|
+
while len(toks) >= 4 and toks[-1].type == "token_tree" and toks[-2].type == "identifier" and toks[-3].type == "." \
|
|
1523
|
+
and _txt(toks[-2]) in PASS_METHODS and _txt(toks[-1]).replace(" ", "") == "()":
|
|
1524
|
+
toks = toks[:-3]
|
|
1525
|
+
if len(toks) < 2 or toks[-1].type != "token_tree" or not _txt(toks[-1]).startswith("("):
|
|
1526
|
+
return None
|
|
1527
|
+
head = re.sub(r"\s+", "", self.src_text(toks[0].start_byte, toks[-2].end_byte))
|
|
1528
|
+
m = re.match(r"^(self\.)?((?:[A-Za-z_]\w*::)*)([a-z_]\w*)$", head)
|
|
1529
|
+
if not m:
|
|
1530
|
+
return None
|
|
1531
|
+
on_self = bool(m.group(1))
|
|
1532
|
+
quals = [x for x in m.group(2).split("::") if x]
|
|
1533
|
+
name = m.group(3)
|
|
1534
|
+
args = self._tt_args(toks[-1])
|
|
1535
|
+
if not on_self and not quals:
|
|
1536
|
+
closure = self._local_closure(name, at)
|
|
1537
|
+
if closure is not None:
|
|
1538
|
+
return None
|
|
1539
|
+
target = self._find_fn(name, [] if on_self else quals, at)
|
|
1540
|
+
if target is None:
|
|
1541
|
+
return None
|
|
1542
|
+
tfile, tfunc = target
|
|
1543
|
+
ret = tfunc.child_by_field_name("return_type")
|
|
1544
|
+
if ret is None or not STR_TYPE.search(_txt(ret)):
|
|
1545
|
+
return None
|
|
1546
|
+
names, has_self = self._params(tfunc)
|
|
1547
|
+
if has_self and not on_self:
|
|
1548
|
+
args = args[1:]
|
|
1549
|
+
bound = {}
|
|
1550
|
+
for nm, a in zip(names, args):
|
|
1551
|
+
if nm:
|
|
1552
|
+
bound[nm] = self._tokens(a, at, env, depth + 1)
|
|
1553
|
+
return tfile._fn_body(tfunc, {"fn": tfunc.id, "args": bound}, depth + 1)
|
|
1554
|
+
|
|
1555
|
+
def src_text(self, start: int, end: int) -> str:
|
|
1556
|
+
return self.src[start:end].decode("utf-8", "replace")
|
|
1557
|
+
|
|
1558
|
+
def _format(self, tt: Node | None, at: Node, env: dict | None, depth: int, skip_first: bool = False) -> Res | None:
|
|
1559
|
+
if tt is None:
|
|
1560
|
+
return None
|
|
1561
|
+
args = self._tt_args(tt)
|
|
1562
|
+
if skip_first:
|
|
1563
|
+
args = args[1:]
|
|
1564
|
+
if not args or len(args[0]) != 1 or args[0][0].type not in ("string_literal", "raw_string_literal"):
|
|
1565
|
+
if args and len(args[0]) >= 3: # format!(concat!("a", "b"), x)
|
|
1566
|
+
head = self._tokens(args[0], at, env, depth + 1)
|
|
1567
|
+
if head.dynamic:
|
|
1568
|
+
return None
|
|
1569
|
+
fmt = head.text
|
|
1570
|
+
else:
|
|
1571
|
+
return None
|
|
1572
|
+
else:
|
|
1573
|
+
fmt = decode_literal(_txt(args[0][0]))
|
|
1574
|
+
if fmt is None:
|
|
1575
|
+
return None
|
|
1576
|
+
if self.ctx.touched is not None:
|
|
1577
|
+
self.ctx.touched.append((self.rel, args[0][0].id))
|
|
1578
|
+
positional: list[list[Node]] = []
|
|
1579
|
+
named: dict[str, list[Node]] = {}
|
|
1580
|
+
for toks in args[1:]:
|
|
1581
|
+
if len(toks) >= 3 and toks[0].type == "identifier" and toks[1].type == "=" and toks[2].type != "=":
|
|
1582
|
+
named[_txt(toks[0])] = toks[2:]
|
|
1583
|
+
else:
|
|
1584
|
+
positional.append(toks)
|
|
1585
|
+
cache: dict[object, Res] = {}
|
|
1586
|
+
counter = [0]
|
|
1587
|
+
dynamic = [False]
|
|
1588
|
+
via = [False]
|
|
1589
|
+
|
|
1590
|
+
def field(m: re.Match) -> str:
|
|
1591
|
+
s = m.group(0)
|
|
1592
|
+
if s == "{{":
|
|
1593
|
+
return "{"
|
|
1594
|
+
if s == "}}":
|
|
1595
|
+
return "}"
|
|
1596
|
+
spec = m.group(1)
|
|
1597
|
+
key, _, fmt_spec = spec.partition(":")
|
|
1598
|
+
key = key.strip()
|
|
1599
|
+
toks: list[Node] | None = None
|
|
1600
|
+
ident: object
|
|
1601
|
+
if key == "":
|
|
1602
|
+
ident = counter[0]
|
|
1603
|
+
counter[0] += 1
|
|
1604
|
+
elif key.isdigit():
|
|
1605
|
+
ident = int(key)
|
|
1606
|
+
else:
|
|
1607
|
+
ident = key
|
|
1608
|
+
if ident in cache:
|
|
1609
|
+
r = cache[ident]
|
|
1610
|
+
else:
|
|
1611
|
+
if isinstance(ident, int):
|
|
1612
|
+
toks = positional[ident] if ident < len(positional) else None
|
|
1613
|
+
r = self._tokens(toks, at, env, depth + 1) if toks else Res("«arg»", True)
|
|
1614
|
+
elif ident in named:
|
|
1615
|
+
r = self._tokens(named[ident], at, env, depth + 1)
|
|
1616
|
+
else:
|
|
1617
|
+
got = self._name(ident, at, env, depth + 1) if re.match(r"^[A-Za-z_]\w*$", ident) else None
|
|
1618
|
+
r = self._inline(got, None) if got is not None else Res("«" + ident + "»", True)
|
|
1619
|
+
cache[ident] = r
|
|
1620
|
+
if "?" in fmt_spec and not r.dynamic:
|
|
1621
|
+
r = Res("«" + (str(ident) if not isinstance(ident, int) else "arg") + ":?»", True)
|
|
1622
|
+
dynamic[0] = dynamic[0] or r.dynamic
|
|
1623
|
+
via[0] = via[0] or r.via_name
|
|
1624
|
+
return r.text
|
|
1625
|
+
|
|
1626
|
+
text = FMT_FIELD.sub(field, fmt)
|
|
1627
|
+
return Res(text, dynamic[0], via[0])
|
|
1628
|
+
|
|
1629
|
+
# ---- calls ----------------------------------------------------------
|
|
1630
|
+
def _call(self, node: Node, env: dict | None, depth: int) -> Res | None:
|
|
1631
|
+
c = callee_of(node)
|
|
1632
|
+
if c is None:
|
|
1633
|
+
return None
|
|
1634
|
+
args = node.child_by_field_name("arguments")
|
|
1635
|
+
argv = [a for a in (args.named_children if args is not None else []) if a.type not in ("line_comment", "block_comment")]
|
|
1636
|
+
if c.is_method:
|
|
1637
|
+
m = c.name
|
|
1638
|
+
if m in PASS_METHODS:
|
|
1639
|
+
return self.resolve(c.receiver, env, depth)
|
|
1640
|
+
if m in ("replace", "replacen") and len(argv) >= 2:
|
|
1641
|
+
base = self.resolve(c.receiver, env, depth + 1)
|
|
1642
|
+
if base is None:
|
|
1643
|
+
return None
|
|
1644
|
+
if base.param:
|
|
1645
|
+
return base # a parameter with a token swapped is still the caller's SQL
|
|
1646
|
+
key = self.resolve(argv[0], env, depth + 1)
|
|
1647
|
+
text = base.text
|
|
1648
|
+
via = base.via_name
|
|
1649
|
+
if key is not None and not key.dynamic and key.text and key.text in text:
|
|
1650
|
+
val = self.resolve(argv[1], env, depth + 1)
|
|
1651
|
+
if val is not None and not val.param:
|
|
1652
|
+
sub = val.text
|
|
1653
|
+
via = via or val.via_name
|
|
1654
|
+
else:
|
|
1655
|
+
sub = _ph(argv[1].child_by_field_name("value") if argv[1].type == "reference_expression" and argv[1].child_by_field_name("value") is not None else argv[1]).text
|
|
1656
|
+
text = text.replace(key.text, sub, 1) if m == "replacen" else text.replace(key.text, sub)
|
|
1657
|
+
return Res(text, True, via, False, "")
|
|
1658
|
+
if m in ("unwrap_or", "unwrap_or_else", "map_or", "map_or_else", "get_or_insert_with", "unwrap_or_else"):
|
|
1659
|
+
base = self.resolve(c.receiver, env, depth + 1)
|
|
1660
|
+
if base is not None and not base.param:
|
|
1661
|
+
return Res(base.text, True, base.via_name)
|
|
1662
|
+
for a in argv:
|
|
1663
|
+
r = self.resolve(a, env, depth + 1)
|
|
1664
|
+
if r is not None and not r.param:
|
|
1665
|
+
return Res(r.text, True, r.via_name)
|
|
1666
|
+
return None
|
|
1667
|
+
if m in ("join", "concat"):
|
|
1668
|
+
got = self._list(c.receiver, env, depth + 1)
|
|
1669
|
+
sep = self.resolve(argv[0], env, depth + 1) if (m == "join" and argv) else Res("")
|
|
1670
|
+
if got is None or sep is None or not got[0]:
|
|
1671
|
+
return None
|
|
1672
|
+
parts: list[Res] = []
|
|
1673
|
+
for i, el in enumerate(got[0]):
|
|
1674
|
+
if i:
|
|
1675
|
+
parts.append(sep)
|
|
1676
|
+
parts.append(el)
|
|
1677
|
+
r = _join(parts)
|
|
1678
|
+
return Res(r.text, r.dynamic or got[1], r.via_name, r.from_file)
|
|
1679
|
+
if m in ("sql", "build", "into_sql") and not argv:
|
|
1680
|
+
return None
|
|
1681
|
+
# self.helper(...) defined in this file, or a method whose name is defined once in the repo
|
|
1682
|
+
return self._through_fn(c, argv, node, env, depth, method=True,
|
|
1683
|
+
on_self=c.receiver is not None and c.receiver.type == "self")
|
|
1684
|
+
path = "::".join(c.segs)
|
|
1685
|
+
tail2 = "::".join(c.segs[-2:])
|
|
1686
|
+
if tail2 in PASS_PATHS or path in PASS_PATHS:
|
|
1687
|
+
return self.resolve(argv[0], env, depth) if len(argv) == 1 else None
|
|
1688
|
+
if tail2 in ("String::new", "String::with_capacity", "String::default"):
|
|
1689
|
+
return Res("")
|
|
1690
|
+
if len(c.segs) == 1 and not c.segs[0][:1].isupper():
|
|
1691
|
+
closure = self._local_closure(c.segs[0], node)
|
|
1692
|
+
if closure is not None: # let build = |x: &str| format!(..); build(a)
|
|
1693
|
+
if depth > MAX_DEPTH - 2:
|
|
1694
|
+
return None
|
|
1695
|
+
params = closure.child_by_field_name("parameters")
|
|
1696
|
+
bound = {}
|
|
1697
|
+
for p, a in zip(params.named_children if params is not None else [], argv):
|
|
1698
|
+
inner = p.child_by_field_name("pattern") if p.type == "parameter" else p
|
|
1699
|
+
if inner is not None:
|
|
1700
|
+
bound[_txt(inner).split()[-1]] = (self, a, env)
|
|
1701
|
+
key = (id(self), closure.id)
|
|
1702
|
+
if key in self.ctx.resolving or params is None:
|
|
1703
|
+
return None
|
|
1704
|
+
self.ctx.resolving.add(key)
|
|
1705
|
+
try:
|
|
1706
|
+
r = self.resolve(closure.child_by_field_name("body"), {"fn": params.id, "args": bound, "parent": env}, depth + 1)
|
|
1707
|
+
finally:
|
|
1708
|
+
self.ctx.resolving.discard(key)
|
|
1709
|
+
if r is None:
|
|
1710
|
+
return None
|
|
1711
|
+
return Res(r.text, r.dynamic, True, r.from_file) if r.param else r.named()
|
|
1712
|
+
if tail2 in LAZY_PATHS and len(argv) == 1:
|
|
1713
|
+
a = argv[0]
|
|
1714
|
+
if a.type in ("identifier", "scoped_identifier") and not CONST_NAME.match(_txt(a).split("::")[-1]):
|
|
1715
|
+
segs = [x for x in re.sub(r"\s+", "", _txt(a)).split("::") if x] # LazyLock::new(build_sql)
|
|
1716
|
+
return self._through_fn(Callee(segs[-1], False, segs, None, _txt(a)), [], node, env, depth, method=False)
|
|
1717
|
+
return self.resolve(a, env, depth + 1)
|
|
1718
|
+
return self._through_fn(c, argv, node, env, depth, method=False)
|
|
1719
|
+
|
|
1720
|
+
def _local_closure(self, name: str, at: Node) -> Node | None:
|
|
1721
|
+
func = self._scope_root(at)
|
|
1722
|
+
if func is None:
|
|
1723
|
+
return None
|
|
1724
|
+
best = None
|
|
1725
|
+
for d in self._scope(func)[0].get(name, ()):
|
|
1726
|
+
if d.end_byte > at.start_byte:
|
|
1727
|
+
break
|
|
1728
|
+
best = d
|
|
1729
|
+
if best is None or best.type != "let_declaration":
|
|
1730
|
+
return None
|
|
1731
|
+
v = best.child_by_field_name("value")
|
|
1732
|
+
return v if v is not None and v.type == "closure_expression" else None
|
|
1733
|
+
|
|
1734
|
+
def _find_fn(self, name: str, qual: list[str], at: Node) -> tuple["RsFile", Node] | None:
|
|
1735
|
+
full_qual = list(qual)
|
|
1736
|
+
qual = [q for q in qual if q not in ("crate", "self", "super")]
|
|
1737
|
+
local = self.fns.get(name)
|
|
1738
|
+
if local and (not qual or qual[-1] == "Self" or len(qual) == 1):
|
|
1739
|
+
if len(local) == 1:
|
|
1740
|
+
if not qual or qual[-1] == "Self" or self._impl_type(local[0]) == qual[-1] or \
|
|
1741
|
+
(self.mod_path and self.mod_path[-1] == qual[-1]) or not self._foreign_fn(name, qual):
|
|
1742
|
+
return self, local[0]
|
|
1743
|
+
else:
|
|
1744
|
+
mine = self._impl_type(at) if (not qual or qual[-1] == "Self") else qual[-1]
|
|
1745
|
+
same = [f for f in local if self._impl_type(f) == mine]
|
|
1746
|
+
if len(same) == 1:
|
|
1747
|
+
return self, same[0]
|
|
1748
|
+
if not qual:
|
|
1749
|
+
free = [f for f in local if not self._impl_type(f)]
|
|
1750
|
+
if len(free) == 1:
|
|
1751
|
+
return self, free[0]
|
|
1752
|
+
# same name in sibling inline modules: the one sharing the innermost scope
|
|
1753
|
+
for f in local:
|
|
1754
|
+
scope = f.parent
|
|
1755
|
+
if scope is not None and self._is_ancestor(scope, at) and scope.type != "source_file":
|
|
1756
|
+
return self, f
|
|
1757
|
+
return None
|
|
1758
|
+
if not full_qual and name in self.uses:
|
|
1759
|
+
full_qual = self.uses[name][:-1]
|
|
1760
|
+
cands = self.ctx.fns.get(name)
|
|
1761
|
+
if not cands:
|
|
1762
|
+
return None
|
|
1763
|
+
if not full_qual:
|
|
1764
|
+
if local:
|
|
1765
|
+
return None
|
|
1766
|
+
cands = self._via_glob([(f, n) for f, n in cands if not f._impl_type(n)]) # `use super::*`
|
|
1767
|
+
return cands[0] if len(cands) == 1 else None
|
|
1768
|
+
if full_qual:
|
|
1769
|
+
narrowed = self._narrow(cands, full_qual)
|
|
1770
|
+
if narrowed is cands:
|
|
1771
|
+
last = [q for q in full_qual if q not in ("crate", "self", "super")][-1:]
|
|
1772
|
+
narrowed = [(f, n) for f, n in cands if last and self._suffix_match(f, n, last)]
|
|
1773
|
+
cands = narrowed
|
|
1774
|
+
if len(cands) == 1:
|
|
1775
|
+
return cands[0]
|
|
1776
|
+
if len(cands) > 1:
|
|
1777
|
+
scored = sorted(((self._closeness(f.rel), i) for i, (f, n) in enumerate(cands)), key=lambda x: -x[0])
|
|
1778
|
+
if scored[0][0] > scored[1][0]:
|
|
1779
|
+
return cands[scored[0][1]]
|
|
1780
|
+
return None
|
|
1781
|
+
|
|
1782
|
+
def _foreign_fn(self, name: str, qual: list[str]) -> bool:
|
|
1783
|
+
return any(self._suffix_match(f, n, qual) for f, n in self.ctx.fns.get(name, ()) if f is not self)
|
|
1784
|
+
|
|
1785
|
+
def _recv_type(self, recv: Node | None) -> str:
|
|
1786
|
+
"""The type name of a method receiver when it is a parameter or a local with an evident type."""
|
|
1787
|
+
if recv is None:
|
|
1788
|
+
return ""
|
|
1789
|
+
while recv.type in ("reference_expression", "parenthesized_expression") and recv.named_children:
|
|
1790
|
+
recv = recv.named_children[-1]
|
|
1791
|
+
if recv.type == "self":
|
|
1792
|
+
return self._impl_type(recv)
|
|
1793
|
+
if recv.type == "call_expression":
|
|
1794
|
+
c = callee_of(recv) # Type::new(..).method()
|
|
1795
|
+
if c is not None and not c.is_method and len(c.segs) >= 2 and c.segs[-2][:1].isupper():
|
|
1796
|
+
return self._impl_type(recv) if c.segs[-2] == "Self" else c.segs[-2]
|
|
1797
|
+
return ""
|
|
1798
|
+
if recv.type == "scoped_identifier": # Enum::Variant.method()
|
|
1799
|
+
segs = [x for x in re.sub(r"\s+", "", _txt(recv)).split("::") if x]
|
|
1800
|
+
return segs[-2] if len(segs) >= 2 and segs[-2][:1].isupper() else ""
|
|
1801
|
+
if recv.type != "identifier":
|
|
1802
|
+
return ""
|
|
1803
|
+
name = _txt(recv)
|
|
1804
|
+
func = self._enclosing(recv, FUNC_STOP)
|
|
1805
|
+
if func is None:
|
|
1806
|
+
return ""
|
|
1807
|
+
lets, _ = self._scope(func)
|
|
1808
|
+
best = None
|
|
1809
|
+
for d in lets.get(name, ()):
|
|
1810
|
+
if d.end_byte > recv.start_byte:
|
|
1811
|
+
break
|
|
1812
|
+
best = d
|
|
1813
|
+
if best is not None:
|
|
1814
|
+
if best.type != "let_declaration":
|
|
1815
|
+
return ""
|
|
1816
|
+
ty = best.child_by_field_name("type")
|
|
1817
|
+
if ty is not None:
|
|
1818
|
+
return _type_name(ty)
|
|
1819
|
+
return self._recv_type(best.child_by_field_name("value"))
|
|
1820
|
+
params = func.child_by_field_name("parameters")
|
|
1821
|
+
for p in (params.named_children if params is not None else []):
|
|
1822
|
+
if p.type == "parameter":
|
|
1823
|
+
pat = p.child_by_field_name("pattern")
|
|
1824
|
+
if pat is not None and _txt(pat).split()[-1] == name:
|
|
1825
|
+
return _type_name(p.child_by_field_name("type"))
|
|
1826
|
+
return ""
|
|
1827
|
+
|
|
1828
|
+
def _target(self, c: Callee, argv: list[Node], call: Node, env: dict | None) -> tuple["RsFile", Node, dict] | None:
|
|
1829
|
+
"""The function a call refers to, with its parameters bound to the call's arguments."""
|
|
1830
|
+
on_self = c.is_method and c.receiver is not None and c.receiver.type == "self"
|
|
1831
|
+
if c.is_method and not on_self:
|
|
1832
|
+
cands = [(f, n) for f, n in self.ctx.fns.get(c.name, ()) if self._params(n)[1]]
|
|
1833
|
+
target = None
|
|
1834
|
+
ty = self._recv_type(c.receiver)
|
|
1835
|
+
if ty:
|
|
1836
|
+
typed = [(f, n) for f, n in cands if f._impl_type(n) == ty]
|
|
1837
|
+
local = [(f, n) for f, n in typed if f is self]
|
|
1838
|
+
if len(local) == 1:
|
|
1839
|
+
target = local[0]
|
|
1840
|
+
elif len(typed) == 1:
|
|
1841
|
+
target = typed[0]
|
|
1842
|
+
elif len(typed) > 1:
|
|
1843
|
+
scored = sorted(((self._closeness(f.rel), i) for i, (f, n) in enumerate(typed)), key=lambda x: -x[0])
|
|
1844
|
+
target = typed[scored[0][1]] if scored[0][0] > scored[1][0] else None
|
|
1845
|
+
if target is None and not ty:
|
|
1846
|
+
# the receiver's type is unknown: only a method name with a single definition
|
|
1847
|
+
local = [(f, n) for f, n in cands if f is self]
|
|
1848
|
+
target = local[0] if len(local) == 1 else cands[0] if len(cands) == 1 else None
|
|
1849
|
+
else:
|
|
1850
|
+
target = self._find_fn(c.name, [] if c.is_method else c.segs[:-1], call)
|
|
1851
|
+
if target is None:
|
|
1852
|
+
return None
|
|
1853
|
+
tfile, tfunc = target
|
|
1854
|
+
ret = tfunc.child_by_field_name("return_type")
|
|
1855
|
+
if ret is None or not STR_TYPE.search(_txt(ret)):
|
|
1856
|
+
return None
|
|
1857
|
+
names, has_self = self._params(tfunc)
|
|
1858
|
+
if has_self and not c.is_method:
|
|
1859
|
+
argv = argv[1:]
|
|
1860
|
+
bound = {}
|
|
1861
|
+
for nm, a in zip(names, argv):
|
|
1862
|
+
if nm:
|
|
1863
|
+
bound[nm] = (self, a, env)
|
|
1864
|
+
return tfile, tfunc, {"fn": tfunc.id, "args": bound}
|
|
1865
|
+
|
|
1866
|
+
def _through_fn(self, c: Callee, argv: list[Node], call: Node, env: dict | None, depth: int, method: bool,
|
|
1867
|
+
on_self: bool = False) -> Res | None:
|
|
1868
|
+
"""Resolve a call to a function that returns a string, binding arguments to its parameters."""
|
|
1869
|
+
if depth > MAX_DEPTH - 2:
|
|
1870
|
+
return None
|
|
1871
|
+
target = self._target(c, argv, call, env)
|
|
1872
|
+
if target is None:
|
|
1873
|
+
return None
|
|
1874
|
+
tfile, tfunc, fenv = target
|
|
1875
|
+
return tfile._fn_body(tfunc, fenv, depth + 1)
|
|
1876
|
+
|
|
1877
|
+
def _fn_body(self, func: Node, env: dict, depth: int) -> Res | None:
|
|
1878
|
+
key = (id(self), func.id)
|
|
1879
|
+
if key in self.ctx.resolving:
|
|
1880
|
+
return None
|
|
1881
|
+
self.ctx.resolving.add(key)
|
|
1882
|
+
try:
|
|
1883
|
+
r = self._block(func.child_by_field_name("body"), env, depth) if func.child_by_field_name("body") is not None else None
|
|
1884
|
+
finally:
|
|
1885
|
+
self.ctx.resolving.discard(key)
|
|
1886
|
+
if r is None:
|
|
1887
|
+
return None
|
|
1888
|
+
return Res(r.text, r.dynamic, True, r.from_file) if r.param else r.named()
|
|
1889
|
+
|
|
1890
|
+
# ---- sinks ----------------------------------------------------------
|
|
1891
|
+
def match_sink(self, c: Callee) -> tuple[str, list[int], bool, bool] | None:
|
|
1892
|
+
"""(engine, argument indexes, from the rules, is a path sink) for a callee, or None."""
|
|
1893
|
+
ctx = self.ctx
|
|
1894
|
+
if c.is_method:
|
|
1895
|
+
on_self = c.receiver is not None and c.receiver.type == "self"
|
|
1896
|
+
idxs: list[int] = []
|
|
1897
|
+
engine, from_rules, hit = "", False, False
|
|
1898
|
+
if c.name in ctx.method_sinks:
|
|
1899
|
+
engine, from_rules, hit = ctx.method_sinks[c.name], True, True
|
|
1900
|
+
idxs.extend(ctx.sink_args.get(c.name, [0]))
|
|
1901
|
+
for w in ctx.wrappers.get(c.name, ()):
|
|
1902
|
+
# A method wrapper is matched by name alone, so the name has to say "database"
|
|
1903
|
+
# (`fetch_rows`, `run_query`); any other name only counts for `self.name(..)` in its own file.
|
|
1904
|
+
if w.is_method and (DISTINCT_METHOD.search(c.name) or (on_self and w.rel == self.rel)):
|
|
1905
|
+
if not hit:
|
|
1906
|
+
engine, hit = w.engine, True
|
|
1907
|
+
if w.index not in idxs:
|
|
1908
|
+
idxs.append(w.index)
|
|
1909
|
+
return (engine, idxs, from_rules, False) if hit else None
|
|
1910
|
+
segs = c.segs
|
|
1911
|
+
full = self.uses.get(segs[0])
|
|
1912
|
+
expanded = (full + segs[1:]) if full else segs
|
|
1913
|
+
for rule, engine in ctx.path_sinks:
|
|
1914
|
+
k = len(rule)
|
|
1915
|
+
if expanded[-k:] == rule or (segs[-k:] == rule and len(segs) >= k):
|
|
1916
|
+
return engine, ctx.sink_args.get("::".join(rule), [0]), True, True
|
|
1917
|
+
for w in ctx.wrappers.get(c.name, ()):
|
|
1918
|
+
if w.impl_type:
|
|
1919
|
+
if len(segs) < 2 or segs[-2] not in (w.impl_type, "Self") or (segs[-2] == "Self" and w.rel != self.rel):
|
|
1920
|
+
continue # an associated function is called as Type::name or Self::name
|
|
1921
|
+
elif w.rel != self.rel:
|
|
1922
|
+
# a free function in another file: the call's path, or the `use` that imports it, must name its module
|
|
1923
|
+
path = (full + segs[1:]) if full else segs
|
|
1924
|
+
absolute = self._absolute(path)
|
|
1925
|
+
if absolute is not None:
|
|
1926
|
+
if absolute[:-1] != w.mod:
|
|
1927
|
+
continue
|
|
1928
|
+
elif len(path) > 1:
|
|
1929
|
+
plain = path[:-1]
|
|
1930
|
+
child = self.mod_path + plain
|
|
1931
|
+
if w.mod[-len(plain):] != plain and child != w.mod:
|
|
1932
|
+
continue
|
|
1933
|
+
elif not any(self._absolute(g) == w.mod for g in self.globs):
|
|
1934
|
+
continue
|
|
1935
|
+
elif len(segs) > 1 and segs[-2][:1].isupper():
|
|
1936
|
+
continue
|
|
1937
|
+
return w.engine, [w.index + 1 if w.is_method else w.index], False, True
|
|
1938
|
+
return None
|
|
1939
|
+
|
|
1940
|
+
def sink_calls(self, names: set[str]) -> list[tuple[Node, Callee]]:
|
|
1941
|
+
if not names:
|
|
1942
|
+
return []
|
|
1943
|
+
pre, query = self.ctx.call_query(names)
|
|
1944
|
+
if not pre.search(self.src):
|
|
1945
|
+
return []
|
|
1946
|
+
out = []
|
|
1947
|
+
seen = set()
|
|
1948
|
+
for call in QueryCursor(query).captures(self.root).get("c", []):
|
|
1949
|
+
if call.id in seen:
|
|
1950
|
+
continue
|
|
1951
|
+
seen.add(call.id)
|
|
1952
|
+
c = callee_of(call)
|
|
1953
|
+
if c is not None and c.name in names:
|
|
1954
|
+
out.append((call, c))
|
|
1955
|
+
out.sort(key=lambda x: x[0].start_byte)
|
|
1956
|
+
return out
|
|
1957
|
+
|
|
1958
|
+
@staticmethod
|
|
1959
|
+
def _args(call: Node) -> list[Node]:
|
|
1960
|
+
args = call.child_by_field_name("arguments")
|
|
1961
|
+
return [a for a in (args.named_children if args is not None else []) if a.type not in ("line_comment", "block_comment")]
|
|
1962
|
+
|
|
1963
|
+
def find_wrappers(self, names: set[str]) -> list[Wrapper]:
|
|
1964
|
+
"""Functions in this file that pass one of their parameters to a sink named in `names`."""
|
|
1965
|
+
found = []
|
|
1966
|
+
for call, c in self.sink_calls(names):
|
|
1967
|
+
sink = self.match_sink(c)
|
|
1968
|
+
if sink is None:
|
|
1969
|
+
continue
|
|
1970
|
+
engine, idxs, _, _ = sink
|
|
1971
|
+
argv = self._args(call)
|
|
1972
|
+
for i in idxs:
|
|
1973
|
+
if i >= len(argv):
|
|
1974
|
+
continue
|
|
1975
|
+
self.ctx.budget = 4000
|
|
1976
|
+
res = self.resolve(argv[i], None, 0)
|
|
1977
|
+
if res is None:
|
|
1978
|
+
found.extend(self._field_wrappers(argv[i], engine))
|
|
1979
|
+
continue
|
|
1980
|
+
if not res.param or res.binder is not None:
|
|
1981
|
+
continue
|
|
1982
|
+
func = self._enclosing(call, FUNC_STOP)
|
|
1983
|
+
if func is None:
|
|
1984
|
+
continue
|
|
1985
|
+
pnames, has_self = self._params(func)
|
|
1986
|
+
nm = func.child_by_field_name("name")
|
|
1987
|
+
if nm is None or res.param not in pnames or not self._param_is_text(func, res.param):
|
|
1988
|
+
continue
|
|
1989
|
+
if not SQLISH_NAME.search(res.param) and not SQLISH_NAME.search(_txt(nm)):
|
|
1990
|
+
continue # `fn f(&self, tenant: &str) { other.bind(tenant) }` is not an SQL wrapper
|
|
1991
|
+
found.append(Wrapper(_txt(nm), has_self, pnames.index(res.param), engine, self._impl_type(func), self.rel))
|
|
1992
|
+
return found
|
|
1993
|
+
|
|
1994
|
+
@staticmethod
|
|
1995
|
+
def _self_field(arg: Node) -> str:
|
|
1996
|
+
"""`&self.text`, `self.text.as_str()` -> "text"."""
|
|
1997
|
+
m = re.match(r"^&?\s*self\s*\.\s*([a-z_]\w*)((?:\s*\.\s*(?:as_str|clone|to_string|as_ref|to_owned)\(\))*)$", _txt(arg))
|
|
1998
|
+
return m.group(1) if m else ""
|
|
1999
|
+
|
|
2000
|
+
def _field_wrappers(self, arg: Node, engine: str) -> list[Wrapper]:
|
|
2001
|
+
"""`client.query(&self.text)` in `impl Sql`: a constructor that stores its parameter in `text` is a sink."""
|
|
2002
|
+
field = self._self_field(arg)
|
|
2003
|
+
ty = self._impl_type(arg)
|
|
2004
|
+
if not field or not ty:
|
|
2005
|
+
return []
|
|
2006
|
+
found = []
|
|
2007
|
+
for name, items in self.fns.items():
|
|
2008
|
+
for func in items:
|
|
2009
|
+
if self._impl_type(func) != ty:
|
|
2010
|
+
continue
|
|
2011
|
+
pnames, has_self = self._params(func)
|
|
2012
|
+
body = func.child_by_field_name("body")
|
|
2013
|
+
if body is None or has_self:
|
|
2014
|
+
continue
|
|
2015
|
+
text = _txt(body)
|
|
2016
|
+
for i, pn in enumerate(pnames):
|
|
2017
|
+
if not pn or not self._param_is_text(func, pn):
|
|
2018
|
+
continue
|
|
2019
|
+
stored = re.search(rf"\b{field}\s*:\s*{pn}\b\s*(?:\.\s*\w+\(\)\s*)*[,}}]", text) or \
|
|
2020
|
+
(pn == field and re.search(rf"[{{,]\s*{field}\s*[,}}]", text))
|
|
2021
|
+
if stored:
|
|
2022
|
+
found.append(Wrapper(name, False, i, engine, ty, self.rel))
|
|
2023
|
+
if found:
|
|
2024
|
+
self.ctx.field_sinks.add((self.rel, ty, field))
|
|
2025
|
+
self.ctx.field_ctors.update((ty, w.name) for w in found)
|
|
2026
|
+
return found
|
|
2027
|
+
|
|
2028
|
+
# ---- call sites -----------------------------------------------------
|
|
2029
|
+
def sites(self, names: set[str]) -> list[RawSite]:
|
|
2030
|
+
out: list[RawSite] = []
|
|
2031
|
+
ctx = self.ctx
|
|
2032
|
+
file_engine = self.file_engine()
|
|
2033
|
+
file_test = ctx.is_test_file(self.rel) or self.cfg_test
|
|
2034
|
+
has_db = any(c in ctx.rules.imports for c in self.crates)
|
|
2035
|
+
|
|
2036
|
+
def emit(node: Node, end: Node, kind: str, sink_text: str, engine: str, known: bool, res: Res | None, expr: str,
|
|
2037
|
+
resolution: str | None = None) -> None:
|
|
2038
|
+
if res is not None and len(res.alts) > 1: # one statement per if / else arm
|
|
2039
|
+
for text in dict.fromkeys(res.alts):
|
|
2040
|
+
one = Res(text, True, res.via_name, res.from_file)
|
|
2041
|
+
emit(node, end, kind, sink_text, engine, known, one, expr, resolution)
|
|
2042
|
+
return
|
|
2043
|
+
out.append(RawSite(
|
|
2044
|
+
file=self.rel, line=node.start_point[0] + 1, end_line=end.end_point[0] + 1, language="rust",
|
|
2045
|
+
kind=kind, sink=trim(sink_text, 80), symbol=self.symbol(node),
|
|
2046
|
+
sql=res.text if res is not None else None,
|
|
2047
|
+
resolution=resolution or (res.resolution if res is not None else "unresolved"),
|
|
2048
|
+
expr=trim(expr), in_loop=self.in_loop(node), engine_hint=self.sqlx_engine(node, engine or file_engine),
|
|
2049
|
+
is_test=file_test or self.is_test_node(node), known_sink=known,
|
|
2050
|
+
))
|
|
2051
|
+
|
|
2052
|
+
work: list[tuple[Node, Callee, str, list[int], bool, bool]] = []
|
|
2053
|
+
for call, c in self.sink_calls(names):
|
|
2054
|
+
sink = self.match_sink(c)
|
|
2055
|
+
if sink is not None:
|
|
2056
|
+
work.append((call, c, *sink))
|
|
2057
|
+
seen_closures: set[int] = set()
|
|
2058
|
+
while work:
|
|
2059
|
+
call, c, engine, idxs, from_rules, is_path = work.pop(0)
|
|
2060
|
+
argv = self._args(call)
|
|
2061
|
+
for i in idxs:
|
|
2062
|
+
if i >= len(argv):
|
|
2063
|
+
continue
|
|
2064
|
+
arg = argv[i]
|
|
2065
|
+
ctx.touched = []
|
|
2066
|
+
ctx.budget = 20000
|
|
2067
|
+
res = self.resolve(arg, None, 0)
|
|
2068
|
+
if res is not None and not res.param and not c.is_method and len(c.segs) >= 2 and \
|
|
2069
|
+
((c.name == "new" and "QueryBuilder" in c.segs) or (c.segs[-2], c.name) in ctx.field_ctors):
|
|
2070
|
+
res = self._builder_pushes(call, res)
|
|
2071
|
+
touched, ctx.touched = ctx.touched, None
|
|
2072
|
+
line_node = call
|
|
2073
|
+
if c.is_method: # report the line of `.query(`, not the start of a long chain
|
|
2074
|
+
fn = call.child_by_field_name("function")
|
|
2075
|
+
f = fn.child_by_field_name("function") if fn is not None and fn.type == "generic_function" else fn
|
|
2076
|
+
field = f.child_by_field_name("field") if f is not None else None
|
|
2077
|
+
line_node = field or call
|
|
2078
|
+
sink_text = self._sink_text(c)
|
|
2079
|
+
if res is None and (self.rel, self._impl_type(arg), self._self_field(arg)) in ctx.field_sinks:
|
|
2080
|
+
emit(line_node, call, "call", sink_text, engine, True, None, _txt(arg), "parameter")
|
|
2081
|
+
break
|
|
2082
|
+
if res is not None and res.param:
|
|
2083
|
+
if not self._text_param(arg, res) or not self._sqlish_param(arg, res):
|
|
2084
|
+
continue # the parameter is a client, a pool, a list of pairs: not SQL
|
|
2085
|
+
emit(line_node, call, "call", sink_text, engine, True, None, _txt(arg), "parameter")
|
|
2086
|
+
if res.binder is not None and res.binder.id not in seen_closures:
|
|
2087
|
+
seen_closures.add(res.binder.id)
|
|
2088
|
+
work.extend(self._closure_calls(res.binder, res.param, engine))
|
|
2089
|
+
break
|
|
2090
|
+
if res is not None:
|
|
2091
|
+
text = res.text
|
|
2092
|
+
if not SINK_SQL.match(text):
|
|
2093
|
+
if not text.lstrip().startswith("«"):
|
|
2094
|
+
continue # resolved, and it is not SQL
|
|
2095
|
+
if not SQL_WORDS.search(text):
|
|
2096
|
+
res = None # begins with an unknown part and shows no SQL: unresolved
|
|
2097
|
+
if res is None and not self._plausible_unresolved(c, arg, is_path and from_rules, bool(engine), has_db):
|
|
2098
|
+
continue
|
|
2099
|
+
emit(line_node, call, "call", sink_text, engine, True, res, _txt(arg))
|
|
2100
|
+
ctx.consumed.update(touched)
|
|
2101
|
+
for s in _walk(arg):
|
|
2102
|
+
if s.type in ("string_literal", "raw_string_literal"):
|
|
2103
|
+
ctx.consumed.add((self.rel, s.id))
|
|
2104
|
+
if arg.type in ("string_literal", "raw_string_literal"):
|
|
2105
|
+
ctx.consumed.add((self.rel, arg.id))
|
|
2106
|
+
break
|
|
2107
|
+
out.sort(key=lambda r: (r.line, r.end_line))
|
|
2108
|
+
ctx.touched = None
|
|
2109
|
+
return out
|
|
2110
|
+
|
|
2111
|
+
@staticmethod
|
|
2112
|
+
def _sink_text(c: Callee) -> str:
|
|
2113
|
+
"""`state.db.query`, `sqlx::query_as`; for a long receiver chain only `.method`."""
|
|
2114
|
+
if not c.is_method:
|
|
2115
|
+
return "::".join(c.segs)
|
|
2116
|
+
recv = re.sub(r"\s+", "", _txt(c.receiver)) if c.receiver is not None else ""
|
|
2117
|
+
if recv and len(recv) <= 48 and re.match(r"^[\w.:&*]+$", recv):
|
|
2118
|
+
return recv.lstrip("&*") + "." + c.name
|
|
2119
|
+
tail = re.search(r"([A-Za-z_]\w*)$", recv)
|
|
2120
|
+
return (tail.group(1) + "." if tail else ".") + c.name
|
|
2121
|
+
|
|
2122
|
+
def _text_param(self, arg: Node, res: Res) -> bool:
|
|
2123
|
+
"""Whether the parameter an argument resolves to can hold SQL text."""
|
|
2124
|
+
if res.binder is not None:
|
|
2125
|
+
for p in res.binder.named_children:
|
|
2126
|
+
inner = p.child_by_field_name("pattern") if p.type == "parameter" else p
|
|
2127
|
+
if inner is not None and _txt(inner).split()[-1] == res.param:
|
|
2128
|
+
ty = p.child_by_field_name("type") if p.type == "parameter" else None
|
|
2129
|
+
if ty is not None:
|
|
2130
|
+
return bool(TEXT_PARAM.match(re.sub(r"\s+", "", _txt(ty))))
|
|
2131
|
+
return bool(SQLISH_NAME.search(res.param))
|
|
2132
|
+
return False
|
|
2133
|
+
func = self._enclosing(arg, FUNC_STOP)
|
|
2134
|
+
return func is not None and self._param_is_text(func, res.param)
|
|
2135
|
+
|
|
2136
|
+
def _sqlish_param(self, arg: Node, res: Res) -> bool:
|
|
2137
|
+
"""The parameter's name, or the function's, says SQL (`sql`, `query`, `statement`, `fetch_rows`)."""
|
|
2138
|
+
if SQLISH_NAME.search(res.param):
|
|
2139
|
+
return True
|
|
2140
|
+
func = self._enclosing(arg, FUNC_STOP)
|
|
2141
|
+
nm = func.child_by_field_name("name") if func is not None else None
|
|
2142
|
+
return res.binder is None and nm is not None and bool(SQLISH_NAME.search(_txt(nm)))
|
|
2143
|
+
|
|
2144
|
+
def _closure_calls(self, params: Node, name: str, engine: str) -> list[tuple[Node, Callee, str, list[int], bool, bool]]:
|
|
2145
|
+
"""`let run = |sql: &str| client.query(sql);` makes `run(..)` a sink inside the same function."""
|
|
2146
|
+
closure = params.parent
|
|
2147
|
+
let = closure.parent if closure is not None else None
|
|
2148
|
+
if let is None or let.type != "let_declaration":
|
|
2149
|
+
return []
|
|
2150
|
+
pat = let.child_by_field_name("pattern")
|
|
2151
|
+
func = self._enclosing(let, FUNC_STOP)
|
|
2152
|
+
if pat is None or pat.type != "identifier" or func is None:
|
|
2153
|
+
return []
|
|
2154
|
+
index = -1
|
|
2155
|
+
for i, p in enumerate(params.named_children):
|
|
2156
|
+
inner = p.child_by_field_name("pattern") if p.type == "parameter" else p
|
|
2157
|
+
if inner is not None and _txt(inner).split()[-1] == name:
|
|
2158
|
+
index = i
|
|
2159
|
+
if index < 0:
|
|
2160
|
+
return []
|
|
2161
|
+
local = _txt(pat)
|
|
2162
|
+
found = []
|
|
2163
|
+
for n in _walk(func.child_by_field_name("body") or func, stop=FUNC_STOP):
|
|
2164
|
+
if n.type == "call_expression" and n.start_byte > let.end_byte:
|
|
2165
|
+
c = callee_of(n)
|
|
2166
|
+
if c is not None and not c.is_method and c.segs == [local]:
|
|
2167
|
+
found.append((n, c, engine, [index], False, False))
|
|
2168
|
+
return found
|
|
2169
|
+
|
|
2170
|
+
def _builder_pushes(self, call: Node, base: Res) -> Res:
|
|
2171
|
+
"""`let mut qb = QueryBuilder::new("..."); qb.push("...")`: append the pushed text."""
|
|
2172
|
+
n = call.parent
|
|
2173
|
+
while n is not None and n.type in ("try_expression", "await_expression", "parenthesized_expression"):
|
|
2174
|
+
n = n.parent
|
|
2175
|
+
if n is None or n.type != "let_declaration":
|
|
2176
|
+
return base
|
|
2177
|
+
pat = n.child_by_field_name("pattern")
|
|
2178
|
+
func = self._enclosing(n, FUNC_STOP)
|
|
2179
|
+
if pat is None or pat.type != "identifier" or func is None:
|
|
2180
|
+
return base
|
|
2181
|
+
name = _txt(pat)
|
|
2182
|
+
lets, _ = self._scope(func)
|
|
2183
|
+
end = func.end_byte
|
|
2184
|
+
for d in lets.get(name, ()):
|
|
2185
|
+
if d.start_byte > n.end_byte:
|
|
2186
|
+
end = d.start_byte # the name is bound again: stop there
|
|
2187
|
+
break
|
|
2188
|
+
r = self._apply_muts(name, base, None, func, n, end, None, 1, builder=True)
|
|
2189
|
+
return r if r is not None else base
|
|
2190
|
+
|
|
2191
|
+
def _plausible_unresolved(self, c: Callee, arg: Node, rule_path: bool, has_engine: bool, has_db: bool) -> bool:
|
|
2192
|
+
"""Keep an unresolved call only when it plausibly is a database call."""
|
|
2193
|
+
inner = arg
|
|
2194
|
+
while inner.type in ("reference_expression", "parenthesized_expression") and inner.named_children:
|
|
2195
|
+
inner = inner.named_children[-1]
|
|
2196
|
+
if inner.type in ("array_expression", "tuple_expression", "integer_literal", "boolean_literal", "closure_expression",
|
|
2197
|
+
"struct_expression", "float_literal", "unit_expression", "string_literal", "raw_string_literal"):
|
|
2198
|
+
return False
|
|
2199
|
+
if inner.type == "identifier":
|
|
2200
|
+
func = self._enclosing(inner, FUNC_STOP)
|
|
2201
|
+
if func is not None: # a local that is plainly a list of pairs, not text
|
|
2202
|
+
for d in self._scope(func)[0].get(_txt(inner), ()):
|
|
2203
|
+
v = d.child_by_field_name("value") if d.type == "let_declaration" else None
|
|
2204
|
+
if v is not None and d.end_byte <= inner.start_byte and re.match(r"(vec\s*!|\[|HashMap|BTreeMap|Vec::)", _txt(v)[:12]):
|
|
2205
|
+
return False
|
|
2206
|
+
if rule_path:
|
|
2207
|
+
return True
|
|
2208
|
+
text = _txt(arg)
|
|
2209
|
+
arg_ok = bool(SQLISH_NAME.search(text[:120]))
|
|
2210
|
+
if not c.is_method:
|
|
2211
|
+
return arg_ok
|
|
2212
|
+
recv = c.receiver
|
|
2213
|
+
if recv is None:
|
|
2214
|
+
return False
|
|
2215
|
+
if recv.type == "self" and any(w.is_method and w.rel == self.rel for w in self.ctx.wrappers.get(c.name, ())):
|
|
2216
|
+
return True # self.query(..) where this file defines `query` as a wrapper
|
|
2217
|
+
rtext = _txt(recv)
|
|
2218
|
+
if HTTP_CHAIN.search(rtext[-300:]):
|
|
2219
|
+
return False
|
|
2220
|
+
if recv.type == "call_expression":
|
|
2221
|
+
rc = callee_of(recv)
|
|
2222
|
+
if rc is not None and not rc.is_method:
|
|
2223
|
+
return False # Builder::new(..).query(pairs): a request builder, not a client
|
|
2224
|
+
last = re.findall(r"[A-Za-z_]\w*", rtext[-60:])
|
|
2225
|
+
receiver_ok = bool(last) and not rtext.rstrip().endswith(")") and bool(RECEIVER.search(last[-1]))
|
|
2226
|
+
if has_engine:
|
|
2227
|
+
return arg_ok or receiver_ok
|
|
2228
|
+
return arg_ok and (receiver_ok or has_db)
|
|
2229
|
+
|
|
2230
|
+
# ---- SQL strings not attached to a known sink -----------------------
|
|
2231
|
+
def loose_strings(self) -> list[RawSite]:
|
|
2232
|
+
out: list[RawSite] = []
|
|
2233
|
+
if not re.search(rb"SELECT|INSERT|CREATE|ALTER|DELETE|UPDATE|DROP|WITH|OPTIMIZE|TRUNCATE|SHOW|EXPLAIN|DESCRIBE|SYSTEM|PRAGMA|EXISTS", self.src):
|
|
2234
|
+
return out
|
|
2235
|
+
ctx = self.ctx
|
|
2236
|
+
file_engine = self.file_engine()
|
|
2237
|
+
file_test = ctx.is_test_file(self.rel) or self.cfg_test
|
|
2238
|
+
for s in QueryCursor(STRING_QUERY).captures(self.root).get("s", []):
|
|
2239
|
+
if (self.rel, s.id) in ctx.consumed or s.end_byte - s.start_byte < 14:
|
|
2240
|
+
continue
|
|
2241
|
+
raw = decode_literal(_txt(s))
|
|
2242
|
+
if raw is None or not looks_like_sql(raw):
|
|
2243
|
+
continue
|
|
2244
|
+
node = s
|
|
2245
|
+
parent = s.parent
|
|
2246
|
+
if parent is not None and parent.type == "token_tree":
|
|
2247
|
+
mac = parent.parent
|
|
2248
|
+
if mac is None or mac.type != "macro_invocation":
|
|
2249
|
+
continue
|
|
2250
|
+
name = re.sub(r"\s+", "", _txt(mac.child_by_field_name("macro"))).split("::")[-1] if mac.child_by_field_name("macro") is not None else ""
|
|
2251
|
+
first = self._tt_args(parent)
|
|
2252
|
+
if name in ("format", "formatdoc", "concat", "indoc", "format_args", "concatcp", "formatcp") and first and first[0] and first[0][0].id == s.id:
|
|
2253
|
+
node = mac
|
|
2254
|
+
elif name in ("write", "writeln"):
|
|
2255
|
+
continue # a fragment appended to a string that did not reach a sink we resolved
|
|
2256
|
+
elif mac.parent is not None and mac.parent.type == "token_tree":
|
|
2257
|
+
continue # nested deeper in a macro: handled (or not) by the outer one
|
|
2258
|
+
elif name not in ("vec", "json", "lazy_static", "sql", "query", "query_as", "query_scalar"):
|
|
2259
|
+
continue # assert!, println!, log macros, ...
|
|
2260
|
+
ctx.budget = 20000
|
|
2261
|
+
res = self.resolve(node, None, 0)
|
|
2262
|
+
if res is None or not looks_like_sql(res.text):
|
|
2263
|
+
continue
|
|
2264
|
+
# climb through conversions: "..".to_string(), String::from(".."), &"..", "..".replace(..)
|
|
2265
|
+
top = node
|
|
2266
|
+
while top.parent is not None:
|
|
2267
|
+
p = top.parent
|
|
2268
|
+
if p.type in ("reference_expression", "parenthesized_expression"):
|
|
2269
|
+
top = p
|
|
2270
|
+
elif p.type == "field_expression" and p.parent is not None and p.parent.type == "call_expression" \
|
|
2271
|
+
and p.child_by_field_name("value") is not None and p.child_by_field_name("value").id == top.id:
|
|
2272
|
+
cc = callee_of(p.parent)
|
|
2273
|
+
if cc is None or (cc.name not in PASS_METHODS and cc.name not in ("replace", "replacen")):
|
|
2274
|
+
break
|
|
2275
|
+
if cc.name in ("replace", "replacen"):
|
|
2276
|
+
r2 = self.resolve(p.parent, None, 0)
|
|
2277
|
+
if r2 is not None:
|
|
2278
|
+
res = r2
|
|
2279
|
+
top = p.parent
|
|
2280
|
+
elif p.type == "arguments" and p.parent is not None and p.parent.type == "call_expression":
|
|
2281
|
+
cc = callee_of(p.parent)
|
|
2282
|
+
if cc is None or cc.is_method or "::".join(cc.segs[-2:]) not in PASS_PATHS:
|
|
2283
|
+
break
|
|
2284
|
+
top = p.parent
|
|
2285
|
+
else:
|
|
2286
|
+
break
|
|
2287
|
+
call = None
|
|
2288
|
+
if top.parent is not None and top.parent.type == "arguments" and top.parent.parent is not None \
|
|
2289
|
+
and top.parent.parent.type == "call_expression":
|
|
2290
|
+
call = top.parent.parent
|
|
2291
|
+
sink_text = ""
|
|
2292
|
+
if call is not None:
|
|
2293
|
+
fn = call.child_by_field_name("function")
|
|
2294
|
+
sink_text = _txt(fn) if fn is not None else ""
|
|
2295
|
+
if NOT_A_SINK.search(sink_text.split("::<")[0]):
|
|
2296
|
+
continue
|
|
2297
|
+
out.append(RawSite(
|
|
2298
|
+
file=self.rel, line=node.start_point[0] + 1, end_line=node.end_point[0] + 1, language="rust",
|
|
2299
|
+
kind="call" if call is not None else "sql_string", sink=trim(sink_text, 80), symbol=self.symbol(node),
|
|
2300
|
+
sql=res.text, resolution=res.resolution, expr=trim(_txt(node)), in_loop=self.in_loop(node),
|
|
2301
|
+
engine_hint=file_engine, is_test=file_test or self.is_test_node(node), known_sink=False,
|
|
2302
|
+
))
|
|
2303
|
+
return out
|
|
2304
|
+
|
|
2305
|
+
|
|
2306
|
+
def _dedent(text: str) -> str:
|
|
2307
|
+
lines = text.split("\n")
|
|
2308
|
+
if lines and not lines[0].strip():
|
|
2309
|
+
lines = lines[1:]
|
|
2310
|
+
indent = min((len(l) - len(l.lstrip()) for l in lines if l.strip()), default=0)
|
|
2311
|
+
return "\n".join(l[indent:] for l in lines)
|
|
2312
|
+
|
|
2313
|
+
|
|
2314
|
+
def extract(root: Path, files: list[str], rules: LangRules) -> list[RawSite]:
|
|
2315
|
+
"""Index every file, find wrapper functions, then find call sites and loose SQL strings."""
|
|
2316
|
+
ctx = Ctx(root, rules)
|
|
2317
|
+
sources: dict[str, bytes] = {}
|
|
2318
|
+
for rel in files:
|
|
2319
|
+
text = read_text(root / rel)
|
|
2320
|
+
if text is not None:
|
|
2321
|
+
sources[rel] = text.encode("utf-8")
|
|
2322
|
+
ctx.string_macros = string_macros(list(sources.values()))
|
|
2323
|
+
for rel, src in sources.items():
|
|
2324
|
+
try:
|
|
2325
|
+
f = RsFile(rel, src, ctx)
|
|
2326
|
+
except (RecursionError, ValueError):
|
|
2327
|
+
continue
|
|
2328
|
+
ctx.files[rel] = f
|
|
2329
|
+
for name, items in f.consts.items():
|
|
2330
|
+
for item in items:
|
|
2331
|
+
ctx.consts[name].append((f, item))
|
|
2332
|
+
for name, items in f.fns.items():
|
|
2333
|
+
for item in items:
|
|
2334
|
+
ctx.fns[name].append((f, item))
|
|
2335
|
+
for name, item in f.macros.items():
|
|
2336
|
+
ctx.macros[name].append((f, item))
|
|
2337
|
+
|
|
2338
|
+
# Wrappers, to a fixed point: a function that passes its parameter to a sink is a sink.
|
|
2339
|
+
names = set(ctx.method_sinks) | {rule[-1] for rule, _ in ctx.path_sinks}
|
|
2340
|
+
frontier = set(names)
|
|
2341
|
+
for _ in range(5):
|
|
2342
|
+
new: set[str] = set()
|
|
2343
|
+
for f in ctx.files.values():
|
|
2344
|
+
try:
|
|
2345
|
+
found = f.find_wrappers(frontier)
|
|
2346
|
+
except RecursionError:
|
|
2347
|
+
continue
|
|
2348
|
+
for w in found:
|
|
2349
|
+
known = ctx.wrappers[w.name]
|
|
2350
|
+
if any(k.is_method == w.is_method and k.index == w.index and k.impl_type == w.impl_type and k.rel == w.rel for k in known):
|
|
2351
|
+
continue
|
|
2352
|
+
known.append(w)
|
|
2353
|
+
if w.name not in names:
|
|
2354
|
+
new.add(w.name)
|
|
2355
|
+
if not new:
|
|
2356
|
+
break
|
|
2357
|
+
names |= new
|
|
2358
|
+
frontier = new
|
|
2359
|
+
|
|
2360
|
+
out: list[RawSite] = []
|
|
2361
|
+
for f in ctx.files.values():
|
|
2362
|
+
try:
|
|
2363
|
+
out.extend(f.sites(names))
|
|
2364
|
+
except RecursionError:
|
|
2365
|
+
ctx.touched = None
|
|
2366
|
+
continue
|
|
2367
|
+
for f in ctx.files.values():
|
|
2368
|
+
try:
|
|
2369
|
+
out.extend(f.loose_strings())
|
|
2370
|
+
except RecursionError:
|
|
2371
|
+
continue
|
|
2372
|
+
from . import orm_rust # Diesel: the table! schema and query DSL chains as SQL
|
|
2373
|
+
return orm_rust.extend(root, ctx, out)
|
|
2374
|
+
|
|
2375
|
+
|
|
2376
|
+
def summary_extras() -> dict:
|
|
2377
|
+
from . import orm_rust
|
|
2378
|
+
return orm_rust.summary_extras()
|