Skip to main content

sqry_core/ast/
scope.rs

1//! Scope types for context-aware search.
2
3use serde::{Deserialize, Serialize};
4use std::path::PathBuf;
5
6/// Unique identifier for a scope within a file.
7///
8/// Scope IDs are assigned sequentially during scope extraction, starting from 0.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
10pub struct ScopeId(pub usize);
11
12impl ScopeId {
13    /// Create a new `ScopeId`.
14    #[must_use]
15    pub fn new(id: usize) -> Self {
16        Self(id)
17    }
18}
19
20impl From<usize> for ScopeId {
21    fn from(id: usize) -> Self {
22        Self(id)
23    }
24}
25
26impl From<ScopeId> for usize {
27    fn from(id: ScopeId) -> Self {
28        id.0
29    }
30}
31
32/// Scope information for context-aware search.
33///
34/// Represents a lexical scope in source code (function, class, module, etc.).
35#[derive(Debug, Clone, Serialize, Deserialize)]
36pub struct Scope {
37    /// Unique identifier for this scope (file-local).
38    ///
39    /// Assigned during extraction, sequential starting from 0.
40    pub id: ScopeId,
41
42    /// Scope type (function, class, module, etc.).
43    pub scope_type: String,
44
45    /// Scope name.
46    pub name: String,
47
48    /// File path where scope is defined.
49    pub file_path: PathBuf,
50
51    /// Line number where scope starts (1-based).
52    pub start_line: usize,
53
54    /// Column where scope starts (0-based).
55    pub start_column: usize,
56
57    /// Line number where scope ends (1-based).
58    pub end_line: usize,
59
60    /// Column where scope ends (0-based).
61    pub end_column: usize,
62
63    /// Parent scope ID (immediate containing scope).
64    ///
65    /// Set by `link_nested_scopes()` algorithm.
66    pub parent_id: Option<ScopeId>,
67}
68
69impl Scope {
70    /// Create a new scope.
71    #[must_use]
72    pub fn new(scope_type: String, name: String, file_path: PathBuf) -> Self {
73        Self {
74            id: ScopeId::new(0),
75            scope_type,
76            name,
77            file_path,
78            start_line: 0,
79            start_column: 0,
80            end_line: 0,
81            end_column: 0,
82            parent_id: None,
83        }
84    }
85
86    /// Set the location (start and end position).
87    #[must_use]
88    pub fn with_location(
89        mut self,
90        start_line: usize,
91        start_column: usize,
92        end_line: usize,
93        end_column: usize,
94    ) -> Self {
95        self.start_line = start_line;
96        self.start_column = start_column;
97        self.end_line = end_line;
98        self.end_column = end_column;
99        self
100    }
101
102    /// Set the parent scope ID.
103    #[must_use]
104    pub fn with_parent(mut self, parent_id: ScopeId) -> Self {
105        self.parent_id = Some(parent_id);
106        self
107    }
108}