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: do not panic doing scope analysis before emit #240

Merged
merged 3 commits into from
Apr 16, 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
50 changes: 49 additions & 1 deletion src/parsed_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
use std::fmt;
use std::sync::Arc;

use swc_common::Mark;

use crate::comments::MultiThreadedComments;
use crate::scope_analysis_transform;
use crate::swc::ast::Module;
Expand All @@ -17,6 +19,42 @@ use crate::ParseDiagnostic;
use crate::SourceRangedForSpanned;
use crate::SourceTextInfo;

#[derive(Debug, Clone)]
pub struct Marks {
pub unresolved: Mark,
pub top_level: Mark,
}

#[derive(Clone)]
pub struct Globals {
marks: Marks,
globals: Arc<crate::swc::common::Globals>,
}

impl Default for Globals {
fn default() -> Self {
let globals = crate::swc::common::Globals::new();
let marks = crate::swc::common::GLOBALS.set(&globals, || Marks {
unresolved: Mark::new(),
top_level: Mark::fresh(Mark::root()),
});
Self {
marks,
globals: Arc::new(globals),
}
}
}

impl Globals {
pub fn with<T>(&self, action: impl FnOnce(&Marks) -> T) -> T {
crate::swc::common::GLOBALS.set(&self.globals, || action(&self.marks))
}

pub fn marks(&self) -> &Marks {
&self.marks
}
}

#[derive(Clone)]
pub(crate) struct SyntaxContexts {
pub unresolved: SyntaxContext,
Expand All @@ -30,6 +68,7 @@ pub(crate) struct ParsedSourceInner {
pub comments: MultiThreadedComments,
pub program: Arc<Program>,
pub tokens: Option<Arc<Vec<TokenAndSpan>>>,
pub globals: Globals,
pub syntax_contexts: Option<SyntaxContexts>,
pub diagnostics: Vec<ParseDiagnostic>,
}
Expand All @@ -51,6 +90,7 @@ impl ParsedSource {
comments: MultiThreadedComments,
program: Arc<Program>,
tokens: Option<Arc<Vec<TokenAndSpan>>>,
globals: Globals,
syntax_contexts: Option<SyntaxContexts>,
diagnostics: Vec<ParseDiagnostic>,
) -> Self {
Expand All @@ -62,6 +102,7 @@ impl ParsedSource {
comments,
program,
tokens,
globals,
syntax_contexts,
diagnostics,
}),
Expand Down Expand Up @@ -118,6 +159,11 @@ impl ParsedSource {
&self.inner.comments
}

/// Wrapper around globals that swc uses for transpiling.
pub fn globals(&self) -> &Globals {
&self.inner.globals
}

/// Get the source's leading comments, where triple slash directives might
/// be located.
pub fn get_leading_comments(&self) -> Option<&Vec<Comment>> {
Expand Down Expand Up @@ -156,13 +202,15 @@ impl ParsedSource {
tokens: arc_inner.tokens.clone(),
syntax_contexts: arc_inner.syntax_contexts.clone(),
diagnostics: arc_inner.diagnostics.clone(),
globals: arc_inner.globals.clone(),
},
};
let program = match Arc::try_unwrap(inner.program) {
Ok(program) => program,
Err(program) => (*program).clone(),
};
let (program, context) = scope_analysis_transform(program);
let (program, context) =
scope_analysis_transform(program, &inner.globals);
inner.program = Arc::new(program);
inner.syntax_contexts = context;
ParsedSource {
Expand Down
64 changes: 36 additions & 28 deletions src/parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use crate::swc::parser::token::TokenAndSpan;
use crate::swc::parser::EsConfig;
use crate::swc::parser::Syntax;
use crate::swc::parser::TsConfig;
use crate::Globals;
use crate::MediaType;
use crate::ModuleSpecifier;
use crate::ParseDiagnostic;
Expand Down Expand Up @@ -48,7 +49,7 @@ pub struct ParseParams {
pub fn parse_program(
params: ParseParams,
) -> Result<ParsedSource, ParseDiagnostic> {
parse(params, ParseMode::Program, |p| p)
parse(params, ParseMode::Program, |p, _| p)
}

/// Parses the provided information as a program with the option of providing some
Expand All @@ -66,15 +67,15 @@ pub fn parse_program(
/// maybe_syntax: None,
/// scope_analysis: false,
/// },
/// |program| {
/// |program, _globals| {
/// // do something with the program here before it gets stored
/// program
/// },
/// );
/// ```
pub fn parse_program_with_post_process(
params: ParseParams,
post_process: impl FnOnce(Program) -> Program,
post_process: impl FnOnce(Program, &Globals) -> Program,
) -> Result<ParsedSource, ParseDiagnostic> {
parse(params, ParseMode::Program, post_process)
}
Expand All @@ -83,36 +84,44 @@ pub fn parse_program_with_post_process(
pub fn parse_module(
params: ParseParams,
) -> Result<ParsedSource, ParseDiagnostic> {
parse(params, ParseMode::Module, |p| p)
parse(params, ParseMode::Module, |p, _| p)
}

/// Parses a module with post processing (see docs on `parse_program_with_post_process`).
pub fn parse_module_with_post_process(
params: ParseParams,
post_process: impl FnOnce(Module) -> Module,
post_process: impl FnOnce(Module, &Globals) -> Module,
) -> Result<ParsedSource, ParseDiagnostic> {
parse(params, ParseMode::Module, |program| match program {
Program::Module(module) => Program::Module(post_process(module)),
Program::Script(_) => unreachable!(),
})
parse(
params,
ParseMode::Module,
|program, globals| match program {
Program::Module(module) => Program::Module(post_process(module, globals)),
Program::Script(_) => unreachable!(),
},
)
}

/// Parses the provided information to a script.
pub fn parse_script(
params: ParseParams,
) -> Result<ParsedSource, ParseDiagnostic> {
parse(params, ParseMode::Script, |p| p)
parse(params, ParseMode::Script, |p, _| p)
}

/// Parses a script with post processing (see docs on `parse_program_with_post_process`).
pub fn parse_script_with_post_process(
params: ParseParams,
post_process: impl FnOnce(Script) -> Script,
post_process: impl FnOnce(Script, &Globals) -> Script,
) -> Result<ParsedSource, ParseDiagnostic> {
parse(params, ParseMode::Script, |program| match program {
Program::Module(_) => unreachable!(),
Program::Script(script) => Program::Script(post_process(script)),
})
parse(
params,
ParseMode::Script,
|program, globals| match program {
Program::Module(_) => unreachable!(),
Program::Script(script) => Program::Script(post_process(script, globals)),
},
)
}

enum ParseMode {
Expand All @@ -124,7 +133,7 @@ enum ParseMode {
fn parse(
params: ParseParams,
parse_mode: ParseMode,
post_process: impl FnOnce(Program) -> Program,
post_process: impl FnOnce(Program, &Globals) -> Program,
) -> Result<ParsedSource, ParseDiagnostic> {
let source = params.text_info;
let specifier = params.specifier;
Expand All @@ -142,10 +151,11 @@ fn parse(
.into_iter()
.map(|err| ParseDiagnostic::from_swc_error(err, &specifier, source.clone()))
.collect();
let program = post_process(program);
let globals = Globals::default();
let program = post_process(program, &globals);

let (program, syntax_contexts) = if params.scope_analysis {
scope_analysis_transform(program)
scope_analysis_transform(program, &globals)
} else {
(program, None)
};
Expand All @@ -157,17 +167,19 @@ fn parse(
MultiThreadedComments::from_single_threaded(comments),
Arc::new(program),
tokens.map(Arc::new),
globals,
syntax_contexts,
diagnostics,
))
}

pub(crate) fn scope_analysis_transform(
_program: Program,
_globals: &crate::Globals,
) -> (Program, Option<crate::SyntaxContexts>) {
#[cfg(feature = "transforms")]
{
scope_analysis_transform_inner(_program)
scope_analysis_transform_inner(_program, _globals)
}
#[cfg(not(feature = "transforms"))]
panic!(
Expand All @@ -178,25 +190,21 @@ pub(crate) fn scope_analysis_transform(
#[cfg(feature = "transforms")]
fn scope_analysis_transform_inner(
program: Program,
globals: &crate::Globals,
) -> (Program, Option<crate::SyntaxContexts>) {
use crate::swc::common::Globals;
use crate::swc::common::Mark;
use crate::swc::common::SyntaxContext;
use crate::swc::transforms::resolver;
use crate::swc::visit::FoldWith;

let globals = Globals::new();
crate::swc::common::GLOBALS.set(&globals, || {
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();
globals.with(|marks| {
let program =
program.fold_with(&mut resolver(unresolved_mark, top_level_mark, true));
program.fold_with(&mut resolver(marks.unresolved, marks.top_level, true));

(
program,
Some(crate::SyntaxContexts {
unresolved: SyntaxContext::empty().apply_mark(unresolved_mark),
top_level: SyntaxContext::empty().apply_mark(top_level_mark),
unresolved: SyntaxContext::empty().apply_mark(marks.unresolved),
top_level: SyntaxContext::empty().apply_mark(marks.top_level),
}),
)
})
Expand Down
Loading