swc_estree_compat/swcify/
ctx.rs1use swc_common::{sync::Lrc, BytePos, FileName, SourceFile, SourceMap, Span, DUMMY_SP};
2use swc_estree_ast::{BaseNode, LineCol, Loc};
3use swc_node_comments::SwcComments;
4
5pub struct Context {
6 #[allow(unused)]
7 pub(crate) cm: Lrc<SourceMap>,
8 pub(crate) fm: Lrc<SourceFile>,
9 #[allow(unused)]
10 pub(crate) comments: SwcComments,
11}
12
13impl Context {
14 fn locate_line_col(&self, loc: LineCol) -> BytePos {
15 if let Some(&line_start) = self.fm.analyze().lines.get(loc.line) {
16 line_start + BytePos(loc.column as _)
17 } else {
18 BytePos(0)
19 }
20 }
21
22 fn locate_loc(&self, loc: Option<Loc>) -> Span {
23 let loc = match loc {
24 Some(v) => v,
25 None => return DUMMY_SP,
26 };
27
28 let start = self.locate_line_col(loc.start);
29 let end = self.locate_line_col(loc.end);
30
31 Span::new(start, end)
32 }
33
34 pub(crate) fn span(&self, node: &BaseNode) -> Span {
35 let span = self.locate_loc(node.loc);
36
37 if !span.is_dummy() {
38 return span;
39 }
40
41 let start = node
42 .start
43 .map(|offset| self.fm.start_pos + BytePos(offset as _))
44 .unwrap_or(BytePos::DUMMY);
45
46 let end = node
47 .end
48 .map(|offset| self.fm.start_pos + BytePos(offset as _))
49 .unwrap_or(BytePos::DUMMY);
50
51 Span::new(start, end)
52 }
53
54 pub fn new(cm: Lrc<SourceMap>, comments: SwcComments, filename: FileName, src: String) -> Self {
59 let fm = cm.new_source_file(filename.into(), src);
60 Self::new_without_alloc(cm, comments, fm)
61 }
62
63 pub fn new_without_alloc(
64 cm: Lrc<SourceMap>,
65 comments: SwcComments,
66 fm: Lrc<SourceFile>,
67 ) -> Self {
68 Self { cm, comments, fm }
69 }
70}