Skip to main content

malt_index/
model.rs

1//! The data model: what the index knows about a MATLAB path entry.
2//!
3//! An [`Entity`] is a function, class, property, enumeration, script, live script,
4//! package (`+pkg`), class folder (`@cls`) or plain folder. Entities form a tree
5//! through [`Entity::members`]. Every field is a fact read from the source: nothing
6//! is evaluated. Types, defaults, validators and bases are [`Expr`]s (raw text with
7//! its span), and docstrings are the comment block as text (see [`Docstring`]).
8
9use std::collections::{BTreeMap, BTreeSet};
10use std::path::PathBuf;
11
12use serde::{Deserialize, Serialize};
13
14pub use crate::expr::Expr;
15
16/// The kind of an entity. Names follow the MATLAB concepts, not maxx's `Kind` enum.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "snake_case")]
19pub enum Kind {
20    /// A plain folder on the path (or below one), with its files and folders.
21    Folder,
22    /// A package, a folder named `+pkg`.
23    Namespace,
24    /// A class folder, a folder named `@cls`, with the class file and methods.
25    ClassFolder,
26    /// A classdef class.
27    Class,
28    /// A member of an `enumeration` block.
29    Enumeration,
30    /// A function, a method, a getter or setter, or a local or nested function.
31    Function,
32    /// A script file (one without a leading function or classdef).
33    Script,
34    /// A live script: a `.mlx` file, or a plain-text live code `.m` file.
35    LiveScript,
36    /// A property of a class.
37    Property,
38}
39
40impl Kind {
41    /// The kind name used in the dump and by the Python objects.
42    pub fn as_str(self) -> &'static str {
43        match self {
44            Kind::Folder => "folder",
45            Kind::Namespace => "namespace",
46            Kind::ClassFolder | Kind::Class => "class",
47            Kind::Enumeration => "enumeration",
48            Kind::Function => "function",
49            Kind::Script => "script",
50            Kind::LiveScript => "live_script",
51            Kind::Property => "property",
52        }
53    }
54}
55
56/// A comment block next to a declaration.
57///
58/// `value` is the comment text with the comment markers removed and the common
59/// indentation taken off, as maxx's docstring extraction does. There is no
60/// section parsing here: `raw` is the exact source text of the block, and
61/// `lineno`/`endlineno` are its span (1-based, inclusive).
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63pub struct Docstring {
64    /// The comment text, markers removed.
65    pub value: String,
66    /// The exact source text of the comment block.
67    pub raw: String,
68    /// First line of the block (1-based).
69    pub lineno: usize,
70    /// Last line of the block (1-based, inclusive).
71    pub endlineno: usize,
72}
73
74/// How an argument is passed.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
76pub enum ArgumentKind {
77    /// Passed by position, no default.
78    #[serde(rename = "positional-only")]
79    PositionalOnly,
80    /// Passed by position, with a default in the arguments block.
81    #[serde(rename = "optional")]
82    Optional,
83    /// Passed by name (`opts.Name` in an arguments block).
84    #[serde(rename = "keyword-only")]
85    KeywordOnly,
86    /// The `varargin` input.
87    #[serde(rename = "varargin")]
88    Varargin,
89}
90
91impl ArgumentKind {
92    /// The kind name used in the dump.
93    pub fn as_str(self) -> &'static str {
94        match self {
95            ArgumentKind::PositionalOnly => "positional-only",
96            ArgumentKind::Optional => "optional",
97            ArgumentKind::KeywordOnly => "keyword-only",
98            ArgumentKind::Varargin => "varargin",
99        }
100    }
101}
102
103/// An input or output of a function, from the signature and its arguments block.
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105pub struct Argument {
106    /// The name as written (`~` for an ignored input or output).
107    pub name: String,
108    /// How the argument is passed.
109    pub kind: ArgumentKind,
110    /// The declared class, as written (`double`, `Other.Prop` for `opts.?Other.Prop`).
111    #[serde(rename = "type")]
112    pub type_: Option<Expr>,
113    /// The dimensions as written: numbers and `:` (spread operators).
114    pub dimensions: Option<Vec<String>>,
115    /// The validation functions as written, for example `{mustBePositive}`.
116    pub validators: Option<Expr>,
117    /// The default value as written.
118    pub default: Option<Expr>,
119    /// The comment block next to the argument.
120    pub docstring: Option<Docstring>,
121}
122
123impl Argument {
124    /// A new argument with only a name and a kind.
125    pub fn new(name: &str, kind: ArgumentKind) -> Self {
126        Argument {
127            name: name.to_string(),
128            kind,
129            type_: None,
130            dimensions: None,
131            validators: None,
132            default: None,
133            docstring: None,
134        }
135    }
136}
137
138/// The part of an entity that only functions have.
139#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
140pub struct FunctionDetail {
141    /// Inputs, in signature order, then name-value arguments.
142    pub arguments: Vec<Argument>,
143    /// Outputs, in signature order.
144    pub returns: Vec<Argument>,
145    /// `get.Name` method.
146    pub is_getter: bool,
147    /// `set.Name` method.
148    pub is_setter: bool,
149}
150
151/// The part of an entity that only properties have.
152#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
153pub struct PropertyDetail {
154    /// The declared class, as written.
155    #[serde(rename = "type")]
156    pub type_: Option<Expr>,
157    /// The dimensions as written.
158    pub dimensions: Option<Vec<String>>,
159    /// The validation functions as written.
160    pub validators: Option<Expr>,
161    /// The default value as written.
162    pub default: Option<Expr>,
163    /// The `get.Name` method of the property, if declared in the class.
164    pub getter: Option<Box<Entity>>,
165    /// The `set.Name` method of the property, if declared in the class.
166    pub setter: Option<Box<Entity>>,
167}
168
169/// The kind of a live script section: prose, or code (with its outputs left out).
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
171#[serde(rename_all = "snake_case")]
172pub enum SectionKind {
173    /// Formatted text (a `%[text]` paragraph, or a paragraph in a `.mlx`).
174    Text,
175    /// Code.
176    Code,
177}
178
179impl SectionKind {
180    /// The kind name used by the Python objects: `text` or `code`.
181    pub fn as_str(self) -> &'static str {
182        match self {
183            SectionKind::Text => "text",
184            SectionKind::Code => "code",
185        }
186    }
187}
188
189/// One run of a live script: consecutive text paragraphs, or consecutive code lines.
190#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
191pub struct LiveSection {
192    /// Text or code.
193    pub kind: SectionKind,
194    /// The text of the run: the paragraphs' text joined by newlines (markers removed),
195    /// or the code lines as written.
196    pub content: String,
197    /// First line (1-based). `None` for a `.mlx`, whose paragraphs have no lines.
198    pub lineno: Option<usize>,
199    /// Last line (1-based, inclusive). `None` for a `.mlx`.
200    pub endlineno: Option<usize>,
201}
202
203/// What an entity is, beyond its common fields.
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
205pub enum Detail {
206    /// No extra fields (folders, packages, class folders, scripts).
207    None,
208    /// A classdef class: its superclasses, as written, its events and its constructor.
209    Class {
210        /// The superclasses, in order.
211        bases: Vec<Expr>,
212        /// The names of the entries of its `events` blocks, in source order (no attributes).
213        #[serde(default)]
214        events: Vec<String>,
215        /// Whether the class file declares a method named as the class (its constructor).
216        #[serde(default)]
217        declares_constructor: bool,
218    },
219    /// A function or method.
220    Function(FunctionDetail),
221    /// A property.
222    Property(PropertyDetail),
223    /// An enumeration member: its value as written.
224    Enumeration {
225        /// The value expression, as written (`(1)` gives `1`).
226        value: Option<Expr>,
227    },
228    /// A live script: its sections, in order.
229    LiveScript {
230        /// The runs of text and code, in the order of the file.
231        sections: Vec<LiveSection>,
232    },
233}
234
235/// One entity of the MATLAB path.
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237pub struct Entity {
238    /// The kind of entity.
239    pub kind: Kind,
240    /// The name: the file stem for files, the method or property name for members.
241    pub name: String,
242    /// The file that declares the entity (the folder for packages, class folders and
243    /// plain folders). Members inherit the file of their class.
244    pub path: Option<PathBuf>,
245    /// First line (1-based). `None` when the entity has no span (maxx's convention for
246    /// folders, packages, class folders and scripts).
247    pub lineno: Option<usize>,
248    /// Last line (1-based, inclusive).
249    pub endlineno: Option<usize>,
250    /// The comment block next to the declaration (or the file header, see the README).
251    pub docstring: Option<Docstring>,
252    /// The attributes, sorted, as `Name` or `Name=value` (for example `Access=private`).
253    pub attributes: BTreeSet<String>,
254    /// The kind-specific fields.
255    pub detail: Detail,
256    /// The members: properties, methods, enumeration members, local functions, and
257    /// for packages, class folders and plain folders their files and sub-packages.
258    pub members: BTreeMap<String, Entity>,
259}
260
261impl Entity {
262    /// A new entity with only the common fields set.
263    pub fn new(kind: Kind, name: &str) -> Self {
264        Entity {
265            kind,
266            name: name.to_string(),
267            path: None,
268            lineno: None,
269            endlineno: None,
270            docstring: None,
271            attributes: BTreeSet::new(),
272            detail: Detail::None,
273            members: BTreeMap::new(),
274        }
275    }
276
277    /// The function detail, if this entity is a function or method.
278    pub fn function(&self) -> Option<&FunctionDetail> {
279        match &self.detail {
280            Detail::Function(f) => Some(f),
281            _ => None,
282        }
283    }
284
285    /// The property detail, if this entity is a property.
286    pub fn property(&self) -> Option<&PropertyDetail> {
287        match &self.detail {
288            Detail::Property(p) => Some(p),
289            _ => None,
290        }
291    }
292
293    /// The superclasses, if this entity is a class.
294    pub fn bases(&self) -> &[Expr] {
295        match &self.detail {
296            Detail::Class { bases, .. } => bases,
297            _ => &[],
298        }
299    }
300
301    /// The names of the `events` entries, if this entity is a class (source order).
302    pub fn events(&self) -> &[String] {
303        match &self.detail {
304            Detail::Class { events, .. } => events,
305            _ => &[],
306        }
307    }
308
309    /// Whether the class file declares a constructor (a method named as the class), if this
310    /// entity is a class. An implicit constructor is not declared, so it is `false`.
311    pub fn declares_constructor(&self) -> bool {
312        matches!(
313            self.detail,
314            Detail::Class {
315                declares_constructor: true,
316                ..
317            }
318        )
319    }
320
321    /// The sections, if this entity is a live script.
322    pub fn sections(&self) -> &[LiveSection] {
323        match &self.detail {
324            Detail::LiveScript { sections } => sections,
325            _ => &[],
326        }
327    }
328
329    /// The enumeration value, if this entity is an enumeration member with one.
330    pub fn enumeration_value(&self) -> Option<&Expr> {
331        match &self.detail {
332            Detail::Enumeration { value } => value.as_ref(),
333            _ => None,
334        }
335    }
336}