supa_mdx_lint/
parser.rs

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
use std::any::Any;

use anyhow::{anyhow, Result};
use log::{debug, trace};
use markdown::{mdast::Node, to_mdast, Constructs, ParseOptions};

use crate::{geometry::AdjustedOffset, rope::Rope};

type Frontmatter = Box<dyn Any>;

#[derive(Debug)]
pub(crate) struct ParseMetadata {
    content_start_offset: AdjustedOffset,
    #[allow(unused)]
    frontmatter: Option<Frontmatter>,
}

#[derive(Debug)]
pub(crate) struct ParseResult {
    ast: Node,
    rope: Rope,
    metadata: ParseMetadata,
}

impl ParseResult {
    pub(crate) fn ast(&self) -> &Node {
        &self.ast
    }

    pub(crate) fn rope(&self) -> &Rope {
        &self.rope
    }

    pub(crate) fn content_start_offset(&self) -> AdjustedOffset {
        self.metadata.content_start_offset
    }
}

pub(crate) fn parse(input: &str) -> Result<ParseResult> {
    let (content, rope, content_start_offset, frontmatter) = process_raw_content_string(input);
    let ast = parse_internal(content)?;

    trace!("AST: {:#?}", ast);

    Ok(ParseResult {
        ast,
        rope,
        metadata: ParseMetadata {
            content_start_offset,
            frontmatter,
        },
    })
}

fn process_raw_content_string(input: &str) -> (&str, Rope, AdjustedOffset, Option<Frontmatter>) {
    let rope = Rope::from(input);
    let mut frontmatter = None;
    let mut content = input;

    let mut content_start_offset = AdjustedOffset::default();

    if content.trim_start().starts_with("---") {
        let frontmatter_start_offset: AdjustedOffset = (content.find("---").unwrap() + 3).into();

        if let Some(frontmatter_end_index) = content[frontmatter_start_offset.into()..].find("---")
        {
            let mut end_offset: AdjustedOffset =
                (Into::<usize>::into(frontmatter_start_offset) + frontmatter_end_index).into();

            let frontmatter_str = &content[frontmatter_start_offset.into()..end_offset.into()];

            if let Ok(toml_frontmatter) = toml::from_str::<toml::Value>(frontmatter_str) {
                debug!("Parsed as TOML: {toml_frontmatter:#?}");
                frontmatter = Some(Box::new(toml_frontmatter) as Frontmatter);
            } else if let Ok(yaml_frontmatter) =
                serde_yaml::from_str::<serde_yaml::Value>(frontmatter_str)
            {
                debug!("Parsed as YAML: {yaml_frontmatter:#?}");
                frontmatter = Some(Box::new(yaml_frontmatter) as Frontmatter);
            } else {
                debug!("Failed to parse frontmatter as TOML or YAML: {frontmatter_str}")
            }

            // Update end_offset to include the closing "---" and following blank lines

            // Move past the closing "---"
            end_offset.increment(3);

            // Skip all whitespace and newlines after the closing "---"
            let mut remaining_index = 0;
            let remaining = &content[end_offset.into()..];
            while remaining_index < remaining.len() {
                if remaining[remaining_index..].starts_with(char::is_whitespace) {
                    remaining_index += 1;
                } else {
                    break;
                }
            }
            end_offset.increment(remaining_index);

            content_start_offset = end_offset;
        }
    }

    content = &input[content_start_offset.into()..];

    (content, rope, content_start_offset, frontmatter)
}

fn parse_internal(input: &str) -> Result<Node> {
    let mdast = to_mdast(
        input,
        &ParseOptions {
            constructs: Constructs {
                autolink: false,
                code_indented: false,
                frontmatter: true,
                gfm_footnote_definition: true,
                gfm_label_start_footnote: true,
                gfm_table: true,
                html_flow: false,
                html_text: false,
                mdx_esm: true,
                mdx_expression_flow: true,
                mdx_expression_text: true,
                mdx_jsx_flow: true,
                mdx_jsx_text: true,
                ..Default::default()
            },
            ..Default::default()
        },
    )
    .map_err(|e| anyhow!("Not valid Markdown: {:?}", e))?;

    Ok(mdast)
}

pub(crate) trait CommentString {
    fn is_comment(&self) -> bool;
    fn into_comment(&self) -> Option<&str>;
}

impl CommentString for str {
    fn is_comment(&self) -> bool {
        let trimmed = self.trim();
        trimmed.starts_with("/*") && trimmed.ends_with("*/")
    }

    fn into_comment(&self) -> Option<&str> {
        let trimmed = self.trim();
        if !self.is_comment() {
            return None;
        }

        Some(
            trimmed
                .trim_start_matches("/*")
                .trim_end_matches("*/")
                .trim(),
        )
    }
}

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

    #[test]
    fn test_parse_markdown_without_frontmatter() {
        let input = r#"# Heading

Content here."#;
        let result = parse(input).unwrap();

        assert_eq!(
            result.metadata.content_start_offset,
            AdjustedOffset::from(0)
        );
        assert!(result.metadata.frontmatter.is_none());

        let root = result.ast;
        let heading = root.children().unwrap().first().unwrap();
        assert_eq!(heading.position().unwrap().start.line, 1);
        assert_eq!(heading.position().unwrap().start.column, 1);
        assert_eq!(heading.position().unwrap().start.offset, 0);
    }

    #[test]
    fn test_parse_markdown_with_yaml_frontmatter() {
        let input = r#"---
title: Test
---

# Heading

Content here."#;
        let result = parse(input).unwrap();

        assert_eq!(
            result.metadata.content_start_offset,
            AdjustedOffset::from(21)
        );
        assert!(result.metadata.frontmatter.is_some());

        let frontmatter = result.metadata.frontmatter.unwrap();
        let yaml = frontmatter.downcast_ref::<serde_yaml::Value>().unwrap();
        if let serde_yaml::Value::Mapping(map) = yaml {
            assert_eq!(map.len(), 1);
            assert!(map.contains_key(&serde_yaml::Value::String("title".to_string())));
        } else {
            panic!("Expected YAML frontmatter to be a mapping");
        }

        let root = result.ast;
        let heading = root.children().unwrap().first().unwrap();
        assert_eq!(heading.position().unwrap().start.line, 1);
        assert_eq!(heading.position().unwrap().start.column, 1);
    }

    #[test]
    fn test_parse_markdown_with_toml_frontmatter() {
        let input = r#"---
title = "TOML Test"
[author]
name = "John Doe"
---

# TOML Heading

Content with TOML frontmatter."#;
        let result = parse(input).unwrap();

        assert_eq!(
            result.metadata.content_start_offset,
            AdjustedOffset::from(56)
        );
        assert!(result.metadata.frontmatter.is_some());

        let frontmatter = result.metadata.frontmatter.unwrap();
        let toml = frontmatter.downcast_ref::<toml::Value>().unwrap();

        assert!(toml.is_table());
        let table = toml.as_table().unwrap();

        assert!(table.contains_key("title"));

        let root = result.ast;
        let heading = root.children().unwrap().first().unwrap();
        assert_eq!(heading.position().unwrap().start.line, 1);
        assert_eq!(heading.position().unwrap().start.column, 1);
    }

    #[test]
    fn test_parse_markdown_with_frontmatter_and_multiple_newlines() {
        let input = r#"---
title: Test
---


# Heading

Content here."#;
        let result = parse(input).unwrap();
        assert_eq!(
            result.metadata.content_start_offset,
            AdjustedOffset::from(22)
        );
        assert!(result.metadata.frontmatter.is_some());

        let root = result.ast;
        let heading = root.children().unwrap().first().unwrap();
        assert_eq!(heading.position().unwrap().start.line, 1);
        assert_eq!(heading.position().unwrap().start.column, 1);
    }
}