seshat-core 0.3.0

Core types, traits, and intermediate representation for Seshat
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
553
554
555
556
use serde::{Deserialize, Serialize};
use std::fmt;
use std::path::PathBuf;

use crate::error::ParseEnumError;

/// Supported programming languages.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Language {
    Rust,
    TypeScript,
    JavaScript,
    Python,
}

impl Language {
    /// Return the canonical snake_case representation.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Rust => "rust",
            Self::TypeScript => "typescript",
            Self::JavaScript => "javascript",
            Self::Python => "python",
        }
    }
}

impl fmt::Display for Language {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Rust => write!(f, "Rust"),
            Self::TypeScript => write!(f, "TypeScript"),
            Self::JavaScript => write!(f, "JavaScript"),
            Self::Python => write!(f, "Python"),
        }
    }
}

impl std::str::FromStr for Language {
    type Err = ParseEnumError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "rust" => Ok(Self::Rust),
            "typescript" => Ok(Self::TypeScript),
            "javascript" => Ok(Self::JavaScript),
            "python" => Ok(Self::Python),
            _ => Err(ParseEnumError {
                type_name: "Language",
                value: s.to_owned(),
            }),
        }
    }
}

impl Language {
    /// Returns file extensions associated with this language.
    pub fn extensions(&self) -> &'static [&'static str] {
        match self {
            Self::Rust => &["rs"],
            Self::TypeScript => &["ts", "tsx"],
            Self::JavaScript => &["js", "jsx", "mjs", "cjs"],
            Self::Python => &["py"],
        }
    }

    /// All supported language variants for iteration.
    pub fn all() -> &'static [Language] {
        &[Self::Rust, Self::TypeScript, Self::JavaScript, Self::Python]
    }

    /// Detect language from a file extension (without the leading dot).
    ///
    /// Returns `None` for unrecognised extensions.
    pub fn from_extension(ext: &str) -> Option<Self> {
        match ext {
            "rs" => Some(Self::Rust),
            "ts" | "tsx" => Some(Self::TypeScript),
            "js" | "jsx" | "mjs" | "cjs" => Some(Self::JavaScript),
            "py" => Some(Self::Python),
            _ => None,
        }
    }

    /// Visibility/export marker rendered before a public symbol in this
    /// language's syntax. Empty string when the symbol is private or when the
    /// language has no syntactic visibility keyword.
    ///
    /// Used by [`crate::symbol_snippet`] so synthetic definition snippets read
    /// natively for each language instead of always borrowing Rust's `pub`.
    ///
    /// - Rust: `pub ` for public, `""` for private.
    /// - TypeScript / JavaScript: `export ` for public, `""` for private.
    ///   (TS/JS parsers set `is_public = true` exactly when a symbol carries
    ///   the `export` keyword.)
    /// - Python: always `""` — Python has no syntactic visibility marker.
    #[must_use]
    pub fn visibility_keyword(self, is_public: bool) -> &'static str {
        if !is_public {
            return "";
        }
        match self {
            Self::Rust => "pub ",
            Self::TypeScript | Self::JavaScript => "export ",
            Self::Python => "",
        }
    }

    /// Source keyword for declaring a function in this language: `fn` /
    /// `function` / `def`.
    #[must_use]
    pub fn function_keyword(self) -> &'static str {
        match self {
            Self::Rust => "fn",
            Self::TypeScript | Self::JavaScript => "function",
            Self::Python => "def",
        }
    }
}

/// Normalized intermediate representation of a parsed source file.
///
/// Common fields are shared across all languages. Language-specific
/// details live in the `language_ir` enum variant.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ProjectFile {
    pub path: PathBuf,
    pub language: Language,
    pub content_hash: String,
    pub imports: Vec<Import>,
    pub exports: Vec<Export>,
    pub functions: Vec<Function>,
    pub types: Vec<TypeDef>,
    pub dependencies_used: Vec<DependencyUsage>,
    pub language_ir: LanguageIR,
    /// File-level doc comment extracted by the parser.
    ///
    /// - Rust: `//!` inner doc comment at the top of the file.
    /// - Python: module-level docstring (first `"""..."""` or `'''...'''`).
    /// - TypeScript/JavaScript: leading `/** ... */` or `//` comment block.
    ///
    /// `None` when no file-level documentation is present or the parser
    /// has not yet been updated to extract it.
    #[serde(default)]
    pub file_doc: Option<String>,
}

/// An import statement extracted from source code.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Import {
    pub module: String,
    pub names: Vec<String>,
    pub is_type_only: bool,
    pub line: usize,
}

/// An export declaration extracted from source code.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Export {
    pub name: String,
    pub is_default: bool,
    pub is_type_only: bool,
    pub line: usize,
    /// 1-indexed source line where the export declaration ends.
    ///
    /// Equals [`Self::line`] for single-line statements such as
    /// `pub use foo::*;`, `export { Foo };`, or `type Alias = X;`. For
    /// multi-line declarations (e.g. `export class Foo { ... }`) this is the
    /// closing line of the declaration node — matching the existing
    /// [`Function::end_line`] semantics. Hunk-intersection logic in
    /// `map_diff_impact` uses `[line, end_line]` as the symbol's range.
    ///
    /// Required (no `#[serde(default)]`): IR_SCHEMA_VERSION 8 added this
    /// field; older v7 IR rows fail StaleIR detection and are re-scanned,
    /// so deserialisation here should never legitimately encounter a
    /// missing value. Failing loudly surfaces actual data corruption.
    pub end_line: usize,
}

/// A function or method definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct Function {
    pub name: String,
    pub is_public: bool,
    pub is_async: bool,
    pub line: usize,
    pub end_line: usize,
    /// Parameter names extracted by tree-sitter (empty if not yet extracted).
    #[serde(default)]
    pub parameters: Vec<String>,
    /// Doc comment / docstring attached to this function.
    ///
    /// - Rust: consecutive `///` lines immediately preceding the function.
    /// - Python: triple-quoted string as the first statement of the body.
    /// - TypeScript/JavaScript: JSDoc `/** ... */` comment preceding the function.
    ///
    /// `None` when absent or when the parser has not yet been updated.
    #[serde(default)]
    pub doc_comment: Option<String>,
}

/// A type definition (struct, enum, interface, class, type alias).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct TypeDef {
    pub name: String,
    pub kind: TypeDefKind,
    pub is_public: bool,
    pub line: usize,
    /// 1-indexed source line where the type definition ends.
    ///
    /// Equals [`Self::line`] for single-line type aliases (`type Alias = X;`).
    /// For multi-line declarations (struct, enum, trait, interface, class)
    /// this is the closing line of the declaration node — matching the
    /// existing [`Function::end_line`] semantics. Hunk-intersection logic in
    /// `map_diff_impact` uses `[line, end_line]` as the symbol's range.
    ///
    /// Required (no `#[serde(default)]`): IR_SCHEMA_VERSION 8 added this
    /// field; older v7 IR rows fail StaleIR detection and are re-scanned,
    /// so deserialisation here should never legitimately encounter a
    /// missing value. Failing loudly surfaces actual data corruption.
    pub end_line: usize,
    /// Doc comment attached to this type definition.
    ///
    /// Same conventions as [`Function::doc_comment`].
    /// `None` when absent or parser not yet updated.
    #[serde(default)]
    pub doc_comment: Option<String>,
}

/// The kind of a type definition.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TypeDefKind {
    Struct,
    Enum,
    Trait,
    Interface,
    Class,
    TypeAlias,
}

impl TypeDefKind {
    /// Source keyword used to declare a type of this kind: `struct` / `enum` /
    /// `trait` / `interface` / `class` / `type`.
    ///
    /// Note `TypeAlias` renders as `type`, matching both Rust's `type Foo =
    /// …;` and TS's `type Foo = …;`. The old debug-derived spelling
    /// `typealias` was not valid syntax in any supported language.
    #[must_use]
    pub fn keyword(&self) -> &'static str {
        match self {
            Self::Struct => "struct",
            Self::Enum => "enum",
            Self::Trait => "trait",
            Self::Interface => "interface",
            Self::Class => "class",
            Self::TypeAlias => "type",
        }
    }
}

/// A dependency usage reference found in source code.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct DependencyUsage {
    pub package: String,
    pub import_path: String,
    pub line: usize,
}

/// Language-specific IR details.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LanguageIR {
    Rust(RustIR),
    TypeScript(TypeScriptIR),
    JavaScript(JavaScriptIR),
    Python(PythonIR),
}

/// A `mod foo;` or `mod foo { ... }` declaration in a Rust file.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct ModDeclaration {
    /// Name of the declared module (e.g. `"config"`, `"tests"`).
    pub name: String,
    /// 1-indexed source line of the `mod` keyword.
    pub line: usize,
}

/// A macro invocation in a Rust file (e.g. `tracing::info!(...)`, `vec![...]`).
///
/// Stores the full macro path as written in source and the call-site line so
/// that detectors can point to real usage rather than import declarations.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct MacroCall {
    /// Full macro name as written, e.g. `"tracing::info"`, `"vec"`.
    pub name: String,
    /// 1-indexed source line of the macro invocation.
    pub line: usize,
}

/// A function or method call-site in a Rust file.
///
/// Stores **one example per unique callee name** (deduplication happens in the
/// parser).  The snippet captures a window around the call so that MCP clients
/// can show real usage patterns without additional disk I/O at query time.
///
/// # Snippet layout
///
/// ```text
/// [2 lines of context before the opening line]
/// [all lines of the call expression — may span many lines for multi-arg calls]
/// [4 lines of context after the closing line]
/// ```
///
/// Hard cap: 30 lines total.  Lines are taken from the raw source file and
/// include the original indentation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct FunctionCall {
    /// Full callee name as written in source, e.g. `"scan_project"`,
    /// `"Arc::new"`, `"db.execute"`, `"tracing::info"`.
    pub callee: String,
    /// 1-indexed line of the **opening** of the call expression (function name
    /// position).
    pub line: usize,
    /// 1-indexed line of the **closing parenthesis** of the call expression.
    /// Equals `line` for single-line calls.
    pub end_line: usize,
    /// Multi-line snippet centered on the call site (see type-level docs).
    /// Empty string if source was unavailable at parse time.
    pub snippet: String,
}

/// Rust-specific IR details.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct RustIR {
    pub mod_declarations: Vec<ModDeclaration>,
    pub derive_macros: Vec<DeriveUsage>,
    pub trait_implementations: Vec<TraitImpl>,
    pub error_types: Vec<String>,
    /// All macro invocations found in this file.
    ///
    /// Populated by the Rust tree-sitter parser.  Detectors use this to
    /// produce call-site evidence (e.g. `tracing::info!` lines) instead of
    /// pointing at import declarations.
    #[serde(default)]
    pub macro_calls: Vec<MacroCall>,
    /// Function and method call-sites found in this file.
    ///
    /// Deduplicated by callee name — at most one example per unique callee.
    /// Hard limit: 500 entries per file.  Used by `query_code_pattern` to
    /// return real call-site snippets alongside symbol definitions.
    #[serde(default)]
    pub function_calls: Vec<FunctionCall>,
}

/// A `#[derive(...)]` usage.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct DeriveUsage {
    pub type_name: String,
    pub derives: Vec<String>,
    pub line: usize,
}

/// A trait implementation (`impl Trait for Type`).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct TraitImpl {
    pub trait_name: String,
    pub type_name: String,
    pub line: usize,
}

/// TypeScript-specific IR details.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct TypeScriptIR {
    pub has_barrel_exports: bool,
    pub type_only_imports: Vec<String>,
    pub decorators: Vec<String>,
    pub default_export: bool,
    /// Function and method call-sites found in this file (v7+).
    ///
    /// Deduplicated by callee name — at most one example per unique callee.
    /// Hard limit: 500 entries per file.
    #[serde(default)]
    pub function_calls: Vec<FunctionCall>,
}

/// JavaScript-specific IR details.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct JavaScriptIR {
    pub module_system: ModuleSystem,
    pub has_module_exports: bool,
    pub require_calls: Vec<String>,
    /// Function and method call-sites found in this file (v7+).
    ///
    /// Deduplicated by callee name — at most one example per unique callee.
    /// Hard limit: 500 entries per file.  `require` calls are excluded
    /// (already captured in `require_calls`).
    #[serde(default)]
    pub function_calls: Vec<FunctionCall>,
}

/// JavaScript module system.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModuleSystem {
    #[default]
    Unknown,
    CommonJS,
    ESM,
}

/// Python-specific IR details.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct PythonIR {
    pub has_all_export: bool,
    pub is_init_file: bool,
    pub type_hints_used: bool,
    pub decorators: Vec<String>,
    /// Function and method call-sites found in this file (v7+).
    ///
    /// Deduplicated by callee name — at most one example per unique callee.
    /// Hard limit: 500 entries per file.
    #[serde(default)]
    pub function_calls: Vec<FunctionCall>,
}

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

    #[test]
    fn language_display() {
        assert_eq!(Language::Rust.to_string(), "Rust");
        assert_eq!(Language::TypeScript.to_string(), "TypeScript");
        assert_eq!(Language::JavaScript.to_string(), "JavaScript");
        assert_eq!(Language::Python.to_string(), "Python");
    }

    #[test]
    fn language_roundtrip_str() {
        let langs = [
            Language::Rust,
            Language::TypeScript,
            Language::JavaScript,
            Language::Python,
        ];
        for l in langs {
            let parsed: Language = l.as_str().parse().unwrap();
            assert_eq!(parsed, l);
        }
    }

    #[test]
    fn language_parse_unknown() {
        assert!("go".parse::<Language>().is_err());
    }

    #[test]
    fn language_extensions() {
        assert_eq!(Language::Rust.extensions(), &["rs"]);
        assert!(Language::TypeScript.extensions().contains(&"tsx"));
        assert!(Language::JavaScript.extensions().contains(&"mjs"));
        assert_eq!(Language::Python.extensions(), &["py"]);
    }

    #[test]
    fn language_from_extension() {
        assert_eq!(Language::from_extension("rs"), Some(Language::Rust));
        assert_eq!(Language::from_extension("ts"), Some(Language::TypeScript));
        assert_eq!(Language::from_extension("tsx"), Some(Language::TypeScript));
        assert_eq!(Language::from_extension("js"), Some(Language::JavaScript));
        assert_eq!(Language::from_extension("jsx"), Some(Language::JavaScript));
        assert_eq!(Language::from_extension("mjs"), Some(Language::JavaScript));
        assert_eq!(Language::from_extension("cjs"), Some(Language::JavaScript));
        assert_eq!(Language::from_extension("py"), Some(Language::Python));
        assert_eq!(Language::from_extension("go"), None);
        assert_eq!(Language::from_extension(""), None);
    }

    #[test]
    fn language_all() {
        let all = Language::all();
        assert_eq!(all.len(), 4);
        assert!(all.contains(&Language::Rust));
        assert!(all.contains(&Language::TypeScript));
        assert!(all.contains(&Language::JavaScript));
        assert!(all.contains(&Language::Python));
    }

    #[test]
    fn language_ir_enum_covers_all_languages() {
        // Verify each variant can be constructed
        let _rust = LanguageIR::Rust(RustIR::default());
        let _ts = LanguageIR::TypeScript(TypeScriptIR::default());
        let _js = LanguageIR::JavaScript(JavaScriptIR::default());
        let _py = LanguageIR::Python(PythonIR::default());
    }

    #[test]
    fn project_file_serialization_roundtrip() {
        let pf = ProjectFile {
            path: PathBuf::from("src/main.rs"),
            language: Language::Rust,
            content_hash: "abc123".to_owned(),
            imports: vec![Import {
                module: "std::io".to_owned(),
                names: vec!["Read".to_owned()],
                is_type_only: false,
                line: 1,
            }],
            exports: Vec::new(),
            functions: vec![Function {
                name: "main".to_owned(),
                is_public: false,
                is_async: false,
                line: 3,
                end_line: 5,
                parameters: vec![],
                doc_comment: None,
            }],
            types: Vec::new(),
            dependencies_used: Vec::new(),
            language_ir: LanguageIR::Rust(RustIR::default()),
            file_doc: None,
        };

        let json = serde_json::to_string(&pf).expect("serialize");
        let deserialized: ProjectFile = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(deserialized.path, pf.path);
        assert_eq!(deserialized.language, pf.language);
        assert_eq!(deserialized.content_hash, pf.content_hash);
        assert_eq!(deserialized.imports.len(), 1);
        assert_eq!(deserialized.functions.len(), 1);
    }

    #[test]
    fn module_system_default_is_unknown() {
        assert_eq!(ModuleSystem::default(), ModuleSystem::Unknown);
    }
}