Skip to main content

malt_index/
expr.rs

1//! Expressions: the source text of a type, default value, validator or base class,
2//! with the span it was read from.
3//!
4//! An [`Expr`] is raw text, as written. It is not evaluated, and it is not resolved
5//! (a type `double` is the text `double`; what it means is for the consumer). The
6//! text joins the tokens of the expression with nothing between them, as maxx does
7//! (so `uint8 scalar` reads as `uint8scalar`); the span runs from the first token to
8//! the last. Lines are 1-based, columns are 0-based and count characters.
9
10use std::fmt;
11use std::ops::Deref;
12
13use serde::{Deserialize, Deserializer, Serialize, Serializer};
14use tree_sitter::{Node, Point};
15
16use crate::comments::node_text;
17
18/// Raw source text with its span.
19#[derive(Debug, Clone, PartialEq, Eq, Hash)]
20pub struct Expr {
21    /// The text as written (tokens joined with nothing between them).
22    pub text: String,
23    /// First line (1-based).
24    pub lineno: usize,
25    /// First column (0-based, in characters).
26    pub column: usize,
27    /// Last line (1-based, inclusive).
28    pub endlineno: usize,
29    /// Column just after the last character (0-based, in characters).
30    pub endcolumn: usize,
31}
32
33impl Expr {
34    /// An expression with a text and a span.
35    pub fn new(
36        text: impl Into<String>,
37        lineno: usize,
38        column: usize,
39        endlineno: usize,
40        endcolumn: usize,
41    ) -> Self {
42        Expr {
43            text: text.into(),
44            lineno,
45            column,
46            endlineno,
47            endcolumn,
48        }
49    }
50
51    /// The expression of some tokens of `src`: the text of each token joined, the span
52    /// from the first to the last. `None` when there are no tokens.
53    pub(crate) fn from_nodes(src: &[u8], nodes: &[Node]) -> Option<Expr> {
54        let first = nodes.first()?;
55        let last = nodes.last()?;
56        let text: String = nodes.iter().map(|n| node_text(src, *n)).collect();
57        let (lineno, column) = position(src, first.start_byte(), first.start_position());
58        let (endlineno, endcolumn) = position(src, last.end_byte(), last.end_position());
59        Some(Expr::new(text, lineno, column, endlineno, endcolumn))
60    }
61
62    /// The expression of one node, with `text` in place of the node's text (for a part of
63    /// the node, as the class path of `opts.?Class.path`).
64    pub(crate) fn from_node_text(src: &[u8], node: Node, text: &str) -> Expr {
65        let (lineno, column) = position(src, node.start_byte(), node.start_position());
66        let (endlineno, endcolumn) = position(src, node.end_byte(), node.end_position());
67        Expr::new(text, lineno, column, endlineno, endcolumn)
68    }
69}
70
71/// The 1-based line and the character column of a byte offset, from its tree-sitter point.
72fn position(src: &[u8], byte: usize, point: Point) -> (usize, usize) {
73    let line_start = byte.saturating_sub(point.column);
74    let prefix = String::from_utf8_lossy(&src[line_start..byte.min(src.len())]);
75    (point.row + 1, prefix.chars().count())
76}
77
78/// The text of the expression: `Expr` derefs to its text, so `&str` methods work on it.
79impl Deref for Expr {
80    type Target = str;
81
82    fn deref(&self) -> &str {
83        &self.text
84    }
85}
86
87impl fmt::Display for Expr {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        f.write_str(&self.text)
90    }
91}
92
93impl PartialEq<str> for Expr {
94    fn eq(&self, other: &str) -> bool {
95        self.text == other
96    }
97}
98
99impl PartialEq<&str> for Expr {
100    fn eq(&self, other: &&str) -> bool {
101        self.text == *other
102    }
103}
104
105impl PartialEq<String> for Expr {
106    fn eq(&self, other: &String) -> bool {
107        &self.text == other
108    }
109}
110
111/// An expression is written as its text (the span is not part of the dump).
112impl Serialize for Expr {
113    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
114        serializer.serialize_str(&self.text)
115    }
116}
117
118/// A text read back has no span: the lines and columns are 0.
119impl<'de> Deserialize<'de> for Expr {
120    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
121        String::deserialize(deserializer).map(|text| Expr::new(text, 0, 0, 0, 0))
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    #[test]
130    fn derefs_to_text_and_compares_with_strings() {
131        let e = Expr::new("double", 3, 4, 3, 10);
132        assert_eq!(&*e, "double");
133        assert!(e.starts_with("dou"));
134        assert_eq!(e, "double");
135        assert_eq!(e.to_string(), "double");
136        assert_eq!(serde_json::to_string(&e).unwrap(), "\"double\"");
137    }
138}