-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathemitter.rs
More file actions
2759 lines (2435 loc) · 102 KB
/
emitter.rs
File metadata and controls
2759 lines (2435 loc) · 102 KB
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! JavaScript code emitter for Angular template compilation.
//!
//! This module emits JavaScript code from the Output AST after all
//! IR transformation phases are complete.
//!
//! Ported from Angular's `output/abstract_emitter.ts` and `output/abstract_js_emitter.ts`.
//!
//! ## Source Map Support
//!
//! The emitter supports source map generation via the `ParseSourceSpan` type.
//! Each emitted code part can be associated with a source span, which is used
//! to generate V3 source maps for debugging.
//!
//! See: `packages/compiler/src/output/abstract_emitter.ts:126-184`
use std::sync::Arc;
use oxc_diagnostics::OxcDiagnostic;
use oxc_span::{Atom, Span};
use super::ast::{
ArrowFunctionBody, BinaryOperator, DeclareVarStmt, DynamicImportUrl, FnParam, LeadingComment,
LiteralValue, OutputExpression, OutputStatement, UnaryOperator,
};
use crate::util::{ParseSourceFile, ParseSourceSpan};
// ============================================================================
// Constants
// ============================================================================
const INDENT_WITH: &str = " ";
const LINE_LENGTH_LIMIT: usize = 80;
// ============================================================================
// Emitter Context
// ============================================================================
/// A single emitted line with source span tracking.
///
/// Tracks both the emitted code parts and their corresponding source spans.
/// See: `packages/compiler/src/output/abstract_emitter.ts:18-23`
#[derive(Debug)]
struct EmittedLine {
/// Current indentation level.
indent: usize,
/// Parts of the line (code fragments).
parts: Vec<String>,
/// Source spans for each part (parallel array with `parts`).
/// `None` indicates generated code without a source mapping.
src_spans: Vec<Option<ParseSourceSpan>>,
/// Total length of all parts.
parts_length: usize,
}
impl EmittedLine {
fn new(indent: usize) -> Self {
Self { indent, parts: Vec::new(), src_spans: Vec::new(), parts_length: 0 }
}
}
/// Context for emitting code, managing indentation and lines.
///
/// Tracks source spans for source map generation.
/// See: `packages/compiler/src/output/abstract_emitter.ts:45-126`
#[derive(Debug)]
pub struct EmitterContext {
/// Current indentation level.
indent: usize,
/// All emitted lines.
lines: Vec<EmittedLine>,
/// Diagnostics collected during emission.
pub diagnostics: std::vec::Vec<OxcDiagnostic>,
/// Source file for source map generation.
/// Stores the URL, content, and provides byte offset to line/column conversion.
source_file: Option<Arc<ParseSourceFile>>,
}
impl EmitterContext {
/// Create a new root context.
pub fn new() -> Self {
Self {
indent: 0,
lines: vec![EmittedLine::new(0)],
diagnostics: std::vec::Vec::new(),
source_file: None,
}
}
/// Create a new context with source file information for source maps.
///
/// The `ParseSourceFile` provides both the source URL and content,
/// plus efficient byte offset to line/column conversion.
pub fn with_source_file(source_file: Arc<ParseSourceFile>) -> Self {
Self {
indent: 0,
lines: vec![EmittedLine::new(0)],
diagnostics: std::vec::Vec::new(),
source_file: Some(source_file),
}
}
/// Convert an `oxc_span::Span` (byte offsets) to a `ParseSourceSpan` (line/column).
///
/// Returns `None` if no source file is available.
pub fn span_to_source_span(&self, span: Span) -> Option<ParseSourceSpan> {
let file = self.source_file.as_ref()?;
Some(ParseSourceSpan::from_offsets(file, span.start, span.end, None, None))
}
/// Get the current line.
///
/// # Invariant
/// Lines is always non-empty: initialized with one element in `new()`,
/// and `println()` only pushes (never pops below 1).
fn current_line(&self) -> &EmittedLine {
// Invariant: lines is always non-empty (initialized with one element in new(),
// and println() only pushes, never pops below 1).
&self.lines[self.lines.len() - 1]
}
/// Get the current line mutably.
///
/// # Invariant
/// Lines is always non-empty: initialized with one element in `new()`,
/// and `println()` only pushes (never pops below 1).
fn current_line_mut(&mut self) -> &mut EmittedLine {
// Invariant: lines is always non-empty (initialized with one element in new(),
// and println() only pushes, never pops below 1).
let len = self.lines.len();
&mut self.lines[len - 1]
}
/// Print a string to the current line without source mapping.
pub fn print(&mut self, part: &str) {
self.print_with_span(part, None);
}
/// Print a string with an optional source span for source mapping.
///
/// This is the core print method that tracks source spans.
/// See: `packages/compiler/src/output/abstract_emitter.ts:89-98`
pub fn print_with_span(&mut self, part: &str, source_span: Option<ParseSourceSpan>) {
if !part.is_empty() {
let line = self.current_line_mut();
// Use chars().count() to count Unicode characters, not bytes.
// This matches Angular's JavaScript behavior where "ɵɵ" counts as 2 chars.
line.parts_length += part.chars().count();
line.parts.push(part.to_string());
line.src_spans.push(source_span);
}
}
/// Print a string and start a new line.
pub fn println(&mut self, part: &str) {
self.println_with_span(part, None);
}
/// Print a string with source span and start a new line.
pub fn println_with_span(&mut self, part: &str, source_span: Option<ParseSourceSpan>) {
self.print_with_span(part, source_span);
self.lines.push(EmittedLine::new(self.indent));
}
/// Start a new line.
pub fn newline(&mut self) {
self.lines.push(EmittedLine::new(self.indent));
}
/// Check if the current line is empty.
pub fn line_is_empty(&self) -> bool {
self.current_line().parts.is_empty()
}
/// Get the current line length including indentation.
pub fn line_length(&self) -> usize {
let line = self.current_line();
line.indent * INDENT_WITH.len() + line.parts_length
}
/// Increase indentation.
pub fn inc_indent(&mut self) {
self.indent += 1;
if self.line_is_empty() {
self.current_line_mut().indent = self.indent;
}
}
/// Decrease indentation.
pub fn dec_indent(&mut self) {
self.indent = self.indent.saturating_sub(1);
if self.line_is_empty() {
self.current_line_mut().indent = self.indent;
}
}
/// Remove the last line if it's empty.
pub fn remove_empty_last_line(&mut self) {
if self.line_is_empty() && self.lines.len() > 1 {
self.lines.pop();
}
}
/// Convert the context to a source string.
pub fn to_source(&self) -> String {
let source_lines: &[EmittedLine] =
if !self.lines.is_empty() && self.lines.last().is_some_and(|l| l.parts.is_empty()) {
&self.lines[..self.lines.len() - 1]
} else {
&self.lines
};
source_lines
.iter()
.map(|line| {
if line.parts.is_empty() {
String::new()
} else {
let indent = INDENT_WITH.repeat(line.indent);
format!("{}{}", indent, line.parts.join(""))
}
})
.collect::<Vec<_>>()
.join("\n")
}
/// Generate a source map from the accumulated source spans.
///
/// Returns `None` if no source file information was provided or no mappings exist.
///
/// See: `packages/compiler/src/output/abstract_emitter.ts:126-184`
pub fn to_source_map(&self, generated_file: Option<&str>) -> Option<oxc_sourcemap::SourceMap> {
// Need source file to generate a source map
let source_file = self.source_file.as_ref()?;
let source_url = &source_file.url;
let source_content = Some(source_file.content.as_ref());
let mut builder = oxc_sourcemap::SourceMapBuilder::default();
// Set the generated file name if provided
if let Some(file) = generated_file {
builder.set_file(file);
}
// Register the source file with content
let source_id =
builder.set_source_and_content(source_url.as_ref(), source_content.unwrap_or(" "));
let source_lines: &[EmittedLine] =
if !self.lines.is_empty() && self.lines.last().is_some_and(|l| l.parts.is_empty()) {
&self.lines[..self.lines.len() - 1]
} else {
&self.lines
};
let mut has_mappings = false;
// Iterate through each line
for (generated_line, line) in source_lines.iter().enumerate() {
// Calculate column position within the generated line
let indent_len = line.indent * INDENT_WITH.len();
let mut generated_col = indent_len;
// Track which spans we've seen to deduplicate consecutive mappings
let mut last_span: Option<&ParseSourceSpan> = None;
for (part_idx, part) in line.parts.iter().enumerate() {
let src_span = line.src_spans.get(part_idx).and_then(|s| s.as_ref());
// Only emit a mapping if we have a span and it's different from the last one
if let Some(span) = src_span {
let should_emit = match last_span {
None => true,
Some(last) => {
span.start.offset != last.start.offset
|| span.start.line != last.start.line
|| span.start.col != last.start.col
}
};
if should_emit {
#[expect(clippy::cast_possible_truncation)]
builder.add_token(
generated_line as u32,
generated_col as u32,
span.start.line,
span.start.col,
Some(source_id),
None,
);
has_mappings = true;
last_span = Some(span);
}
}
generated_col += part.len();
}
}
if has_mappings { Some(builder.into_sourcemap()) } else { None }
}
/// Generate source and source map together.
///
/// Returns a tuple of (source_code, source_map).
/// The source map may be `None` if no source file information was provided.
pub fn to_source_with_map(
&self,
generated_file: Option<&str>,
) -> (String, Option<oxc_sourcemap::SourceMap>) {
(self.to_source(), self.to_source_map(generated_file))
}
}
impl Default for EmitterContext {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// JavaScript Emitter
// ============================================================================
// ============================================================================
// Source Span Helpers
// ============================================================================
/// Get the source span from an `OutputExpression`.
fn get_source_span(expr: &OutputExpression<'_>) -> Option<Span> {
match expr {
OutputExpression::Literal(e) => e.source_span,
OutputExpression::LiteralArray(e) => e.source_span,
OutputExpression::LiteralMap(e) => e.source_span,
OutputExpression::RegularExpressionLiteral(e) => e.source_span,
OutputExpression::TemplateLiteral(e) => e.source_span,
OutputExpression::TaggedTemplateLiteral(e) => e.source_span,
OutputExpression::ReadVar(e) => e.source_span,
OutputExpression::ReadProp(e) => e.source_span,
OutputExpression::ReadKey(e) => e.source_span,
OutputExpression::BinaryOperator(e) => e.source_span,
OutputExpression::UnaryOperator(e) => e.source_span,
OutputExpression::Conditional(e) => e.source_span,
OutputExpression::Not(e) => e.source_span,
OutputExpression::Typeof(e) => e.source_span,
OutputExpression::Void(e) => e.source_span,
OutputExpression::Parenthesized(e) => e.source_span,
OutputExpression::Comma(e) => e.source_span,
OutputExpression::Function(e) => e.source_span,
OutputExpression::ArrowFunction(e) => e.source_span,
OutputExpression::InvokeFunction(e) => e.source_span,
OutputExpression::Instantiate(e) => e.source_span,
OutputExpression::DynamicImport(e) => e.source_span,
OutputExpression::External(e) => e.source_span,
OutputExpression::LocalizedString(e) => e.source_span,
OutputExpression::WrappedNode(e) => e.source_span,
OutputExpression::WrappedIrNode(e) => e.source_span,
OutputExpression::SpreadElement(e) => e.source_span,
}
}
// ============================================================================
// JavaScript Emitter
// ============================================================================
/// JavaScript code emitter.
///
/// Converts Output AST to JavaScript source code.
pub struct JsEmitter {
/// Whether to escape $ in strings.
escape_dollar_in_strings: bool,
}
impl JsEmitter {
/// Create a new JavaScript emitter.
pub fn new() -> Self {
Self { escape_dollar_in_strings: false }
}
/// Emit an expression to a string.
pub fn emit_expression<'a>(&self, expr: &OutputExpression<'a>) -> String {
let mut ctx = EmitterContext::new();
self.visit_expression(expr, &mut ctx);
ctx.to_source()
}
/// Emit a statement to a string.
pub fn emit_statement<'a>(&self, stmt: &OutputStatement<'a>) -> String {
let mut ctx = EmitterContext::new();
self.visit_statement(stmt, &mut ctx);
ctx.to_source()
}
/// Emit multiple statements to a string.
pub fn emit_statements<'a>(&self, stmts: &[OutputStatement<'a>]) -> String {
let mut ctx = EmitterContext::new();
self.visit_all_statements(stmts, &mut ctx);
ctx.to_source()
}
/// Emit an expression with source map support.
///
/// Returns a tuple of (source_code, source_map).
/// The source map will be present if source spans are available in the expression.
pub fn emit_expression_with_source_map<'a>(
&self,
expr: &OutputExpression<'a>,
source_file: Arc<ParseSourceFile>,
generated_file: Option<&str>,
) -> (String, Option<oxc_sourcemap::SourceMap>) {
let mut ctx = EmitterContext::with_source_file(source_file);
self.visit_expression(expr, &mut ctx);
ctx.to_source_with_map(generated_file)
}
/// Emit multiple statements with source map support.
///
/// Returns a tuple of (source_code, source_map).
/// The source map will be present if source spans are available in the statements.
pub fn emit_statements_with_source_map<'a>(
&self,
stmts: &[OutputStatement<'a>],
source_file: Arc<ParseSourceFile>,
generated_file: Option<&str>,
) -> (String, Option<oxc_sourcemap::SourceMap>) {
let mut ctx = EmitterContext::with_source_file(source_file);
self.visit_all_statements(stmts, &mut ctx);
ctx.to_source_with_map(generated_file)
}
// ========================================================================
// Statement Visitors
// ========================================================================
fn visit_statement<'a>(&self, stmt: &OutputStatement<'a>, ctx: &mut EmitterContext) {
match stmt {
OutputStatement::DeclareVar(s) => self.visit_declare_var_stmt(s, ctx),
OutputStatement::DeclareFunction(s) => self.visit_declare_function_stmt(s, ctx),
OutputStatement::Expression(s) => self.visit_expression_stmt(&s.expr, ctx),
OutputStatement::Return(s) => self.visit_return_stmt(&s.value, ctx),
OutputStatement::If(s) => self.visit_if_stmt(s, ctx),
}
}
/// Visit all statements, adding blank lines between top-level const/function declarations.
///
/// This matches Angular's output formatting which adds a blank line between:
/// - Consecutive const declarations
/// - Consecutive function declarations
/// - Between const and function declarations
fn visit_all_statements<'a>(&self, stmts: &[OutputStatement<'a>], ctx: &mut EmitterContext) {
for (i, stmt) in stmts.iter().enumerate() {
// Add blank line between top-level declarations (const/function)
if i > 0 {
let prev_stmt = &stmts[i - 1];
let needs_blank_line = matches!(
(prev_stmt, stmt),
(OutputStatement::DeclareVar(_), OutputStatement::DeclareVar(_))
| (OutputStatement::DeclareVar(_), OutputStatement::DeclareFunction(_))
| (
OutputStatement::DeclareFunction(_),
OutputStatement::DeclareFunction(_)
)
| (OutputStatement::DeclareFunction(_), OutputStatement::DeclareVar(_))
);
if needs_blank_line {
ctx.newline();
}
}
self.visit_statement(stmt, ctx);
}
}
fn visit_declare_var_stmt(&self, stmt: &DeclareVarStmt<'_>, ctx: &mut EmitterContext) {
// Print leading comment if present
// See: packages/compiler/src/output/abstract_emitter.ts:218-235
if let Some(ref comment) = stmt.leading_comment {
self.print_leading_comment(comment, ctx);
}
// Use 'const' for FINAL modifier, 'let' otherwise
// This matches Angular's TypeScript translator behavior:
// See: packages/compiler-cli/src/ngtsc/translator/src/translator.ts:87-101
// Angular's abstract_js_emitter always uses 'var' for downleveled output,
// but the TypeScript translator uses const/let for modern output.
let keyword =
if stmt.modifiers.has(super::ast::StmtModifier::FINAL) { "const " } else { "let " };
ctx.print(keyword);
ctx.print(&stmt.name);
if let Some(ref value) = stmt.value {
ctx.print(" = ");
self.visit_expression(value, ctx);
}
ctx.println(";");
}
/// Print a leading comment.
///
/// See: `packages/compiler/src/output/abstract_emitter.ts:218-235`
fn print_leading_comment(&self, comment: &LeadingComment<'_>, ctx: &mut EmitterContext) {
match comment {
LeadingComment::JSDoc(jsdoc) => {
// Format JSDoc comment with @desc, @meaning, and @suppress tags
// See: packages/compiler/src/output/output_jit_trusted_types.ts
ctx.print("/**");
if let Some(ref desc) = jsdoc.description {
ctx.print(" @desc ");
ctx.print(desc.as_str());
}
if let Some(ref meaning) = jsdoc.meaning {
ctx.print(" @meaning ");
ctx.print(meaning.as_str());
}
if jsdoc.suppress_msg_descriptions {
ctx.print(" @suppress {msgDescriptions}");
}
ctx.println(" */");
}
LeadingComment::SingleLine(text) => {
ctx.print("// ");
ctx.println(text.as_str());
}
LeadingComment::MultiLine(text) => {
// Format multi-line comments with proper leading space before * on continuation lines.
// Angular outputs:
// /*
// * @license
// * Copyright Google LLC
// */
// Note the space before * on each line.
let formatted = text
.as_str()
.lines()
.enumerate()
.map(|(i, line)| {
if i == 0 {
// First line: just the content (will be prefixed with /*)
line.to_string()
} else {
// Continuation lines: ensure leading space before *
let trimmed = line.trim_start();
if trimmed.starts_with('*') {
format!(" {trimmed}")
} else {
format!(" * {line}")
}
}
})
.collect::<Vec<_>>()
.join("\n");
ctx.print("/*");
ctx.print(&formatted);
ctx.println(" */");
}
}
}
fn visit_declare_function_stmt(
&self,
stmt: &super::ast::DeclareFunctionStmt<'_>,
ctx: &mut EmitterContext,
) {
ctx.print("function ");
ctx.print(&stmt.name);
ctx.print("(");
self.visit_params(&stmt.params, ctx);
ctx.println(") {");
ctx.inc_indent();
for s in &stmt.statements {
self.visit_statement(s, ctx);
}
ctx.dec_indent();
ctx.println("}");
}
fn visit_expression_stmt<'a>(&self, expr: &OutputExpression<'a>, ctx: &mut EmitterContext) {
self.visit_expression(expr, ctx);
ctx.println(";");
}
fn visit_return_stmt<'a>(&self, value: &OutputExpression<'a>, ctx: &mut EmitterContext) {
ctx.print("return ");
self.visit_expression(value, ctx);
ctx.println(";");
}
fn visit_if_stmt(&self, stmt: &super::ast::IfStmt<'_>, ctx: &mut EmitterContext) {
ctx.print("if (");
self.visit_expression(&stmt.condition, ctx);
ctx.print(") {");
let has_else = !stmt.false_case.is_empty();
if stmt.true_case.len() <= 1 && !has_else {
ctx.print(" ");
for s in &stmt.true_case {
self.visit_statement(s, ctx);
}
ctx.remove_empty_last_line();
ctx.print(" ");
} else {
ctx.newline();
ctx.inc_indent();
for s in &stmt.true_case {
self.visit_statement(s, ctx);
}
ctx.dec_indent();
if has_else {
ctx.println("} else {");
ctx.inc_indent();
for s in &stmt.false_case {
self.visit_statement(s, ctx);
}
ctx.dec_indent();
}
}
ctx.println("}");
}
// ========================================================================
// Expression Visitors
// ========================================================================
fn visit_expression<'a>(&self, expr: &OutputExpression<'a>, ctx: &mut EmitterContext) {
// Get the source span for this expression (if available)
let source_span = get_source_span(expr).and_then(|span| ctx.span_to_source_span(span));
match expr {
OutputExpression::Literal(e) => self.visit_literal(&e.value, source_span, ctx),
OutputExpression::LiteralArray(e) => self.visit_literal_array(&e.entries, ctx),
OutputExpression::LiteralMap(e) => self.visit_literal_map(&e.entries, ctx),
OutputExpression::RegularExpressionLiteral(e) => {
ctx.print_with_span("/", source_span);
ctx.print(&e.body);
ctx.print("/");
if let Some(ref flags) = e.flags {
ctx.print(flags);
}
}
OutputExpression::TemplateLiteral(e) => self.visit_template_literal(e, ctx),
OutputExpression::TaggedTemplateLiteral(e) => {
self.visit_tagged_template_literal(e, ctx);
}
OutputExpression::ReadVar(e) => {
// Variable references are key for source mapping - map the variable name
let var_span = e.source_span.and_then(|span| ctx.span_to_source_span(span));
ctx.print_with_span(&e.name, var_span);
}
OutputExpression::ReadProp(e) => {
self.visit_expression(&e.receiver, ctx);
if e.optional {
ctx.print("?.");
} else {
ctx.print(".");
}
// Map the property name to its source location
let prop_span = e.source_span.and_then(|span| ctx.span_to_source_span(span));
ctx.print_with_span(&e.name, prop_span);
}
OutputExpression::ReadKey(e) => {
self.visit_expression(&e.receiver, ctx);
if e.optional {
ctx.print("?.[");
} else {
ctx.print("[");
}
self.visit_expression(&e.index, ctx);
ctx.print("]");
}
OutputExpression::BinaryOperator(e) => {
ctx.print("(");
// Parentheses are required when mixing nullish coalescing (??) with logical
// operators (&&, ||) to avoid JavaScript syntax errors.
//
// Required cases:
// 1. `(a && b) ?? c` or `(a || b) ?? c` - logical on left of ??
// 2. `a ?? (b && c)` or `a ?? (b || c)` - logical on right of ??
// 3. `(a ?? b) && c` or `(a ?? b) || c` - ?? on left of logical
// 4. `(a ? b : c) ?? d` - conditional on left of ??
//
// See: angular/packages/compiler/src/template/pipeline/src/phases/strip_nonrequired_parentheses.ts
let lhs_needs_extra_parens = self.needs_extra_parens_for_lhs(e.operator, &e.lhs);
let rhs_needs_extra_parens = self.needs_extra_parens_for_rhs(e.operator, &e.rhs);
if lhs_needs_extra_parens {
ctx.print("(");
}
self.visit_expression(&e.lhs, ctx);
if lhs_needs_extra_parens {
ctx.print(")");
}
ctx.print(" ");
ctx.print(binary_operator_to_str(e.operator));
ctx.print(" ");
if rhs_needs_extra_parens {
ctx.print("(");
}
self.visit_expression(&e.rhs, ctx);
if rhs_needs_extra_parens {
ctx.print(")");
}
ctx.print(")");
}
OutputExpression::UnaryOperator(e) => {
if e.parens {
ctx.print("(");
}
ctx.print_with_span(unary_operator_to_str(e.operator), source_span);
self.visit_expression(&e.expr, ctx);
if e.parens {
ctx.print(")");
}
}
OutputExpression::Conditional(e) => {
ctx.print("(");
self.visit_expression(&e.condition, ctx);
ctx.print("? ");
self.visit_expression(&e.true_case, ctx);
ctx.print(": ");
if let Some(ref false_case) = e.false_case {
self.visit_expression(false_case, ctx);
} else {
ctx.print("null");
}
ctx.print(")");
}
OutputExpression::Not(e) => {
ctx.print_with_span("!", source_span);
self.visit_expression(&e.condition, ctx);
}
OutputExpression::Typeof(e) => {
ctx.print_with_span("typeof ", source_span);
self.visit_expression(&e.expr, ctx);
}
OutputExpression::Void(e) => {
ctx.print_with_span("void ", source_span);
self.visit_expression(&e.expr, ctx);
}
OutputExpression::Parenthesized(e) => {
self.visit_expression(&e.expr, ctx);
}
OutputExpression::Comma(e) => {
ctx.print("(");
self.visit_all_expressions(&e.parts, ctx, ",");
ctx.print(")");
}
OutputExpression::Function(e) => {
ctx.print_with_span("function", source_span);
if let Some(ref name) = e.name {
ctx.print(" ");
ctx.print(name);
}
ctx.print("(");
self.visit_params(&e.params, ctx);
ctx.println(") {");
ctx.inc_indent();
for s in &e.statements {
self.visit_statement(s, ctx);
}
ctx.dec_indent();
ctx.print("}");
}
OutputExpression::ArrowFunction(e) => {
ctx.print_with_span("(", source_span);
self.visit_params(&e.params, ctx);
ctx.print(") =>");
match &e.body {
ArrowFunctionBody::Expression(body_expr) => {
// Check if the body is an object literal (needs parens).
// Also unwrap Parenthesized wrapper, which comes from converting
// OXC's ParenthesizedExpression (e.g. `() => ({ key: val })`).
let inner = match body_expr.as_ref() {
OutputExpression::Parenthesized(p) => p.expr.as_ref(),
other => other,
};
let is_object_literal = matches!(inner, OutputExpression::LiteralMap(_));
if is_object_literal {
ctx.print("(");
}
self.visit_expression(body_expr, ctx);
if is_object_literal {
ctx.print(")");
}
}
ArrowFunctionBody::Statements(stmts) => {
ctx.println("{");
ctx.inc_indent();
for s in stmts {
self.visit_statement(s, ctx);
}
ctx.dec_indent();
ctx.print("}");
}
}
}
OutputExpression::InvokeFunction(e) => {
// Emit /*@__PURE__*/ annotation if this is a pure call
if e.pure {
ctx.print("/*@__PURE__*/ ");
}
// Wrap arrow functions in parens for IIFE
let should_parenthesize =
matches!(e.fn_expr.as_ref(), OutputExpression::ArrowFunction(_));
if should_parenthesize {
ctx.print("(");
}
self.visit_expression(&e.fn_expr, ctx);
if should_parenthesize {
ctx.print(")");
}
// Map the function call to its source location
// Use optional chaining syntax if this is an optional call
if e.optional {
ctx.print_with_span("?.(", source_span);
} else {
ctx.print_with_span("(", source_span);
}
self.visit_all_expressions(&e.args, ctx, ",");
ctx.print(")");
}
OutputExpression::Instantiate(e) => {
ctx.print_with_span("new ", source_span);
self.visit_expression(&e.class_expr, ctx);
ctx.print("(");
self.visit_all_expressions(&e.args, ctx, ",");
ctx.print(")");
}
OutputExpression::DynamicImport(e) => {
ctx.print("import(");
// Emit url_comment if present (e.g., /* @vite-ignore */)
if let Some(comment) = &e.url_comment {
ctx.print("/* ");
ctx.print(comment);
ctx.print(" */ ");
}
match &e.url {
DynamicImportUrl::String(s) => {
ctx.print(&escape_string(s, self.escape_dollar_in_strings));
}
DynamicImportUrl::Expression(expr) => {
self.visit_expression(expr, ctx);
}
}
ctx.print(")");
}
OutputExpression::External(e) => {
// External references are handled by the module system
if let Some(ref name) = e.value.name {
ctx.print(name);
}
}
OutputExpression::LocalizedString(e) => {
self.visit_localized_string(e, ctx);
}
OutputExpression::WrappedNode(_) => {
// Wrapped nodes should not appear in JavaScript output.
// This matches Angular's abstract_js_emitter.ts which throws:
// `throw new Error("Cannot emit a WrappedNodeExpr in Javascript.");`
// WrappedNodeExpr is used internally during compilation but should
// be resolved before emission - if we hit this, it's a compiler bug.
ctx.diagnostics.push(OxcDiagnostic::error(
"Cannot emit a WrappedNodeExpr in JavaScript. WrappedNodeExpr should be resolved before emission."
));
// Emit undefined as fallback
ctx.print("undefined");
}
OutputExpression::WrappedIrNode(_) => {
// Wrapped IR expressions should not appear in JavaScript output.
// They should be resolved during the reify phase before emission.
ctx.diagnostics.push(OxcDiagnostic::error(
"Cannot emit a WrappedIrExpr in JavaScript. WrappedIrExpr should be resolved before emission."
));
// Emit undefined as fallback
ctx.print("undefined");
}
OutputExpression::SpreadElement(e) => {
ctx.print("...");
self.visit_expression(&e.expr, ctx);
}
}
}
fn visit_literal(
&self,
value: &LiteralValue<'_>,
source_span: Option<ParseSourceSpan>,
ctx: &mut EmitterContext,
) {
match value {
LiteralValue::Null => ctx.print_with_span("null", source_span),
LiteralValue::Undefined => ctx.print_with_span("undefined", source_span),
LiteralValue::Boolean(b) => {
ctx.print_with_span(if *b { "true" } else { "false" }, source_span);
}
LiteralValue::Number(n) => {
// Use JS-compatible formatting to match Angular's template literal coercion
ctx.print_with_span(&format_number_like_js(*n), source_span);
}
LiteralValue::String(s) => {
ctx.print_with_span(&escape_string(s, self.escape_dollar_in_strings), source_span);
}
}
}
/// Visit a literal array expression.
///
/// When the array would exceed the line length limit, formats it as multi-line
/// with each element on its own line and a trailing comma after the last element.
/// This matches the TypeScript printer behavior used by Angular's ngtsc compiler.
///
/// Single-line: `[a,b,c]`
/// Multi-line:
/// ```text
/// [element1,element2,element3,
/// element4,
/// element5]
/// ```
fn visit_literal_array<'a>(&self, entries: &[OutputExpression<'a>], ctx: &mut EmitterContext) {
ctx.print("[");
self.visit_all_expressions(entries, ctx, ",");
ctx.print("]");
}
/// Visit a literal map (object literal) expression.
///
/// Handles line-breaking for large objects - when line length exceeds 80 chars,
/// entries are wrapped to new lines with double indent for continuations.
///
/// See: `packages/compiler/src/output/abstract_emitter.ts:455-471` (visitLiteralMapExpr)
/// See: `packages/compiler/src/output/abstract_emitter.ts:492-520` (visitAllObjects)
fn visit_literal_map<'a>(
&self,
entries: &[super::ast::LiteralMapEntry<'a>],
ctx: &mut EmitterContext,
) {
ctx.print("{");
let mut incremented_indent = false;
for (i, entry) in entries.iter().enumerate() {
if i > 0 {
// Check line length and break if needed
if ctx.line_length() > LINE_LENGTH_LIMIT {
ctx.println(",");
if !incremented_indent {
// Continuation lines are marked with double indent
ctx.inc_indent();
ctx.inc_indent();
incremented_indent = true;
}
} else {
ctx.print(",");
}
}
let key = escape_identifier(&entry.key, self.escape_dollar_in_strings, entry.quoted);
ctx.print(&key);
ctx.print(":");
self.visit_expression(&entry.value, ctx);
}
if incremented_indent {
ctx.dec_indent();
ctx.dec_indent();
}
ctx.print("}");
}
fn visit_template_literal(
&self,
expr: &super::ast::TemplateLiteralExpr<'_>,
ctx: &mut EmitterContext,
) {
ctx.print("`");
for (i, element) in expr.elements.iter().enumerate() {
ctx.print(&element.raw_text);
if i < expr.expressions.len() {
ctx.print("${");
self.visit_expression(&expr.expressions[i], ctx);
ctx.print("}");
}
}
ctx.print("`");
}
fn visit_tagged_template_literal(
&self,
expr: &super::ast::TaggedTemplateLiteralExpr<'_>,
ctx: &mut EmitterContext,
) {
// Downlevel tagged template to function call for compatibility
// tag`...` becomes tag(__makeTemplateObject(cooked, raw), expr1, expr2, ...)
const MAKE_TEMPLATE_OBJECT_POLYFILL: &str = "(this&&this.__makeTemplateObject||function(e,t){return Object.defineProperty?Object.defineProperty(e,\"raw\",{value:t}):e.raw=t,e})";
self.visit_expression(&expr.tag, ctx);
ctx.print("(");
ctx.print(MAKE_TEMPLATE_OBJECT_POLYFILL);
ctx.print("(");
// Cooked strings
ctx.print("[");
let elements = &expr.template.elements;
for (i, element) in elements.iter().enumerate() {
if i > 0 {
ctx.print(", ");
}