scope-engine 0.3.0

Semantic Code Operation & Propagation Engine
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
use std::path::{Path, PathBuf};

use regex::Regex;

type OptionalLineRangeSuffix<'a> = (&'a str, Option<(usize, usize)>);

/// A parsed SCOPE selector. The selector is a positioning DSL: it locates
/// targets/ranges, but it does not encode operation semantics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedSelector {
    /// File path relative to project root.
    pub file_path: PathBuf,
    /// Parsed selector target.
    pub target: SelectorTarget,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SelectorTarget {
    Symbol(SymbolSelector),
    LineRange {
        start_line: usize,
        end_line: usize,
    },
    AroundLine {
        line: usize,
        context: usize,
    },
    Match {
        pattern: String,
        around: Option<usize>,
    },
    BeforeLine {
        line: usize,
    },
    AfterLine {
        line: usize,
    },
    Enclosing {
        line: usize,
    },
    Outline,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SymbolSelector {
    /// The kind of symbol (function, struct, etc.) or Unknown for bare names.
    pub kind: SymbolKind,
    /// The symbol name to match against AST nodes.
    pub name: String,
    /// Optional 1-based line range disambiguator: `#Lstart-Lend`.
    pub line_range: Option<(usize, usize)>,
}

impl ParsedSelector {
    #[must_use]
    pub const fn as_symbol(&self) -> Option<&SymbolSelector> {
        match &self.target {
            SelectorTarget::Symbol(symbol) => Some(symbol),
            _ => None,
        }
    }

    /// Legacy accessor for callers/tests that still operate on symbol selectors.
    #[must_use]
    pub fn kind(&self) -> Option<&SymbolKind> {
        self.as_symbol().map(|symbol| &symbol.kind)
    }

    /// Legacy accessor for callers/tests that still operate on symbol selectors.
    #[must_use]
    pub fn name(&self) -> Option<&str> {
        self.as_symbol().map(|symbol| symbol.name.as_str())
    }

    /// Legacy accessor for callers/tests that still operate on symbol selectors.
    #[must_use]
    pub fn line_range(&self) -> Option<(usize, usize)> {
        self.as_symbol().and_then(|symbol| symbol.line_range)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SymbolKind {
    Function,
    Struct,
    Enum,
    Trait,
    Impl,
    Class,
    /// Mod, const, static, type alias, or bare name (fuzzy match all).
    Unknown,
}

impl SymbolKind {
    /// Parse a symbol-kind prefix like "fn", "struct", "enum", "trait", "impl".
    fn from_prefix(prefix: &str) -> Self {
        match prefix {
            // Rust
            "struct" | "type" => Self::Struct,
            "enum" => Self::Enum,
            "trait" | "interface" => Self::Trait,
            "impl" => Self::Impl,
            // Go
            // Java/C++/C#/Ruby/PHP
            "class" => Self::Class,
            "fn" | "func" | "method" | "constructor" | "def" => Self::Function,
            _ => Self::Unknown,
        }
    }

    /// Heuristic: guess the kind from a tree-sitter node kind string.
    /// Used to map tree-sitter parse results back to `SymbolKind`.
    #[must_use]
    pub fn from_ts_node_kind(kind: &str) -> Self {
        match kind {
            "struct_item"
            | "type_alias_declaration"
            | "type_declaration"
            | "type_identifier"
            | "struct_specifier" => Self::Struct,
            "enum_item" | "enum_declaration" => Self::Enum,
            "trait_item" | "interface_declaration" => Self::Trait,
            "impl_item" => Self::Impl,
            // Python tree-sitter node types
            "class_definition" | "class_declaration" | "class_specifier" => Self::Class,
            // TypeScript/JavaScript node types
            // Go tree-sitter node types
            // Java tree-sitter node types
            // C/C++ tree-sitter node types
            // Ruby tree-sitter node types
            "function_item"
            | "function_definition"
            | "decorated_definition"
            | "function_declaration"
            | "method_definition"
            | "arrow_function"
            | "variable_declarator"
            | "method_declaration"
            | "constructor_declaration"
            | "singleton_method" => Self::Function,
            _ => Self::Unknown,
        }
    }
}

impl std::fmt::Display for SymbolKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Function => write!(f, "fn"),
            Self::Struct => write!(f, "struct"),
            Self::Enum => write!(f, "enum"),
            Self::Trait => write!(f, "trait"),
            Self::Impl => write!(f, "impl"),
            Self::Class => write!(f, "class"),
            Self::Unknown => write!(f, "symbol"),
        }
    }
}

/// Parse a selector string of the form `file_path::[kind ]name`.
///
/// The `::` separates the file path from the symbol expression.
/// After `::`, an optional kind prefix (`fn`, `struct`, etc.) may appear,
/// followed by the symbol name.  Trailing `()` is stripped from function names.
///
/// # Errors
/// Returns an error string if the input is missing `::`, has an empty file path,
/// or has an empty symbol name.
pub fn parse_selector(input: &str) -> Result<ParsedSelector, String> {
    if !input.contains("::")
        && let Some((file_part, suffix)) = input.split_once('#')
    {
        return parse_hash_selector(file_part, suffix, input);
    }

    // Split on the first `::`
    let (file_part, symbol_part) = input.split_once("::").ok_or_else(|| {
        format!("selector must contain '::' separating file path from symbol: '{input}'")
    })?;

    let file_path = parse_file_path(file_part)?;

    let symbol_part = symbol_part.trim();
    if symbol_part.is_empty() {
        return Err("selector symbol part is empty after '::'".to_string());
    }

    let (symbol_part, line_range) = parse_line_range_suffix(symbol_part)?;

    // Parse the symbol part: optional kind prefix + name
    let (kind, name) = parse_symbol_expr(symbol_part);

    if name.is_empty() {
        return Err(format!("selector symbol name is empty: '{symbol_part}'"));
    }

    Ok(ParsedSelector {
        file_path,
        target: SelectorTarget::Symbol(SymbolSelector {
            kind,
            name,
            line_range,
        }),
    })
}

fn parse_file_path(file_part: &str) -> Result<PathBuf, String> {
    let file_path = PathBuf::from(file_part.trim());
    if file_path.as_os_str().is_empty() {
        return Err("selector file path is empty".to_string());
    }
    Ok(file_path)
}

fn parse_hash_selector(
    file_part: &str,
    suffix: &str,
    input: &str,
) -> Result<ParsedSelector, String> {
    let file_path = parse_file_path(file_part)?;
    let target = if let Some(range_expr) = suffix.strip_prefix('L') {
        let (start_line, end_line) = parse_line_range_expr(range_expr)?;
        SelectorTarget::LineRange {
            start_line,
            end_line,
        }
    } else if let Some(expr) = suffix.strip_prefix("around:L") {
        let (line, context) = parse_around_line_expr(expr)?;
        SelectorTarget::AroundLine { line, context }
    } else if let Some(expr) = suffix.strip_prefix("match:/") {
        parse_match_target(expr)?
    } else if let Some(expr) = suffix.strip_prefix("before:L") {
        let line = parse_positive_usize(expr, "before line")?;
        SelectorTarget::BeforeLine { line }
    } else if let Some(expr) = suffix.strip_prefix("after:L") {
        let line = parse_positive_usize(expr, "after line")?;
        SelectorTarget::AfterLine { line }
    } else if let Some(expr) = suffix.strip_prefix("enclosing:L") {
        let line = parse_positive_usize(expr, "enclosing line")?;
        SelectorTarget::Enclosing { line }
    } else if suffix == "outline" {
        SelectorTarget::Outline
    } else {
        return Err(format!("unsupported selector suffix in '{input}'"));
    };

    Ok(ParsedSelector { file_path, target })
}

/// Parse an optional `#Lstart-Lend` line-range disambiguator suffix.
fn parse_line_range_suffix(expr: &str) -> Result<OptionalLineRangeSuffix<'_>, String> {
    let Some((symbol_expr, range_expr)) = expr.rsplit_once("#L") else {
        return Ok((expr, None));
    };

    let symbol_expr = symbol_expr.trim_end();
    if symbol_expr.is_empty() {
        return Err(format!(
            "selector symbol name is empty before line range: '{expr}'"
        ));
    }

    let (start_str, end_str) = range_expr
        .split_once("-L")
        .or_else(|| range_expr.split_once('-'))
        .ok_or_else(|| format!("bad selector line range '#L{range_expr}'"))?;
    let start = start_str
        .parse::<usize>()
        .map_err(|_| format!("bad selector line range start: '#L{range_expr}'"))?;
    let end = end_str
        .parse::<usize>()
        .map_err(|_| format!("bad selector line range end: '#L{range_expr}'"))?;
    if start == 0 || end == 0 || start > end {
        return Err(format!("bad selector line range '#L{range_expr}'"));
    }

    Ok((symbol_expr, Some((start, end))))
}

fn parse_line_range_expr(expr: &str) -> Result<(usize, usize), String> {
    let (start_str, end_str) = expr
        .split_once("-L")
        .or_else(|| expr.split_once('-'))
        .ok_or_else(|| format!("bad selector line range '#L{expr}'"))?;
    let start = parse_positive_usize(start_str, "line range start")?;
    let end = parse_positive_usize(end_str, "line range end")?;
    if start > end {
        return Err(format!("bad selector line range '#L{expr}'"));
    }
    Ok((start, end))
}

fn parse_around_line_expr(expr: &str) -> Result<(usize, usize), String> {
    let (line_str, context_str) = expr
        .split_once('±')
        .or_else(|| expr.split_once("+-"))
        .or_else(|| expr.split_once("+/-"))
        .ok_or_else(|| format!("bad around selector '#around:L{expr}'"))?;
    Ok((
        parse_positive_usize(line_str, "around line")?,
        parse_positive_usize(context_str, "around context")?,
    ))
}

fn parse_match_target(expr: &str) -> Result<SelectorTarget, String> {
    let (pattern, rest) = expr
        .split_once('/')
        .ok_or_else(|| "bad match selector; expected #match:/pattern/".to_string())?;
    if pattern.is_empty() {
        return Err("match selector pattern is empty".to_string());
    }
    Regex::new(pattern).map_err(|e| format!("bad match selector regex: {e}"))?;
    let around = if rest.is_empty() {
        None
    } else if let Some(around_expr) = rest.strip_prefix("#around:") {
        Some(parse_positive_usize(around_expr, "match around context")?)
    } else {
        return Err(format!("unsupported match selector suffix: '{rest}'"));
    };
    Ok(SelectorTarget::Match {
        pattern: pattern.to_string(),
        around,
    })
}

fn parse_positive_usize(input: &str, label: &str) -> Result<usize, String> {
    let value = input
        .parse::<usize>()
        .map_err(|_| format!("bad {label}: '{input}'"))?;
    if value == 0 {
        return Err(format!("bad {label}: '{input}'"));
    }
    Ok(value)
}

/// Parse the symbol expression (everything after `::`).
///
/// Recognised forms:
/// - `fn name` or `fn name()` → (Function, "name")
/// - `struct Name`            → (Struct, "Name")
/// - `enum Name`              → (Enum, "Name")
/// - `trait Name`             → (Trait, "Name")
/// - `impl Type`              → (Impl, "Type")
/// - `impl Trait for Type`    → (Impl, "Trait")  — we take the trait name
/// - bare name                → (Unknown, "name")
fn parse_symbol_expr(expr: &str) -> (SymbolKind, String) {
    let expr = expr.trim();

    // Strip trailing `()` from function-like names
    let expr = expr.strip_suffix("()").unwrap_or(expr);

    // Check for kind prefixes
    let parts: Vec<&str> = expr.splitn(2, char::is_whitespace).collect();
    if parts.len() == 2 {
        let prefix = parts[0];
        let remainder = parts[1].trim();
        let kind = SymbolKind::from_prefix(prefix);
        if !matches!(kind, SymbolKind::Unknown) {
            // For `impl Trait for Type`, take the trait name
            if matches!(kind, SymbolKind::Impl)
                && let Some(trait_name) = remainder.split_whitespace().next()
            {
                return (kind, trait_name.to_string());
            }
            // Strip trailing parens from remainder too (e.g. "fn old()")
            let name = remainder.strip_suffix("()").unwrap_or(remainder);
            return (kind, name.to_string());
        }
    }

    // Bare name — fuzzy match all kinds
    (SymbolKind::Unknown, expr.to_string())
}

/// Resolve a selector's file path against a project root, and return the absolute path
/// along with the file extension (for language detection).
///
/// # Errors
///
/// Returns an error if the selected file does not exist or has no extension.
pub fn resolve_file(
    selector: &ParsedSelector,
    project_root: &Path,
) -> Result<(PathBuf, String), String> {
    let full_path = project_root.join(&selector.file_path);
    if !full_path.exists() {
        return Err(format!("file not found: {}", full_path.display()));
    }
    let ext = full_path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_string();
    if ext.is_empty() {
        return Err(format!(
            "cannot determine language from file: {}",
            full_path.display()
        ));
    }
    Ok((full_path, ext))
}

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

    #[test]
    fn parse_fn_selector() {
        let sel = parse_selector("src/foo.rs::fn authenticate").unwrap();
        assert_eq!(sel.file_path, PathBuf::from("src/foo.rs"));
        assert_eq!(sel.kind(), Some(&SymbolKind::Function));
        assert_eq!(sel.name(), Some("authenticate"));
    }

    #[test]
    fn parse_fn_with_parens() {
        let sel = parse_selector("src/foo.rs::fn authenticate()").unwrap();
        assert_eq!(sel.name(), Some("authenticate"));
    }

    #[test]
    fn parse_line_range_disambiguator() {
        let sel = parse_selector("src/foo.rs::fn authenticate #L10-L20").unwrap();
        assert_eq!(sel.name(), Some("authenticate"));
        assert_eq!(sel.line_range(), Some((10, 20)));
    }

    #[test]
    fn invalid_line_range_disambiguator_is_error() {
        assert!(parse_selector("src/foo.rs::fn authenticate #L20-L10").is_err());
        assert!(parse_selector("src/foo.rs::fn authenticate #Labc-L20").is_err());
    }

    #[test]
    fn parse_struct_selector() {
        let sel = parse_selector("src/lib.rs::struct Config").unwrap();
        assert_eq!(sel.kind(), Some(&SymbolKind::Struct));
        assert_eq!(sel.name(), Some("Config"));
    }

    #[test]
    fn parse_enum_selector() {
        let sel = parse_selector("src/types.rs::enum Color").unwrap();
        assert_eq!(sel.kind(), Some(&SymbolKind::Enum));
        assert_eq!(sel.name(), Some("Color"));
    }

    #[test]
    fn parse_trait_selector() {
        let sel = parse_selector("src/lib.rs::trait Serialize").unwrap();
        assert_eq!(sel.kind(), Some(&SymbolKind::Trait));
        assert_eq!(sel.name(), Some("Serialize"));
    }

    #[test]
    fn parse_impl_selector() {
        let sel = parse_selector("src/foo.rs::impl MyStruct").unwrap();
        assert_eq!(sel.kind(), Some(&SymbolKind::Impl));
        assert_eq!(sel.name(), Some("MyStruct"));
    }

    #[test]
    fn parse_impl_for_selector() {
        let sel = parse_selector("src/foo.rs::impl Display for MyStruct").unwrap();
        assert_eq!(sel.kind(), Some(&SymbolKind::Impl));
        assert_eq!(sel.name(), Some("Display"));
    }

    #[test]
    fn parse_bare_name() {
        let sel = parse_selector("src/foo.rs::authenticate").unwrap();
        assert_eq!(sel.kind(), Some(&SymbolKind::Unknown));
        assert_eq!(sel.name(), Some("authenticate"));
    }

    #[test]
    fn parse_with_spaces_in_path() {
        // File paths with spaces are unusual but valid
        let sel = parse_selector("some dir/file.rs::fn hello").unwrap();
        assert_eq!(sel.file_path, PathBuf::from("some dir/file.rs"));
        assert_eq!(sel.name(), Some("hello"));
    }

    #[test]
    fn missing_double_colon_is_error() {
        assert!(parse_selector("src/foo.rs").is_err());
    }

    #[test]
    fn empty_file_path_is_error() {
        assert!(parse_selector("::fn foo").is_err());
    }

    #[test]
    fn empty_symbol_is_error() {
        assert!(parse_selector("src/foo.rs::").is_err());
    }
    #[test]
    fn parse_scope_range_and_context_selectors() {
        let sel = parse_selector("src/foo.rs#L120-L180").unwrap();
        assert_eq!(sel.file_path, PathBuf::from("src/foo.rs"));
        assert_eq!(
            sel.target,
            SelectorTarget::LineRange {
                start_line: 120,
                end_line: 180
            }
        );

        let sel = parse_selector("src/foo.rs#around:L150±40").unwrap();
        assert_eq!(
            sel.target,
            SelectorTarget::AroundLine {
                line: 150,
                context: 40
            }
        );

        let sel = parse_selector("src/foo.rs#enclosing:L150").unwrap();
        assert_eq!(sel.target, SelectorTarget::Enclosing { line: 150 });

        let sel = parse_selector("src/foo.rs#before:L150").unwrap();
        assert_eq!(sel.target, SelectorTarget::BeforeLine { line: 150 });

        let sel = parse_selector("src/foo.rs#after:L150").unwrap();
        assert_eq!(sel.target, SelectorTarget::AfterLine { line: 150 });

        let sel = parse_selector("src/foo.rs#outline").unwrap();
        assert_eq!(sel.target, SelectorTarget::Outline);
    }

    #[test]
    fn parse_scope_match_selectors() {
        let sel = parse_selector("src/foo.rs#match:/ProjectInstructions/").unwrap();
        assert_eq!(
            sel.target,
            SelectorTarget::Match {
                pattern: "ProjectInstructions".to_string(),
                around: None
            }
        );

        let sel = parse_selector("src/foo.rs#match:/ProjectInstructions/#around:40").unwrap();
        assert_eq!(
            sel.target,
            SelectorTarget::Match {
                pattern: "ProjectInstructions".to_string(),
                around: Some(40)
            }
        );
    }
}