Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: compute whether script #286

Merged
merged 3 commits into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions src/parsed_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,40 @@ pub enum ProgramRef<'a> {
}

impl<'a> ProgramRef<'a> {
/// Computes whether the program is a script.
pub fn compute_is_script(&self) -> bool {
// Necessary because swc will make a program a module when it contains
// typescript specific CJS imports/exports like `import add = require('./add');`.
match self {
ProgramRef::Module(m) => {
for m in m.body.iter() {
match m {
ModuleItem::ModuleDecl(m) => match m {
ModuleDecl::Import(_)
| ModuleDecl::ExportDecl(_)
| ModuleDecl::ExportNamed(_)
| ModuleDecl::ExportDefaultDecl(_)
| ModuleDecl::ExportDefaultExpr(_)
| ModuleDecl::ExportAll(_) => return false,
// the prescence of these means it's a script
ModuleDecl::TsImportEquals(_)
| ModuleDecl::TsExportAssignment(_) => {
return true;
}
ModuleDecl::TsNamespaceExport(_) => {
// ignore `export as namespace x;` as it's type only
}
},
ModuleItem::Stmt(_) => {}
}
}

false
}
ProgramRef::Script(_) => true,
}
}

pub fn unwrap_module(&self) -> &Module {
match self {
ProgramRef::Module(m) => m,
Expand Down Expand Up @@ -386,14 +420,21 @@ impl ParsedSource {
}

/// Gets if this source is a module.
#[deprecated(note = "use compute_is_script() instead")]
pub fn is_module(&self) -> bool {
matches!(self.program_ref(), ProgramRef::Module(_))
}

/// Gets if this source is a script.
#[deprecated(note = "use compute_is_script() instead")]
pub fn is_script(&self) -> bool {
matches!(self.program_ref(), ProgramRef::Script(_))
}

/// Computes whether this program should be treated as a script.
pub fn compute_is_script(&self) -> bool {
self.program_ref().compute_is_script()
}
}

impl<'a> SourceTextProvider<'a> for &'a ParsedSource {
Expand Down
Loading