macroforge_ts_syn 0.5.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
use oxc::allocator::Allocator;
use oxc::ast::ast::{
    AssignmentExpression, AssignmentTarget, BindingIdentifier, BindingPattern, Expression,
    FormalParameter, Function, IdentifierName, IdentifierReference, ObjectPropertyKind, Program,
    Statement, StringLiteral, TSType,
};
use oxc::codegen::{Codegen, Context, Gen};
use oxc::parser::Parser;
use oxc::span::SourceType;

use crate::TsSynError;

fn source_type() -> SourceType {
    SourceType::tsx()
}

// Every parser here takes the caller's arena. The returned node lives as long
// as that arena, which the caller frees by dropping it; the source is copied
// into the same arena because the node borrows from it.

/// The arena `ts_quote!` parses into, from either an owned `Allocator` or an
/// `&'a Allocator` the caller holds. `ts_quote!` always borrows its arena
/// argument, so a reference parameter keeps its own lifetime and the quoted
/// node can be returned to the caller.
pub trait QuoteArena<'a> {
    fn quote_arena(self) -> &'a Allocator;
}

impl<'a> QuoteArena<'a> for &'a Allocator {
    fn quote_arena(self) -> &'a Allocator {
        self
    }
}

impl<'a> QuoteArena<'a> for &&'a Allocator {
    fn quote_arena(self) -> &'a Allocator {
        let &arena = self;
        arena
    }
}

fn parse_program_in<'a>(allocator: &'a Allocator, source: &str) -> Result<Program<'a>, TsSynError> {
    let source = allocator.alloc_str(source);
    let parsed = Parser::new(allocator, source, source_type()).parse();
    if !parsed.diagnostics.is_empty() {
        return Err(TsSynError::Parse(format!(
            "Oxc parse errors: {}",
            parsed
                .diagnostics
                .into_iter()
                .map(|diagnostic| diagnostic.to_string())
                .collect::<Vec<_>>()
                .join("; ")
        )));
    }
    Ok(parsed.program)
}

fn codegen_node<T: Gen>(node: &T) -> String {
    let mut codegen = Codegen::new();
    node.print(&mut codegen, Context::default());
    codegen.into_source_text()
}

fn escape_string_literal(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len() + 2);
    escaped.push('"');
    for ch in value.chars() {
        match ch {
            '\\' => escaped.push_str("\\\\"),
            '"' => escaped.push_str("\\\""),
            '\n' => escaped.push_str("\\n"),
            '\r' => escaped.push_str("\\r"),
            '\t' => escaped.push_str("\\t"),
            '\u{08}' => escaped.push_str("\\b"),
            '\u{0C}' => escaped.push_str("\\f"),
            ch if ch.is_control() => {
                let code = ch as u32;
                escaped.push_str(&format!("\\u{:04X}", code));
            }
            _ => escaped.push(ch),
        }
    }
    escaped.push('"');
    escaped
}

pub fn parse_program<'a>(
    allocator: &'a Allocator,
    source: &str,
) -> Result<Program<'a>, TsSynError> {
    parse_program_in(allocator, source)
}

pub fn parse_expr<'a>(
    allocator: &'a Allocator,
    source: &str,
) -> Result<Expression<'a>, TsSynError> {
    let source = allocator.alloc_str(source);
    Parser::new(allocator, source, source_type())
        .parse_expression()
        .map_err(expression_parse_error)
}

fn expression_parse_error(errors: oxc::diagnostics::Diagnostics) -> TsSynError {
    TsSynError::Parse(
        errors
            .into_iter()
            .map(|diagnostic| diagnostic.to_string())
            .collect::<Vec<_>>()
            .join("; "),
    )
}

pub fn parse_statement<'a>(
    allocator: &'a Allocator,
    source: &str,
) -> Result<Statement<'a>, TsSynError> {
    let program = parse_program_in(allocator, source)?;
    program
        .body
        .into_iter()
        .next()
        .ok_or_else(|| TsSynError::Parse("no statement found".to_string()))
}

pub fn parse_module_item<'a>(
    allocator: &'a Allocator,
    source: &str,
) -> Result<Statement<'a>, TsSynError> {
    parse_statement(allocator, source)
}

pub fn parse_assignment_target<'a>(
    allocator: &'a Allocator,
    source: &str,
) -> Result<AssignmentTarget<'a>, TsSynError> {
    let statement = parse_statement(allocator, &format!("({source}) = __macroforge_target;"))?;
    let Statement::ExpressionStatement(expr_stmt) = statement else {
        return Err(TsSynError::Parse(
            "assignment target wrapper did not parse as an expression statement".to_string(),
        ));
    };
    let expr_stmt = expr_stmt.unbox();

    let Expression::AssignmentExpression(assignment) = expr_stmt.expression else {
        return Err(TsSynError::Parse(
            "assignment target wrapper did not parse as an assignment expression".to_string(),
        ));
    };
    let AssignmentExpression { left, .. } = assignment.unbox();
    Ok(left)
}

pub fn parse_binding_pattern<'a>(
    allocator: &'a Allocator,
    source: &str,
) -> Result<BindingPattern<'a>, TsSynError> {
    let statement = parse_statement(
        allocator,
        &format!("function __macroforge__({source}) {{}}"),
    )?;
    let Statement::FunctionDeclaration(function_decl) = statement else {
        return Err(TsSynError::Parse(
            "binding pattern wrapper did not parse as a function declaration".to_string(),
        ));
    };
    let function_decl = function_decl.unbox();

    let Function { params, .. } = function_decl;
    let params = params.unbox();
    let FormalParameter { pattern, .. } =
        params.items.into_iter().next().ok_or_else(|| {
            TsSynError::Parse("binding pattern wrapper had no parameter".to_string())
        })?;

    Ok(pattern)
}

pub fn parse_type<'a>(allocator: &'a Allocator, source: &str) -> Result<TSType<'a>, TsSynError> {
    let statement = parse_statement(allocator, &format!("type __MacroforgeType = {source};"))?;
    let Statement::TSTypeAliasDeclaration(type_alias) = statement else {
        return Err(TsSynError::Parse(
            "type wrapper did not parse as a type alias declaration".to_string(),
        ));
    };
    let type_alias = type_alias.unbox();

    Ok(type_alias.type_annotation)
}

pub fn parse_prop_or_spread<'a>(
    allocator: &'a Allocator,
    source: &str,
) -> Result<ObjectPropertyKind<'a>, TsSynError> {
    let expression = parse_expr(allocator, &format!("({{ {source} }})"))?;
    let object = match expression {
        Expression::ObjectExpression(object) => object,
        Expression::ParenthesizedExpression(paren) => {
            let inner = paren.unbox().expression;
            let Expression::ObjectExpression(object) = inner else {
                return Err(TsSynError::Parse(
                    "property wrapper did not parse as an object expression".to_string(),
                ));
            };
            object
        }
        _ => {
            return Err(TsSynError::Parse(
                "property wrapper did not parse as an object expression".to_string(),
            ));
        }
    };
    let object = object.unbox();

    object.properties.into_iter().next().ok_or_else(|| {
        TsSynError::Parse("property wrapper did not produce any object properties".to_string())
    })
}

pub fn stmt_to_string(stmt: &Statement<'_>) -> String {
    codegen_node(stmt)
}

pub fn binding_pattern_to_string(pattern: &BindingPattern<'_>) -> String {
    codegen_node(pattern)
}

pub fn assignment_target_to_string(target: &AssignmentTarget<'_>) -> String {
    codegen_node(target)
}

pub fn type_to_string(ty: &TSType<'_>) -> String {
    codegen_node(ty)
}

pub fn string_literal_to_string(lit: &StringLiteral<'_>) -> String {
    codegen_node(lit)
}

pub fn expr_to_string(expr: &Expression<'_>) -> String {
    let mut codegen = Codegen::new();
    codegen.print_expression(expr);
    codegen.into_source_text()
}

pub trait ToExprSource {
    fn to_expr_source(&self) -> String;
}

pub trait ToIdentSource {
    fn to_ident_source(&self) -> String;
}

pub trait ToPatSource {
    fn to_pat_source(&self) -> String;
}

pub trait ToAssignTargetSource {
    fn to_assign_target_source(&self) -> String;
}

pub trait ToTypeSource {
    fn to_type_source(&self) -> String;
}

pub trait ToStringLiteralSource {
    fn to_string_literal_source(&self) -> String;
}

impl<T> ToExprSource for &T
where
    T: ToExprSource + ?Sized,
{
    fn to_expr_source(&self) -> String {
        (*self).to_expr_source()
    }
}

impl<T> ToIdentSource for &T
where
    T: ToIdentSource + ?Sized,
{
    fn to_ident_source(&self) -> String {
        (*self).to_ident_source()
    }
}

impl<T> ToPatSource for &T
where
    T: ToPatSource + ?Sized,
{
    fn to_pat_source(&self) -> String {
        (*self).to_pat_source()
    }
}

impl<T> ToAssignTargetSource for &T
where
    T: ToAssignTargetSource + ?Sized,
{
    fn to_assign_target_source(&self) -> String {
        (*self).to_assign_target_source()
    }
}

impl<T> ToTypeSource for &T
where
    T: ToTypeSource + ?Sized,
{
    fn to_type_source(&self) -> String {
        (*self).to_type_source()
    }
}

impl<T> ToStringLiteralSource for &T
where
    T: ToStringLiteralSource + ?Sized,
{
    fn to_string_literal_source(&self) -> String {
        (*self).to_string_literal_source()
    }
}

macro_rules! impl_str_conversions {
    ($ty:ty) => {
        impl ToExprSource for $ty {
            fn to_expr_source(&self) -> String {
                self.to_string()
            }
        }

        impl ToIdentSource for $ty {
            fn to_ident_source(&self) -> String {
                self.to_string()
            }
        }

        impl ToPatSource for $ty {
            fn to_pat_source(&self) -> String {
                self.to_string()
            }
        }

        impl ToAssignTargetSource for $ty {
            fn to_assign_target_source(&self) -> String {
                self.to_string()
            }
        }

        impl ToTypeSource for $ty {
            fn to_type_source(&self) -> String {
                self.to_string()
            }
        }

        impl ToStringLiteralSource for $ty {
            fn to_string_literal_source(&self) -> String {
                escape_string_literal(self)
            }
        }
    };
}

impl_str_conversions!(str);
impl_str_conversions!(String);

impl ToExprSource for Expression<'_> {
    fn to_expr_source(&self) -> String {
        expr_to_string(self)
    }
}

impl ToExprSource for IdentifierReference<'_> {
    fn to_expr_source(&self) -> String {
        self.name.to_string()
    }
}

impl ToExprSource for IdentifierName<'_> {
    fn to_expr_source(&self) -> String {
        self.name.to_string()
    }
}

impl ToExprSource for BindingIdentifier<'_> {
    fn to_expr_source(&self) -> String {
        self.name.to_string()
    }
}

impl ToIdentSource for IdentifierReference<'_> {
    fn to_ident_source(&self) -> String {
        self.name.to_string()
    }
}

impl ToIdentSource for IdentifierName<'_> {
    fn to_ident_source(&self) -> String {
        self.name.to_string()
    }
}

impl ToIdentSource for BindingIdentifier<'_> {
    fn to_ident_source(&self) -> String {
        self.name.to_string()
    }
}

impl ToPatSource for BindingPattern<'_> {
    fn to_pat_source(&self) -> String {
        binding_pattern_to_string(self)
    }
}

impl ToPatSource for BindingIdentifier<'_> {
    fn to_pat_source(&self) -> String {
        self.name.to_string()
    }
}

impl ToAssignTargetSource for AssignmentTarget<'_> {
    fn to_assign_target_source(&self) -> String {
        assignment_target_to_string(self)
    }
}

impl ToAssignTargetSource for IdentifierReference<'_> {
    fn to_assign_target_source(&self) -> String {
        self.name.to_string()
    }
}

impl ToAssignTargetSource for BindingIdentifier<'_> {
    fn to_assign_target_source(&self) -> String {
        self.name.to_string()
    }
}

impl ToTypeSource for TSType<'_> {
    fn to_type_source(&self) -> String {
        type_to_string(self)
    }
}

impl ToTypeSource for IdentifierReference<'_> {
    fn to_type_source(&self) -> String {
        self.name.to_string()
    }
}

impl ToTypeSource for IdentifierName<'_> {
    fn to_type_source(&self) -> String {
        self.name.to_string()
    }
}

impl ToTypeSource for BindingIdentifier<'_> {
    fn to_type_source(&self) -> String {
        self.name.to_string()
    }
}

impl ToStringLiteralSource for StringLiteral<'_> {
    fn to_string_literal_source(&self) -> String {
        string_literal_to_string(self)
    }
}

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

    #[test]
    fn parses_expression() {
        let allocator = Allocator::new();
        let expr = parse_expr(&allocator, "foo?.bar ?? baz").unwrap();
        let source = expr_to_string(&expr);
        assert!(source.contains("foo"));
        assert!(source.contains("baz"));
    }

    #[test]
    fn parses_statement() {
        let allocator = Allocator::new();
        let stmt = parse_statement(&allocator, "export class Foo {}").unwrap();
        let source = stmt_to_string(&stmt);
        assert!(source.contains("class Foo"));
    }

    #[test]
    fn parses_binding_pattern() {
        let allocator = Allocator::new();
        let pattern = parse_binding_pattern(&allocator, "{ foo, bar }: Props").unwrap();
        let source = binding_pattern_to_string(&pattern);
        assert!(source.contains("foo"));
        assert!(source.contains("bar"));
    }

    #[test]
    fn parses_assignment_target() {
        let allocator = Allocator::new();
        let target = parse_assignment_target(&allocator, "foo.bar").unwrap();
        let source = assignment_target_to_string(&target);
        assert!(source.contains("foo.bar"));
    }

    #[test]
    fn parses_type() {
        let allocator = Allocator::new();
        let ty = parse_type(&allocator, "Record<string, number>").unwrap();
        let source = type_to_string(&ty);
        assert!(source.contains("Record"));
        assert!(source.contains("number"));
    }

    #[test]
    fn parses_prop_or_spread() {
        let allocator = Allocator::new();
        let prop = parse_prop_or_spread(&allocator, "foo: bar").unwrap();
        let source = codegen_node(&prop);
        assert!(source.contains("foo"));
        assert!(source.contains("bar"));
    }

    #[test]
    fn escapes_string_literals() {
        let escaped = "hello\n\"world\"".to_string_literal_source();
        assert_eq!(escaped, "\"hello\\n\\\"world\\\"\"");
    }
}