srb-lens 0.5.1

Static analysis tool for Sorbet-typed Ruby projects — extracts method signatures, call graphs, and type information from Sorbet's CFG, symbol table, and parse tree
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
#[derive(Debug)]
pub struct AutogenFile {
    pub path: String,
    pub requires: Vec<String>,
    pub defs: Vec<AutogenDef>,
    pub refs: Vec<AutogenRef>,
}

#[derive(Debug)]
pub struct AutogenDef {
    pub id: usize,
    pub kind: DefKind,
    pub defines_behavior: bool,
    pub is_empty: bool,
    pub defining_ref: Option<Vec<String>>,
    pub parent_ref: Option<Vec<String>>,
    pub aliased_ref: Option<Vec<String>>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DefKind {
    Class,
    Module,
}

#[derive(Debug)]
pub struct AutogenRef {
    pub id: usize,
    pub scope: Vec<String>,
    pub name: Vec<String>,
    pub nesting: Vec<Vec<String>>,
    pub resolved: Vec<String>,
    pub loc: String,
    pub is_defining_ref: bool,
    pub parent_of: Option<Vec<String>>,
}

#[derive(Debug, thiserror::Error)]
pub enum AutogenParseError {
    #[error("parse error at line {line}: {message}")]
    ParseError { line: usize, message: String },
}

pub fn parse(input: &str) -> Result<Vec<AutogenFile>, AutogenParseError> {
    let mut files = Vec::new();
    let mut current_file: Option<AutogenFileBuilder> = None;
    let mut section = Section::None;
    let mut current_def: Option<AutogenDefBuilder> = None;
    let mut current_ref: Option<AutogenRefBuilder> = None;

    for (_line_no, line) in input.lines().enumerate() {
        // New file section
        if let Some(path) = line.strip_prefix("# ParsedFile: ") {
            // Flush previous
            flush_entry(&mut current_def, &mut current_ref, &mut current_file);
            if let Some(file) = current_file.take() {
                files.push(file.finish());
            }
            current_file = Some(AutogenFileBuilder {
                path: path.to_string(),
                requires: Vec::new(),
                defs: Vec::new(),
                refs: Vec::new(),
            });
            section = Section::None;
            continue;
        }

        // requires: [...]
        if let Some(rest) = line.strip_prefix("requires: ") {
            if let Some(file) = &mut current_file {
                file.requires = parse_bracket_list(rest);
            }
            continue;
        }

        // Section headers
        if line == "## defs:" {
            flush_entry(&mut current_def, &mut current_ref, &mut current_file);
            section = Section::Defs;
            continue;
        }
        if line == "## refs:" {
            flush_entry(&mut current_def, &mut current_ref, &mut current_file);
            section = Section::Refs;
            continue;
        }

        // Entry headers
        if let Some(rest) = line.strip_prefix("[def id=") {
            flush_entry(&mut current_def, &mut current_ref, &mut current_file);
            let id_str = rest.strip_suffix(']').unwrap_or(rest);
            let id: usize = id_str.parse().unwrap_or(0);
            current_def = Some(AutogenDefBuilder::new(id));
            continue;
        }
        if let Some(rest) = line.strip_prefix("[ref id=") {
            flush_entry(&mut current_def, &mut current_ref, &mut current_file);
            let id_str = rest.strip_suffix(']').unwrap_or(rest);
            let id: usize = id_str.parse().unwrap_or(0);
            current_ref = Some(AutogenRefBuilder::new(id));
            continue;
        }

        // Field lines (space-prefixed)
        if let Some(field_line) = line.strip_prefix(' ') {
            match section {
                Section::Defs => {
                    if let Some(def) = &mut current_def {
                        parse_def_field(def, field_line);
                    }
                }
                Section::Refs => {
                    if let Some(refb) = &mut current_ref {
                        parse_ref_field(refb, field_line);
                    }
                }
                Section::None => {}
            }
        }
    }

    // Flush remaining
    flush_entry(&mut current_def, &mut current_ref, &mut current_file);
    if let Some(file) = current_file.take() {
        files.push(file.finish());
    }

    Ok(files)
}

#[derive(Clone, Copy)]
enum Section {
    None,
    Defs,
    Refs,
}

struct AutogenFileBuilder {
    path: String,
    requires: Vec<String>,
    defs: Vec<AutogenDef>,
    refs: Vec<AutogenRef>,
}

impl AutogenFileBuilder {
    fn finish(self) -> AutogenFile {
        AutogenFile {
            path: self.path,
            requires: self.requires,
            defs: self.defs,
            refs: self.refs,
        }
    }
}

struct AutogenDefBuilder {
    id: usize,
    kind: Option<DefKind>,
    defines_behavior: bool,
    is_empty: bool,
    defining_ref: Option<Vec<String>>,
    parent_ref: Option<Vec<String>>,
    aliased_ref: Option<Vec<String>>,
}

impl AutogenDefBuilder {
    fn new(id: usize) -> Self {
        Self {
            id,
            kind: None,
            defines_behavior: false,
            is_empty: false,
            defining_ref: None,
            parent_ref: None,
            aliased_ref: None,
        }
    }

    fn finish(self) -> AutogenDef {
        AutogenDef {
            id: self.id,
            kind: self.kind.unwrap_or(DefKind::Class),
            defines_behavior: self.defines_behavior,
            is_empty: self.is_empty,
            defining_ref: self.defining_ref,
            parent_ref: self.parent_ref,
            aliased_ref: self.aliased_ref,
        }
    }
}

struct AutogenRefBuilder {
    id: usize,
    scope: Vec<String>,
    name: Vec<String>,
    nesting: Vec<Vec<String>>,
    resolved: Vec<String>,
    loc: String,
    is_defining_ref: bool,
    parent_of: Option<Vec<String>>,
}

impl AutogenRefBuilder {
    fn new(id: usize) -> Self {
        Self {
            id,
            scope: Vec::new(),
            name: Vec::new(),
            nesting: Vec::new(),
            resolved: Vec::new(),
            loc: String::new(),
            is_defining_ref: false,
            parent_of: None,
        }
    }

    fn finish(self) -> AutogenRef {
        AutogenRef {
            id: self.id,
            scope: self.scope,
            name: self.name,
            nesting: self.nesting,
            resolved: self.resolved,
            loc: self.loc,
            is_defining_ref: self.is_defining_ref,
            parent_of: self.parent_of,
        }
    }
}

fn flush_entry(
    current_def: &mut Option<AutogenDefBuilder>,
    current_ref: &mut Option<AutogenRefBuilder>,
    current_file: &mut Option<AutogenFileBuilder>,
) {
    if let Some(def) = current_def.take() {
        if let Some(file) = current_file {
            file.defs.push(def.finish());
        }
    }
    if let Some(refb) = current_ref.take() {
        if let Some(file) = current_file {
            file.refs.push(refb.finish());
        }
    }
}

fn parse_def_field(def: &mut AutogenDefBuilder, field: &str) {
    if let Some(val) = field.strip_prefix("type=") {
        def.kind = Some(match val {
            "class" => DefKind::Class,
            "module" => DefKind::Module,
            _ => DefKind::Class,
        });
    } else if let Some(val) = field.strip_prefix("defines_behavior=") {
        def.defines_behavior = val == "1";
    } else if let Some(val) = field.strip_prefix("is_empty=") {
        def.is_empty = val == "1";
    } else if let Some(val) = field.strip_prefix("defining_ref=") {
        def.defining_ref = Some(parse_bracket_names(val));
    } else if let Some(val) = field.strip_prefix("parent_ref=") {
        def.parent_ref = Some(parse_bracket_names(val));
    } else if let Some(val) = field.strip_prefix("aliased_ref=") {
        def.aliased_ref = Some(parse_bracket_names(val));
    }
}

fn parse_ref_field(refb: &mut AutogenRefBuilder, field: &str) {
    if let Some(val) = field.strip_prefix("scope=") {
        refb.scope = parse_bracket_names(val);
    } else if let Some(val) = field.strip_prefix("name=") {
        refb.name = parse_bracket_names(val);
    } else if let Some(val) = field.strip_prefix("nesting=") {
        refb.nesting = parse_nesting(val);
    } else if let Some(val) = field.strip_prefix("resolved=") {
        refb.resolved = parse_bracket_names(val);
    } else if let Some(val) = field.strip_prefix("loc=") {
        refb.loc = val.to_string();
    } else if let Some(val) = field.strip_prefix("is_defining_ref=") {
        refb.is_defining_ref = val == "1";
    } else if let Some(val) = field.strip_prefix("parent_of=") {
        refb.parent_of = Some(parse_bracket_names(val));
    }
}

/// Parse "[Name1 Name2]" → ["Name1", "Name2"]
fn parse_bracket_names(s: &str) -> Vec<String> {
    let s = s.trim();
    let inner = s.strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(s);
    if inner.is_empty() {
        return Vec::new();
    }
    inner.split_whitespace().map(String::from).collect()
}

/// Parse "[[A B] [C]]" → [["A", "B"], ["C"]]
fn parse_nesting(s: &str) -> Vec<Vec<String>> {
    let s = s.trim();
    let inner = s.strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(s);
    if inner.is_empty() {
        return Vec::new();
    }

    let mut result = Vec::new();
    let mut depth = 0;
    let mut start = 0;

    for (i, c) in inner.char_indices() {
        match c {
            '[' => {
                if depth == 0 {
                    start = i + 1;
                }
                depth += 1;
            }
            ']' => {
                depth -= 1;
                if depth == 0 {
                    let group = &inner[start..i];
                    result.push(group.split_whitespace().map(String::from).collect());
                }
            }
            _ => {}
        }
    }

    result
}

/// Parse bracket list like "[foo, bar]" or "[]"
fn parse_bracket_list(s: &str) -> Vec<String> {
    let s = s.trim();
    let inner = s.strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(s);
    if inner.is_empty() {
        return Vec::new();
    }
    inner.split(',').map(|s| s.trim().to_string()).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_sample_file() {
        let input = r#"# ParsedFile: ./app/components/datetime_picker_component.rb
requires: []
## defs:
[def id=0]
 type=module
 defines_behavior=0
 is_empty=0
[def id=1]
 type=class
 defines_behavior=1
 is_empty=0
 defining_ref=[DatetimePickerComponent]
 parent_ref=[ApplicationComponent]
## refs:
[ref id=0]
 scope=[]
 name=[DatetimePickerComponent]
 nesting=[]
 resolved=[DatetimePickerComponent]
 loc=app/components/datetime_picker_component.rb:4
 is_defining_ref=1
[ref id=1]
 scope=[]
 name=[ApplicationComponent]
 nesting=[]
 resolved=[ApplicationComponent]
 loc=app/components/datetime_picker_component.rb:4
 is_defining_ref=0
 parent_of=[DatetimePickerComponent]
[ref id=2]
 scope=[DatetimePickerComponent]
 name=[SecureRandom]
 nesting=[[DatetimePickerComponent]]
 resolved=[SecureRandom]
 loc=app/components/datetime_picker_component.rb:9
 is_defining_ref=0"#;

        let files = parse(input).unwrap();
        assert_eq!(files.len(), 1);

        let f = &files[0];
        assert_eq!(f.path, "./app/components/datetime_picker_component.rb");
        assert!(f.requires.is_empty());

        // defs
        assert_eq!(f.defs.len(), 2);
        assert_eq!(f.defs[0].kind, DefKind::Module);
        assert!(!f.defs[0].defines_behavior);
        assert_eq!(f.defs[1].kind, DefKind::Class);
        assert!(f.defs[1].defines_behavior);
        assert_eq!(
            f.defs[1].defining_ref.as_deref(),
            Some(["DatetimePickerComponent".to_string()].as_slice())
        );
        assert_eq!(
            f.defs[1].parent_ref.as_deref(),
            Some(["ApplicationComponent".to_string()].as_slice())
        );

        // refs
        assert_eq!(f.refs.len(), 3);

        let r0 = &f.refs[0];
        assert_eq!(r0.resolved, vec!["DatetimePickerComponent"]);
        assert!(r0.is_defining_ref);

        let r1 = &f.refs[1];
        assert_eq!(r1.resolved, vec!["ApplicationComponent"]);
        assert!(!r1.is_defining_ref);
        assert_eq!(
            r1.parent_of.as_deref(),
            Some(["DatetimePickerComponent".to_string()].as_slice())
        );

        let r2 = &f.refs[2];
        assert_eq!(r2.scope, vec!["DatetimePickerComponent"]);
        assert_eq!(r2.name, vec!["SecureRandom"]);
        assert_eq!(r2.nesting, vec![vec!["DatetimePickerComponent".to_string()]]);
        assert_eq!(r2.loc, "app/components/datetime_picker_component.rb:9");
    }

    #[test]
    fn test_parse_nested_names() {
        let input = r#"# ParsedFile: ./app/controllers/user_area/campaigns_controller.rb
requires: []
## defs:
[def id=0]
 type=module
 defines_behavior=0
 is_empty=0
## refs:
[ref id=0]
 scope=[]
 name=[UserArea Campaigns Sections ProjectForwardingComponent]
 nesting=[]
 resolved=[UserArea Campaigns Sections ProjectForwardingComponent]
 loc=app/controllers/user_area/campaigns_controller.rb:10
 is_defining_ref=0"#;

        let files = parse(input).unwrap();
        let r = &files[0].refs[0];
        assert_eq!(
            r.resolved,
            vec!["UserArea", "Campaigns", "Sections", "ProjectForwardingComponent"]
        );
    }

    #[test]
    fn test_parse_multiple_files() {
        let input = r#"# ParsedFile: ./a.rb
requires: []
## defs:
## refs:
# ParsedFile: ./b.rb
requires: []
## defs:
## refs:"#;

        let files = parse(input).unwrap();
        assert_eq!(files.len(), 2);
        assert_eq!(files[0].path, "./a.rb");
        assert_eq!(files[1].path, "./b.rb");
    }
}