causoryn 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/.claude-plugin/plugin.json +36 -0
  2. package/.codex-plugin/mcp.json +19 -0
  3. package/.codex-plugin/plugin.json +38 -0
  4. package/.zcode-plugin/plugin.json +42 -0
  5. package/LICENSE +21 -0
  6. package/README.md +171 -2
  7. package/THIRD-PARTY-NOTICES.md +443 -0
  8. package/dist/bundle-manifest.json +39 -0
  9. package/dist/cli.d.ts +3 -0
  10. package/dist/cli.js +253 -0
  11. package/dist/doctor.d.ts +13 -0
  12. package/dist/doctor.js +507 -0
  13. package/dist/index.d.ts +10 -0
  14. package/dist/index.js +10 -0
  15. package/dist/mcp-server.mjs +288477 -0
  16. package/dist/mcp-server.mjs.LEGAL.txt +17 -0
  17. package/dist/node_modules/better-sqlite3/LICENSE +21 -0
  18. package/dist/node_modules/better-sqlite3/lib/binding.js +62 -0
  19. package/dist/node_modules/better-sqlite3/lib/darwin-arm64.js +3 -0
  20. package/dist/node_modules/better-sqlite3/lib/darwin-x64.js +3 -0
  21. package/dist/node_modules/better-sqlite3/lib/database.js +109 -0
  22. package/dist/node_modules/better-sqlite3/lib/index.js +3 -0
  23. package/dist/node_modules/better-sqlite3/lib/linux-arm64.js +3 -0
  24. package/dist/node_modules/better-sqlite3/lib/linux-x64.js +3 -0
  25. package/dist/node_modules/better-sqlite3/lib/linuxmusl-arm64.js +4 -0
  26. package/dist/node_modules/better-sqlite3/lib/linuxmusl-x64.js +4 -0
  27. package/dist/node_modules/better-sqlite3/lib/methods/aggregate.js +43 -0
  28. package/dist/node_modules/better-sqlite3/lib/methods/backup.js +67 -0
  29. package/dist/node_modules/better-sqlite3/lib/methods/explain.js +9 -0
  30. package/dist/node_modules/better-sqlite3/lib/methods/function.js +31 -0
  31. package/dist/node_modules/better-sqlite3/lib/methods/inspect.js +7 -0
  32. package/dist/node_modules/better-sqlite3/lib/methods/pragma.js +12 -0
  33. package/dist/node_modules/better-sqlite3/lib/methods/serialize.js +16 -0
  34. package/dist/node_modules/better-sqlite3/lib/methods/table.js +195 -0
  35. package/dist/node_modules/better-sqlite3/lib/methods/transaction.js +78 -0
  36. package/dist/node_modules/better-sqlite3/lib/methods/wrappers.js +54 -0
  37. package/dist/node_modules/better-sqlite3/lib/sqlite-error.js +25 -0
  38. package/dist/node_modules/better-sqlite3/lib/util.js +12 -0
  39. package/dist/node_modules/better-sqlite3/lib/win32-arm64.js +3 -0
  40. package/dist/node_modules/better-sqlite3/lib/win32-x64.js +3 -0
  41. package/dist/node_modules/better-sqlite3/package.json +67 -0
  42. package/dist/node_modules/better-sqlite3/prebuilds/darwin-arm64.node +0 -0
  43. package/dist/node_modules/better-sqlite3/prebuilds/darwin-x64.node +0 -0
  44. package/dist/node_modules/better-sqlite3/prebuilds/linux-arm64.node +0 -0
  45. package/dist/node_modules/better-sqlite3/prebuilds/linux-x64.node +0 -0
  46. package/dist/node_modules/better-sqlite3/prebuilds/linuxmusl-arm64.node +0 -0
  47. package/dist/node_modules/better-sqlite3/prebuilds/linuxmusl-x64.node +0 -0
  48. package/dist/node_modules/better-sqlite3/prebuilds/win32-arm64.node +0 -0
  49. package/dist/node_modules/better-sqlite3/prebuilds/win32-x64.node +0 -0
  50. package/dist/runtime-stage.d.ts +8 -0
  51. package/dist/runtime-stage.js +159 -0
  52. package/dist/setup.d.ts +15 -0
  53. package/dist/setup.js +735 -0
  54. package/dist/toml-patch.d.ts +10 -0
  55. package/dist/toml-patch.js +587 -0
  56. package/dist/types.d.ts +144 -0
  57. package/dist/types.js +35 -0
  58. package/dist/typescript-lib/lib.d.ts +22 -0
  59. package/dist/typescript-lib/lib.decorators.d.ts +384 -0
  60. package/dist/typescript-lib/lib.decorators.legacy.d.ts +22 -0
  61. package/dist/typescript-lib/lib.dom.asynciterable.d.ts +41 -0
  62. package/dist/typescript-lib/lib.dom.d.ts +39429 -0
  63. package/dist/typescript-lib/lib.dom.iterable.d.ts +571 -0
  64. package/dist/typescript-lib/lib.es2015.collection.d.ts +147 -0
  65. package/dist/typescript-lib/lib.es2015.core.d.ts +597 -0
  66. package/dist/typescript-lib/lib.es2015.d.ts +28 -0
  67. package/dist/typescript-lib/lib.es2015.generator.d.ts +77 -0
  68. package/dist/typescript-lib/lib.es2015.iterable.d.ts +605 -0
  69. package/dist/typescript-lib/lib.es2015.promise.d.ts +81 -0
  70. package/dist/typescript-lib/lib.es2015.proxy.d.ts +128 -0
  71. package/dist/typescript-lib/lib.es2015.reflect.d.ts +144 -0
  72. package/dist/typescript-lib/lib.es2015.symbol.d.ts +46 -0
  73. package/dist/typescript-lib/lib.es2015.symbol.wellknown.d.ts +326 -0
  74. package/dist/typescript-lib/lib.es2016.array.include.d.ts +116 -0
  75. package/dist/typescript-lib/lib.es2016.d.ts +21 -0
  76. package/dist/typescript-lib/lib.es2016.full.d.ts +23 -0
  77. package/dist/typescript-lib/lib.es2016.intl.d.ts +31 -0
  78. package/dist/typescript-lib/lib.es2017.arraybuffer.d.ts +21 -0
  79. package/dist/typescript-lib/lib.es2017.d.ts +26 -0
  80. package/dist/typescript-lib/lib.es2017.date.d.ts +31 -0
  81. package/dist/typescript-lib/lib.es2017.full.d.ts +23 -0
  82. package/dist/typescript-lib/lib.es2017.intl.d.ts +44 -0
  83. package/dist/typescript-lib/lib.es2017.object.d.ts +49 -0
  84. package/dist/typescript-lib/lib.es2017.sharedmemory.d.ts +135 -0
  85. package/dist/typescript-lib/lib.es2017.string.d.ts +45 -0
  86. package/dist/typescript-lib/lib.es2017.typedarrays.d.ts +53 -0
  87. package/dist/typescript-lib/lib.es2018.asyncgenerator.d.ts +77 -0
  88. package/dist/typescript-lib/lib.es2018.asynciterable.d.ts +53 -0
  89. package/dist/typescript-lib/lib.es2018.d.ts +24 -0
  90. package/dist/typescript-lib/lib.es2018.full.d.ts +24 -0
  91. package/dist/typescript-lib/lib.es2018.intl.d.ts +83 -0
  92. package/dist/typescript-lib/lib.es2018.promise.d.ts +30 -0
  93. package/dist/typescript-lib/lib.es2018.regexp.d.ts +37 -0
  94. package/dist/typescript-lib/lib.es2019.array.d.ts +79 -0
  95. package/dist/typescript-lib/lib.es2019.d.ts +24 -0
  96. package/dist/typescript-lib/lib.es2019.full.d.ts +24 -0
  97. package/dist/typescript-lib/lib.es2019.intl.d.ts +23 -0
  98. package/dist/typescript-lib/lib.es2019.object.d.ts +33 -0
  99. package/dist/typescript-lib/lib.es2019.string.d.ts +37 -0
  100. package/dist/typescript-lib/lib.es2019.symbol.d.ts +24 -0
  101. package/dist/typescript-lib/lib.es2020.bigint.d.ts +765 -0
  102. package/dist/typescript-lib/lib.es2020.d.ts +27 -0
  103. package/dist/typescript-lib/lib.es2020.date.d.ts +42 -0
  104. package/dist/typescript-lib/lib.es2020.full.d.ts +24 -0
  105. package/dist/typescript-lib/lib.es2020.intl.d.ts +474 -0
  106. package/dist/typescript-lib/lib.es2020.number.d.ts +28 -0
  107. package/dist/typescript-lib/lib.es2020.promise.d.ts +47 -0
  108. package/dist/typescript-lib/lib.es2020.sharedmemory.d.ts +99 -0
  109. package/dist/typescript-lib/lib.es2020.string.d.ts +44 -0
  110. package/dist/typescript-lib/lib.es2020.symbol.wellknown.d.ts +41 -0
  111. package/dist/typescript-lib/lib.es2021.d.ts +23 -0
  112. package/dist/typescript-lib/lib.es2021.full.d.ts +24 -0
  113. package/dist/typescript-lib/lib.es2021.intl.d.ts +166 -0
  114. package/dist/typescript-lib/lib.es2021.promise.d.ts +48 -0
  115. package/dist/typescript-lib/lib.es2021.string.d.ts +33 -0
  116. package/dist/typescript-lib/lib.es2021.weakref.d.ts +78 -0
  117. package/dist/typescript-lib/lib.es2022.array.d.ts +121 -0
  118. package/dist/typescript-lib/lib.es2022.d.ts +25 -0
  119. package/dist/typescript-lib/lib.es2022.error.d.ts +75 -0
  120. package/dist/typescript-lib/lib.es2022.full.d.ts +24 -0
  121. package/dist/typescript-lib/lib.es2022.intl.d.ts +145 -0
  122. package/dist/typescript-lib/lib.es2022.object.d.ts +26 -0
  123. package/dist/typescript-lib/lib.es2022.regexp.d.ts +39 -0
  124. package/dist/typescript-lib/lib.es2022.string.d.ts +25 -0
  125. package/dist/typescript-lib/lib.es2023.array.d.ts +924 -0
  126. package/dist/typescript-lib/lib.es2023.collection.d.ts +21 -0
  127. package/dist/typescript-lib/lib.es2023.d.ts +22 -0
  128. package/dist/typescript-lib/lib.es2023.full.d.ts +24 -0
  129. package/dist/typescript-lib/lib.es2023.intl.d.ts +56 -0
  130. package/dist/typescript-lib/lib.es2024.arraybuffer.d.ts +65 -0
  131. package/dist/typescript-lib/lib.es2024.collection.d.ts +29 -0
  132. package/dist/typescript-lib/lib.es2024.d.ts +26 -0
  133. package/dist/typescript-lib/lib.es2024.full.d.ts +24 -0
  134. package/dist/typescript-lib/lib.es2024.object.d.ts +29 -0
  135. package/dist/typescript-lib/lib.es2024.promise.d.ts +35 -0
  136. package/dist/typescript-lib/lib.es2024.regexp.d.ts +25 -0
  137. package/dist/typescript-lib/lib.es2024.sharedmemory.d.ts +68 -0
  138. package/dist/typescript-lib/lib.es2024.string.d.ts +29 -0
  139. package/dist/typescript-lib/lib.es5.d.ts +4601 -0
  140. package/dist/typescript-lib/lib.es6.d.ts +23 -0
  141. package/dist/typescript-lib/lib.esnext.array.d.ts +35 -0
  142. package/dist/typescript-lib/lib.esnext.collection.d.ts +96 -0
  143. package/dist/typescript-lib/lib.esnext.d.ts +29 -0
  144. package/dist/typescript-lib/lib.esnext.decorators.d.ts +28 -0
  145. package/dist/typescript-lib/lib.esnext.disposable.d.ts +193 -0
  146. package/dist/typescript-lib/lib.esnext.error.d.ts +24 -0
  147. package/dist/typescript-lib/lib.esnext.float16.d.ts +445 -0
  148. package/dist/typescript-lib/lib.esnext.full.d.ts +24 -0
  149. package/dist/typescript-lib/lib.esnext.intl.d.ts +21 -0
  150. package/dist/typescript-lib/lib.esnext.iterator.d.ts +148 -0
  151. package/dist/typescript-lib/lib.esnext.promise.d.ts +34 -0
  152. package/dist/typescript-lib/lib.esnext.sharedmemory.d.ts +25 -0
  153. package/dist/typescript-lib/lib.scripthost.d.ts +322 -0
  154. package/dist/typescript-lib/lib.webworker.asynciterable.d.ts +41 -0
  155. package/dist/typescript-lib/lib.webworker.d.ts +13150 -0
  156. package/dist/typescript-lib/lib.webworker.importscripts.d.ts +23 -0
  157. package/dist/typescript-lib/lib.webworker.iterable.d.ts +340 -0
  158. package/licenses/Apache-2.0.txt +55 -0
  159. package/licenses/TypeScript-ThirdPartyNoticeText.txt +193 -0
  160. package/licenses/better-sqlite3-LICENSE.txt +21 -0
  161. package/mcp_config.json +16 -0
  162. package/native/go-worker/PROTOCOL.md +316 -0
  163. package/native/go-worker/cmd/worker/main.go +440 -0
  164. package/native/go-worker/go.mod +3 -0
  165. package/native/go-worker/internal/analyze/analyze.go +820 -0
  166. package/native/go-worker/internal/analyze/model.go +182 -0
  167. package/native/go-worker/internal/analyze/routes.go +181 -0
  168. package/native/python-worker/PROTOCOL.md +342 -0
  169. package/native/python-worker/worker.py +1190 -0
  170. package/native/roslyn-worker/Causoryn.RoslynWorker.csproj +40 -0
  171. package/native/roslyn-worker/Causoryn.RoslynWorker.deps.json +59 -0
  172. package/native/roslyn-worker/Causoryn.RoslynWorker.dll +0 -0
  173. package/native/roslyn-worker/Causoryn.RoslynWorker.runtimeconfig.json +13 -0
  174. package/native/roslyn-worker/Microsoft.CodeAnalysis.CSharp.dll +0 -0
  175. package/native/roslyn-worker/Microsoft.CodeAnalysis.dll +0 -0
  176. package/native/roslyn-worker/PROTOCOL.md +285 -0
  177. package/native/roslyn-worker/Program.cs +249 -0
  178. package/native/roslyn-worker/Protocol.cs +397 -0
  179. package/native/roslyn-worker/ReferenceResolver.cs +235 -0
  180. package/native/roslyn-worker/WorkerAnalyzer.cs +1669 -0
  181. package/native/roslyn-worker/packages.lock.json +30 -0
  182. package/native/rust-worker/Cargo.lock +107 -0
  183. package/native/rust-worker/Cargo.toml +23 -0
  184. package/native/rust-worker/PROTOCOL.md +294 -0
  185. package/native/rust-worker/src/analyzer.rs +1209 -0
  186. package/native/rust-worker/src/main.rs +127 -0
  187. package/native/rust-worker/src/protocol.rs +284 -0
  188. package/native/rust-worker/src/sha256.rs +136 -0
  189. package/package.json +71 -4
  190. package/plugin.json +17 -0
  191. package/scripts/causoryn.mjs +40 -0
  192. package/scripts/lib/node-version-guard.mjs +24 -0
  193. package/scripts/plugin-mcp-launcher.mjs +111 -0
  194. package/skills/causoryn/SKILL.md +53 -0
  195. package/skills/map-system/SKILL.md +69 -0
  196. package/skills/preflight-change/SKILL.md +38 -0
  197. package/skills/verify-change/SKILL.md +31 -0
@@ -0,0 +1,1209 @@
1
+ //! syn 2 tabanlı deterministik analiz — M1-Rust.
2
+ //!
3
+ //! Çıkarım sözleşmesi (native/rust-worker/PROTOCOL.md v1):
4
+ //! - Bildirimler: fn → Function, struct/enum → Class, trait → Interface,
5
+ //! impl fn → Method (CONTAINS File→tip, tip→Method).
6
+ //! - CALLS resolution üçlüsü:
7
+ //! * aynı modülde tanımlı fn'e doğrudan (bare) çağrı → verified,
8
+ //! * nitelikli yol çağrısı (a::B::c / B::c) → analiz seti isim
9
+ //! tablosunda TEK eşleşme → verified (modül önekleri tam
10
+ //! doğrulanmaz — belgeli sınırlama), çok eşleşme → heuristic +
11
+ //! ambiguity, hiç eşleşme yok → unresolved + UnknownExternal,
12
+ //! * metot çağrısı (x.foo()) → alıcı türü çözülmez (trait dispatch
13
+ //! bu dilimde yok) → heuristic; tek isim tablosu adayı hedef,
14
+ //! çok aday → ambiguity, aday yok → unresolved.
15
+ //! verified/heuristic kenarlar "semantic-symbol", unresolved kenarlar ve
16
+ //! CONTAINS "ast-span", ROUTES_TO "route-attribute" kanıt türünü taşır
17
+ //! (kanıt türleri TŞ §8 kümesinden; rationale metni isim tablosu
18
+ //! dayanağını DÜRÜST belirtir — semantik çözümleyici yoktur).
19
+ //! - Route tespiti: #[get/post/put/delete/patch/head/options/connect/trace("…")]
20
+ //! ve #[route("…", method = …)] (axum/actix/rocket örüntüleri) → Endpoint
21
+ //! node + ROUTES_TO (verified, sözdizimsel bağ).
22
+ //! - Determinizm: BTreeMap/BTreeSet, kanonik sıralama, saat okunmaz.
23
+
24
+ use std::collections::{BTreeMap, BTreeSet};
25
+
26
+ use serde_json::{json, Value};
27
+ use syn::spanned::Spanned;
28
+ use syn::visit::Visit;
29
+ use syn::{Attribute, Expr, Item, Lit};
30
+
31
+ use crate::protocol::{ANALYZER_ID, ANALYZER_VERSION, MAX_RESPONSE_NODES, ROUTE_DETECTION};
32
+ use crate::sha256::sha256_hex;
33
+
34
+ pub struct FileEntry {
35
+ pub path: String,
36
+ pub content: String,
37
+ }
38
+
39
+ pub struct Diagnostic {
40
+ pub relative_path: String,
41
+ pub code: String,
42
+ pub message: String,
43
+ pub line: usize,
44
+ }
45
+
46
+ /// Node kimliği (domain NodeRef karşılığı; rel_path boşsa relativePath yok).
47
+ #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
48
+ struct NodeKey {
49
+ kind: &'static str,
50
+ qualified: String,
51
+ rel_path: String,
52
+ }
53
+
54
+ impl NodeKey {
55
+ fn with_path(kind: &'static str, qualified: String, rel_path: &str) -> Self {
56
+ NodeKey {
57
+ kind,
58
+ qualified,
59
+ rel_path: rel_path.to_string(),
60
+ }
61
+ }
62
+
63
+ fn virtual_(kind: &'static str, qualified: String) -> Self {
64
+ NodeKey {
65
+ kind,
66
+ qualified,
67
+ rel_path: String::new(),
68
+ }
69
+ }
70
+ }
71
+
72
+ #[derive(Clone)]
73
+ struct EdgeRec {
74
+ kind: &'static str,
75
+ from: NodeKey,
76
+ to: NodeKey,
77
+ resolution: &'static str,
78
+ evidence: Vec<Value>,
79
+ ambiguity: Option<Value>,
80
+ }
81
+
82
+ /// Kenar birleştirme anahtarı — (kind, from, to, resolution) dörtlüsü.
83
+ /// Aynı anahtarlı kenarlar tek EdgeRec'te birleşir; kanonik çıktı sırası
84
+ /// da bu anahtarla kurulur (analyze sonundaki sıralama ile aynı alanlar).
85
+ #[derive(PartialEq, Eq, PartialOrd, Ord)]
86
+ struct EdgeKey {
87
+ kind: &'static str,
88
+ from: NodeKey,
89
+ to: NodeKey,
90
+ resolution: &'static str,
91
+ }
92
+
93
+ /// Bu dilimde modellenmeyen yapılar — TŞ §7 unsupportedConstructs beyanı.
94
+ const UNSUPPORTED_CONSTRUCTS: [&str; 6] = [
95
+ // Metot çağrısının alıcı türü çözülmez: trait metodu hangi implementasyon
96
+ // üzerinde koşar, sorusu bu dilimde cevaplanmaz (isim tablosu adayları
97
+ // heuristic + ambiguity ile raporlanır).
98
+ "trait-method-dispatch",
99
+ // Makro gövdeleri gezilmez (println!, vec! vb. ürettikleri kod analiz
100
+ // edilmez); makro ile tanımlı üst-düzey öğeler atlanır.
101
+ "macro-defined-items",
102
+ // `use` import'ları IMPORTS kenarı üretmez ve çözümlenmez.
103
+ "use-import-resolution",
104
+ // Analiz seti dışındaki crate sembolleri çözülmez (UnknownExternal).
105
+ "cross-crate-symbol-resolution",
106
+ // Fonksiyon İÇİ nested fn/trait/impl öğelerinin gövdeleri gezilmez.
107
+ "nested-fn-items",
108
+ // struct literal (Order { .. }) REFERENCES kenarı üretmez.
109
+ "struct-literal-references",
110
+ ];
111
+
112
+ #[derive(Default)]
113
+ struct Tables {
114
+ nodes: BTreeMap<NodeKey, Value>,
115
+ /// Aynı dosya (modül) içindeki serbest fn: ident → node anahtarı.
116
+ free_fn_by_file: Vec<(String, BTreeMap<String, NodeKey>)>,
117
+ /// (modül son segmenti, fn adı) → adaylar (nitelikli yol çağrısı için).
118
+ free_fn_global: BTreeMap<(String, String), Vec<NodeKey>>,
119
+ /// Bare fn adı → adaylar (import kanıtı olmayan çapraz dosya eşleşmesi).
120
+ free_fn_bare: BTreeMap<String, Vec<NodeKey>>,
121
+ /// (ebeveyn tip adı, metot adı) → adaylar.
122
+ methods: BTreeMap<(String, String), Vec<NodeKey>>,
123
+ /// Bare metot adı → adaylar (metot çağrısı çözümü).
124
+ methods_bare: BTreeMap<String, Vec<NodeKey>>,
125
+ /// Bildirilen tipler: tip adı → node anahtarı (impl bağlama için).
126
+ declared_types: BTreeMap<String, NodeKey>,
127
+ edges: Vec<EdgeRec>,
128
+ /// EdgeKey → edges dizin konumu. push_edge'in her yeni kenarda tüm
129
+ /// edges dizisini doğrusal taraması (O(E²)) yerine BTreeMap araması
130
+ /// (O(E log E)) — sembol-yoğun girdide tek istek başına CPU savunması.
131
+ edge_index: BTreeMap<EdgeKey, usize>,
132
+ evidence_seen: BTreeSet<String>,
133
+ evidence: Vec<Value>,
134
+ diagnostics: Vec<Diagnostic>,
135
+ }
136
+
137
+ fn span_lines<T: Spanned>(item: &T) -> (usize, usize) {
138
+ let span = item.span();
139
+ let start = span.start().line.max(1);
140
+ let end = span.end().line.max(start);
141
+ (start, end)
142
+ }
143
+
144
+ fn node_value(key: &NodeKey, attributes: Value) -> Value {
145
+ let mut value = json!({
146
+ "kind": key.kind,
147
+ "qualifiedName": key.qualified,
148
+ "language": "rust",
149
+ "attributes": attributes,
150
+ });
151
+ if !key.rel_path.is_empty() {
152
+ value["relativePath"] = Value::String(key.rel_path.clone());
153
+ }
154
+ value
155
+ }
156
+
157
+ fn insert_node(tables: &mut Tables, key: NodeKey, attributes: Value) -> NodeKey {
158
+ tables
159
+ .nodes
160
+ .entry(key.clone())
161
+ .or_insert_with(|| node_value(&key, attributes));
162
+ key
163
+ }
164
+
165
+ fn push_evidence(
166
+ tables: &mut Tables,
167
+ kind: &str,
168
+ rel_path: &str,
169
+ start_line: usize,
170
+ end_line: usize,
171
+ source_hash: &str,
172
+ rationale: String,
173
+ ) -> Value {
174
+ let evidence = json!({
175
+ "kind": kind,
176
+ "span": {
177
+ "relativePath": rel_path,
178
+ "startLine": start_line,
179
+ "endLine": end_line,
180
+ "sourceHash": source_hash,
181
+ },
182
+ "analyzerId": ANALYZER_ID,
183
+ "analyzerVersion": ANALYZER_VERSION,
184
+ "rationale": rationale,
185
+ });
186
+ let key = serde_json::to_string(&evidence).unwrap_or_default();
187
+ if tables.evidence_seen.insert(key) {
188
+ tables.evidence.push(evidence.clone());
189
+ }
190
+ evidence
191
+ }
192
+
193
+ #[allow(clippy::too_many_arguments)]
194
+ fn push_edge(
195
+ tables: &mut Tables,
196
+ kind: &'static str,
197
+ from: NodeKey,
198
+ to: NodeKey,
199
+ resolution: &'static str,
200
+ evidence: Value,
201
+ ambiguity: Option<Value>,
202
+ ) {
203
+ // Birleştirme araması BTreeMap indeksiyle: doğrusal tarama yok.
204
+ let key = EdgeKey {
205
+ kind,
206
+ from: from.clone(),
207
+ to: to.clone(),
208
+ resolution,
209
+ };
210
+ if let Some(&index) = tables.edge_index.get(&key) {
211
+ let existing = &mut tables.edges[index];
212
+ if !existing.evidence.contains(&evidence) {
213
+ existing.evidence.push(evidence);
214
+ existing.evidence.sort_by(|a, b| {
215
+ let key_a = serde_json::to_string(a).unwrap_or_default();
216
+ let key_b = serde_json::to_string(b).unwrap_or_default();
217
+ key_a.cmp(&key_b)
218
+ });
219
+ }
220
+ return;
221
+ }
222
+ tables.edge_index.insert(key, tables.edges.len());
223
+ tables.edges.push(EdgeRec {
224
+ kind,
225
+ from,
226
+ to,
227
+ resolution,
228
+ evidence: vec![evidence],
229
+ ambiguity,
230
+ });
231
+ }
232
+
233
+ /// relativePath → modül yolu (belgeli kural: "src/" öneki atılır; son
234
+ /// segment main/lib/mod atılır; kalan boşsa "crate").
235
+ fn module_path_of(rel_path: &str) -> String {
236
+ let trimmed = rel_path.strip_suffix(".rs").unwrap_or(rel_path);
237
+ let mut segments: Vec<&str> = trimmed
238
+ .split('/')
239
+ .filter(|s| !s.is_empty() && *s != ".")
240
+ .collect();
241
+ if segments.first() == Some(&"src") {
242
+ segments.remove(0);
243
+ }
244
+ if let Some(last) = segments.last() {
245
+ if *last == "main" || *last == "lib" || *last == "mod" {
246
+ segments.pop();
247
+ }
248
+ }
249
+ if segments.is_empty() {
250
+ "crate".to_string()
251
+ } else {
252
+ format!("crate::{}", segments.join("::"))
253
+ }
254
+ }
255
+
256
+ const ROUTE_VERBS: [&str; 9] = [
257
+ "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "CONNECT", "TRACE",
258
+ ];
259
+
260
+ fn expr_to_method(expr: &Expr) -> Option<String> {
261
+ match expr {
262
+ Expr::Lit(lit) => match &lit.lit {
263
+ Lit::Str(s) => Some(s.value().to_ascii_uppercase()),
264
+ _ => None,
265
+ },
266
+ Expr::Path(path) => path
267
+ .path
268
+ .segments
269
+ .last()
270
+ .map(|segment| segment.ident.to_string().to_ascii_uppercase()),
271
+ _ => None,
272
+ }
273
+ }
274
+
275
+ /// #[get("/orders")] / #[route("/orders", method = "GET")] / axum tarzı
276
+ /// #[route("/orders", method(GET))] ayrıştırması. Return: (method, path).
277
+ fn parse_route_attr(attr: &Attribute) -> Option<(String, String)> {
278
+ let ident = attr
279
+ .path()
280
+ .segments
281
+ .last()
282
+ .map(|segment| segment.ident.to_string().to_ascii_uppercase())?;
283
+
284
+ let mut method: Option<String> = None;
285
+ if ROUTE_VERBS.contains(&ident.as_str()) {
286
+ method = Some(ident);
287
+ } else if ident != "ROUTE" {
288
+ return None;
289
+ }
290
+
291
+ let exprs = attr
292
+ .parse_args_with(
293
+ syn::punctuated::Punctuated::<Expr, syn::token::Comma>::parse_terminated,
294
+ )
295
+ .ok()?;
296
+
297
+ let mut path: Option<String> = None;
298
+ let mut arg_method: Option<String> = None;
299
+ for expr in exprs {
300
+ match expr {
301
+ Expr::Lit(lit) => {
302
+ if let Lit::Str(s) = &lit.lit {
303
+ if path.is_none() {
304
+ path = Some(s.value());
305
+ }
306
+ }
307
+ }
308
+ Expr::Assign(assign) => {
309
+ let is_method_name = matches!(
310
+ &*assign.left,
311
+ Expr::Path(p)
312
+ if p.path
313
+ .segments
314
+ .last()
315
+ .map(|segment| segment.ident == "method")
316
+ .unwrap_or(false)
317
+ );
318
+ if is_method_name {
319
+ arg_method = expr_to_method(&assign.right);
320
+ }
321
+ }
322
+ Expr::Call(call) => {
323
+ let is_method_name = matches!(
324
+ &*call.func,
325
+ Expr::Path(p)
326
+ if p.path
327
+ .segments
328
+ .last()
329
+ .map(|segment| segment.ident == "method")
330
+ .unwrap_or(false)
331
+ );
332
+ if is_method_name {
333
+ for arg in &call.args {
334
+ if let Some(m) = expr_to_method(arg) {
335
+ arg_method = Some(m);
336
+ }
337
+ }
338
+ }
339
+ }
340
+ _ => {}
341
+ }
342
+ }
343
+
344
+ if arg_method.is_some() {
345
+ method = arg_method;
346
+ }
347
+ let method = method?;
348
+ let path = path?;
349
+ let normalized_path = if path.starts_with('/') {
350
+ path
351
+ } else {
352
+ format!("/{path}")
353
+ };
354
+ Some((method, normalized_path))
355
+ }
356
+
357
+ struct CallVisitor<'a> {
358
+ rel_path: &'a str,
359
+ source_hash: &'a str,
360
+ tables: &'a mut Tables,
361
+ caller: NodeKey,
362
+ }
363
+
364
+ impl<'a> CallVisitor<'a> {
365
+ fn resolve_candidates(&mut self, mut candidates: Vec<NodeKey>) -> Vec<NodeKey> {
366
+ candidates.sort();
367
+ candidates.dedup();
368
+ candidates
369
+ }
370
+
371
+ fn emit_call_edge(
372
+ &mut self,
373
+ target: NodeKey,
374
+ resolution: &'static str,
375
+ start_line: usize,
376
+ end_line: usize,
377
+ rationale: String,
378
+ ambiguity: Option<Value>,
379
+ ) {
380
+ let evidence = push_evidence(
381
+ self.tables,
382
+ if resolution == "unresolved" {
383
+ "ast-span"
384
+ } else {
385
+ "semantic-symbol"
386
+ },
387
+ self.rel_path,
388
+ start_line,
389
+ end_line,
390
+ self.source_hash,
391
+ rationale,
392
+ );
393
+ push_edge(
394
+ self.tables,
395
+ "CALLS",
396
+ self.caller.clone(),
397
+ target,
398
+ resolution,
399
+ evidence,
400
+ ambiguity,
401
+ );
402
+ }
403
+
404
+ /// Çözülemeyen çağrı: UnknownExternal node'u (varsa) ve unresolved
405
+ /// kenar üretir — UYDURMA hedef üretilmez.
406
+ fn emit_unresolved(
407
+ &mut self,
408
+ qualified_name: String,
409
+ call_text: &str,
410
+ start_line: usize,
411
+ end_line: usize,
412
+ ) {
413
+ let target = insert_node(
414
+ self.tables,
415
+ NodeKey::virtual_("UnknownExternal", qualified_name),
416
+ json!({}),
417
+ );
418
+ let rationale = format!(
419
+ "CALLS: '{call_text}' çağrısı analiz setinde hiçbir sembolle eşleşmedi (unresolved); hedef UnknownExternal — uydurma sembol üretilmez."
420
+ );
421
+ self.emit_call_edge(
422
+ target,
423
+ "unresolved",
424
+ start_line,
425
+ end_line,
426
+ rationale,
427
+ None,
428
+ );
429
+ }
430
+
431
+ fn resolve_path_call(&mut self, idents: &[String], start_line: usize, end_line: usize) {
432
+ let call_text = idents.join("::");
433
+ if idents.len() == 1 {
434
+ let name = &idents[0];
435
+ // 1) Aynı modülde doğrudan çağrı → verified (ask sözleşmesi).
436
+ if let Some((_, file_fns)) = self
437
+ .tables
438
+ .free_fn_by_file
439
+ .iter()
440
+ .find(|(module, _)| *module == self.caller_module_of())
441
+ {
442
+ if let Some(target) = file_fns.get(name) {
443
+ let target = target.clone();
444
+ let rationale = format!(
445
+ "CALLS: '{name}' doğrudan çağrısı aynı modülde tanımlı '{t}' sembolüne çözümlendi (verified; syn AST, semantik çözümleyici yoktur).",
446
+ t = target.qualified
447
+ );
448
+ self.emit_call_edge(target, "verified", start_line, end_line, rationale, None);
449
+ return;
450
+ }
451
+ }
452
+ // 2) Başka dosyada tek aday → heuristic (import kanıtı yok).
453
+ let candidates =
454
+ self.resolve_candidates(self.tables.free_fn_bare.get(name).cloned().unwrap_or_default());
455
+ match candidates.len() {
456
+ 0 => self.emit_unresolved(name.clone(), &call_text, start_line, end_line),
457
+ 1 => {
458
+ let target = candidates[0].clone();
459
+ let rationale = format!(
460
+ "CALLS: '{name}' çağrısı import kanıtı olmadan isim tablosunda tek eşleşme '{t}' buldu (heuristic; modül/import doğrulaması bu dilimde yoktur).",
461
+ t = target.qualified
462
+ );
463
+ self.emit_call_edge(target, "heuristic", start_line, end_line, rationale, None);
464
+ }
465
+ _ => {
466
+ let candidates_names: Vec<String> =
467
+ candidates.iter().map(|c| c.qualified.clone()).collect();
468
+ let target = candidates[0].clone();
469
+ let rationale = format!(
470
+ "CALLS: '{name}' çağrısı isim tablosunda birden çok eşleşme buldu (heuristic + ambiguity)."
471
+ );
472
+ let ambiguity = json!({
473
+ "candidates": candidates_names,
474
+ "reason": format!("'{name}' adı analiz setinde birden çok serbest fn ile eşleşiyor; alıcı/modül kanıtı yok"),
475
+ });
476
+ self.emit_call_edge(
477
+ target,
478
+ "heuristic",
479
+ start_line,
480
+ end_line,
481
+ rationale,
482
+ Some(ambiguity),
483
+ );
484
+ }
485
+ }
486
+ return;
487
+ }
488
+
489
+ // Nitelikli yol çağrısı: son iki segment (tip/modül, isim).
490
+ let type_name = &idents[idents.len() - 2];
491
+ let name = &idents[idents.len() - 1];
492
+ let mut candidates: Vec<NodeKey> = Vec::new();
493
+ if let Some(list) = self.tables.methods.get(&(type_name.clone(), name.clone())) {
494
+ candidates.extend(list.iter().cloned());
495
+ }
496
+ if let Some(list) = self
497
+ .tables
498
+ .free_fn_global
499
+ .get(&(type_name.clone(), name.clone()))
500
+ {
501
+ candidates.extend(list.iter().cloned());
502
+ }
503
+ let candidates = self.resolve_candidates(candidates);
504
+ match candidates.len() {
505
+ 0 => self.emit_unresolved(call_text.clone(), &call_text, start_line, end_line),
506
+ 1 => {
507
+ let target = candidates[0].clone();
508
+ let rationale = format!(
509
+ "CALLS: nitelikli yol çağrısı '{call_text}' → '{t}' isim tablosunda tek eşleşme (verified; modül önekleri bu dilimde tam doğrulanmaz — belgeli sınırlama).",
510
+ t = target.qualified
511
+ );
512
+ self.emit_call_edge(target, "verified", start_line, end_line, rationale, None);
513
+ }
514
+ _ => {
515
+ let candidates_names: Vec<String> =
516
+ candidates.iter().map(|c| c.qualified.clone()).collect();
517
+ let target = candidates[0].clone();
518
+ let rationale = format!(
519
+ "CALLS: nitelikli yol çağrısı '{call_text}' isim tablosunda birden çok eşleşme buldu (heuristic + ambiguity)."
520
+ );
521
+ let ambiguity = json!({
522
+ "candidates": candidates_names,
523
+ "reason": format!("'{type_name}::{name}' analiz setinde birden çok sembolle eşleşiyor"),
524
+ });
525
+ self.emit_call_edge(
526
+ target,
527
+ "heuristic",
528
+ start_line,
529
+ end_line,
530
+ rationale,
531
+ Some(ambiguity),
532
+ );
533
+ }
534
+ }
535
+ }
536
+
537
+ fn resolve_method_call(&mut self, name: &str, start_line: usize, end_line: usize) {
538
+ let candidates =
539
+ self.resolve_candidates(self.tables.methods_bare.get(name).cloned().unwrap_or_default());
540
+ match candidates.len() {
541
+ 0 => self.emit_unresolved(name.to_string(), name, start_line, end_line),
542
+ 1 => {
543
+ let target = candidates[0].clone();
544
+ let rationale = format!(
545
+ "CALLS: metot çağrısı '{name}' — alıcı türü çözülemedi (trait dispatch bu dilimde çözülmez); isim tablosu eşleşmesi '{t}' (heuristic).",
546
+ t = target.qualified
547
+ );
548
+ self.emit_call_edge(target, "heuristic", start_line, end_line, rationale, None);
549
+ }
550
+ _ => {
551
+ let candidates_names: Vec<String> =
552
+ candidates.iter().map(|c| c.qualified.clone()).collect();
553
+ let target = candidates[0].clone();
554
+ let rationale = format!(
555
+ "CALLS: metot çağrısı '{name}' birden çok aday buldu — trait/implementasyon ayrımı çözülemedi (heuristic + ambiguity)."
556
+ );
557
+ let ambiguity = json!({
558
+ "candidates": candidates_names,
559
+ "reason": format!("'{name}' adında birden çok trait/implementasyon metodu var; alıcı türü bilinmiyor"),
560
+ });
561
+ self.emit_call_edge(
562
+ target,
563
+ "heuristic",
564
+ start_line,
565
+ end_line,
566
+ rationale,
567
+ Some(ambiguity),
568
+ );
569
+ }
570
+ }
571
+ }
572
+
573
+ fn caller_module_of(&self) -> String {
574
+ // Caller qname "crate::..::fn" biçimindedir; dosya modül yolunu
575
+ // rel_path'ten türet (tek doğruluk kaynağı dosya modülüdür).
576
+ module_path_of(self.rel_path)
577
+ }
578
+ }
579
+
580
+ impl<'a> Visit<'a> for CallVisitor<'a> {
581
+ // Fonksiyon İÇİ nested öğeler gezilmez (belgeli unsupported).
582
+ fn visit_item(&mut self, _item: &'a Item) {}
583
+
584
+ fn visit_expr_call(&mut self, call: &'a syn::ExprCall) {
585
+ let (start_line, end_line) = span_lines(call);
586
+ match &*call.func {
587
+ Expr::Path(path) => {
588
+ let idents: Vec<String> = path
589
+ .path
590
+ .segments
591
+ .iter()
592
+ .map(|segment| segment.ident.to_string())
593
+ .collect();
594
+ self.resolve_path_call(&idents, start_line, end_line);
595
+ }
596
+ _ => {
597
+ self.emit_unresolved(
598
+ "(anonim-cağrı)".to_string(),
599
+ "(anonim-cağrı)",
600
+ start_line,
601
+ end_line,
602
+ );
603
+ }
604
+ }
605
+ // Argümanların İÇİNDEKİ çağrılar da taranmalı (f(g()), closure'lar).
606
+ syn::visit::visit_expr_call(self, call);
607
+ }
608
+
609
+ fn visit_expr_method_call(&mut self, call: &'a syn::ExprMethodCall) {
610
+ let (start_line, end_line) = span_lines(call);
611
+ let name = call.method.to_string();
612
+ self.resolve_method_call(&name, start_line, end_line);
613
+ // Alıcı zincirleri ve argümanlar (a.b().c()) taranmalı.
614
+ syn::visit::visit_expr_method_call(self, call);
615
+ }
616
+ }
617
+
618
+ fn emit_route(
619
+ tables: &mut Tables,
620
+ attr: &Attribute,
621
+ target: &NodeKey,
622
+ rel_path: &str,
623
+ source_hash: &str,
624
+ ) -> bool {
625
+ if let Some((method, path)) = parse_route_attr(attr) {
626
+ let endpoint_key = insert_node(
627
+ tables,
628
+ NodeKey::virtual_("Endpoint", format!("{method} {path}")),
629
+ json!({ "method": method, "path": path }),
630
+ );
631
+ let (start_line, end_line) = span_lines(attr);
632
+ let evidence = push_evidence(
633
+ tables,
634
+ "route-attribute",
635
+ rel_path,
636
+ start_line,
637
+ end_line,
638
+ source_hash,
639
+ format!(
640
+ "ROUTES_TO: #[{attr_path}] özniteliği '{target}' öğesine sözdizimsel olarak bağlı (route-attribute; verified; syn AST).",
641
+ attr_path = format!("{method} \"{path}\"").to_lowercase(),
642
+ target = target.qualified
643
+ ),
644
+ );
645
+ push_edge(
646
+ tables,
647
+ "ROUTES_TO",
648
+ endpoint_key,
649
+ target.clone(),
650
+ "verified",
651
+ evidence,
652
+ None,
653
+ );
654
+ return true;
655
+ }
656
+ false
657
+ }
658
+
659
+ fn join_q(module: &str, name: &str) -> String {
660
+ format!("{module}::{name}")
661
+ }
662
+
663
+ /// Tek dosyanın bildirim geçişi: node'lar + CONTAINS + tablolar.
664
+ #[allow(clippy::too_many_arguments)]
665
+ fn process_items(
666
+ tables: &mut Tables,
667
+ _file_idx: usize,
668
+ module: &str,
669
+ rel_path: &str,
670
+ source_hash: &str,
671
+ items: &[Item],
672
+ ) {
673
+ let file_key = NodeKey::with_path("File", rel_path.to_string(), rel_path);
674
+ for item in items {
675
+ match item {
676
+ Item::Fn(item_fn) => {
677
+ let name = item_fn.sig.ident.to_string();
678
+ let key = insert_node(
679
+ tables,
680
+ NodeKey::with_path("Function", join_q(module, &name), rel_path),
681
+ json!({}),
682
+ );
683
+ let (start_line, end_line) = span_lines(item_fn);
684
+ let evidence = push_evidence(
685
+ tables,
686
+ "ast-span",
687
+ rel_path,
688
+ start_line,
689
+ end_line,
690
+ source_hash,
691
+ format!("CONTAINS: '{rel_path}' '{name}' fn bildirimini içerir (syn AST)."),
692
+ );
693
+ push_edge(tables, "CONTAINS", file_key.clone(), key.clone(), "verified", evidence, None);
694
+
695
+ if let Some((_, file_fns)) = tables
696
+ .free_fn_by_file
697
+ .iter_mut()
698
+ .find(|(m, _)| m == module)
699
+ {
700
+ file_fns.insert(name.clone(), key.clone());
701
+ }
702
+ let last_module_segment = module.rsplit("::").next().unwrap_or(module).to_string();
703
+ tables
704
+ .free_fn_global
705
+ .entry((last_module_segment, name.clone()))
706
+ .or_default()
707
+ .push(key.clone());
708
+ tables
709
+ .free_fn_bare
710
+ .entry(name.clone())
711
+ .or_default()
712
+ .push(key.clone());
713
+
714
+ for attr in &item_fn.attrs {
715
+ emit_route(tables, attr, &key, rel_path, source_hash);
716
+ }
717
+ }
718
+ Item::Struct(_) | Item::Enum(_) => {
719
+ // ask sözleşmesi: struct ve enum → Class node.
720
+ let name = match item {
721
+ Item::Struct(s) => s.ident.to_string(),
722
+ Item::Enum(e) => e.ident.to_string(),
723
+ _ => unreachable!(),
724
+ };
725
+ let key = insert_node(
726
+ tables,
727
+ NodeKey::with_path("Class", join_q(module, &name), rel_path),
728
+ json!({}),
729
+ );
730
+ let (start_line, end_line) = span_lines(item);
731
+ let evidence = push_evidence(
732
+ tables,
733
+ "ast-span",
734
+ rel_path,
735
+ start_line,
736
+ end_line,
737
+ source_hash,
738
+ format!("CONTAINS: '{rel_path}' '{name}' bildirimini içerir (syn AST)."),
739
+ );
740
+ push_edge(tables, "CONTAINS", file_key.clone(), key.clone(), "verified", evidence, None);
741
+ tables.declared_types.insert(name, key);
742
+ }
743
+ Item::Trait(item_trait) => {
744
+ let name = item_trait.ident.to_string();
745
+ let key = insert_node(
746
+ tables,
747
+ NodeKey::with_path("Interface", join_q(module, &name), rel_path),
748
+ json!({}),
749
+ );
750
+ let (start_line, end_line) = span_lines(item_trait);
751
+ let evidence = push_evidence(
752
+ tables,
753
+ "ast-span",
754
+ rel_path,
755
+ start_line,
756
+ end_line,
757
+ source_hash,
758
+ format!("CONTAINS: '{rel_path}' '{name}' trait bildirimini içerir (syn AST)."),
759
+ );
760
+ push_edge(tables, "CONTAINS", file_key.clone(), key.clone(), "verified", evidence, None);
761
+ tables.declared_types.insert(name.clone(), key.clone());
762
+
763
+ for trait_item in &item_trait.items {
764
+ if let syn::TraitItem::Fn(method) = trait_item {
765
+ let method_name = method.sig.ident.to_string();
766
+ let method_key = insert_node(
767
+ tables,
768
+ NodeKey::with_path(
769
+ "Method",
770
+ join_q(module, &format!("{name}::{method_name}")),
771
+ rel_path,
772
+ ),
773
+ json!({}),
774
+ );
775
+ let (ms, me) = span_lines(method);
776
+ let evidence = push_evidence(
777
+ tables,
778
+ "ast-span",
779
+ rel_path,
780
+ ms,
781
+ me,
782
+ source_hash,
783
+ format!("CONTAINS: '{name}' trait'i '{method_name}' metot bildirimini içerir (syn AST)."),
784
+ );
785
+ push_edge(
786
+ tables,
787
+ "CONTAINS",
788
+ key.clone(),
789
+ method_key.clone(),
790
+ "verified",
791
+ evidence,
792
+ None,
793
+ );
794
+ tables
795
+ .methods
796
+ .entry((name.clone(), method_name.clone()))
797
+ .or_default()
798
+ .push(method_key.clone());
799
+ tables
800
+ .methods_bare
801
+ .entry(method_name.clone())
802
+ .or_default()
803
+ .push(method_key.clone());
804
+ for attr in &method.attrs {
805
+ emit_route(tables, attr, &method_key, rel_path, source_hash);
806
+ }
807
+ }
808
+ }
809
+ }
810
+ Item::Impl(item_impl) => {
811
+ let type_name = match &*item_impl.self_ty {
812
+ syn::Type::Path(tp) => tp
813
+ .path
814
+ .segments
815
+ .last()
816
+ .map(|segment| segment.ident.to_string()),
817
+ _ => None,
818
+ };
819
+ let Some(type_name) = type_name else {
820
+ continue;
821
+ };
822
+ let Some(type_key) = tables.declared_types.get(&type_name).cloned() else {
823
+ // Bildirimi analiz setinde olmayan tipin impl'i modellenmez
824
+ // (açık tanı — sessiz kesim yok).
825
+ let (line, _) = span_lines(item_impl);
826
+ tables.diagnostics.push(Diagnostic {
827
+ relative_path: rel_path.to_string(),
828
+ code: "IMPL_UNKNOWN_TYPE".to_string(),
829
+ message: format!(
830
+ "'{type_name}' analiz setinde bildirilmedi; impl metotları modellenmedi"
831
+ ),
832
+ line,
833
+ });
834
+ continue;
835
+ };
836
+
837
+ for impl_item in &item_impl.items {
838
+ if let syn::ImplItem::Fn(method) = impl_item {
839
+ let method_name = method.sig.ident.to_string();
840
+ let method_key = insert_node(
841
+ tables,
842
+ NodeKey::with_path(
843
+ "Method",
844
+ join_q(module, &format!("{type_name}::{method_name}")),
845
+ rel_path,
846
+ ),
847
+ json!({}),
848
+ );
849
+ let (ms, me) = span_lines(method);
850
+ let evidence = push_evidence(
851
+ tables,
852
+ "ast-span",
853
+ rel_path,
854
+ ms,
855
+ me,
856
+ source_hash,
857
+ format!("CONTAINS: '{type_name}' '{method_name}' metot tanımını içerir (syn AST)."),
858
+ );
859
+ push_edge(
860
+ tables,
861
+ "CONTAINS",
862
+ type_key.clone(),
863
+ method_key.clone(),
864
+ "verified",
865
+ evidence,
866
+ None,
867
+ );
868
+ tables
869
+ .methods
870
+ .entry((type_name.clone(), method_name.clone()))
871
+ .or_default()
872
+ .push(method_key.clone());
873
+ tables
874
+ .methods_bare
875
+ .entry(method_name.clone())
876
+ .or_default()
877
+ .push(method_key.clone());
878
+ for attr in &method.attrs {
879
+ emit_route(tables, attr, &method_key, rel_path, source_hash);
880
+ }
881
+ }
882
+ }
883
+ }
884
+ Item::Macro(item_macro) => {
885
+ // Makro ile tanımlı öğeler atlanır (belgeli unsupported).
886
+ let (line, _) = span_lines(item_macro);
887
+ tables.diagnostics.push(Diagnostic {
888
+ relative_path: rel_path.to_string(),
889
+ code: "MACRO_ITEM_SKIPPED".to_string(),
890
+ message: format!(
891
+ "'{}' makro öğesi modellenmedi (macro-defined-items)",
892
+ item_macro
893
+ .mac
894
+ .path
895
+ .segments
896
+ .last()
897
+ .map(|segment| segment.ident.to_string())
898
+ .unwrap_or_default()
899
+ ),
900
+ line,
901
+ });
902
+ }
903
+ // mod/use/const/static/extern/verbatim öğeleri node üretmez
904
+ // (belgeli unsupported: use-import-resolution).
905
+ _ => {}
906
+ }
907
+ }
908
+ }
909
+
910
+ /// Aynı dosyanın gövde geçişi: her fn/impl metodu için CallVisitor.
911
+ fn process_bodies(
912
+ tables: &mut Tables,
913
+ module: &str,
914
+ rel_path: &str,
915
+ source_hash: &str,
916
+ items: &[Item],
917
+ ) {
918
+ for item in items {
919
+ match item {
920
+ Item::Fn(item_fn) => {
921
+ let name = item_fn.sig.ident.to_string();
922
+ let caller =
923
+ NodeKey::with_path("Function", join_q(module, &name), rel_path);
924
+ let mut visitor = CallVisitor {
925
+ rel_path,
926
+ source_hash,
927
+ tables,
928
+ caller,
929
+ };
930
+ visitor.visit_block(&item_fn.block);
931
+ }
932
+ Item::Trait(item_trait) => {
933
+ let name = item_trait.ident.to_string();
934
+ for trait_item in &item_trait.items {
935
+ if let syn::TraitItem::Fn(method) = trait_item {
936
+ if let Some(block) = &method.default {
937
+ let method_name = method.sig.ident.to_string();
938
+ let caller = NodeKey::with_path(
939
+ "Method",
940
+ join_q(module, &format!("{name}::{method_name}")),
941
+ rel_path,
942
+ );
943
+ let mut visitor = CallVisitor {
944
+ rel_path,
945
+ source_hash,
946
+ tables,
947
+ caller,
948
+ };
949
+ visitor.visit_block(block);
950
+ }
951
+ }
952
+ }
953
+ }
954
+ Item::Impl(item_impl) => {
955
+ let type_name = match &*item_impl.self_ty {
956
+ syn::Type::Path(tp) => tp
957
+ .path
958
+ .segments
959
+ .last()
960
+ .map(|segment| segment.ident.to_string()),
961
+ _ => None,
962
+ };
963
+ let Some(type_name) = type_name else {
964
+ continue;
965
+ };
966
+ let Some(_) = tables.declared_types.get(&type_name) else {
967
+ continue;
968
+ };
969
+ for impl_item in &item_impl.items {
970
+ if let syn::ImplItem::Fn(method) = impl_item {
971
+ let method_name = method.sig.ident.to_string();
972
+ let caller = NodeKey::with_path(
973
+ "Method",
974
+ join_q(module, &format!("{type_name}::{method_name}")),
975
+ rel_path,
976
+ );
977
+ let mut visitor = CallVisitor {
978
+ rel_path,
979
+ source_hash,
980
+ tables,
981
+ caller,
982
+ };
983
+ visitor.visit_block(&method.block);
984
+ }
985
+ }
986
+ }
987
+ _ => {}
988
+ }
989
+ }
990
+ }
991
+
992
+ fn round4(value: f64) -> f64 {
993
+ (value * 10_000.0).round() / 10_000.0
994
+ }
995
+
996
+ /// Tam analizi yürütür ve protokol yanıt Value'sunu üretir.
997
+ /// max_nodes ≤ 0 ya da üst sınırın üstünde → MaxResponseNodes uygulanır
998
+ /// (go worker Analyze clamp deseniyle aynı; protokol katmanı zaten
999
+ /// doğrular — buradaki clamp savunma derinliğidir).
1000
+ pub fn analyze(id: &Value, files: &[FileEntry], max_nodes: usize) -> Value {
1001
+ let budget = if max_nodes == 0 || max_nodes > MAX_RESPONSE_NODES {
1002
+ MAX_RESPONSE_NODES
1003
+ } else {
1004
+ max_nodes
1005
+ };
1006
+ let mut tables = Tables::default();
1007
+
1008
+ // Pass 1: bildirimler (File node'ları her zaman üretilir — bozuk dosya
1009
+ // bile sourceHash kanıtlı File node taşır; parse hatası tanıya yazılır).
1010
+ let mut parsed_trees: Vec<Option<syn::File>> = Vec::with_capacity(files.len());
1011
+ for entry in files {
1012
+ let module = module_path_of(&entry.path);
1013
+ let source_hash = sha256_hex(entry.content.as_bytes());
1014
+
1015
+ let file_key = NodeKey::with_path("File", entry.path.clone(), &entry.path);
1016
+ insert_node(
1017
+ &mut tables,
1018
+ file_key,
1019
+ json!({ "sourceHash": source_hash }),
1020
+ );
1021
+ tables.free_fn_by_file.push((module.clone(), BTreeMap::new()));
1022
+
1023
+ match syn::parse_file(&entry.content) {
1024
+ Ok(tree) => {
1025
+ parsed_trees.push(Some(tree));
1026
+ }
1027
+ Err(err) => {
1028
+ let line = err.span().start().line.max(1);
1029
+ tables.diagnostics.push(Diagnostic {
1030
+ relative_path: entry.path.clone(),
1031
+ code: "PARSE_ERROR".to_string(),
1032
+ message: format!("dosya ayrıştırılamadı: {err}"),
1033
+ line,
1034
+ });
1035
+ parsed_trees.push(None);
1036
+ continue;
1037
+ }
1038
+ }
1039
+ }
1040
+
1041
+ // Pass 2: CONTAINS + tablolar + route'lar (yalnızca parse edilenler).
1042
+ for (idx, entry) in files.iter().enumerate() {
1043
+ let Some(tree) = &parsed_trees[idx] else {
1044
+ continue;
1045
+ };
1046
+ let module = module_path_of(&entry.path);
1047
+ let source_hash = sha256_hex(entry.content.as_bytes());
1048
+ process_items(
1049
+ &mut tables,
1050
+ idx,
1051
+ &module,
1052
+ &entry.path,
1053
+ &source_hash,
1054
+ &tree.items,
1055
+ );
1056
+ }
1057
+
1058
+ // Pass 3: gövdelerdeki çağrılar (tablo tam olduktan SONRA).
1059
+ for (idx, entry) in files.iter().enumerate() {
1060
+ let Some(tree) = &parsed_trees[idx] else {
1061
+ continue;
1062
+ };
1063
+ let module = module_path_of(&entry.path);
1064
+ let source_hash = sha256_hex(entry.content.as_bytes());
1065
+ process_bodies(
1066
+ &mut tables,
1067
+ &module,
1068
+ &entry.path,
1069
+ &source_hash,
1070
+ &tree.items,
1071
+ );
1072
+ }
1073
+
1074
+ // Kanonik çıktı düzeni (TŞ §8 invariant iv).
1075
+ let mut nodes: Vec<Value> = tables.nodes.values().cloned().collect();
1076
+ // Yanıt node bütçesi (go worker RESPONSE_TRUNCATED deseni): kanonik
1077
+ // sırada ilk `budget` node yayınlanır; uçları yayınlanmayan kenarlar
1078
+ // DÜŞER (dangling yok); evidence yalnızca yayımlanan kenarların
1079
+ // taşıdığı kanıtlardan yeniden kurulur; aşım tanısı yazılır — sessiz
1080
+ // kesim yoktur (bulgu: kırpılmış yanıt yerine tam L0/L1 degradesi).
1081
+ if nodes.len() > budget {
1082
+ let kept: BTreeSet<NodeKey> = tables.nodes.keys().take(budget).cloned().collect();
1083
+ nodes.truncate(budget);
1084
+ tables
1085
+ .edges
1086
+ .retain(|edge| kept.contains(&edge.from) && kept.contains(&edge.to));
1087
+ let mut kept_evidence: Vec<Value> = Vec::new();
1088
+ for edge in &tables.edges {
1089
+ kept_evidence.extend(edge.evidence.iter().cloned());
1090
+ }
1091
+ tables.evidence = kept_evidence;
1092
+ tables.diagnostics.push(Diagnostic {
1093
+ relative_path: String::new(),
1094
+ code: "RESPONSE_TRUNCATED".to_string(),
1095
+ message: format!(
1096
+ "yanıt node bütçesi ({budget}) aşıldı; {budget} node yayınlandı, uçları yayınlanmayan {} kenar düştü (dangling yok)",
1097
+ tables.edge_index.len() - tables.edges.len()
1098
+ ),
1099
+ line: 0,
1100
+ });
1101
+ }
1102
+ tables.edges.sort_by(|a, b| {
1103
+ let key_a = (
1104
+ a.kind,
1105
+ a.from.clone(),
1106
+ a.to.clone(),
1107
+ a.resolution,
1108
+ );
1109
+ let key_b = (
1110
+ b.kind,
1111
+ b.from.clone(),
1112
+ b.to.clone(),
1113
+ b.resolution,
1114
+ );
1115
+ key_a.cmp(&key_b)
1116
+ });
1117
+ let edges: Vec<Value> = tables
1118
+ .edges
1119
+ .iter()
1120
+ .map(|edge| {
1121
+ let mut value = json!({
1122
+ "kind": edge.kind,
1123
+ "from": node_ref_value(&edge.from),
1124
+ "to": node_ref_value(&edge.to),
1125
+ "resolution": edge.resolution,
1126
+ "evidence": edge.evidence,
1127
+ });
1128
+ if let Some(ambiguity) = &edge.ambiguity {
1129
+ value["ambiguity"] = ambiguity.clone();
1130
+ }
1131
+ value
1132
+ })
1133
+ .collect();
1134
+ let mut evidence: Vec<Value> = tables.evidence.clone();
1135
+ evidence.sort_by(|a, b| {
1136
+ let key_a = serde_json::to_string(a).unwrap_or_default();
1137
+ let key_b = serde_json::to_string(b).unwrap_or_default();
1138
+ key_a.cmp(&key_b)
1139
+ });
1140
+ evidence.dedup_by(|a, b| a == b);
1141
+
1142
+ let diagnostics: Vec<Value> = tables
1143
+ .diagnostics
1144
+ .iter()
1145
+ .map(|diagnostic| {
1146
+ json!({
1147
+ "relativePath": diagnostic.relative_path,
1148
+ "code": diagnostic.code,
1149
+ "message": diagnostic.message,
1150
+ "line": diagnostic.line,
1151
+ })
1152
+ })
1153
+ .collect();
1154
+
1155
+ let total_edges = edges.len();
1156
+ let verified_edges = tables
1157
+ .edges
1158
+ .iter()
1159
+ .filter(|edge| edge.resolution == "verified")
1160
+ .count();
1161
+ let coverage = if total_edges == 0 {
1162
+ 0.0
1163
+ } else {
1164
+ round4(verified_edges as f64 / total_edges as f64)
1165
+ };
1166
+
1167
+ let status = if tables.diagnostics.is_empty() {
1168
+ "ready"
1169
+ } else {
1170
+ "partial"
1171
+ };
1172
+
1173
+ json!({
1174
+ "id": id,
1175
+ "protocolVersion": crate::protocol::PROTOCOL_VERSION,
1176
+ "status": status,
1177
+ "worker": {
1178
+ "analyzerId": ANALYZER_ID,
1179
+ "analyzerVersion": ANALYZER_VERSION,
1180
+ },
1181
+ "capabilities": {
1182
+ "astParse": true,
1183
+ "symbolResolution": true,
1184
+ "containsEdges": true,
1185
+ "callEdges": true,
1186
+ "importEdges": false,
1187
+ "routeDetection": ROUTE_DETECTION,
1188
+ "frameworkLinkers": false,
1189
+ },
1190
+ "coverageRatio": coverage,
1191
+ "unsupportedConstructs": UNSUPPORTED_CONSTRUCTS,
1192
+ "warnings": [],
1193
+ "diagnostics": diagnostics,
1194
+ "nodes": nodes,
1195
+ "edges": edges,
1196
+ "evidence": evidence,
1197
+ })
1198
+ }
1199
+
1200
+ fn node_ref_value(key: &NodeKey) -> Value {
1201
+ let mut value = json!({
1202
+ "kind": key.kind,
1203
+ "qualifiedName": key.qualified,
1204
+ });
1205
+ if !key.rel_path.is_empty() {
1206
+ value["relativePath"] = Value::String(key.rel_path.clone());
1207
+ }
1208
+ value
1209
+ }