summaryrefslogtreecommitdiff
path: root/converter/src/syntax_checker.rs
blob: 334fa9d28f504938623ccb3ceef88f3dbc5c431c (plain) (blame)
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
use crate::error::Exit;

pub fn check_markdown_syntax(i: &String) -> Result<(), Exit> {
    let mut stack = Vec::new();
    let lines: Vec<&str> = i.lines().collect();
    let mut anchors = Vec::new();
    let mut heading_ids = Vec::new();

    for (line_num, line) in lines.iter().enumerate() {
        let line_num = line_num as i64 + 1;

        // Check for headings to collect anchor IDs
        if line.starts_with('#') {
            let heading_text = line.trim_start_matches('#').trim();
            let id = heading_text
                .to_lowercase()
                .chars()
                .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
                .collect::<String>();
            if !id.is_empty() {
                heading_ids.push(id);
            }
        }

        let mut chars = line.chars().enumerate().peekable();
        while let Some((pos, ch)) = chars.next() {
            let pos = pos as i64 + 1;

            match ch {
                '[' => {
                    // Check if it's a link or image
                    let is_image = chars.peek().map(|&(_, c)| c) == Some('!');
                    if is_image {
                        chars.next(); // Skip '!'
                    }
                    stack.push(('['.to_string(), line_num, pos, is_image));
                }
                ']' => {
                    if let Some((last, _l, b, is_image)) = stack.pop() {
                        if last != "[" {
                            return Err(Exit::SyntaxError {
                                content: line.to_string(),
                                reason: format!(
                                    "Mismatched bracket: expected '[' but found '{}'",
                                    last
                                ),
                                line: line_num,
                                begin: b,
                                end: pos,
                            });
                        }
                        // Check if it's followed by '(' for a link
                        if chars.peek().map(|&(_, c)| c) == Some('(') {
                            chars.next(); // Skip '('
                            // Look for closing ')'
                            let mut found = false;
                            let mut anchor_started = false;
                            let mut anchor = String::new();
                            while let Some((_, c)) = chars.next() {
                                if c == ')' {
                                    found = true;
                                    break;
                                }
                                if c == '#' && !anchor_started {
                                    anchor_started = true;
                                    continue;
                                }
                                if anchor_started {
                                    anchor.push(c);
                                }
                            }
                            if !found {
                                return Err(Exit::SyntaxError {
                                    content: line.to_string(),
                                    reason: "Link parentheses not closed".to_string(),
                                    line: line_num,
                                    begin: pos,
                                    end: pos,
                                });
                            }
                            if !anchor.is_empty() {
                                // Remove whitespace from anchor
                                let anchor = anchor.replace(|c: char| c.is_whitespace(), "");
                                anchors.push((anchor, line_num, pos));
                            }
                        } else if !is_image {
                            // It's a reference link, collect the anchor
                            // Check for anchor like [](#anchor)
                            if chars.peek().map(|&(_, c)| c) == Some('(') {
                                chars.next(); // Skip '('
                                if chars.peek().map(|&(_, c)| c) == Some('#') {
                                    chars.next(); // Skip '#'
                                    let mut anchor = String::new();
                                    while let Some(&(_, c)) = chars.peek() {
                                        if c == ')' {
                                            break;
                                        }
                                        anchor.push(c);
                                        chars.next();
                                    }
                                    if !anchor.is_empty() {
                                        // Remove whitespace from anchor
                                        let anchor =
                                            anchor.replace(|c: char| c.is_whitespace(), "");
                                        anchors.push((anchor, line_num, pos));
                                    }
                                }
                            }
                        }
                    } else {
                        return Err(Exit::SyntaxError {
                            content: line.to_string(),
                            reason: "Unmatched ']'".to_string(),
                            line: line_num,
                            begin: pos,
                            end: pos,
                        });
                    }
                }
                '(' => {
                    // Check for standalone anchor like (#anchor)
                    if chars.peek().map(|&(_, c)| c) == Some('#') {
                        chars.next(); // Skip '#'
                        let mut anchor = String::new();
                        while let Some(&(_, c)) = chars.peek() {
                            if c == ')' {
                                break;
                            }
                            anchor.push(c);
                            chars.next();
                        }
                        if !anchor.is_empty() {
                            // Remove whitespace from anchor
                            let anchor = anchor.replace(|c: char| c.is_whitespace(), "");
                            anchors.push((anchor, line_num, pos));
                        }
                    } else {
                        stack.push(('('.to_string(), line_num, pos, false));
                    }
                }
                ')' => {
                    if let Some((last, _l, b, _)) = stack.pop() {
                        if last != "(" {
                            return Err(Exit::SyntaxError {
                                content: line.to_string(),
                                reason: format!(
                                    "Mismatched parenthesis: expected '(' but found '{}'",
                                    last
                                ),
                                line: line_num,
                                begin: b,
                                end: pos,
                            });
                        }
                    } else {
                        return Err(Exit::SyntaxError {
                            content: line.to_string(),
                            reason: "Unmatched ')'".to_string(),
                            line: line_num,
                            begin: pos,
                            end: pos,
                        });
                    }
                }
                '`' => {
                    // Check for backticks
                    let mut count = 1;
                    while chars.peek().map(|&(_, c)| c) == Some('`') {
                        count += 1;
                        chars.next();
                    }
                    let marker = "`".repeat(count);

                    if let Some((last, _, _, _)) = stack.last() {
                        if last == &marker {
                            stack.pop();
                        } else {
                            stack.push((marker.clone(), line_num, pos, false));
                        }
                    } else {
                        stack.push((marker, line_num, pos, false));
                    }
                }
                _ => {}
            }
        }
    }

    // Check for unclosed brackets/parentheses
    if let Some((last, line, begin, _)) = stack.pop() {
        return Err(Exit::SyntaxError {
            content: lines[(line - 1) as usize].to_string(),
            reason: format!("Unclosed '{}'", last),
            line,
            begin,
            end: begin,
        });
    }

    Ok(())
}