Skip to main content

malt_index/
parse.rs

1//! Parsing one MATLAB file into entities, with tree-sitter.
2//!
3//! The file kind follows the first declaration: a file whose first statement is a
4//! `function` is a function file, one starting with `classdef` is a class file,
5//! and anything else is a script. Syntax errors never stop the parse: tree-sitter
6//! recovers, and nodes that are not understood are skipped.
7
8use std::cell::RefCell;
9use std::path::Path;
10
11use tree_sitter::{Node, Parser, Tree};
12
13use crate::comments::{comment_docstring, node_text};
14use crate::config::ParserConfig;
15use crate::error::IndexError;
16use crate::expr::Expr;
17use crate::live::is_mlx;
18use crate::model::{
19    Argument, ArgumentKind, Detail, Docstring, Entity, FunctionDetail, Kind, PropertyDetail,
20};
21
22thread_local! {
23    static PARSER: RefCell<Option<Parser>> = const { RefCell::new(None) };
24}
25
26/// Parse a file from disk. The text is decoded lossily; a UTF-8 BOM is ignored.
27///
28/// A `.mlx` file is a live script and is read by [`crate::live`].
29pub fn parse_file(path: &Path, config: &ParserConfig) -> Result<Entity, IndexError> {
30    if is_mlx(path) {
31        return crate::live::parse_live_file(path);
32    }
33    let bytes = std::fs::read(path).map_err(|e| IndexError::io(path, &e))?;
34    log::debug!("parsing {}", path.display());
35    parse_source(path, &bytes, config)
36}
37
38/// Parse MATLAB source bytes that belong to `path`.
39pub fn parse_source(
40    path: &Path,
41    bytes: &[u8],
42    config: &ParserConfig,
43) -> Result<Entity, IndexError> {
44    let bytes = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]).unwrap_or(bytes);
45    // Text that is not UTF-8 is read as Latin-1 (maxx detects the encoding; the
46    // Latin-1 reading matches it for the Western files MATLAB users write).
47    let transcoded: Vec<u8>;
48    let src: &[u8] = if std::str::from_utf8(bytes).is_ok() {
49        bytes
50    } else {
51        transcoded = bytes
52            .iter()
53            .flat_map(|b| char::from(*b).to_string().into_bytes())
54            .collect();
55        &transcoded
56    };
57    let tree = parse_tree(src)?;
58    if tree.root_node().has_error() {
59        log::warn!("{}: syntax errors were recovered", path.display());
60    }
61    let ctx = Ctx {
62        src,
63        path,
64        stem: path
65            .file_stem()
66            .map(|s| s.to_string_lossy().into_owned())
67            .unwrap_or_default(),
68        config,
69    };
70    Ok(ctx.file(&tree))
71}
72
73fn parse_tree(src: &[u8]) -> Result<Tree, IndexError> {
74    PARSER.with(|cell| {
75        let mut slot = cell.borrow_mut();
76        if slot.is_none() {
77            let mut parser = Parser::new();
78            parser
79                .set_language(&tree_sitter_matlab::LANGUAGE.into())
80                .map_err(|e| IndexError::Grammar(e.to_string()))?;
81            *slot = Some(parser);
82        }
83        let parser = slot
84            .as_mut()
85            .ok_or_else(|| IndexError::Grammar("parser unavailable".into()))?;
86        parser
87            .parse(src, None)
88            .ok_or_else(|| IndexError::Grammar("parse was cancelled".into()))
89    })
90}
91
92/// The named children of a node, in order.
93pub(crate) fn named(node: Node) -> Vec<Node> {
94    let mut cursor = node.walk();
95    node.named_children(&mut cursor).collect()
96}
97
98/// All children of a node (named and anonymous tokens), in order.
99fn all(node: Node) -> Vec<Node> {
100    (0..node.child_count())
101        .filter_map(|i| node.child(i))
102        .collect()
103}
104
105/// The first named child of a given kind.
106fn named_of_kind<'t>(node: Node<'t>, kind: &str) -> Option<Node<'t>> {
107    named(node).into_iter().find(|n| n.kind() == kind)
108}
109
110/// Start and end line of a node, 1-based and inclusive.
111fn span(node: Node) -> (usize, usize) {
112    (node.start_position().row + 1, node.end_position().row + 1)
113}
114
115/// The value of an attribute: `Name` alone is `true`.
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub(crate) enum AttrValue {
118    Flag(bool),
119    Text(String),
120}
121
122impl AttrValue {
123    fn truthy(&self) -> bool {
124        match self {
125            AttrValue::Flag(b) => *b,
126            AttrValue::Text(s) => !s.is_empty(),
127        }
128    }
129}
130
131/// The parse context: the source of one file.
132pub(crate) struct Ctx<'a> {
133    src: &'a [u8],
134    path: &'a Path,
135    stem: String,
136    config: &'a ParserConfig,
137}
138
139impl Ctx<'_> {
140    fn text(&self, node: Node) -> String {
141        node_text(self.src, node)
142    }
143
144    /// The file: its kind is decided by the first statement.
145    fn file(&self, tree: &Tree) -> Entity {
146        let root = tree.root_node();
147        let children = named(root);
148        let first = children.iter().position(|n| n.kind() != "comment");
149        let header: Vec<Node> = children[..first.unwrap_or(children.len())].to_vec();
150        let header_doc = comment_docstring(self.src, &header);
151        let first_node = first.map(|i| children[i]);
152
153        let mut entity = match first_node.map(|n| n.kind()) {
154            Some("function_definition") => {
155                let node = first_node.unwrap_or(root);
156                let mut entity = self
157                    .function(node, Role::File, &Default::default())
158                    .unwrap_or_else(|| Entity::new(Kind::Function, &self.stem));
159                entity.docstring = entity.docstring.or(header_doc);
160                entity
161            }
162            Some("class_definition") => {
163                let node = first_node.unwrap_or(root);
164                let mut entity = self.class(node);
165                entity.docstring = entity.docstring.or(header_doc);
166                entity
167            }
168            _ => {
169                let mut entity = Entity::new(Kind::Script, &self.stem);
170                entity.path = Some(self.path.to_path_buf());
171                entity.docstring = header_doc;
172                entity
173            }
174        };
175        // Local functions: every other top-level function of the file. A function
176        // file's local functions are its members; a script's are too.
177        if entity.kind != Kind::Class {
178            for child in &children {
179                if child.kind() == "function_definition" && Some(*child) != first_node {
180                    if let Some(local) = self.function(*child, Role::Nested, &Default::default()) {
181                        entity.members.insert(local.name.clone(), local);
182                    }
183                }
184            }
185        }
186        entity
187    }
188
189    /// A classdef: bases, class attributes, enumerations, properties and methods.
190    fn class(&self, node: Node) -> Entity {
191        let children = named(node);
192        let name = self.stem.clone();
193        let bases: Vec<Expr> = children
194            .iter()
195            .filter(|c| c.kind() == "superclasses")
196            .flat_map(|s| named(*s))
197            .filter(|c| c.kind() == "property_name")
198            .filter_map(|c| Expr::from_nodes(self.src, &[c]))
199            .collect();
200        let mut attributes = std::collections::BTreeSet::new();
201        for attrs in children.iter().filter(|c| c.kind() == "attributes") {
202            for attribute in named(*attrs)
203                .into_iter()
204                .filter(|c| c.kind() == "attribute")
205            {
206                if let Some((key, value)) = self.attribute(attribute) {
207                    if matches!(key.as_str(), "Sealed" | "Abstract" | "Hidden") && value.truthy() {
208                        attributes.insert(key);
209                    }
210                }
211            }
212        }
213        let block_start = children
214            .iter()
215            .position(|c| {
216                matches!(
217                    c.kind(),
218                    "properties" | "methods" | "enumeration" | "events"
219                )
220            })
221            .unwrap_or(children.len());
222        let leading: Vec<Node> = children[..block_start]
223            .iter()
224            .filter(|c| c.kind() == "comment")
225            .copied()
226            .collect();
227
228        let events: Vec<String> = children
229            .iter()
230            .filter(|c| c.kind() == "events")
231            .flat_map(|block| named(*block))
232            .filter(|c| c.kind() == "identifier")
233            .map(|c| self.text(c))
234            .collect();
235
236        let mut entity = Entity::new(Kind::Class, &name);
237        let (lineno, endlineno) = span(node);
238        entity.lineno = Some(lineno);
239        entity.endlineno = Some(endlineno);
240        entity.path = Some(self.path.to_path_buf());
241        entity.docstring = comment_docstring(self.src, &leading);
242        entity.attributes = attributes;
243        entity.detail = Detail::Class {
244            bases,
245            events,
246            declares_constructor: false,
247        };
248
249        for block in children.iter().filter(|c| c.kind() == "enumeration") {
250            for member in self.enumeration(*block) {
251                entity.members.insert(member.name.clone(), member);
252            }
253        }
254        for block in children.iter().filter(|c| c.kind() == "properties") {
255            for property in self.properties(*block) {
256                entity.members.insert(property.name.clone(), property);
257            }
258        }
259        let mut declares_constructor = false;
260        for block in children.iter().filter(|c| c.kind() == "methods") {
261            let attrs = self.method_attributes(*block);
262            // An abstract method is a signature with no body (`function_signature`).
263            for method in named(*block)
264                .into_iter()
265                .filter(|c| matches!(c.kind(), "function_definition" | "function_signature"))
266            {
267                if let Some(method) = self.function(method, Role::Method, &attrs) {
268                    declares_constructor |= method.name == name;
269                    self.attach_method(&mut entity, method);
270                }
271            }
272        }
273        if let Detail::Class {
274            declares_constructor: flag,
275            ..
276        } = &mut entity.detail
277        {
278            *flag = declares_constructor;
279        }
280        entity
281    }
282
283    /// A getter or setter attaches to the property of the same name, when the
284    /// class declares it; otherwise it is an ordinary member. Like maxx, a
285    /// getter or setter whose name is taken by a non-property member is dropped.
286    fn attach_method(&self, class: &mut Entity, method: Entity) {
287        let is_accessor = method.function().map(|f| (f.is_getter, f.is_setter));
288        let (getter, setter) = is_accessor.unwrap_or((false, false));
289        if getter || setter {
290            if let Some(existing) = class.members.get_mut(&method.name) {
291                if let Detail::Property(detail) = &mut existing.detail {
292                    if getter {
293                        detail.getter = Some(Box::new(method));
294                    } else {
295                        detail.setter = Some(Box::new(method));
296                    }
297                }
298                return;
299            }
300        }
301        class.members.insert(method.name.clone(), method);
302    }
303
304    /// The `attribute` node: its name and its value (`Name`, `Name = value`).
305    pub(crate) fn attribute(&self, node: Node) -> Option<(String, AttrValue)> {
306        let key_node = named_of_kind(node, "identifier")?;
307        let key = self.text(key_node);
308        let values: Vec<Node> = all(node)
309            .into_iter()
310            .filter(|c| c.id() != key_node.id() && c.kind() != "=" && c.is_named())
311            .collect();
312        let value = match values.as_slice() {
313            [] => AttrValue::Flag(true),
314            [single] if single.kind() == "boolean" => {
315                let t = self.text(*single).to_lowercase();
316                AttrValue::Flag(t == "true" || t == "1")
317            }
318            _ => AttrValue::Text(
319                values
320                    .iter()
321                    .map(|v| self.text(*v))
322                    .collect::<Vec<_>>()
323                    .join(""),
324            ),
325        };
326        Some((key, value))
327    }
328
329    /// Attributes of a `methods` block, as the set of attribute strings.
330    fn method_attributes(&self, block: Node) -> std::collections::BTreeSet<String> {
331        let mut set = std::collections::BTreeSet::new();
332        for attrs in named(block)
333            .into_iter()
334            .filter(|c| c.kind() == "attributes")
335        {
336            for attribute in named(attrs).into_iter().filter(|c| c.kind() == "attribute") {
337                let Some((key, value)) = self.attribute(attribute) else {
338                    continue;
339                };
340                match key.as_str() {
341                    "Abstract" | "Hidden" | "Sealed" | "Static" if value.truthy() => {
342                        set.insert(key);
343                    }
344                    "Access" => {
345                        let access = access_value(&value);
346                        if access != "public" {
347                            set.insert(format!("Access={access}"));
348                        }
349                    }
350                    _ => {}
351                }
352            }
353        }
354        set
355    }
356
357    /// The members of a `properties` block, in order.
358    fn properties(&self, block: Node) -> Vec<Entity> {
359        let mut set = std::collections::BTreeSet::new();
360        for attrs in named(block)
361            .into_iter()
362            .filter(|c| c.kind() == "attributes")
363        {
364            for attribute in named(attrs).into_iter().filter(|c| c.kind() == "attribute") {
365                let Some((key, value)) = self.attribute(attribute) else {
366                    continue;
367                };
368                match key.as_str() {
369                    "AbortSet" | "Abstract" | "Constant" | "Dependent" | "GetObservable"
370                    | "Hidden" | "NonCopyable" | "SetObservable" | "Transient" | "WeakHandle"
371                        if value.truthy() =>
372                    {
373                        set.insert(key);
374                    }
375                    "Access" | "GetAccess" | "SetAccess" => {
376                        let access = access_value(&value);
377                        if access != "public" {
378                            set.insert(format!("{key}={access}"));
379                        }
380                    }
381                    _ => {}
382                }
383            }
384        }
385
386        let items: Vec<Node> = named(block)
387            .into_iter()
388            .filter(|c| matches!(c.kind(), "property" | "comment"))
389            .collect();
390        let mut properties: Vec<Entity> = Vec::new();
391        let mut pending: Option<Docstring> = None;
392        for item in items {
393            if item.kind() == "comment" {
394                let doc = comment_docstring(self.src, &[item]);
395                if self.config.docstring_before_properties {
396                    pending = doc;
397                } else if let (Some(doc), Some(last)) = (doc, properties.last_mut()) {
398                    last.docstring = Some(doc);
399                }
400                continue;
401            }
402            let (name, detail) = self.property_parts(item);
403            let mut entity = Entity::new(Kind::Property, &name);
404            let (lineno, endlineno) = span(item);
405            entity.lineno = Some(lineno);
406            entity.endlineno = Some(endlineno);
407            entity.path = Some(self.path.to_path_buf());
408            entity.attributes = set.clone();
409            entity.detail = Detail::Property(detail);
410            if self.config.docstring_before_properties {
411                entity.docstring = pending.take();
412            }
413            properties.push(entity);
414        }
415        properties
416    }
417
418    /// The name, type, dimensions, validators and default of a property node.
419    fn property_parts(&self, node: Node) -> (String, PropertyDetail) {
420        let name_node = node.child_by_field_name("name");
421        let name = match name_node {
422            Some(n) if n.kind() == "property_name" => {
423                named(n).last().map(|i| self.text(*i)).unwrap_or_default()
424            }
425            Some(n) => self.text(n),
426            None => String::new(),
427        };
428        // The type is every identifier after the name (maxx joins them: `uint8 scalar`
429        // is read as `uint8scalar`), up to the validators and the default.
430        let mut detail = PropertyDetail::default();
431        let mut type_parts: Vec<Node> = Vec::new();
432        for child in named(node) {
433            if name_node.is_some_and(|n| n.id() == child.id()) {
434                continue;
435            }
436            match child.kind() {
437                "dimensions" => detail.dimensions = Some(self.dimensions(child)),
438                "validation_functions" => detail.validators = Expr::from_nodes(self.src, &[child]),
439                "default_value" => detail.default = self.default_expr(child),
440                "identifier" | "property_name"
441                    if detail.default.is_none() && detail.validators.is_none() =>
442                {
443                    type_parts.push(child);
444                }
445                _ => {}
446            }
447        }
448        detail.type_ = Expr::from_nodes(self.src, &type_parts);
449        (name, detail)
450    }
451
452    /// The dimensions as written: the numbers and `:` (spread operators) of a `dimensions` node.
453    fn dimensions(&self, node: Node) -> Vec<String> {
454        named(node)
455            .into_iter()
456            .filter(|c| matches!(c.kind(), "number" | "spread_operator"))
457            .map(|c| self.text(c))
458            .collect()
459    }
460
461    /// The default value as written: the nodes after `=`, joined.
462    fn default_expr(&self, node: Node) -> Option<Expr> {
463        let value: Vec<Node> = all(node).into_iter().filter(|c| c.kind() != "=").collect();
464        Expr::from_nodes(self.src, &value)
465    }
466
467    /// The enumeration members of an `enumeration` block.
468    fn enumeration(&self, block: Node) -> Vec<Entity> {
469        // The block's content in source order: each member name (the first
470        // identifier of an `enum` node), its value nodes, and the comments.
471        enum Item<'t> {
472            Name(Node<'t>, String),
473            Value(Node<'t>),
474            Comment(Node<'t>),
475        }
476        let mut content: Vec<(usize, Item)> = Vec::new();
477        for child in named(block) {
478            match child.kind() {
479                "enum" => {
480                    for (i, part) in named(child).into_iter().enumerate() {
481                        if i == 0 && part.kind() == "identifier" {
482                            content.push((part.start_byte(), Item::Name(child, self.text(part))));
483                        } else {
484                            content.push((part.start_byte(), Item::Value(part)));
485                        }
486                    }
487                }
488                "comment" => content.push((child.start_byte(), Item::Comment(child))),
489                _ => {}
490            }
491        }
492        content.sort_by_key(|(start, _)| *start);
493
494        let before_mode = self.config.docstring_before_enumerations;
495        let mut members: Vec<Entity> = Vec::new();
496        let mut current: Option<(Node, String)> = None;
497        let mut values: Vec<Node> = Vec::new();
498        let mut after: Vec<Node> = Vec::new();
499        let mut before: Vec<Node> = Vec::new();
500        let mut flush = |current: &Option<(Node, String)>, comments: &[Node], values: &[Node]| {
501            if let Some((enum_node, name)) = current {
502                let mut entity = Entity::new(Kind::Enumeration, name);
503                let (lineno, endlineno) = span(*enum_node);
504                entity.lineno = Some(lineno);
505                entity.endlineno = Some(endlineno);
506                entity.path = Some(self.path.to_path_buf());
507                entity.docstring = comment_docstring(self.src, comments);
508                entity.detail = Detail::Enumeration {
509                    value: Expr::from_nodes(self.src, values),
510                };
511                members.push(entity);
512            }
513        };
514        for (_, item) in content {
515            match item {
516                Item::Name(enum_node, name) => {
517                    let comments = if before_mode { &before } else { &after };
518                    flush(&current, comments, &values);
519                    before = std::mem::take(&mut after);
520                    values.clear();
521                    current = Some((enum_node, name));
522                }
523                Item::Comment(node) => after.push(node),
524                Item::Value(node) => values.push(node),
525            }
526        }
527        let comments = if before_mode { &before } else { &after };
528        flush(&current, comments, &values);
529        members
530    }
531
532    /// Parse a function node. Returns `None` when the name is missing (a
533    /// syntax error in a method).
534    pub(crate) fn function(
535        &self,
536        node: Node,
537        role: Role,
538        attrs: &std::collections::BTreeSet<String>,
539    ) -> Option<Entity> {
540        let is_method = role == Role::Method;
541        let name = match role {
542            Role::File => self.stem.clone(),
543            Role::Method | Role::Nested => self.text(node.child_by_field_name("name")?),
544        };
545        if name.is_empty() {
546            return None;
547        }
548        let children = named(node);
549        let is_getter = all(node)
550            .iter()
551            .any(|c| !c.is_named() && self.text(*c).trim() == "get.");
552        let is_setter = all(node)
553            .iter()
554            .any(|c| !c.is_named() && self.text(*c).trim() == "set.");
555
556        let block_start = children
557            .iter()
558            .position(|c| matches!(c.kind(), "arguments_statement" | "block"))
559            .unwrap_or(children.len());
560        let leading: Vec<Node> = children[..block_start]
561            .iter()
562            .filter(|c| c.kind() == "comment")
563            .copied()
564            .collect();
565
566        let mut inputs: Vec<Argument> = Vec::new();
567        if let Some(args) = children.iter().find(|c| c.kind() == "function_arguments") {
568            for child in named(*args) {
569                if let Some(arg) = self.signature_name(child) {
570                    inputs.push(Argument::new(&arg, ArgumentKind::PositionalOnly));
571                }
572            }
573        }
574        let mut returns: Vec<Argument> = Vec::new();
575        if let Some(output) = children.iter().find(|c| c.kind() == "function_output") {
576            for child in named(*output) {
577                if child.kind() == "multioutput_variable" {
578                    for part in named(child) {
579                        if let Some(arg) = self.signature_name(part) {
580                            returns.push(Argument::new(&arg, ArgumentKind::PositionalOnly));
581                        }
582                    }
583                } else if let Some(arg) = self.signature_name(child) {
584                    returns.push(Argument::new(&arg, ArgumentKind::PositionalOnly));
585                }
586            }
587        }
588
589        for block in children
590            .iter()
591            .filter(|c| c.kind() == "arguments_statement")
592        {
593            self.arguments_block(*block, &mut inputs, &mut returns);
594        }
595        for input in inputs.iter_mut() {
596            if input.name == "varargin" {
597                input.kind = ArgumentKind::Varargin;
598            }
599        }
600
601        let is_static = attrs.contains("Static");
602        if is_method && name != self.stem && !is_static && !inputs.is_empty() {
603            // The first input of a method is the object itself.
604            inputs.remove(0);
605        }
606
607        let (lineno, endlineno) = span(node);
608        let mut entity = Entity::new(Kind::Function, &name);
609        entity.lineno = Some(lineno);
610        entity.endlineno = Some(endlineno);
611        entity.path = Some(self.path.to_path_buf());
612        entity.docstring = comment_docstring(self.src, &leading);
613        entity.attributes = attrs.clone();
614        entity.detail = Detail::Function(FunctionDetail {
615            arguments: inputs,
616            returns,
617            is_getter,
618            is_setter,
619        });
620
621        // Local and nested functions: the functions in the body of this one.
622        if let Some(body) = children.iter().find(|c| c.kind() == "block") {
623            for child in named(*body) {
624                if child.kind() == "function_definition" {
625                    if let Some(nested) = self.function(child, Role::Nested, &Default::default()) {
626                        entity.members.insert(nested.name.clone(), nested);
627                    }
628                }
629            }
630        }
631        Some(entity)
632    }
633
634    /// The name of a signature item: an identifier, or `~` for an ignored one.
635    fn signature_name(&self, node: Node) -> Option<String> {
636        match node.kind() {
637            "identifier" => Some(self.text(node)),
638            "ignored_argument" => Some("~".to_string()),
639            _ => None,
640        }
641    }
642
643    /// Apply one `arguments` block to the inputs and outputs of a function, as maxx
644    /// does: only names in the signature are updated; a name-value argument
645    /// (`opts.Name`) is added as a keyword-only argument.
646    fn arguments_block(
647        &self,
648        block: Node,
649        inputs: &mut Vec<Argument>,
650        returns: &mut Vec<Argument>,
651    ) {
652        let attrs: Vec<String> = named_of_kind(block, "attributes")
653            .map(|a| {
654                named(a)
655                    .into_iter()
656                    .filter(|c| c.kind() == "identifier")
657                    .map(|c| self.text(c))
658                    .collect()
659            })
660            .unwrap_or_default();
661        let is_input = attrs.iter().any(|a| a == "Input") || !attrs.iter().any(|a| a == "Output");
662        let before_mode = self.config.docstring_before_arguments;
663
664        // Where the next comment attaches: the input or output named here, or nothing.
665        let mut current: Option<(Slot, String)> = None;
666        let mut pending: Option<Docstring> = None;
667        for item in named(block) {
668            match item.kind() {
669                "comment" => {
670                    let doc = comment_docstring(self.src, &[item]);
671                    if before_mode {
672                        pending = doc;
673                    } else if let (Some(doc), Some((slot, name))) = (doc, current.clone()) {
674                        if let Some(arg) = find_mut(inputs, returns, slot, &name) {
675                            arg.docstring = Some(doc);
676                        }
677                    }
678                }
679                "class_property" => {
680                    // `opts.?Class.path`: a keyword argument whose class is a class path.
681                    let text = self.text(item);
682                    let (opts, rest) = match text.split_once(".?") {
683                        Some(parts) => parts,
684                        None => continue,
685                    };
686                    let class_path = rest.trim().trim_end_matches(';').trim();
687                    if class_path.is_empty() {
688                        continue;
689                    }
690                    let mut arg = Argument::new(opts.trim(), ArgumentKind::KeywordOnly);
691                    arg.type_ = Some(Expr::from_node_text(self.src, item, class_path));
692                    if before_mode {
693                        arg.docstring = pending.take();
694                    }
695                    upsert(inputs, arg);
696                    current = Some((Slot::Input, opts.trim().to_string()));
697                }
698                "property" => {
699                    let (name, detail) = self.property_parts(item);
700                    let name_node = item.child_by_field_name("name");
701                    let is_keyword = name_node.is_some_and(|n| n.kind() == "property_name");
702                    let has_default = detail.default.is_some();
703                    let doc = if before_mode { pending.take() } else { None };
704                    if is_keyword {
705                        let options = name_node
706                            .and_then(|n| named(n).first().map(|i| self.text(*i)))
707                            .unwrap_or_default();
708                        inputs.retain(|a| a.name != options);
709                        let mut arg = Argument::new(&name, ArgumentKind::KeywordOnly);
710                        fill_argument(&mut arg, &detail);
711                        arg.docstring = doc;
712                        upsert(inputs, arg);
713                        current = Some((Slot::Input, name));
714                    } else {
715                        let kind = if has_default {
716                            ArgumentKind::Optional
717                        } else {
718                            ArgumentKind::PositionalOnly
719                        };
720                        let (slot, list) = if is_input {
721                            (Slot::Input, &mut *inputs)
722                        } else {
723                            (Slot::Output, &mut *returns)
724                        };
725                        if let Some(arg) = list.iter_mut().find(|a| a.name == name) {
726                            arg.kind = kind;
727                            fill_argument(arg, &detail);
728                            arg.docstring = doc;
729                            current = Some((slot, name));
730                        } else {
731                            // A name that is not in the signature is dropped, as maxx does.
732                            current = Some((Slot::Detached, name));
733                        }
734                    }
735                }
736                _ => {}
737            }
738        }
739    }
740}
741
742/// What a function node is: the file's own function (named after the file), a method
743/// of a classdef, or a local or nested function (named by its identifier).
744#[derive(Debug, Clone, Copy, PartialEq, Eq)]
745pub(crate) enum Role {
746    File,
747    Method,
748    Nested,
749}
750
751/// The access level of an attribute value: one of the known levels; a list of classes
752/// (`{?Cls1, ?Cls2}`) or one class (`?Cls`) is `restricted`; anything else is `private`.
753fn access_value(value: &AttrValue) -> String {
754    match value {
755        AttrValue::Text(s)
756            if matches!(s.as_str(), "public" | "protected" | "private" | "immutable") =>
757        {
758            s.clone()
759        }
760        AttrValue::Text(s) if s.starts_with('{') || s.starts_with('?') => "restricted".to_string(),
761        _ => "private".to_string(),
762    }
763}
764
765/// Copy the dimensions, validators, type and default of a property into an argument.
766fn fill_argument(arg: &mut Argument, detail: &PropertyDetail) {
767    if detail.dimensions.is_some() {
768        arg.dimensions = detail.dimensions.clone();
769    }
770    if detail.type_.is_some() {
771        arg.type_ = detail.type_.clone();
772    }
773    if detail.validators.is_some() {
774        arg.validators = detail.validators.clone();
775    }
776    if detail.default.is_some() {
777        arg.default = detail.default.clone();
778    }
779}
780
781/// Replace the argument of the same name in place, or append it.
782fn upsert(list: &mut Vec<Argument>, arg: Argument) {
783    match list.iter().position(|a| a.name == arg.name) {
784        Some(i) => list[i] = arg,
785        None => list.push(arg),
786    }
787}
788
789/// The list an arguments-block comment attaches to.
790#[derive(Clone, Copy, PartialEq, Eq)]
791enum Slot {
792    Input,
793    Output,
794    /// A name that is not in the signature: its comments go nowhere.
795    Detached,
796}
797
798fn find_mut<'a>(
799    inputs: &'a mut [Argument],
800    returns: &'a mut [Argument],
801    slot: Slot,
802    name: &str,
803) -> Option<&'a mut Argument> {
804    match slot {
805        Slot::Input => inputs.iter_mut().find(|a| a.name == name),
806        Slot::Output => returns.iter_mut().find(|a| a.name == name),
807        Slot::Detached => None,
808    }
809}
810
811#[cfg(test)]
812mod tests {
813    use super::*;
814
815    fn parse(src: &str) -> Entity {
816        parse_source(
817            Path::new("/x/Sample.m"),
818            src.as_bytes(),
819            &ParserConfig::default(),
820        )
821        .unwrap()
822    }
823
824    #[test]
825    fn function_file_takes_its_name_from_the_file() {
826        let e = parse("function r = Sample(a)\nr = a;\nend\n");
827        assert_eq!(e.kind, Kind::Function);
828        assert_eq!(e.name, "Sample");
829        assert_eq!(e.lineno, Some(1));
830        assert_eq!(e.endlineno, Some(3));
831    }
832}