aboutsummaryrefslogtreecommitdiffstats
path: root/src/construct/mdx_esm.rs
blob: 13d7991f9be9f54d6c90938267a874668915cfbd (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
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
//! MDX ESM occurs in the [flow][] content type.
//!
//! ## Grammar
//!
//! MDX expression (flow) forms with the following BNF
//! (<small>see [construct][crate::construct] for character groups</small>):
//!
//! ```bnf
//! mdx_esm ::= word *line *(eol *line)
//!
//! word ::= 'e' 'x' 'p' 'o' 'r' 't' | 'i' 'm' 'p' 'o' 'r' 't'
//! ```
//!
//! This construct must be followed by a blank line or eof (end of file).
//! It can include blank lines if [`MdxEsmParse`][crate::MdxEsmParse] passed in
//! [`ParseOptions`][parse_options] allows it.
//!
//! ## Tokens
//!
//! *   [`LineEnding`][Name::LineEnding]
//! *   [`MdxEsm`][Name::MdxEsm]
//! *   [`MdxEsmData`][Name::MdxEsmData]
//!
//! ## References
//!
//! *   [`syntax.js` in `micromark-extension-mdxjs-esm`](https://github.com/micromark/micromark-extension-mdxjs-esm/blob/main/dev/lib/syntax.js)
//! *   [`mdxjs.com`](https://mdxjs.com)
//!
//! [flow]: crate::construct::flow
//! [parse_options]: crate::ParseOptions

use crate::event::Name;
use crate::state::{Name as StateName, State};
use crate::tokenizer::Tokenizer;
use crate::util::{mdx_collect::collect, slice::Slice};
use crate::MdxSignal;
use alloc::format;

/// Start of MDX ESM.
///
/// ```markdown
/// > | import a from 'b'
///     ^
/// ```
pub fn start(tokenizer: &mut Tokenizer) -> State {
    // If it’s turned on.
    if tokenizer.parse_state.options.constructs.mdx_esm
        // If there is a gnostic parser.
        && tokenizer.parse_state.options.mdx_esm_parse.is_some()
        // When not interrupting.
        && !tokenizer.interrupt
        // Only at the start of a line, not at whitespace or in a container.
        && tokenizer.point.column == 1
        && matches!(tokenizer.current, Some(b'e' | b'i'))
    {
        // Place where keyword starts.
        tokenizer.tokenize_state.start = tokenizer.point.index;
        tokenizer.enter(Name::MdxEsm);
        tokenizer.enter(Name::MdxEsmData);
        tokenizer.consume();
        State::Next(StateName::MdxEsmWord)
    } else {
        State::Nok
    }
}

/// In keyword.
///
/// ```markdown
/// > | import a from 'b'
///     ^^^^^^
/// ```
pub fn word(tokenizer: &mut Tokenizer) -> State {
    if matches!(tokenizer.current, Some(b'a'..=b'z')) {
        tokenizer.consume();
        State::Next(StateName::MdxEsmWord)
    } else {
        let slice = Slice::from_indices(
            tokenizer.parse_state.bytes,
            tokenizer.tokenize_state.start,
            tokenizer.point.index,
        );

        if matches!(slice.as_str(), "export" | "import") && tokenizer.current == Some(b' ') {
            tokenizer.concrete = true;
            tokenizer.tokenize_state.start = tokenizer.events.len() - 1;
            tokenizer.consume();
            State::Next(StateName::MdxEsmInside)
        } else {
            tokenizer.tokenize_state.start = 0;
            State::Nok
        }
    }
}

/// In data.
///
/// ```markdown
/// > | import a from 'b'
///           ^
/// ```
pub fn inside(tokenizer: &mut Tokenizer) -> State {
    match tokenizer.current {
        None | Some(b'\n') => {
            tokenizer.exit(Name::MdxEsmData);
            State::Retry(StateName::MdxEsmLineStart)
        }
        _ => {
            tokenizer.consume();
            State::Next(StateName::MdxEsmInside)
        }
    }
}

/// At start of line.
///
/// ```markdown
///   | import a from 'b'
/// > | export {a}
///     ^
/// ```
pub fn line_start(tokenizer: &mut Tokenizer) -> State {
    match tokenizer.current {
        None => State::Retry(StateName::MdxEsmAtEnd),
        Some(b'\n') => {
            tokenizer.check(
                State::Next(StateName::MdxEsmAtEnd),
                State::Next(StateName::MdxEsmContinuationStart),
            );
            State::Retry(StateName::MdxEsmBlankLineBefore)
        }
        _ => {
            tokenizer.enter(Name::MdxEsmData);
            tokenizer.consume();
            State::Next(StateName::MdxEsmInside)
        }
    }
}

/// At start of line that continues.
///
/// ```markdown
///   | import a from 'b'
/// > | export {a}
///     ^
/// ```
pub fn continuation_start(tokenizer: &mut Tokenizer) -> State {
    tokenizer.enter(Name::LineEnding);
    tokenizer.consume();
    tokenizer.exit(Name::LineEnding);
    State::Next(StateName::MdxEsmLineStart)
}

/// At start of a potentially blank line.
///
/// ```markdown
///   | import a from 'b'
/// > | export {a}
///     ^
/// ```
pub fn blank_line_before(tokenizer: &mut Tokenizer) -> State {
    tokenizer.enter(Name::LineEnding);
    tokenizer.consume();
    tokenizer.exit(Name::LineEnding);
    State::Next(StateName::BlankLineStart)
}

/// At end of line (blank or eof).
///
/// ```markdown
/// > | import a from 'b'
///                      ^
/// ```
pub fn at_end(tokenizer: &mut Tokenizer) -> State {
    let result = parse_esm(tokenizer);

    // Done!.
    if matches!(result, State::Ok) {
        tokenizer.concrete = false;
        tokenizer.exit(Name::MdxEsm);
    }

    result
}

/// Parse ESM with a given function.
fn parse_esm(tokenizer: &mut Tokenizer) -> State {
    // We can `unwrap` because we don’t parse if this is `None`.
    let parse = tokenizer
        .parse_state
        .options
        .mdx_esm_parse
        .as_ref()
        .unwrap();

    // Collect the body of the ESM and positional info for each run of it.
    let result = collect(
        &tokenizer.events,
        tokenizer.parse_state.bytes,
        tokenizer.tokenize_state.start,
        &[Name::MdxEsmData, Name::LineEnding],
        &[],
    );

    // Parse and handle what was signaled back.
    match parse(&result.value) {
        MdxSignal::Ok => State::Ok,
        MdxSignal::Error(message, relative) => {
            let point = tokenizer
                .parse_state
                .location
                .as_ref()
                .expect("expected location index if aware mdx is on")
                .relative_to_point(&result.stops, relative)
                .expect("expected non-empty string");
            State::Error(format!("{}:{}: {}", point.line, point.column, message))
        }
        MdxSignal::Eof(message) => {
            if tokenizer.current.is_none() {
                State::Error(format!(
                    "{}:{}: {}",
                    tokenizer.point.line, tokenizer.point.column, message
                ))
            } else {
                tokenizer.tokenize_state.mdx_last_parse_error = Some(message);
                State::Retry(StateName::MdxEsmContinuationStart)
            }
        }
    }
}