rustcodegraph 1.2.10

Local-first code intelligence graph and CLI for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! SwiftUI, UIKit, and Vapor framework resolvers translated from `swift.ts`.
//!
//! Swift 生态的 UI 与服务端框架都高度依赖命名/目录约定。这里把 SwiftUI/UIKit
//! 类型和 Vapor 路由补进图,让跨框架入口能继续走普通引用解析。

use regex::Regex;

use crate::resolution::strip_comments::{CommentLang, strip_comments_for_regex};
use crate::resolution::types::{
    FrameworkExtractionResult, FrameworkResolver, ResolutionContext, ResolvedRef, UnresolvedRef,
    line_for_byte, make_node, make_reference, resolve_by_name_and_kind,
};
use crate::types::{Language, NodeKind, ReferenceKind};

const VIEW_DIRS: &[&str] = &["/Views/", "/View/", "/Screens/", "/Components/", "/UI/"];
const VIEWMODEL_DIRS: &[&str] = &[
    "/ViewModels/",
    "/ViewModel/",
    "/Stores/",
    "/Managers/",
    "/Services/",
];
const MODEL_DIRS: &[&str] = &["/Models/", "/Model/", "/Entities/", "/Domain/"];
const VC_DIRS: &[&str] = &[
    "/ViewControllers/",
    "/ViewController/",
    "/Controllers/",
    "/Screens/",
];
const UIVIEW_DIRS: &[&str] = &["/Views/", "/View/", "/UI/", "/Components/"];
const CELL_DIRS: &[&str] = &[
    "/Cells/",
    "/Cell/",
    "/Views/",
    "/TableViewCells/",
    "/CollectionViewCells/",
];
const VAPOR_CONTROLLER_DIRS: &[&str] = &["/Controllers/", "/Controller/", "/Routes/"];
const FLUENT_MODEL_DIRS: &[&str] = &["/Models/", "/Model/", "/Entities/", "/Database/"];
const VAPOR_MIDDLEWARE_DIRS: &[&str] = &["/Middleware/", "/Middlewares/"];

const VIEW_KINDS: &[NodeKind] = &[NodeKind::Struct, NodeKind::Component];
const CLASS_KINDS: &[NodeKind] = &[NodeKind::Class];
const MODEL_KINDS: &[NodeKind] = &[NodeKind::Struct, NodeKind::Class];
const PROTOCOL_KINDS: &[NodeKind] = &[NodeKind::Protocol];
const VAPOR_CONTROLLER_KINDS: &[NodeKind] = &[NodeKind::Class, NodeKind::Struct];

pub struct SwiftUiResolver;
pub struct UIKitResolver;
pub struct VaporResolver;

pub const SWIFTUI_RESOLVER: SwiftUiResolver = SwiftUiResolver;
pub const UIKIT_RESOLVER: UIKitResolver = UIKitResolver;
pub const VAPOR_RESOLVER: VaporResolver = VaporResolver;

impl FrameworkResolver for SwiftUiResolver {
    fn name(&self) -> &'static str {
        "swiftui"
    }

    fn languages(&self) -> Option<&'static [Language]> {
        Some(&[Language::Swift])
    }

    fn detect(&self, context: &mut dyn ResolutionContext) -> bool {
        for file in context.get_all_files() {
            if file.ends_with(".swift")
                && context
                    .read_file(&file)
                    .is_some_and(|content| content.contains("import SwiftUI"))
            {
                return true;
            }
            if file.ends_with(".xcodeproj") || file.ends_with(".xcworkspace") {
                return true;
            }
        }
        false
    }

    fn resolve(
        &self,
        reference: &UnresolvedRef,
        context: &mut dyn ResolutionContext,
    ) -> Option<ResolvedRef> {
        // SwiftUI 里 View、ViewModel、Store 等后缀很强,但仍按目录过滤,
        // 避免同名模型或工具类型抢占 UI flow。
        if reference.reference_name.ends_with("View")
            && starts_upper(&reference.reference_name)
            && let Some(target) =
                resolve_by_name_and_kind(&reference.reference_name, VIEW_KINDS, VIEW_DIRS, context)
        {
            return Some(ResolvedRef::framework(reference, target, 0.85));
        }
        if (reference.reference_name.ends_with("ViewModel")
            || reference.reference_name.ends_with("Store")
            || reference.reference_name.ends_with("Manager"))
            && let Some(target) = resolve_by_name_and_kind(
                &reference.reference_name,
                CLASS_KINDS,
                VIEWMODEL_DIRS,
                context,
            )
        {
            return Some(ResolvedRef::framework(reference, target, 0.85));
        }
        if is_pascal_word(&reference.reference_name)
            && let Some(target) = resolve_by_name_and_kind(
                &reference.reference_name,
                MODEL_KINDS,
                MODEL_DIRS,
                context,
            )
        {
            return Some(ResolvedRef::framework(reference, target, 0.7));
        }
        None
    }

    fn extract(&self, file_path: &str, content: &str) -> FrameworkExtractionResult {
        if !file_path.ends_with(".swift") {
            return FrameworkExtractionResult::default();
        }
        let safe = strip_comments_for_regex(content, CommentLang::Swift);
        let content = safe.as_str();
        let mut result = FrameworkExtractionResult::default();
        let view_re = Regex::new(r"struct\s+(\w+)\s*:\s*(?:\w+\s*,\s*)*View").unwrap();
        for caps in view_re.captures_iter(content) {
            let whole = caps.get(0).unwrap();
            let name = caps.get(1).unwrap().as_str();
            let line = line_for_byte(content, whole.start());
            result.nodes.push(make_node(
                format!("view:{file_path}:{name}:{line}"),
                NodeKind::Component,
                name,
                format!("{file_path}::{name}"),
                file_path,
                Language::Swift,
                line,
                None,
                None,
            ));
        }
        let app_re = Regex::new(r"@main\s+struct\s+(\w+)\s*:\s*App").unwrap();
        for caps in app_re.captures_iter(content) {
            let whole = caps.get(0).unwrap();
            let name = caps.get(1).unwrap().as_str();
            let line = line_for_byte(content, whole.start());
            result.nodes.push(make_node(
                format!("app:{file_path}:{name}:{line}"),
                NodeKind::Class,
                name,
                format!("{file_path}::{name}"),
                file_path,
                Language::Swift,
                line,
                None,
                None,
            ));
        }
        result
    }
}

impl FrameworkResolver for UIKitResolver {
    fn name(&self) -> &'static str {
        "uikit"
    }

    fn languages(&self) -> Option<&'static [Language]> {
        Some(&[Language::Swift])
    }

    fn detect(&self, context: &mut dyn ResolutionContext) -> bool {
        context.get_all_files().into_iter().any(|file| {
            file.ends_with(".swift")
                && context.read_file(&file).is_some_and(|content| {
                    content.contains("import UIKit")
                        || content.contains("UIViewController")
                        || content.contains("UIView")
                })
        })
    }

    fn resolve(
        &self,
        reference: &UnresolvedRef,
        context: &mut dyn ResolutionContext,
    ) -> Option<ResolvedRef> {
        // UIKit 的 ViewController/View/Cell 后缀对应不同目录和节点 kind,
        // 拆开处理能减少 `FooView` 和 `FooViewController` 的互相误配。
        if reference.reference_name.ends_with("ViewController")
            && let Some(target) =
                resolve_by_name_and_kind(&reference.reference_name, CLASS_KINDS, VC_DIRS, context)
        {
            return Some(ResolvedRef::framework(reference, target, 0.85));
        }
        if reference.reference_name.ends_with("View")
            && !reference.reference_name.ends_with("ViewController")
            && let Some(target) = resolve_by_name_and_kind(
                &reference.reference_name,
                CLASS_KINDS,
                UIVIEW_DIRS,
                context,
            )
        {
            return Some(ResolvedRef::framework(reference, target, 0.8));
        }
        if reference.reference_name.ends_with("Cell")
            && let Some(target) =
                resolve_by_name_and_kind(&reference.reference_name, CLASS_KINDS, CELL_DIRS, context)
        {
            return Some(ResolvedRef::framework(reference, target, 0.85));
        }
        if (reference.reference_name.ends_with("Delegate")
            || reference.reference_name.ends_with("DataSource"))
            && let Some(target) =
                resolve_by_name_and_kind(&reference.reference_name, PROTOCOL_KINDS, &[], context)
        {
            return Some(ResolvedRef::framework(reference, target, 0.8));
        }
        None
    }

    fn extract(&self, file_path: &str, content: &str) -> FrameworkExtractionResult {
        if !file_path.ends_with(".swift") {
            return FrameworkExtractionResult::default();
        }
        // Vapor 分组路由会把前缀保存在局部变量或 closure 参数里;先收集 group
        // 前缀,再提取最终 method/path/handler。
        let safe = strip_comments_for_regex(content, CommentLang::Swift);
        let content = safe.as_str();
        let mut result = FrameworkExtractionResult::default();
        let vc_re = Regex::new(r"class\s+(\w+)\s*:\s*(?:\w+\s*,\s*)*UIViewController").unwrap();
        for caps in vc_re.captures_iter(content) {
            let whole = caps.get(0).unwrap();
            let name = caps.get(1).unwrap().as_str();
            let line = line_for_byte(content, whole.start());
            result.nodes.push(make_node(
                format!("viewcontroller:{file_path}:{name}:{line}"),
                NodeKind::Class,
                name,
                format!("{file_path}::{name}"),
                file_path,
                Language::Swift,
                line,
                None,
                None,
            ));
        }
        let view_re = Regex::new(r"class\s+(\w+)\s*:\s*(?:\w+\s*,\s*)*UIView[^C]").unwrap();
        for caps in view_re.captures_iter(content) {
            let whole = caps.get(0).unwrap();
            let name = caps.get(1).unwrap().as_str();
            let line = line_for_byte(content, whole.start());
            result.nodes.push(make_node(
                format!("uiview:{file_path}:{name}:{line}"),
                NodeKind::Class,
                name,
                format!("{file_path}::{name}"),
                file_path,
                Language::Swift,
                line,
                None,
                None,
            ));
        }
        result
    }
}

impl FrameworkResolver for VaporResolver {
    fn name(&self) -> &'static str {
        "vapor"
    }

    fn languages(&self) -> Option<&'static [Language]> {
        Some(&[Language::Swift])
    }

    fn detect(&self, context: &mut dyn ResolutionContext) -> bool {
        context
            .read_file("Package.swift")
            .is_some_and(|content| content.contains("vapor"))
            || context.get_all_files().into_iter().any(|file| {
                file.ends_with(".swift")
                    && context
                        .read_file(&file)
                        .is_some_and(|content| content.contains("import Vapor"))
            })
    }

    fn resolve(
        &self,
        reference: &UnresolvedRef,
        context: &mut dyn ResolutionContext,
    ) -> Option<ResolvedRef> {
        if reference.reference_name.ends_with("Controller")
            && let Some(target) = resolve_by_name_and_kind(
                &reference.reference_name,
                VAPOR_CONTROLLER_KINDS,
                VAPOR_CONTROLLER_DIRS,
                context,
            )
        {
            return Some(ResolvedRef::framework(reference, target, 0.85));
        }
        if is_pascal_word(&reference.reference_name)
            && let Some(target) = resolve_by_name_and_kind(
                &reference.reference_name,
                CLASS_KINDS,
                FLUENT_MODEL_DIRS,
                context,
            )
        {
            return Some(ResolvedRef::framework(reference, target, 0.75));
        }
        if reference.reference_name.ends_with("Middleware")
            && let Some(target) = resolve_by_name_and_kind(
                &reference.reference_name,
                VAPOR_CONTROLLER_KINDS,
                VAPOR_MIDDLEWARE_DIRS,
                context,
            )
        {
            return Some(ResolvedRef::framework(reference, target, 0.8));
        }
        None
    }

    fn extract(&self, file_path: &str, content: &str) -> FrameworkExtractionResult {
        if !file_path.ends_with(".swift") {
            return FrameworkExtractionResult::default();
        }
        let safe = strip_comments_for_regex(content, CommentLang::Swift);
        let content = safe.as_str();
        let mut result = FrameworkExtractionResult::default();
        let mut group_prefix = std::collections::HashMap::<String, String>::new();
        let grouped_re = Regex::new(r#"\blet\s+(\w+)\s*=\s*(\w+)\.grouped\s*\(([^)]*)\)"#).unwrap();
        for caps in grouped_re.captures_iter(content) {
            let var = caps.get(1).unwrap().as_str();
            let parent = caps.get(2).unwrap().as_str();
            let prefix = group_prefix.get(parent).cloned().unwrap_or_default();
            group_prefix.insert(
                var.to_string(),
                seg_join(&prefix, caps.get(3).unwrap().as_str()),
            );
        }
        let group_closure_re =
            Regex::new(r#"\b(\w+)\.group\s*\(([^)]*)\)\s*\{\s*(\w+)\s+in"#).unwrap();
        for caps in group_closure_re.captures_iter(content) {
            let parent = caps.get(1).unwrap().as_str();
            let var = caps.get(3).unwrap().as_str();
            let prefix = group_prefix.get(parent).cloned().unwrap_or_default();
            group_prefix.insert(
                var.to_string(),
                seg_join(&prefix, caps.get(2).unwrap().as_str()),
            );
        }

        let route_re = Regex::new(r#"\b(\w+)\.(get|post|put|patch|delete|head|options)\s*\(\s*((?:[^,()]+,\s*)*)use:\s*([A-Za-z_][\w.]*)"#).unwrap();
        for caps in route_re.captures_iter(content) {
            let whole = caps.get(0).unwrap();
            let receiver = caps.get(1).unwrap().as_str();
            let method = caps.get(2).unwrap().as_str().to_ascii_uppercase();
            let prefix = group_prefix.get(receiver).cloned().unwrap_or_default();
            let route_path = {
                let route = format!("{}{}", prefix, seg_join("", caps.get(3).unwrap().as_str()));
                if route.is_empty() {
                    "/".to_string()
                } else {
                    route
                }
            };
            let handler = caps
                .get(4)
                .unwrap()
                .as_str()
                .rsplit('.')
                .next()
                .unwrap_or("");
            let line = line_for_byte(content, whole.start());
            let route_id = format!("route:{file_path}:{line}:{method}:{route_path}");
            result.nodes.push(make_node(
                route_id.clone(),
                NodeKind::Route,
                format!("{method} {route_path}"),
                format!("{file_path}::route:{route_path}"),
                file_path,
                Language::Swift,
                line,
                None,
                None,
            ));
            if !handler.is_empty() {
                result.references.push(make_reference(
                    route_id,
                    handler,
                    ReferenceKind::References,
                    line,
                    0,
                    file_path,
                    Language::Swift,
                ));
            }
        }
        result
    }
}

fn seg_join(existing: &str, segs: &str) -> String {
    // Vapor 路由段通常是多个字符串参数:`grouped("api", "v1")`。
    // 这里只拼接字面量段,动态表达式留给后续更精细的分析。
    let segment_re = Regex::new(r#""([^"]*)""#).unwrap();
    let suffix = segment_re
        .captures_iter(segs)
        .map(|caps| format!("/{}", caps.get(1).unwrap().as_str()))
        .collect::<String>();
    format!("{existing}{suffix}")
}

fn starts_upper(value: &str) -> bool {
    value
        .chars()
        .next()
        .is_some_and(|ch| ch.is_ascii_uppercase())
}

fn is_pascal_word(value: &str) -> bool {
    let mut chars = value.chars();
    matches!(chars.next(), Some('A'..='Z')) && chars.all(|ch| ch.is_ascii_alphabetic())
}