Skip to main content

yomi_core/
analysis.rs

1//! Analysis results of scripts (for editors and tools): a table of declarations (symbols) and how they are used (references).
2//!
3//! The syntax tree is not public. This parses the source of modules and returns only where names are declared and used.
4//! Even for broken source, it builds results for the parts the parser could read. Positions are 1-based for both line and
5//! column; columns and lengths are counted in characters (`char`).
6
7use std::collections::HashMap;
8
9use crate::syntax::ast::{
10    AssignOp, ChoiceOpt, Expr, IdentRef, LabelDecl, LabelRef, Module, Param, PathElem, Pattern,
11    Pos, Stmt, StrPart, TyName, TypeDeclKind,
12};
13use crate::syntax::parser::{IdentMap, parse_with, scan_identities};
14
15/// The kind of a symbol.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum SymbolKind {
18    /// A `label`.
19    Label,
20    /// A `fn`.
21    Fn,
22    /// A module variable (`var`, `save var`, `persistent var`).
23    Var,
24    /// An `identity`.
25    Identity,
26    /// A `struct`.
27    Struct,
28    /// An `enum`.
29    Enum,
30    /// A variant of an `enum`.
31    Variant,
32    /// A field of a `struct`.
33    Field,
34    /// A parameter of a label or function.
35    Param,
36    /// A name bound by `let`, `for` or `match`.
37    Local,
38}
39
40/// A range in the source (within one line).
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub struct Span {
43    /// Line (1-based).
44    pub line: u32,
45    /// Column (1-based, in characters).
46    pub col: u32,
47    /// Length (in characters).
48    pub len: u32,
49}
50
51impl Span {
52    /// Whether this contains the position (line, column).
53    pub fn contains(&self, line: u32, col: u32) -> bool {
54        self.line == line && col >= self.col && col <= self.col + self.len
55    }
56}
57
58/// One declared name.
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub struct Symbol {
61    /// Kind.
62    pub kind: SymbolKind,
63    /// Name.
64    pub name: String,
65    /// The module that has the declaration.
66    pub module: String,
67    /// The range of the declared name.
68    pub span: Span,
69    /// A one-line description of the declaration (such as `label start(n: int) -> str`).
70    pub detail: String,
71    /// The enclosing name (the type name for fields and variants, the label name for locals and parameters).
72    pub container: Option<String>,
73}
74
75/// A position where a name is used.
76#[derive(Clone, Debug, PartialEq, Eq)]
77pub struct Reference {
78    /// The module where it is used.
79    pub module: String,
80    /// The range of the name.
81    pub span: Span,
82    /// The symbol it refers to (an index into [`Analysis::symbols`]).
83    pub target: usize,
84}
85
86/// The result of analysis.
87#[derive(Clone, Debug, Default, PartialEq, Eq)]
88pub struct Analysis {
89    /// Declared names (in module order, then declaration order).
90    pub symbols: Vec<Symbol>,
91    /// Positions where names are used. Only those that could be resolved.
92    pub references: Vec<Reference>,
93}
94
95impl Analysis {
96    /// The symbol that the name at the position (a declaration itself, or a use) refers to.
97    pub fn symbol_at(&self, module: &str, line: u32, col: u32) -> Option<usize> {
98        let by_ref = self
99            .references
100            .iter()
101            .find(|r| r.module == module && r.span.contains(line, col))
102            .map(|r| r.target);
103        by_ref.or_else(|| {
104            self.symbols
105                .iter()
106                .position(|s| s.module == module && s.span.contains(line, col))
107        })
108    }
109
110    /// References to the symbol (declarations are not included).
111    pub fn references_to(&self, symbol: usize) -> impl Iterator<Item = &Reference> {
112        self.references.iter().filter(move |r| r.target == symbol)
113    }
114}
115
116/// Analyzes modules (name and source).
117pub fn analyze(modules: &[(&str, &str)]) -> Analysis {
118    let mut idents = IdentMap::new();
119    for (name, source) in modules {
120        idents
121            .entry((*name).to_string())
122            .or_insert_with(|| scan_identities(source));
123    }
124    let mut out = Analysis::default();
125    let mut parsed: Vec<(&str, Module, Vec<&str>, Tops)> = Vec::new();
126    for (name, source) in modules {
127        let (ast, _) = parse_with(source, name, &idents);
128        let lines = source_lines(source);
129        let tops = declare(&mut out, name, &ast, &lines);
130        parsed.push((name, ast, lines, tops));
131    }
132    let all: HashMap<&str, &Tops> = parsed.iter().map(|(n, _, _, t)| (*n, t)).collect();
133    for (name, ast, lines, tops) in &parsed {
134        let imports: HashMap<&str, &str> = ast
135            .imports
136            .iter()
137            .map(|i| (i.local.as_str(), i.path.as_str()))
138            .collect();
139        let mut w = Walker {
140            out: &mut out,
141            module: name,
142            lines,
143            tops,
144            all: &all,
145            imports,
146            scopes: Vec::new(),
147            current: String::new(),
148        };
149        w.module(ast);
150    }
151    out
152}
153
154/// Whether the token can be used as a name (for completion and extracting names).
155pub fn is_name_char(c: char) -> bool {
156    c.is_alphanumeric() || c == '_'
157}
158
159mod declare;
160#[cfg(test)]
161mod tests;
162mod walk;
163
164use declare::*;
165use walk::*;