oxc_napi/
lib.rs

1mod comment;
2mod error;
3
4pub use comment::*;
5pub use error::*;
6
7use oxc_ast::{CommentKind, ast::Program};
8use oxc_ast_visit::utf8_to_utf16::Utf8ToUtf16;
9use oxc_span::SourceType;
10use oxc_syntax::module_record::ModuleRecord;
11
12/// Convert spans to UTF-16
13pub fn convert_utf8_to_utf16(
14    source_text: &str,
15    program: &mut Program,
16    module_record: &mut ModuleRecord,
17    errors: &mut [OxcError],
18) -> Vec<Comment> {
19    let span_converter = Utf8ToUtf16::new(source_text);
20    span_converter.convert_program(program);
21
22    // Convert comments
23    let mut offset_converter = span_converter.converter();
24    let comments = program
25        .comments
26        .iter()
27        .map(|comment| {
28            let value = comment.content_span().source_text(source_text).to_string();
29            let mut span = comment.span;
30            if let Some(converter) = offset_converter.as_mut() {
31                converter.convert_span(&mut span);
32            }
33            Comment {
34                r#type: match comment.kind {
35                    CommentKind::Line => String::from("Line"),
36                    CommentKind::Block => String::from("Block"),
37                },
38                value,
39                start: span.start,
40                end: span.end,
41            }
42        })
43        .collect::<Vec<_>>();
44
45    // Convert spans in module record to UTF-16
46    span_converter.convert_module_record(module_record);
47
48    // Convert spans in errors to UTF-16
49    if let Some(mut converter) = span_converter.converter() {
50        for error in errors {
51            for label in &mut error.labels {
52                converter.convert_offset(&mut label.start);
53                converter.convert_offset(&mut label.end);
54            }
55        }
56    }
57
58    comments
59}
60
61pub fn get_source_type(
62    filename: &str,
63    lang: Option<&str>,
64    source_type: Option<&str>,
65) -> SourceType {
66    let ty = match lang {
67        Some("js") => SourceType::mjs(),
68        Some("jsx") => SourceType::jsx(),
69        Some("ts") => SourceType::ts(),
70        Some("tsx") => SourceType::tsx(),
71        Some("dts") => SourceType::d_ts(),
72        _ => SourceType::from_path(filename).unwrap_or_default(),
73    };
74    match source_type {
75        Some("script") => ty.with_script(true),
76        Some("module") => ty.with_module(true),
77        Some("unambiguous") => ty.with_unambiguous(true),
78        _ => ty,
79    }
80}