code2graph 0.0.0-beta.15

Purpose-neutral code-graph extraction: source files → symbols, references, and cross-file edges. Tree-sitter based, no storage opinion.
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
// SPDX-License-Identifier: Apache-2.0

//! SCIP-aligned symbol descriptors.
//!
//! A symbol's identity is a sequence of descriptors that together form a fully
//! qualified name, following Sourcegraph's SCIP grammar. Each descriptor kind
//! renders with a distinct suffix so the joined string is unambiguous; the
//! rendered SCIP string is for display/interoperability, while structural
//! identity lives in `SymbolId`'s language/local-file coordinates.
//!
//! Grammar (subset we emit), from `scip.proto`:
//! ```text
//! namespace       ident '/'
//! type            ident '#'
//! term            ident '.'
//! method          ident '(' disambiguator ')' '.'
//! type-parameter  '[' ident ']'
//! parameter       '(' ident ')'
//! meta            ident ':'
//! macro           ident '!'
//! ```

/// A SCIP method overload disambiguator.
///
/// SCIP permits only a simple identifier (or an empty value) and provides no
/// escaping for this coordinate. The inner value is private so a public
/// [`Descriptor::Method`] can never be constructed with an unrenderable value.
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct MethodDisambiguator(String);

impl MethodDisambiguator {
    /// The common, non-overloaded method coordinate.
    pub fn empty() -> Self {
        Self(String::new())
    }

    /// Construct a SCIP-valid overload coordinate.
    pub fn new(value: impl Into<String>) -> Result<Self, super::id::SymbolParseError> {
        let value = value.into();
        if value.chars().all(is_simple_ident_char) {
            Ok(Self(value))
        } else {
            Err(super::id::SymbolParseError::InvalidDisambiguator)
        }
    }

    fn as_str(&self) -> &str {
        &self.0
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for MethodDisambiguator {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

/// One element of a fully-qualified symbol path.
///
/// Its explicit structural sort order is namespace, type, term, method, type
/// parameter, parameter, meta, then macro. New variants must be appended (or
/// assigned a new explicit rank) rather than reordered.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Descriptor {
    /// A namespace / module / package segment (`ident/`).
    Namespace(String),
    /// A type: struct, class, enum, trait, interface (`ident#`).
    Type(String),
    /// A term: const, static, variable, value (`ident.`).
    Term(String),
    /// A method or free function (`ident(disambiguator).`). The `disambiguator`
    /// distinguishes overloads and **must** be a SCIP *simple-identifier* (chars
    /// per `is_simple_ident_char`) or empty: SCIP's grammar is
    /// `method-disambiguator ::= simple-identifier?` with **no escaped form**, so
    /// a non-simple disambiguator cannot be rendered to a parseable SCIP string.
    /// Empty disambiguator is the common case.
    Method {
        name: String,
        disambiguator: MethodDisambiguator,
    },
    /// A generic type parameter (`[ident]`).
    TypeParameter(String),
    /// A value parameter (`(ident)`).
    Parameter(String),
    /// Meta (e.g. a module's attribute namespace) (`ident:`).
    Meta(String),
    /// A macro (`ident!`).
    Macro(String),
}

impl Descriptor {
    /// Explicit, stable descriptor-kind rank used by structural ordering.
    fn kind_rank(&self) -> u8 {
        match self {
            Self::Namespace(_) => 0,
            Self::Type(_) => 1,
            Self::Term(_) => 2,
            Self::Method { .. } => 3,
            Self::TypeParameter(_) => 4,
            Self::Parameter(_) => 5,
            Self::Meta(_) => 6,
            Self::Macro(_) => 7,
        }
    }

    /// The bare identifier this descriptor names (used for name-only matching).
    pub fn name(&self) -> &str {
        match self {
            Descriptor::Namespace(n)
            | Descriptor::Type(n)
            | Descriptor::Term(n)
            | Descriptor::TypeParameter(n)
            | Descriptor::Parameter(n)
            | Descriptor::Meta(n)
            | Descriptor::Macro(n) => n,
            Descriptor::Method { name, .. } => name,
        }
    }

    /// Append this descriptor's SCIP rendering to `out`.
    pub fn render<W: core::fmt::Write>(&self, out: &mut W) -> core::fmt::Result {
        match self {
            Descriptor::Namespace(n) => {
                push_ident(out, n)?;
                out.write_char('/')
            }
            Descriptor::Type(n) => {
                push_ident(out, n)?;
                out.write_char('#')
            }
            Descriptor::Term(n) => {
                push_ident(out, n)?;
                out.write_char('.')
            }
            Descriptor::Method {
                name,
                disambiguator,
            } => {
                push_ident(out, name)?;
                out.write_char('(')?;
                out.write_str(disambiguator.as_str())?;
                out.write_str(").")
            }
            Descriptor::TypeParameter(n) => {
                out.write_char('[')?;
                push_ident(out, n)?;
                out.write_char(']')
            }
            Descriptor::Parameter(n) => {
                out.write_char('(')?;
                push_ident(out, n)?;
                out.write_char(')')
            }
            Descriptor::Meta(n) => {
                push_ident(out, n)?;
                out.write_char(':')
            }
            Descriptor::Macro(n) => {
                push_ident(out, n)?;
                out.write_char('!')
            }
        }
    }
}

impl Ord for Descriptor {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        let kind = self.kind_rank().cmp(&other.kind_rank());
        if kind != core::cmp::Ordering::Equal {
            return kind;
        }

        match (self, other) {
            (Self::Namespace(a), Self::Namespace(b))
            | (Self::Type(a), Self::Type(b))
            | (Self::Term(a), Self::Term(b))
            | (Self::TypeParameter(a), Self::TypeParameter(b))
            | (Self::Parameter(a), Self::Parameter(b))
            | (Self::Meta(a), Self::Meta(b))
            | (Self::Macro(a), Self::Macro(b)) => a.cmp(b),
            (
                Self::Method {
                    name: a_name,
                    disambiguator: a_disambiguator,
                },
                Self::Method {
                    name: b_name,
                    disambiguator: b_disambiguator,
                },
            ) => (a_name, a_disambiguator).cmp(&(b_name, b_disambiguator)),
            _ => unreachable!("equal descriptor ranks have the same variant"),
        }
    }
}

impl PartialOrd for Descriptor {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// Render an identifier per SCIP rules: bare if it is a simple identifier,
/// otherwise backtick-escaped (backticks inside doubled).
fn push_ident<W: core::fmt::Write>(out: &mut W, ident: &str) -> core::fmt::Result {
    let simple = !ident.is_empty() && ident.chars().all(is_simple_ident_char);
    if simple {
        out.write_str(ident)
    } else {
        out.write_char('`')?;
        for c in ident.chars() {
            if c == '`' {
                out.write_char('`')?;
            }
            out.write_char(c)?;
        }
        out.write_char('`')
    }
}

/// A character is part of a *simple* (bare) identifier per SCIP rules.
fn is_simple_ident_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_' || c == '+' || c == '-' || c == '$'
}

/// Parse one identifier from the front of `s`, inverting [`push_ident`].
///
/// Handles both the bare form (a maximal run of simple chars) and the
/// backtick-quoted form (doubled `` `` `` decodes to a literal `` ` ``).
/// Returns the decoded name and the remaining slice.
pub(crate) fn parse_ident(s: &str) -> Result<(String, &str), super::id::SymbolParseError> {
    use super::id::SymbolParseError;
    if let Some(quoted) = s.strip_prefix('`') {
        // Quoted: scan char-by-char over a moving slice; a `` ` `` followed by
        // another `` ` `` is a literal backtick, a lone `` ` `` closes the ident.
        let mut name = String::new();
        let mut rest = quoted;
        loop {
            let mut chars = rest.char_indices();
            match chars.next() {
                None => return Err(SymbolParseError::UnterminatedQuote),
                Some((_, '`')) => {
                    // `chars.as_str()` is everything after this backtick.
                    let after = chars.as_str();
                    if let Some(next) = after.strip_prefix('`') {
                        // Doubled backtick → literal backtick; keep scanning.
                        name.push('`');
                        rest = next;
                    } else {
                        // Closing backtick.
                        return Ok((name, after));
                    }
                }
                Some((_, c)) => {
                    name.push(c);
                    rest = chars.as_str();
                }
            }
        }
    } else {
        // Bare: maximal run of simple chars.
        let end = s
            .char_indices()
            .find(|&(_, c)| !is_simple_ident_char(c))
            .map(|(i, _)| i)
            .unwrap_or(s.len());
        if end == 0 {
            return Err(SymbolParseError::ExpectedIdent);
        }
        let (name, rest) = s.split_at(end);
        Ok((name.to_owned(), rest))
    }
}

/// Parse one descriptor from the front of `s`, inverting [`Descriptor::render`].
///
/// Returns the descriptor and the remaining slice. Each successful call
/// consumes at least one character, so a parse loop always terminates.
pub(crate) fn parse_descriptor(s: &str) -> Result<(Descriptor, &str), super::id::SymbolParseError> {
    use super::id::SymbolParseError;
    // Structured forms first: their leading delimiter is unambiguous.
    if let Some(rest) = s.strip_prefix('[') {
        let (name, rest) = parse_ident(rest)?;
        let rest = rest
            .strip_prefix(']')
            .ok_or(SymbolParseError::UnknownDescriptor)?;
        return Ok((Descriptor::TypeParameter(name), rest));
    }
    if let Some(rest) = s.strip_prefix('(') {
        let (name, rest) = parse_ident(rest)?;
        let rest = rest
            .strip_prefix(')')
            .ok_or(SymbolParseError::UnknownDescriptor)?;
        return Ok((Descriptor::Parameter(name), rest));
    }

    // Remaining forms lead with an identifier, then a suffix char decides.
    let (name, rest) = parse_ident(s)?;
    let mut chars = rest.chars();
    match chars.next() {
        Some('(') => {
            // Method: read raw disambiguator until ')', then '.'.
            let (disambiguator, after_close) = chars
                .as_str()
                .split_once(')')
                .ok_or(SymbolParseError::UnknownDescriptor)?;
            if !disambiguator.chars().all(is_simple_ident_char) {
                return Err(SymbolParseError::InvalidDisambiguator);
            }
            let disambiguator = MethodDisambiguator::new(disambiguator.to_owned())?;
            let rest = after_close
                .strip_prefix('.')
                .ok_or(SymbolParseError::UnknownDescriptor)?;
            Ok((
                Descriptor::Method {
                    name,
                    disambiguator,
                },
                rest,
            ))
        }
        Some('/') => Ok((Descriptor::Namespace(name), chars.as_str())),
        Some('#') => Ok((Descriptor::Type(name), chars.as_str())),
        Some('.') => Ok((Descriptor::Term(name), chars.as_str())),
        Some(':') => Ok((Descriptor::Meta(name), chars.as_str())),
        Some('!') => Ok((Descriptor::Macro(name), chars.as_str())),
        _ => Err(SymbolParseError::UnknownDescriptor),
    }
}

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

    #[test]
    fn renders_scip_suffixes() {
        let mut s = String::new();
        Descriptor::Namespace("auth".into()).render(&mut s).unwrap();
        Descriptor::Method {
            name: "validate_token".into(),
            disambiguator: MethodDisambiguator::empty(),
        }
        .render(&mut s)
        .unwrap();
        assert_eq!(s, "auth/validate_token().");
    }

    #[test]
    fn escapes_non_simple_idents() {
        let mut s = String::new();
        Descriptor::Type("Foo Bar".into()).render(&mut s).unwrap();
        assert_eq!(s, "`Foo Bar`#");
    }

    #[test]
    fn descriptor_order_is_explicit_and_consistent_with_equality() {
        let descriptors = [
            Descriptor::Namespace("item".into()),
            Descriptor::Type("item".into()),
            Descriptor::Term("item".into()),
            Descriptor::Method {
                name: "item".into(),
                disambiguator: MethodDisambiguator::empty(),
            },
            Descriptor::TypeParameter("item".into()),
            Descriptor::Parameter("item".into()),
            Descriptor::Meta("item".into()),
            Descriptor::Macro("item".into()),
        ];

        for (index, descriptor) in descriptors.iter().enumerate() {
            assert_eq!(descriptor.cmp(descriptor), core::cmp::Ordering::Equal);
            for later in &descriptors[index + 1..] {
                assert_eq!(descriptor.cmp(later), core::cmp::Ordering::Less);
                assert_eq!(later.cmp(descriptor), core::cmp::Ordering::Greater);
            }
        }

        let overloaded = Descriptor::Method {
            name: "item".into(),
            disambiguator: MethodDisambiguator::new("1").unwrap(),
        };
        assert_ne!(descriptors[3], overloaded);
        assert!(descriptors[3] < overloaded);
    }

    #[test]
    fn method_with_nonempty_disambiguator_round_trips() {
        // A SCIP-valid (simple-identifier) overload disambiguator must survive
        // render → parse → identical descriptor. "1" is the canonical overload
        // index; this locks the disambiguator path that all extractors leave
        // empty today, so a future overload-aware extractor can't silently break
        // identity.
        let desc = Descriptor::Method {
            name: "to_string".into(),
            disambiguator: MethodDisambiguator::new("1").unwrap(),
        };
        let mut s = String::new();
        desc.render(&mut s).unwrap();
        assert_eq!(s, "to_string(1).");
        let (parsed, rest) = parse_descriptor(&s).unwrap();
        assert_eq!(parsed, desc);
        assert!(rest.is_empty(), "no trailing input, got {rest:?}");
    }
}