1use std::fmt::Write;
19
20use parsec_base::{LineIndex, Span};
21
22use crate::SourceType;
23use crate::ast::{Ast, FunctionKind, List, LiteralKind, Node, NodeId};
24use crate::text;
25
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
28pub struct EstreeOptions {
29 pub loc: bool,
32 pub offsets: Offsets,
34}
35
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
39pub enum Offsets {
40 #[default]
42 Utf16,
43 Chars,
45 Bytes,
47}
48
49enum Task {
50 Node(NodeId),
51 Opt(Option<NodeId>),
52 List(List, u32),
53 Lit(&'static str),
54}
55
56struct Writer<'a> {
57 ast: &'a Ast,
58 src: &'a str,
59 lines: Option<LineIndex<'a>>,
62 offsets: Offsets,
63 loc: Option<LineIndex<'a>>,
64 out: String,
65 stack: Vec<Task>,
66}
67
68impl Ast {
69 pub fn to_estree(&self, src: &str) -> String {
79 self.to_estree_with(src, EstreeOptions::default())
80 }
81
82 pub fn to_estree_with(&self, src: &str, options: EstreeOptions) -> String {
83 let mut w = Writer {
84 ast: self,
85 src,
86 lines: (options.offsets != Offsets::Bytes && !src.is_ascii())
87 .then(|| LineIndex::ecmascript(src)),
88 offsets: options.offsets,
89 loc: options.loc.then(|| LineIndex::ecmascript(src)),
90 out: String::with_capacity(src.len() * 8),
91 stack: vec![Task::Node(self.root())],
92 };
93 while let Some(task) = w.stack.pop() {
94 match task {
95 Task::Node(id) => w.node(id),
96 Task::Opt(Some(id)) => w.node(id),
97 Task::Opt(None) => w.out.push_str("null"),
98 Task::Lit(s) => w.out.push_str(s),
99 Task::List(list, i) => {
100 if i == 0 {
101 w.out.push('[');
102 }
103 if i as usize == list.len() {
104 w.out.push(']');
105 continue;
106 }
107 if i > 0 {
108 w.out.push(',');
109 }
110 w.stack.push(Task::List(list, i + 1));
111 w.stack.push(Task::Node(self.get(list)[i as usize]));
112 }
113 }
114 }
115 w.out
116 }
117}
118
119impl<'a> Writer<'a> {
120 fn offset(&self, at: u32) -> u32 {
121 match &self.lines {
122 None => at,
123 Some(lines) if self.offsets == Offsets::Chars => lines.char_offset(at),
124 Some(lines) => lines.utf16_offset(at),
125 }
126 }
127
128 fn header(&mut self, ty: &str, span: Span) {
129 let (start, end) = (self.offset(span.start), self.offset(span.end));
130 let _ = write!(self.out, r#"{{"type":"{ty}","start":{start},"end":{end}"#);
131 if let Some(lines) = &self.loc {
132 let s = lines.line_col_utf16(span.start);
133 let e = lines.line_col_utf16(span.end);
134 let _ = write!(
135 self.out,
136 r#","loc":{{"start":{{"line":{},"column":{}}},"end":{{"line":{},"column":{}}}}}"#,
137 s.line,
138 s.column - 1,
139 e.line,
140 e.column - 1
141 );
142 }
143 }
144
145 fn text(&self, span: Span) -> &'a str {
146 span.text(self.src)
147 }
148
149 fn node(&mut self, id: NodeId) {
151 let span = self.ast.span(id);
152 let node = *self.ast.node(id);
153 let mut tasks: Vec<Task> = Vec::new();
154 macro_rules! lit {
155 ($s:expr) => {
156 tasks.push(Task::Lit($s))
157 };
158 }
159 macro_rules! child {
160 ($key:literal, $id:expr) => {{
161 tasks.push(Task::Lit(concat!(",\"", $key, "\":")));
162 tasks.push(Task::Node($id));
163 }};
164 }
165 macro_rules! opt {
166 ($key:literal, $id:expr) => {{
167 tasks.push(Task::Lit(concat!(",\"", $key, "\":")));
168 tasks.push(Task::Opt($id));
169 }};
170 }
171 macro_rules! list {
172 ($key:literal, $list:expr) => {{
173 tasks.push(Task::Lit(concat!(",\"", $key, "\":")));
174 tasks.push(Task::List($list, 0));
175 }};
176 }
177 let flag = |b: bool| if b { "true" } else { "false" };
178 match node {
179 Node::Paren { expression } => {
180 self.stack.push(Task::Node(expression));
181 return;
182 }
183 Node::Elision => {
184 self.out.push_str("null");
185 return;
186 }
187 Node::Program { body, source_type } => {
188 self.header("Program", span);
189 list!("body", body);
190 lit!(match source_type {
191 SourceType::Script => r#","sourceType":"script""#,
192 SourceType::Module => r#","sourceType":"module""#,
193 });
194 }
195 Node::Expression {
196 expression,
197 directive,
198 } => {
199 self.header("ExpressionStatement", span);
200 child!("expression", expression);
201 if directive {
202 let s = self.ast.span(expression);
203 let raw = Span::new(s.start + 1, s.end - 1);
204 self.out.push_str(r#","directive":"#);
205 text::write_json_str(&mut self.out, raw.text(self.src));
206 }
207 }
208 Node::Block { body } => {
209 self.header("BlockStatement", span);
210 list!("body", body);
211 }
212 Node::Empty => self.header("EmptyStatement", span),
213 Node::Debugger => self.header("DebuggerStatement", span),
214 Node::With { object, body } => {
215 self.header("WithStatement", span);
216 child!("object", object);
217 child!("body", body);
218 }
219 Node::Return { argument } => {
220 self.header("ReturnStatement", span);
221 opt!("argument", argument);
222 }
223 Node::Labeled { label, body } => {
224 self.header("LabeledStatement", span);
225 child!("body", body);
226 child!("label", label);
227 }
228 Node::Break { label } => {
229 self.header("BreakStatement", span);
230 opt!("label", label);
231 }
232 Node::Continue { label } => {
233 self.header("ContinueStatement", span);
234 opt!("label", label);
235 }
236 Node::If {
237 test,
238 consequent,
239 alternate,
240 } => {
241 self.header("IfStatement", span);
242 child!("test", test);
243 child!("consequent", consequent);
244 opt!("alternate", alternate);
245 }
246 Node::Switch {
247 discriminant,
248 cases,
249 } => {
250 self.header("SwitchStatement", span);
251 child!("discriminant", discriminant);
252 list!("cases", cases);
253 }
254 Node::SwitchCase { test, consequent } => {
255 self.header("SwitchCase", span);
256 opt!("test", test);
257 list!("consequent", consequent);
258 }
259 Node::Throw { argument } => {
260 self.header("ThrowStatement", span);
261 child!("argument", argument);
262 }
263 Node::Try {
264 block,
265 handler,
266 finalizer,
267 } => {
268 self.header("TryStatement", span);
269 child!("block", block);
270 opt!("handler", handler);
271 opt!("finalizer", finalizer);
272 }
273 Node::CatchClause { param, body } => {
274 self.header("CatchClause", span);
275 opt!("param", param);
276 child!("body", body);
277 }
278 Node::While { test, body } => {
279 self.header("WhileStatement", span);
280 child!("test", test);
281 child!("body", body);
282 }
283 Node::DoWhile { body, test } => {
284 self.header("DoWhileStatement", span);
285 child!("body", body);
286 child!("test", test);
287 }
288 Node::For {
289 init,
290 test,
291 update,
292 body,
293 } => {
294 self.header("ForStatement", span);
295 opt!("init", init);
296 opt!("test", test);
297 opt!("update", update);
298 child!("body", body);
299 }
300 Node::ForIn { left, right, body } => {
301 self.header("ForInStatement", span);
302 child!("left", left);
303 child!("right", right);
304 child!("body", body);
305 }
306 Node::ForOf {
307 left,
308 right,
309 body,
310 is_await,
311 } => {
312 self.header("ForOfStatement", span);
313 lit!(if is_await {
314 r#","await":true"#
315 } else {
316 r#","await":false"#
317 });
318 child!("left", left);
319 child!("right", right);
320 child!("body", body);
321 }
322 Node::VariableDeclaration { kind, declarations } => {
323 self.header("VariableDeclaration", span);
324 list!("declarations", declarations);
325 let _ = write!(self.out, r#","kind":"{}""#, kind.as_str());
326 }
327 Node::VariableDeclarator { id, init } => {
328 self.header("VariableDeclarator", span);
329 child!("id", id);
330 opt!("init", init);
331 }
332 Node::Function(f) => {
333 self.header(
334 match f.kind {
335 FunctionKind::Declaration => "FunctionDeclaration",
336 FunctionKind::Expression => "FunctionExpression",
337 FunctionKind::Arrow => "ArrowFunctionExpression",
338 },
339 span,
340 );
341 let _ = write!(
342 self.out,
343 r#","expression":{},"generator":{},"async":{}"#,
344 flag(f.expression),
345 flag(f.generator),
346 flag(f.is_async)
347 );
348 opt!("id", f.id);
349 list!("params", f.params);
350 child!("body", f.body);
351 }
352 Node::Class(c) => {
353 self.header(
354 if c.declaration {
355 "ClassDeclaration"
356 } else {
357 "ClassExpression"
358 },
359 span,
360 );
361 opt!("id", c.id);
362 opt!("superClass", c.super_class);
363 child!("body", c.body);
364 }
365 Node::ClassBody { body } => {
366 self.header("ClassBody", span);
367 list!("body", body);
368 }
369 Node::Method {
370 key,
371 value,
372 kind,
373 computed,
374 is_static,
375 } => {
376 self.header("MethodDefinition", span);
377 let _ = write!(
378 self.out,
379 r#","static":{},"computed":{},"kind":"{}""#,
380 flag(is_static),
381 flag(computed),
382 kind.as_str()
383 );
384 child!("key", key);
385 child!("value", value);
386 }
387 Node::Field {
388 key,
389 value,
390 computed,
391 is_static,
392 } => {
393 self.header("PropertyDefinition", span);
394 let _ = write!(
395 self.out,
396 r#","static":{},"computed":{}"#,
397 flag(is_static),
398 flag(computed)
399 );
400 child!("key", key);
401 opt!("value", value);
402 }
403 Node::StaticBlock { body } => {
404 self.header("StaticBlock", span);
405 list!("body", body);
406 }
407 Node::Identifier => {
408 self.header("Identifier", span);
409 self.out.push_str(r#","name":"#);
410 let name = text::ident_name(self.text(span));
411 text::write_json_str(&mut self.out, &name);
412 }
413 Node::PrivateIdentifier => {
414 self.header("PrivateIdentifier", span);
415 self.out.push_str(r#","name":"#);
416 let name = text::ident_name(self.text(Span::new(span.start + 1, span.end)));
417 text::write_json_str(&mut self.out, &name);
418 }
419 Node::Literal(kind) => {
420 self.literal(kind, span);
421 return;
422 }
423 Node::This => self.header("ThisExpression", span),
424 Node::Super => self.header("Super", span),
425 Node::Array { elements, .. } => {
426 self.header("ArrayExpression", span);
427 list!("elements", elements);
428 }
429 Node::Object { properties, .. } => {
430 self.header("ObjectExpression", span);
431 list!("properties", properties);
432 }
433 Node::Property {
434 key,
435 value,
436 kind,
437 method,
438 shorthand,
439 computed,
440 } => {
441 self.header("Property", span);
442 let _ = write!(
443 self.out,
444 r#","method":{},"shorthand":{},"computed":{},"kind":"{}""#,
445 flag(method),
446 flag(shorthand),
447 flag(computed),
448 kind.as_str()
449 );
450 child!("key", key);
451 child!("value", value);
452 }
453 Node::Template {
454 quasis,
455 expressions,
456 } => {
457 self.header("TemplateLiteral", span);
458 list!("expressions", expressions);
459 list!("quasis", quasis);
460 }
461 Node::TemplateElement { tail, cooked } => {
462 self.header("TemplateElement", span);
463 let body = self.text(span);
464 self.out.push_str(r#","value":{"raw":"#);
465 text::write_json_str(&mut self.out, &text::template_raw(body));
466 self.out.push_str(r#","cooked":"#);
467 match text::template_cooked(body).filter(|_| cooked) {
468 Some(units) => text::write_json_units(&mut self.out, &units),
469 None => self.out.push_str("null"),
470 }
471 let _ = write!(self.out, r#"}},"tail":{}"#, flag(tail));
472 }
473 Node::TaggedTemplate { tag, quasi } => {
474 self.header("TaggedTemplateExpression", span);
475 child!("tag", tag);
476 child!("quasi", quasi);
477 }
478 Node::Unary { operator, argument } => {
479 self.header("UnaryExpression", span);
480 let _ = write!(
481 self.out,
482 r#","operator":"{}","prefix":true"#,
483 operator.as_str()
484 );
485 child!("argument", argument);
486 }
487 Node::Update {
488 operator,
489 prefix,
490 argument,
491 } => {
492 self.header("UpdateExpression", span);
493 let _ = write!(
494 self.out,
495 r#","operator":"{}","prefix":{}"#,
496 operator.as_str(),
497 flag(prefix)
498 );
499 child!("argument", argument);
500 }
501 Node::Binary {
502 operator,
503 left,
504 right,
505 } => {
506 self.header("BinaryExpression", span);
507 let _ = write!(self.out, r#","operator":"{}""#, operator.as_str());
508 child!("left", left);
509 child!("right", right);
510 }
511 Node::Logical {
512 operator,
513 left,
514 right,
515 } => {
516 self.header("LogicalExpression", span);
517 let _ = write!(self.out, r#","operator":"{}""#, operator.as_str());
518 child!("left", left);
519 child!("right", right);
520 }
521 Node::Assign {
522 operator,
523 left,
524 right,
525 } => {
526 self.header("AssignmentExpression", span);
527 let _ = write!(self.out, r#","operator":"{}""#, operator.as_str());
528 child!("left", left);
529 child!("right", right);
530 }
531 Node::Conditional {
532 test,
533 consequent,
534 alternate,
535 } => {
536 self.header("ConditionalExpression", span);
537 child!("test", test);
538 child!("consequent", consequent);
539 child!("alternate", alternate);
540 }
541 Node::Call {
542 callee,
543 arguments,
544 optional,
545 } => {
546 self.header("CallExpression", span);
547 let _ = write!(self.out, r#","optional":{}"#, flag(optional));
548 child!("callee", callee);
549 list!("arguments", arguments);
550 }
551 Node::New { callee, arguments } => {
552 self.header("NewExpression", span);
553 child!("callee", callee);
554 list!("arguments", arguments);
555 }
556 Node::Member {
557 object,
558 property,
559 computed,
560 optional,
561 } => {
562 self.header("MemberExpression", span);
563 let _ = write!(
564 self.out,
565 r#","computed":{},"optional":{}"#,
566 flag(computed),
567 flag(optional)
568 );
569 child!("object", object);
570 child!("property", property);
571 }
572 Node::Chain { expression } => {
573 self.header("ChainExpression", span);
574 child!("expression", expression);
575 }
576 Node::Sequence { expressions } => {
577 self.header("SequenceExpression", span);
578 list!("expressions", expressions);
579 }
580 Node::Yield { argument, delegate } => {
581 self.header("YieldExpression", span);
582 let _ = write!(self.out, r#","delegate":{}"#, flag(delegate));
583 opt!("argument", argument);
584 }
585 Node::Await { argument } => {
586 self.header("AwaitExpression", span);
587 child!("argument", argument);
588 }
589 Node::Spread { argument } => {
590 self.header("SpreadElement", span);
591 child!("argument", argument);
592 }
593 Node::MetaProperty { meta, property } => {
594 self.header("MetaProperty", span);
595 child!("meta", meta);
596 child!("property", property);
597 }
598 Node::Import { source, options } => {
599 self.header("ImportExpression", span);
600 child!("source", source);
601 opt!("options", options);
602 }
603 Node::ImportDeclaration {
604 specifiers,
605 source,
606 attributes,
607 } => {
608 self.header("ImportDeclaration", span);
609 list!("specifiers", specifiers);
610 child!("source", source);
611 list!("attributes", attributes);
612 }
613 Node::ImportSpecifier { imported, local } => {
614 self.header("ImportSpecifier", span);
615 child!("imported", imported);
616 child!("local", local);
617 }
618 Node::ImportDefaultSpecifier { local } => {
619 self.header("ImportDefaultSpecifier", span);
620 child!("local", local);
621 }
622 Node::ImportNamespaceSpecifier { local } => {
623 self.header("ImportNamespaceSpecifier", span);
624 child!("local", local);
625 }
626 Node::ImportAttribute { key, value } => {
627 self.header("ImportAttribute", span);
628 child!("key", key);
629 child!("value", value);
630 }
631 Node::ExportNamed {
632 declaration,
633 specifiers,
634 source,
635 attributes,
636 } => {
637 self.header("ExportNamedDeclaration", span);
638 opt!("declaration", declaration);
639 list!("specifiers", specifiers);
640 opt!("source", source);
641 list!("attributes", attributes);
642 }
643 Node::ExportSpecifier { local, exported } => {
644 self.header("ExportSpecifier", span);
645 child!("local", local);
646 child!("exported", exported);
647 }
648 Node::ExportDefault { declaration } => {
649 self.header("ExportDefaultDeclaration", span);
650 child!("declaration", declaration);
651 }
652 Node::ExportAll {
653 exported,
654 source,
655 attributes,
656 } => {
657 self.header("ExportAllDeclaration", span);
658 opt!("exported", exported);
659 child!("source", source);
660 list!("attributes", attributes);
661 }
662 Node::ObjectPattern { properties } => {
663 self.header("ObjectPattern", span);
664 list!("properties", properties);
665 }
666 Node::ArrayPattern { elements } => {
667 self.header("ArrayPattern", span);
668 list!("elements", elements);
669 }
670 Node::Rest { argument } => {
671 self.header("RestElement", span);
672 child!("argument", argument);
673 }
674 Node::AssignmentPattern { left, right } => {
675 self.header("AssignmentPattern", span);
676 child!("left", left);
677 child!("right", right);
678 }
679 }
680 tasks.push(Task::Lit("}"));
681 self.stack.extend(tasks.into_iter().rev());
682 }
683
684 fn literal(&mut self, kind: LiteralKind, span: Span) {
685 self.header("Literal", span);
686 let raw = self.text(span);
687 self.out.push_str(r#","value":"#);
688 match kind {
689 LiteralKind::String => {
690 let body = Span::new(span.start + 1, span.end - 1).text(self.src);
691 text::write_json_units(&mut self.out, &text::string_value(body));
692 }
693 LiteralKind::Number => text::write_js_number(&mut self.out, text::number_value(raw)),
694 LiteralKind::Boolean | LiteralKind::Null => self.out.push_str(raw),
695 LiteralKind::BigInt | LiteralKind::RegExp => self.out.push_str("null"),
696 }
697 self.out.push_str(r#","raw":"#);
698 text::write_json_str(&mut self.out, raw);
699 match kind {
700 LiteralKind::BigInt => {
701 self.out.push_str(r#","bigint":"#);
702 text::write_json_str(&mut self.out, &text::bigint_decimal(raw));
703 }
704 LiteralKind::RegExp => {
705 let slash = raw.rfind('/').unwrap_or(0);
706 self.out.push_str(r#","regex":{"pattern":"#);
707 text::write_json_str(&mut self.out, raw.get(1..slash).unwrap_or(""));
708 self.out.push_str(r#","flags":"#);
709 text::write_json_str(&mut self.out, &raw[slash + 1..]);
710 self.out.push('}');
711 }
712 _ => {}
713 }
714 self.out.push('}');
715 }
716}