macroforge_ts_syn 0.6.0

TypeScript syntax types for build-time macro code generation
Documentation
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! JSDoc directive parsing utilities.
//!
//! Pure string-parsing functions for locating the JSDoc block that belongs to
//! a declaration and extracting `@name(args)` directives from its body. Shared
//! by lowering and the expansion host.

use std::collections::HashSet;

use crate::scan::Nesting;

/// Modifiers that may sit between a declaration's JSDoc and the start of the
/// declaration's own span.
const DECLARATION_MODIFIERS: &[&str] = &["export", "declare", "abstract", "default", "async"];

/// A `/** … */` block, as 0-based byte offsets into the source. `start` is at
/// the opening `/**` and `end` just past the closing `*/`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct JsDocBlock {
    pub start: usize,
    pub end: usize,
}

impl JsDocBlock {
    /// The text between `/**` and `*/`.
    pub fn body<'source>(&self, source: &'source str) -> &'source str {
        &source[self.start + 3..self.end - 2]
    }
}

/// The JSDoc block that belongs to the declaration starting at `target_start`
/// (0-based): the last one before it, provided only whitespace and
/// declaration modifiers separate the two. A comment that documents an
/// earlier declaration is never returned.
pub fn adjacent_jsdoc(source: &str, target_start: usize) -> Option<JsDocBlock> {
    adjacent_jsdoc_after(source, 0, target_start)
}

/// [`adjacent_jsdoc`] for a declaration whose previous sibling ends at
/// `floor`: the comment cannot start before it, so only the gap between the
/// two is searched.
pub fn adjacent_jsdoc_after(source: &str, floor: usize, target_start: usize) -> Option<JsDocBlock> {
    let search_area = source.get(..target_start)?;
    let floor = floor.min(target_start);
    let close = floor + search_area.get(floor..)?.rfind("*/")?;
    let start = comment_start(search_area, floor, close)?;
    let end = close + 2;
    let only_modifiers_between = search_area[end..]
        .split_whitespace()
        .all(|word| DECLARATION_MODIFIERS.contains(&word));
    only_modifiers_between.then_some(JsDocBlock { start, end })
}

/// Where the block comment closed by the `*/` at `close` opens, at or after
/// `floor`. A comment cannot contain `*/`, so it is the first `/**` after the
/// previous `*/`; the last `/**` before `close` could be text inside the
/// comment, such as an example that itself shows a JSDoc.
fn comment_start(source: &str, floor: usize, close: usize) -> Option<usize> {
    let floor = floor.min(close);
    let previous_close = source[floor..close]
        .rfind("*/")
        .map_or(floor, |at| floor + at + 2);
    source[previous_close..close]
        .find("/**")
        .map(|offset| previous_close + offset)
}

/// Whether a JSDoc body is a `/** import macro … */` directive: the body is
/// the import itself. Its module paths (`"@testground/macro"`) would
/// otherwise read as `@` directives, while prose or an example that merely
/// mentions one is ordinary documentation.
pub fn is_macro_import_comment(body: &str) -> bool {
    body.trim_start()
        .trim_start_matches('*')
        .trim_start()
        .get(..MACRO_IMPORT.len())
        .is_some_and(|head| head.eq_ignore_ascii_case(MACRO_IMPORT))
}

/// What a `/** import macro … */` directive starts with, in any case.
pub const MACRO_IMPORT: &str = "import macro";

/// Whether `source` could hold an `import macro` directive anywhere: a scan
/// cheap enough to run before parsing for one.
pub fn may_have_macro_import(source: &str) -> bool {
    source
        .as_bytes()
        .windows(MACRO_IMPORT.len())
        .any(|window| window.eq_ignore_ascii_case(MACRO_IMPORT.as_bytes()))
}

/// The JSDoc block stacked directly above `block`, separated from it by
/// whitespace alone and starting at or after `floor`.
pub fn stacked_jsdoc_above(source: &str, floor: usize, block: JsDocBlock) -> Option<JsDocBlock> {
    let before = source[..block.start].trim_end();
    let close = before.strip_suffix("*/")?.len();
    if close < floor {
        return None;
    }
    let start = comment_start(before, floor, close)?;
    Some(JsDocBlock {
        start,
        end: close + 2,
    })
}

/// Parse the macro directives of a JSDoc comment body as `(name, args)` pairs.
/// A directive opens a line, several may follow one another on it
/// (`@derive(X) @default(Y)`), parentheses are optional (`@default`) and
/// arguments may span lines. Lines inside a ``` fence are skipped.
pub fn parse_all_macro_directives(
    comment_body: &str,
    valid_annotations: Option<&HashSet<String>>,
) -> Vec<(String, String)> {
    read_comment_directives(comment_body, valid_annotations).0
}

/// The names of the directives in a JSDoc comment body whose argument list
/// never closes, as `@default(5` and `@endec({ rename: "x"`. Such a text is
/// no directive, and [`parse_all_macro_directives`] leaves it out.
pub fn unclosed_directives(
    comment_body: &str,
    valid_annotations: Option<&HashSet<String>>,
) -> Vec<String> {
    read_comment_directives(comment_body, valid_annotations).1
}

/// The directives of a comment body, and the names of those whose argument
/// list never closes.
fn read_comment_directives(
    comment_body: &str,
    valid_annotations: Option<&HashSet<String>>,
) -> (Vec<(String, String)>, Vec<String>) {
    let mut results = Vec::new();
    let mut unclosed = Vec::new();

    let lines: Vec<&str> = comment_body
        .lines()
        .map(|line| line.trim().trim_start_matches('*').trim())
        .filter(|line| !line.is_empty())
        .collect();

    let mut accumulated = String::new();
    let mut nesting = Nesting::default();

    let mut in_fence = false;
    for line in &lines {
        let in_continuation = nesting.has_open_bracket();

        // A fenced block is example code; its `@` lines are not directives.
        if !in_continuation && line.starts_with("```") {
            in_fence = !in_fence;
            continue;
        }
        if in_fence {
            continue;
        }

        if in_continuation {
            accumulated.push(' ');
            accumulated.push_str(line);
            nesting.feed_line(line);
            if !nesting.has_open_bracket() {
                read_directives(&accumulated, valid_annotations, &mut results, &mut unclosed);
                accumulated.clear();
                nesting = Nesting::default();
            }
            continue;
        }

        if !line.starts_with('@') {
            continue;
        }

        nesting.feed_line(line);
        if nesting.has_open_bracket() {
            accumulated = line.to_string();
            continue;
        }

        nesting = Nesting::default();
        read_directives(line, valid_annotations, &mut results, &mut unclosed);
    }

    if !accumulated.is_empty() {
        read_directives(&accumulated, valid_annotations, &mut results, &mut unclosed);
    }

    (results, unclosed)
}

/// Parse the directives a text fragment opens with: `@name` or `@name(args)`,
/// one after another. The run ends at the first text that is not a directive,
/// so a tag mentioned in prose (`@returns the enclosing @derive`) is not one.
pub fn parse_directives_from_text(
    text: &str,
    valid_annotations: Option<&HashSet<String>>,
    results: &mut Vec<(String, String)>,
) {
    read_directives(text, valid_annotations, results, &mut Vec::new());
}

/// Reads the directives `text` opens with into `results`, and the name of
/// one whose argument list never closes, which ends the run, into `unclosed`.
fn read_directives(
    text: &str,
    valid_annotations: Option<&HashSet<String>>,
    results: &mut Vec<(String, String)>,
    unclosed: &mut Vec<String>,
) {
    let is_valid = |name: &str| {
        valid_annotations.is_none_or(|valid| valid.contains(&name.to_ascii_lowercase()))
    };
    let mut remaining = text.trim_start();
    while let Some(after_at) = remaining.strip_prefix('@') {
        let name_end = after_at
            .find(|c: char| !c.is_alphanumeric() && c != '_')
            .unwrap_or(after_at.len());
        if name_end == 0 {
            return;
        }
        let name = &after_at[..name_end];
        let after_name = &after_at[name_end..];

        let trimmed_after_name = after_name.trim_start();
        let (args, rest) = if let Some(args_and_rest) = trimmed_after_name.strip_prefix('(') {
            let Some(close) = closing_paren(args_and_rest) else {
                if is_valid(name) {
                    unclosed.push(name.to_string());
                }
                return;
            };
            (args_and_rest[..close].trim(), &args_and_rest[close + 1..])
        } else {
            ("", after_name)
        };

        if is_valid(name) {
            let normalized_name = if name.eq_ignore_ascii_case("derive") {
                "Derive".to_string()
            } else {
                name.to_string()
            };
            results.push((normalized_name, args.to_string()));
        }
        remaining = rest.trim_start();
    }
}

/// The offset of the `)` that closes a directive's argument list, given the
/// text after its `(`. Parentheses, braces and brackets nest, and none of
/// them counts inside a string literal.
fn closing_paren(args: &str) -> Option<usize> {
    let mut nesting = Nesting::default();
    for (offset, letter) in args.char_indices() {
        if letter == ')' && nesting.is_top_level() {
            return Some(offset);
        }
        nesting.feed(letter);
    }
    None
}

#[cfg(test)]
mod adjacency_tests {
    use super::{
        HashSet, adjacent_jsdoc, adjacent_jsdoc_after, is_macro_import_comment,
        parse_all_macro_directives, stacked_jsdoc_above, unclosed_directives,
    };

    #[test]
    fn finds_the_comment_directly_above_a_declaration() {
        let source = "/** @derive(Debug) */\nexport interface Box {}";
        let block = adjacent_jsdoc(source, source.find("interface").unwrap_or_default());
        assert_eq!(
            block.map(|found| found.body(source)),
            Some(" @derive(Debug) ")
        );
    }

    #[test]
    fn ignores_a_comment_that_belongs_to_an_earlier_declaration() {
        let source = "/** @derive(Debug) */\ninterface Box {}\n\nexport type Other = string;";
        let target = source.find("type Other").unwrap_or_default();
        assert_eq!(adjacent_jsdoc(source, target), None);
    }

    #[test]
    fn walks_stacked_comments() {
        let source = "/** first */\n/** second */\ninterface Box {}";
        let target = source.find("interface").unwrap_or_default();
        let nearest = adjacent_jsdoc(source, target);
        assert_eq!(nearest.map(|block| block.body(source)), Some(" second "));
        let above = nearest.and_then(|block| stacked_jsdoc_above(source, 0, block));
        assert_eq!(above.map(|block| block.body(source)), Some(" first "));
    }

    #[test]
    fn a_floor_keeps_the_previous_siblings_comments_out() {
        let source =
            "class A {\n  /** @endec(skip) */\n  a: string;\n  /** b */ /** @x */\n  b: string;\n}";
        let floor = source.find("a: string;").unwrap_or_default() + "a: string;".len();
        let target = source.find("b: string").unwrap_or_default();
        let nearest = adjacent_jsdoc_after(source, floor, target);
        assert_eq!(nearest.map(|block| block.body(source)), Some(" @x "));
        let above = nearest.and_then(|block| stacked_jsdoc_above(source, floor, block));
        assert_eq!(above.map(|block| block.body(source)), Some(" b "));
        let first = above.and_then(|block| stacked_jsdoc_above(source, floor, block));
        assert_eq!(first, None);
    }

    #[test]
    fn an_example_showing_a_jsdoc_stays_inside_its_comment() {
        // The example's inner comments end in `*\u{200b}/`, so they don't close
        // the outer one; its `/**` must not be taken as the comment's start.
        let source = "/**\n * Collects modules.\n *\n * ```ts\n * /** @derive(Form) *\u{200b}/\n * class F {}\n * ```\n */\nexport function collect() {}";
        let target = source.find("export").unwrap_or_default();
        let block = adjacent_jsdoc(source, target);
        assert_eq!(block.map(|found| found.start), Some(0));
        let directives =
            parse_all_macro_directives(block.map_or("", |found| found.body(source)), None);
        assert!(
            directives.is_empty(),
            "the example is not a directive: {directives:?}"
        );
    }

    #[test]
    fn a_bracket_in_a_string_literal_is_text() {
        let directives = |body: &str| parse_all_macro_directives(body, None);
        let pair = |name: &str, args: &str| (name.to_string(), args.to_string());
        assert_eq!(
            directives(r#" @default(":(") @endec({ rename: "a)" }) "#),
            vec![
                pair("default", r#"":(""#),
                pair("endec", r#"{ rename: "a)" }"#)
            ]
        );
        assert_eq!(
            directives(" @endec({ default: \"[\" })\n * @debug({ rename: 'it\\'s {' }) "),
            vec![
                pair("endec", r#"{ default: "[" }"#),
                pair("debug", r"{ rename: 'it\'s {' }"),
            ]
        );
        // Arguments run over lines until their brackets close.
        assert_eq!(
            directives(" @endec({ rename: \"a\",\n *   skip: true })\n * @default(1) "),
            vec![
                pair("endec", r#"{ rename: "a", skip: true }"#),
                pair("default", "1"),
            ]
        );
        // An apostrophe in prose opens no string that outlives its line.
        assert_eq!(
            directives(" @remarks the user's (first\n * @default(1) "),
            vec![pair("remarks", ""), pair("default", "1")]
        );
    }

    #[test]
    fn a_tag_mentioned_in_prose_is_not_a_directive() {
        let body = "\n * @returns names from the enclosing @derive, or null\n * @see {@link find} - For `@derive` decorators\n ";
        let valid: HashSet<String> = ["derive".to_string()].into_iter().collect();
        assert_eq!(parse_all_macro_directives(body, Some(&valid)), Vec::new());
    }

    #[test]
    fn a_fenced_example_is_not_a_directive() {
        let body = "\n * @example\n * ```ts\n * @endec({ skip: true })\n * ```\n * @debug\n ";
        let names: Vec<String> = parse_all_macro_directives(body, None)
            .into_iter()
            .map(|(name, _)| name)
            .collect();
        assert_eq!(names, ["example", "debug"]);
    }

    #[test]
    fn directives_may_follow_one_another_on_a_line() {
        assert_eq!(
            parse_all_macro_directives(" @derive(Debug) @default(1) ", None),
            [
                ("Derive".to_string(), "Debug".to_string()),
                ("default".to_string(), "1".to_string())
            ]
        );
    }

    /// An argument list that never closes is told from a directive without
    /// one, and from a tag of prose, by the names a macro reads.
    #[test]
    fn a_directive_whose_arguments_never_close_is_named() {
        let valid: HashSet<String> = ["default", "endec", "derive"]
            .into_iter()
            .map(str::to_string)
            .collect();
        for (body, name) in [
            (" @default(5 ", "default"),
            (" @default(] ", "default"),
            (" @default({ a: ) ", "default"),
            ("\n * @endec({\n *   rename: \"x\"\n ", "endec"),
            (" @derive(Debug ", "derive"),
            (" @default(\"a)\" ", "default"),
        ] {
            assert_eq!(unclosed_directives(body, Some(&valid)), [name], "{body}");
            assert_eq!(
                parse_all_macro_directives(body, Some(&valid)),
                Vec::new(),
                "{body}"
            );
        }
        // The directives before it are read, and it ends the run.
        assert_eq!(
            parse_all_macro_directives(" @derive(Debug) @default(5 ", Some(&valid)),
            [("Derive".to_string(), "Debug".to_string())]
        );
        assert_eq!(
            unclosed_directives(" @derive(Debug) @default(5 ", Some(&valid)),
            ["default"]
        );
        for closed in [
            " @default(5) ",
            " @default ",
            " @see (the docs ",
            " prose with @default(5 ",
        ] {
            assert_eq!(
                unclosed_directives(closed, Some(&valid)),
                Vec::<String>::new(),
                "{closed}"
            );
        }
    }

    #[test]
    fn only_an_import_macro_directive_is_an_import_comment() {
        assert!(is_macro_import_comment(
            " import macro { $vec } from \"./vec\"; "
        ));
        assert!(!is_macro_import_comment(
            "\n * Parses import macro comments like `import macro { A } from \"pkg\"`.\n "
        ));
    }
}

#[cfg(test)]
mod properties {
    use proptest::collection::vec;
    use proptest::{prop_assert_eq, proptest};

    use super::{parse_all_macro_directives, unclosed_directives};
    use crate::strategies::{js_value, property_config};

    proptest! {
        #![proptest_config(property_config())]

        /// A directive's arguments are read whole, over as many lines as they
        /// are written on, and ones that never close are named.
        #[test]
        fn a_directive_is_given_its_arguments_as_written(items in vec(js_value(), 1..4)) {
            let written = items.join(", ");
            let over_lines = format!(" * @default({})\n ", items.join(",\n * "));
            prop_assert_eq!(
                parse_all_macro_directives(&over_lines, None),
                vec![("default".to_string(), written)]
            );
            prop_assert_eq!(unclosed_directives(&over_lines, None), Vec::<String>::new());

            let unclosed = format!(" * @default({}\n ", items.join(",\n * "));
            prop_assert_eq!(parse_all_macro_directives(&unclosed, None), Vec::new());
            prop_assert_eq!(unclosed_directives(&unclosed, None), vec!["default".to_string()]);
        }
    }
}