Unverified Commit a8ab74ad authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Revert "Add `Effect:TypeOf` and give `typeof`s ... #68842)" (#69156)

Reverts https://github.com/vercel/next.js/pull/68842
parent e2e0644f
......@@ -16,8 +16,8 @@ use turbopack_browser::{react_refresh::assert_can_resolve_react_refresh, Browser
use turbopack_core::{
chunk::ChunkingContext,
compile_time_info::{
CompileTimeDefineValue, CompileTimeDefines, CompileTimeInfo, DefineableNameSegment,
FreeVarReference, FreeVarReferences,
CompileTimeDefineValue, CompileTimeDefines, CompileTimeInfo, FreeVarReference,
FreeVarReferences,
},
condition::ContextCondition,
environment::{BrowserEnvironment, Environment, ExecutionEnvironment},
......@@ -68,11 +68,7 @@ fn defines(define_env: &IndexMap<RcStr, RcStr>) -> CompileTimeDefines {
for (k, v) in define_env {
defines
.entry(
k.split('.')
.map(|s| DefineableNameSegment::Name(s.into()))
.collect::<Vec<_>>(),
)
.entry(k.split('.').map(|s| s.into()).collect::<Vec<RcStr>>())
.or_insert_with(|| {
let val = serde_json::from_str(v);
match val {
......
......@@ -8,8 +8,8 @@ use turbopack_browser::BrowserChunkingContext;
use turbopack_core::{
chunk::ChunkingContext,
compile_time_info::{
CompileTimeDefineValue, CompileTimeDefines, CompileTimeInfo, DefineableNameSegment,
FreeVarReference, FreeVarReferences,
CompileTimeDefineValue, CompileTimeDefines, CompileTimeInfo, FreeVarReference,
FreeVarReferences,
},
environment::{EdgeWorkerEnvironment, Environment, ExecutionEnvironment},
free_var_references,
......@@ -34,11 +34,7 @@ fn defines(define_env: &IndexMap<RcStr, RcStr>) -> CompileTimeDefines {
for (k, v) in define_env {
defines
.entry(
k.split('.')
.map(|s| DefineableNameSegment::Name(s.into()))
.collect::<Vec<_>>(),
)
.entry(k.split('.').map(|s| s.into()).collect::<Vec<RcStr>>())
.or_insert_with(|| {
let val = serde_json::from_str(v);
match val {
......
......@@ -15,8 +15,7 @@ use turbopack::{
};
use turbopack_core::{
compile_time_info::{
CompileTimeDefineValue, CompileTimeDefines, CompileTimeInfo, DefineableNameSegment,
FreeVarReferences,
CompileTimeDefineValue, CompileTimeDefines, CompileTimeInfo, FreeVarReferences,
},
condition::ContextCondition,
environment::{Environment, ExecutionEnvironment, NodeJsEnvironment, RuntimeVersions},
......@@ -317,11 +316,7 @@ fn defines(define_env: &IndexMap<RcStr, RcStr>) -> CompileTimeDefines {
for (k, v) in define_env {
defines
.entry(
k.split('.')
.map(|s| DefineableNameSegment::Name(s.into()))
.collect::<Vec<_>>(),
)
.entry(k.split('.').map(|s| s.into()).collect::<Vec<RcStr>>())
.or_insert_with(|| {
let val = serde_json::from_str(v);
match val {
......
......@@ -5,40 +5,9 @@ use turbo_tasks_fs::FileSystemPath;
use crate::environment::Environment;
#[macro_export]
macro_rules! definable_name_map_pattern_internal {
($name:ident) => {
[stringify!($name).into()]
};
($name:ident typeof) => {
[stringify!($name).into(), $crate::compile_time_info::DefineableNameSegment::TypeOf]
};
// Entry point for non-recursive calls
($name:ident . $($more:ident).+ typeof) => {
$crate::definable_name_map_pattern_internal!($($more).+ typeof, [stringify!($name).into()])
};
($name:ident . $($more:ident).+) => {
$crate::definable_name_map_pattern_internal!($($more).+, [stringify!($name).into()])
};
// Pop first ident and push to end of array: (id, ..., [...]) => (..., [..., id])
($name:ident, [$($array:expr),+]) => {
[$($array),+, stringify!($name).into()]
};
($name:ident . $($more:ident).+, [$($array:expr),+]) => {
$crate::definable_name_map_pattern_internal!($($more).+, [$($array),+, stringify!($name).into()])
};
($name:ident typeof, [$($array:expr),+]) => {
[$($array),+, stringify!($name).into(), $crate::compile_time_info::DefineableNameSegment::TypeOf]
};
($name:ident . $($more:ident).+ typeof, [$($array:expr),+]) => {
$crate::definable_name_map_pattern_internal!($($more).+ typeof, [$($array),+, stringify!($name).into()])
};
}
// TODO stringify split map collect could be optimized with a marco
#[macro_export]
macro_rules! definable_name_map_internal {
// Allow spreading a map: free_var_references!(..xy.into_iter(), FOO = "bar")
($map:ident, .. $value:expr) => {
for (key, value) in $value {
$map.insert(
......@@ -47,33 +16,38 @@ macro_rules! definable_name_map_internal {
);
}
};
($map:ident, .. $value:expr, $($more:tt)+) => {
$crate::definable_name_map_internal!($map, .. $value);
$crate::definable_name_map_internal!($map, $($more)+);
};
// Base case: a single entry
($map:ident, typeof $($name:ident).+ = $value:expr $(,)?) => {
($map:ident, $($name:ident).+ = $value:expr) => {
$map.insert(
$crate::definable_name_map_pattern_internal!($($name).+ typeof).into(),
$crate::definable_name_map_internal!($($name).+).into(),
$value.into()
);
};
($map:ident, $($name:ident).+ = $value:expr $(,)?) => {
($map:ident, $($name:ident).+ = $value:expr,) => {
$map.insert(
$crate::definable_name_map_pattern_internal!($($name).+).into(),
$crate::definable_name_map_internal!($($name).+).into(),
$value.into()
);
};
// Recursion: split off first entry
($map:ident, typeof $($name:ident).+ = $value:expr, $($more:tt)+) => {
$crate::definable_name_map_internal!($map, typeof $($name).+ = $value);
$crate::definable_name_map_internal!($map, $($more)+);
};
($map:ident, $($name:ident).+ = $value:expr, $($more:tt)+) => {
$crate::definable_name_map_internal!($map, $($name).+ = $value);
$crate::definable_name_map_internal!($map, $($more)+);
};
($map:ident, .. $value:expr, $($more:tt)+) => {
$crate::definable_name_map_internal!($map, .. $value);
$crate::definable_name_map_internal!($map, $($more)+);
};
($name:ident) => {
[stringify!($name).into()]
};
($name:ident . $($more:ident).+) => {
$crate::definable_name_map_internal!($($more).+, [stringify!($name).into()])
};
($name:ident, [$($array:expr),+]) => {
[$($array),+, stringify!($name).into()]
};
($name:ident . $($more:ident).+, [$($array:expr),+]) => {
$crate::definable_name_map_internal!($($more).+, [$($array),+, stringify!($name).into()])
};
}
#[macro_export]
......@@ -138,38 +112,13 @@ impl From<serde_json::Value> for CompileTimeDefineValue {
}
}
#[turbo_tasks::value(serialization = "auto_for_input")]
#[derive(Debug, Clone, Hash)]
pub enum DefineableNameSegment {
Name(RcStr),
TypeOf,
}
impl From<RcStr> for DefineableNameSegment {
fn from(value: RcStr) -> Self {
DefineableNameSegment::Name(value)
}
}
impl From<&str> for DefineableNameSegment {
fn from(value: &str) -> Self {
DefineableNameSegment::Name(value.into())
}
}
impl From<String> for DefineableNameSegment {
fn from(value: String) -> Self {
DefineableNameSegment::Name(value.into())
}
}
#[turbo_tasks::value(transparent)]
#[derive(Debug, Clone)]
pub struct CompileTimeDefines(pub IndexMap<Vec<DefineableNameSegment>, CompileTimeDefineValue>);
pub struct CompileTimeDefines(pub IndexMap<Vec<RcStr>, CompileTimeDefineValue>);
impl IntoIterator for CompileTimeDefines {
type Item = (Vec<DefineableNameSegment>, CompileTimeDefineValue);
type IntoIter = indexmap::map::IntoIter<Vec<DefineableNameSegment>, CompileTimeDefineValue>;
type Item = (Vec<RcStr>, CompileTimeDefineValue);
type IntoIter = indexmap::map::IntoIter<Vec<RcStr>, CompileTimeDefineValue>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
......@@ -222,7 +171,7 @@ impl From<CompileTimeDefineValue> for FreeVarReference {
#[turbo_tasks::value(transparent)]
#[derive(Debug, Clone)]
pub struct FreeVarReferences(pub IndexMap<Vec<DefineableNameSegment>, FreeVarReference>);
pub struct FreeVarReferences(pub IndexMap<Vec<RcStr>, FreeVarReference>);
#[turbo_tasks::value_impl]
impl FreeVarReferences {
......@@ -299,67 +248,3 @@ impl CompileTimeInfoBuilder {
self.build().cell()
}
}
#[cfg(test)]
mod test {
use indexmap::IndexMap;
use crate::compile_time_info::{DefineableNameSegment, FreeVarReference, FreeVarReferences};
#[test]
fn macro_parser() {
assert_eq!(
free_var_references!(
FOO = "bar",
FOO = false,
Buffer = FreeVarReference::EcmaScriptModule {
request: "node:buffer".into(),
lookup_path: None,
export: Some("Buffer".into()),
},
),
FreeVarReferences(IndexMap::from_iter(vec![
(vec!["FOO".into()], FreeVarReference::Value("bar".into())),
(vec!["FOO".into()], FreeVarReference::Value(false.into())),
(
vec!["Buffer".into()],
FreeVarReference::EcmaScriptModule {
request: "node:buffer".into(),
lookup_path: None,
export: Some("Buffer".into()),
}
),
]))
);
}
#[test]
fn macro_parser_typeof() {
assert_eq!(
free_var_references!(
typeof x = "a",
typeof x.y = "b",
typeof x.y.z = "c"
),
FreeVarReferences(IndexMap::from_iter(vec![
(
vec!["x".into(), DefineableNameSegment::TypeOf],
FreeVarReference::Value("a".into())
),
(
vec!["x".into(), "y".into(), DefineableNameSegment::TypeOf],
FreeVarReference::Value("b".into())
),
(
vec![
"x".into(),
"y".into(),
"z".into(),
DefineableNameSegment::TypeOf
],
FreeVarReference::Value("c".into())
)
]))
);
}
}
......@@ -5,7 +5,6 @@ use std::{
};
use swc_core::{
atoms::Atom,
common::{pass::AstNodePath, Mark, Span, Spanned, SyntaxContext, GLOBALS},
ecma::{
ast::*,
......@@ -16,10 +15,7 @@ use swc_core::{
use turbo_tasks::{RcStr, Vc};
use turbopack_core::source::Source;
use super::{
is_unresolved_id, ConstantNumber, ConstantValue, ImportMap, JsValue, ObjectPart,
WellKnownFunctionKind,
};
use super::{ConstantNumber, ConstantValue, ImportMap, JsValue, ObjectPart, WellKnownFunctionKind};
use crate::{
analyzer::is_unresolved,
utils::{unparen, AstPathRange},
......@@ -176,12 +172,6 @@ pub enum Effect {
span: Span,
in_try: bool,
},
/// A typeof expression
TypeOf {
arg: JsValue,
ast_path: Vec<AstParentKind>,
span: Span,
},
// TODO ImportMeta should be replaced with Member
/// A reference to `import.meta`.
ImportMeta {
......@@ -233,9 +223,6 @@ impl Effect {
var.normalize();
}
Effect::ImportedBinding { .. } => {}
Effect::TypeOf { arg, .. } => {
arg.normalize();
}
Effect::ImportMeta { .. } => {}
Effect::Url { input, .. } => {
input.normalize();
......@@ -248,8 +235,6 @@ impl Effect {
#[derive(Debug)]
pub struct VarGraph {
pub values: HashMap<Id, JsValue>,
/// Map FreeVar names to their Id to facilitate lookups into [values]
pub free_var_ids: HashMap<Atom, Id>,
pub effects: Vec<Effect>,
}
......@@ -270,7 +255,6 @@ impl VarGraph {
pub fn create_graph(m: &Program, eval_context: &EvalContext) -> VarGraph {
let mut graph = VarGraph {
values: Default::default(),
free_var_ids: Default::default(),
effects: Default::default(),
};
......@@ -756,10 +740,6 @@ pub fn is_in_try(ast_path: &AstNodePath<AstParentNodeRef<'_>>) -> bool {
impl Analyzer<'_> {
fn add_value(&mut self, id: Id, value: JsValue) {
if is_unresolved_id(&id, self.eval_context.unresolved_mark) {
self.data.free_var_ids.insert(id.0.clone(), id.clone());
}
if let Some(prev) = self.data.values.get_mut(&id) {
prev.add_alt(value);
} else {
......@@ -1994,23 +1974,6 @@ impl VisitAstPath for Analyzer<'_> {
}
}
}
fn visit_unary_expr<'ast: 'r, 'r>(
&mut self,
n: &'ast UnaryExpr,
ast_path: &mut swc_core::ecma::visit::AstNodePath<'r>,
) {
if n.op == UnaryOp::TypeOf {
let arg_value = self.eval_context.eval(&n.arg);
self.add_effect(Effect::TypeOf {
arg: arg_value,
ast_path: as_parent_path(ast_path),
span: n.span(),
});
}
n.visit_children_with_ast_path(self, ast_path);
}
}
impl<'a> Analyzer<'a> {
......
......@@ -12,7 +12,6 @@ use std::{
};
use anyhow::{bail, Context, Result};
use graph::VarGraph;
use indexmap::{IndexMap, IndexSet};
use num_bigint::BigInt;
use num_traits::identities::Zero;
......@@ -26,9 +25,7 @@ use swc_core::{
},
};
use turbo_tasks::{RcStr, Vc};
use turbopack_core::compile_time_info::{
CompileTimeDefineValue, DefineableNameSegment, FreeVarReference,
};
use turbopack_core::compile_time_info::CompileTimeDefineValue;
use url::Url;
use self::imports::ImportAnnotations;
......@@ -551,20 +548,6 @@ impl From<&CompileTimeDefineValue> for JsValue {
}
}
impl From<&FreeVarReference> for JsValue {
fn from(v: &FreeVarReference) -> Self {
match v {
FreeVarReference::Value(v) => v.into(),
FreeVarReference::EcmaScriptModule { .. } => {
JsValue::unknown_empty(false, "compile time injected free var module")
}
FreeVarReference::Error(_) => {
JsValue::unknown_empty(false, "compile time injected free var error")
}
}
}
}
impl Default for JsValue {
fn default() -> Self {
JsValue::unknown_empty(false, "")
......@@ -1785,14 +1768,13 @@ impl JsValue {
// Defineable name management
impl JsValue {
/// When the value has a user-defineable name, return the length of it (in segments). Otherwise
/// returns None.
/// - any free var has itself as user-defineable name: ["foo"]
/// - any member access adds the identifier as segment after the object: ["foo", "prop"]
/// - some well-known objects/functions have a user-defineable names: ["import"]
/// When the value has a user-defineable name, return the length of it (in
/// segments). Otherwise returns None.
/// - any free var has itself as user-defineable name.
/// - any member access adds the identifier as segement to the name of the object.
/// - some well-known objects/functions have a user-defineable names.
/// - member calls without arguments also have a user-defineable name which is the property with
/// `()` appended: ["foo", "prop()"]
/// - typeof expressions add `typeof` after the argument's segments: ["foo", "typeof"]
/// `()` appended.
pub fn get_defineable_name_len(&self) -> Option<usize> {
match self {
JsValue::FreeVar(_) => Some(1),
......@@ -1806,7 +1788,6 @@ impl JsValue {
{
Some(callee.get_defineable_name_len()? + 1)
}
JsValue::TypeOf(_, arg) => Some(arg.get_defineable_name_len()? + 1),
_ => None,
}
......@@ -1824,79 +1805,6 @@ impl JsValue {
index: 0,
}
}
/// Returns any matching defined replacement that matches this value.
///
/// Optionally when passed a VarGraph, verifies that the first segment was not reassigned.
///
/// Optionally also prefixes `self` with `prefix`, e.g. to be able to match `typeof foo` if
/// `self` is just `foo`.
pub fn match_free_var_reference<'a>(
&self,
var_graph: Option<&VarGraph>,
free_var_references: &'a IndexMap<Vec<DefineableNameSegment>, FreeVarReference>,
prefix_self: &Option<DefineableNameSegment>,
) -> Option<&'a FreeVarReference> {
if let Some(def_name_len) = self.get_defineable_name_len() {
for (name, value) in free_var_references.iter() {
if name.len() != def_name_len + (prefix_self.is_some() as usize) {
continue;
}
let mut it = name.iter().map(Cow::Borrowed).rev();
if let Some(prefix_self) = prefix_self {
if it.next().unwrap().as_ref() != prefix_self {
continue;
}
}
if let Some(var_graph) = var_graph {
if let DefineableNameSegment::Name(first_str) = name.first().unwrap() {
let first_str: &str = first_str;
if var_graph
.free_var_ids
.get(&first_str.into())
.map_or(false, |id| var_graph.values.contains_key(id))
{
// `typeof foo...` but `foo` was reassigned
return None;
}
}
}
if it.eq(self.iter_defineable_name_rev()) {
return Some(value);
}
}
}
None
}
/// Returns any matching defined replacement that matches this value. Optionally also prefixes
/// `self` with `prefix`, e.g. to be able to match `typeof foo` if `self` is just `foo`.
pub fn match_define<'a>(
&self,
defines: &'a IndexMap<Vec<DefineableNameSegment>, CompileTimeDefineValue>,
) -> Option<&'a CompileTimeDefineValue> {
if let Some(def_name_len) = self.get_defineable_name_len() {
for (name, value) in defines.iter() {
if name.len() != def_name_len {
continue;
}
if name
.iter()
.map(Cow::Borrowed)
.rev()
.eq(self.iter_defineable_name_rev())
{
return Some(value);
}
}
}
None
}
}
pub struct DefineableNameIter<'a> {
......@@ -1905,11 +1813,11 @@ pub struct DefineableNameIter<'a> {
}
impl<'a> Iterator for DefineableNameIter<'a> {
type Item = Cow<'a, DefineableNameSegment>;
type Item = Cow<'a, str>;
fn next(&mut self) -> Option<Self::Item> {
let value = self.next.take()?;
Some(Cow::Owned(match value {
Some(match value {
JsValue::FreeVar(kind) => (&**kind).into(),
JsValue::Member(_, obj, prop) => {
self.next = Some(obj);
......@@ -1937,13 +1845,8 @@ impl<'a> Iterator for DefineableNameIter<'a> {
self.next = Some(callee);
format!("{}()", prop.as_str()?).into()
}
JsValue::TypeOf(_, arg) => {
self.next = Some(arg);
DefineableNameSegment::TypeOf
}
_ => return None,
}))
})
}
}
......@@ -3670,10 +3573,6 @@ fn is_unresolved(i: &Ident, unresolved_mark: Mark) -> bool {
i.ctxt.outer() == unresolved_mark
}
fn is_unresolved_id(i: &Id, unresolved_mark: Mark) -> bool {
i.1.outer() == unresolved_mark
}
#[doc(hidden)]
pub mod test_utils {
use anyhow::Result;
......@@ -4007,13 +3906,6 @@ mod tests {
Effect::FreeVar { var, .. } => {
resolved.push((format!("{parent} -> {i} free var"), var));
}
Effect::TypeOf { arg, .. } => {
let arg = resolve(&var_graph, arg).await;
resolved.push((
format!("{parent} -> {i} typeof"),
JsValue::type_of(Box::new(arg)),
));
}
Effect::MemberCall {
obj, prop, args, ..
} => {
......@@ -4031,10 +3923,7 @@ mod tests {
JsValue::unknown_empty(true, "unreachable"),
));
}
Effect::ImportMeta { .. } => {}
Effect::ImportedBinding { .. } => {}
Effect::Member { .. } => {}
Effect::Url { .. } => {}
_ => {}
}
let time = start.elapsed();
if time.as_millis() > 1 {
......
......@@ -55,9 +55,7 @@ use tracing::Instrument;
use turbo_tasks::{RcStr, TryJoinIterExt, Upcast, Value, ValueToString, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
compile_time_info::{
CompileTimeInfo, DefineableNameSegment, FreeVarReference, FreeVarReferences,
},
compile_time_info::{CompileTimeInfo, FreeVarReference},
error::PrettyPrintError,
issue::{analyze::AnalyzeIssue, IssueExt, IssueSeverity, IssueSource, StyledString},
module::Module,
......@@ -371,15 +369,7 @@ impl<'a> AnalysisState<'a> {
self.var_graph,
value,
&early_value_visitor,
&|value| {
value_visitor(
self.origin,
value,
self.compile_time_info,
self.var_graph,
in_try,
)
},
&|value| value_visitor(self.origin, value, self.compile_time_info, in_try),
fun_args_values,
)
.await
......@@ -454,40 +444,6 @@ pub(crate) async fn analyse_ecmascript_module_internal(
referenced_package_json,
} = *module.determine_module_type().await?;
let compile_time_info = match specified_type {
SpecifiedModuleType::Automatic | SpecifiedModuleType::CommonJs => {
let compile_time_info = compile_time_info.await?;
let mut free_var_references =
compile_time_info.free_var_references.await?.clone_value();
free_var_references
.entry(vec![
DefineableNameSegment::Name("exports".into()),
DefineableNameSegment::TypeOf,
])
.or_insert("object".into());
free_var_references
.entry(vec![
DefineableNameSegment::Name("module".into()),
DefineableNameSegment::TypeOf,
])
.or_insert("object".into());
free_var_references
.entry(vec![
DefineableNameSegment::Name("require".into()),
DefineableNameSegment::TypeOf,
])
.or_insert("function".into());
CompileTimeInfo {
environment: compile_time_info.environment,
defines: compile_time_info.defines,
free_var_references: FreeVarReferences(free_var_references).cell(),
}
.cell()
}
SpecifiedModuleType::EcmaScript => compile_time_info,
};
if let Some(package_json) = referenced_package_json {
analysis.add_reference(PackageJsonReference::new(package_json));
}
......@@ -1182,14 +1138,6 @@ pub(crate) async fn analyse_ecmascript_module_internal(
}
}
}
Effect::TypeOf {
arg,
ast_path,
span,
} => {
let arg = analysis_state.link_value(arg, false).await?;
handle_typeof(&ast_path, arg, span, &analysis_state, &mut analysis).await?;
}
Effect::ImportMeta {
ast_path,
span: _,
......@@ -1963,7 +1911,6 @@ async fn handle_member(
analysis: &mut AnalyzeEcmascriptModuleResultBuilder,
) -> Result<()> {
if let Some(prop) = prop.as_str() {
let prop = DefineableNameSegment::Name(prop.into());
if let Some(def_name_len) = obj.get_defineable_name_len() {
let compile_time_info = state.compile_time_info.await?;
let free_var_references = compile_time_info.free_var_references.await?;
......@@ -1971,8 +1918,8 @@ async fn handle_member(
if name.len() != def_name_len + 1 {
continue;
}
let mut it = name.iter().map(Cow::Borrowed).rev();
if it.next().unwrap().as_ref() != &prop {
let mut it = name.iter().map(|v| Cow::Borrowed(&**v)).rev();
if it.next().unwrap() != Cow::Borrowed(prop) {
continue;
}
if it.eq(obj.iter_defineable_name_rev())
......@@ -2000,24 +1947,6 @@ async fn handle_member(
Ok(())
}
async fn handle_typeof(
ast_path: &[AstParentKind],
arg: JsValue,
span: Span,
state: &AnalysisState<'_>,
analysis: &mut AnalyzeEcmascriptModuleResultBuilder,
) -> Result<()> {
if let Some(value) = arg.match_free_var_reference(
Some(state.var_graph),
&*state.compile_time_info.await?.free_var_references.await?,
&Some(DefineableNameSegment::TypeOf),
) {
handle_free_var_reference(ast_path, value, span, state, analysis).await?;
}
Ok(())
}
async fn handle_free_var(
ast_path: &[AstParentKind],
var: JsValue,
......@@ -2035,9 +1964,9 @@ async fn handle_free_var(
if var
.iter_defineable_name_rev()
.eq(name.iter().map(Cow::Borrowed).rev())
.eq(name.iter().map(|v| Cow::Borrowed(&**v)).rev())
&& handle_free_var_reference(ast_path, value, span, state, analysis).await?
{
handle_free_var_reference(ast_path, value, span, state, analysis).await?;
return Ok(());
}
}
......@@ -2330,11 +2259,9 @@ async fn value_visitor(
origin: Vc<Box<dyn ResolveOrigin>>,
v: JsValue,
compile_time_info: Vc<CompileTimeInfo>,
var_graph: &VarGraph,
in_try: bool,
) -> Result<(JsValue, bool)> {
let (mut v, modified) =
value_visitor_inner(origin, v, compile_time_info, var_graph, in_try).await?;
let (mut v, modified) = value_visitor_inner(origin, v, compile_time_info, in_try).await?;
v.normalize_shallow();
Ok((v, modified))
}
......@@ -2343,25 +2270,21 @@ async fn value_visitor_inner(
origin: Vc<Box<dyn ResolveOrigin>>,
v: JsValue,
compile_time_info: Vc<CompileTimeInfo>,
var_graph: &VarGraph,
in_try: bool,
) -> Result<(JsValue, bool)> {
// This check is just an optimization
if v.get_defineable_name_len().is_some() {
if let Some(def_name_len) = v.get_defineable_name_len() {
let compile_time_info = compile_time_info.await?;
if let JsValue::TypeOf(..) = v {
if let Some(value) = v.match_free_var_reference(
Some(var_graph),
&*compile_time_info.free_var_references.await?,
&None,
) {
let defines = compile_time_info.defines.await?;
for (name, value) in defines.iter() {
if name.len() != def_name_len {
continue;
}
if v.iter_defineable_name_rev()
.eq(name.iter().map(|v| Cow::Borrowed(&**v)).rev())
{
return Ok((value.into(), true));
}
}
if let Some(value) = v.match_define(&*compile_time_info.defines.await?) {
return Ok((value.into(), true));
}
}
let value = match v {
JsValue::Call(
......
[
TypeOf {
arg: FreeVar(
"EdgeRuntime",
),
ast_path: [
Program(
Module,
),
Module(
Body(
2,
),
),
ModuleItem(
Stmt,
),
Stmt(
Decl,
),
Decl(
Var,
),
VarDecl(
Decls(
0,
),
),
VarDeclarator(
Init,
),
Expr(
Cond,
),
CondExpr(
Test,
),
Expr(
Bin,
),
BinExpr(
Left,
),
Expr(
Unary,
),
],
span: 95..113,
},
FreeVar {
var: FreeVar(
"EdgeRuntime",
......
0 -> 1 typeof = typeof(???*0*)
- *0* FreeVar(EdgeRuntime)
⚠️ unknown global
⚠️ This value might have side effects
0 -> 2 free var = FreeVar(EdgeRuntime)
0 -> 1 free var = FreeVar(EdgeRuntime)
0 -> 3 conditional = (???*0* === "undefined")
0 -> 2 conditional = (???*0* === "undefined")
- *0* typeof(???*1*)
⚠️ nested operation
- *1* FreeVar(EdgeRuntime)
⚠️ unknown global
⚠️ This value might have side effects
3 -> 4 free var = FreeVar(require)
2 -> 3 free var = FreeVar(require)
3 -> 5 call = require*0*("ioredis")
2 -> 4 call = require*0*("ioredis")
- *0* require: The require method from CommonJS
[
TypeOf {
arg: FreeVar(
"x",
),
ast_path: [
Program(
Script,
),
Script(
Body(
0,
),
),
Stmt(
Expr,
),
ExprStmt(
Expr,
),
Expr(
Unary,
),
],
span: 1..9,
},
FreeVar {
var: FreeVar(
"x",
),
ast_path: [
Program(
Script,
),
Script(
Body(
0,
),
),
Stmt(
Expr,
),
ExprStmt(
Expr,
),
Expr(
Unary,
),
UnaryExpr(
Arg,
),
Expr(
Ident,
),
],
span: 8..9,
in_try: false,
},
]
0 -> 1 typeof = typeof(???*0*)
- *0* FreeVar(x)
⚠️ unknown global
⚠️ This value might have side effects
0 -> 2 free var = FreeVar(x)
import moduleUniversal from "./module-universal.js";
import moduleReassign from "./module-reassign.js"
it("should use the CommonJS variant of universal module definitions", () => {
expect(moduleUniversal()).toBe("other-dep 1234");
});
it("should not replace typeof exports for non-free variables", () => {
expect(moduleReassign).toBe(1234);
});
exports = () => 'hello'
if (typeof exports === 'object') throw 'oh no'
module.exports = 1234
(function webpackUniversalModuleDefinition(root, factory) {
if (typeof exports === "object" && typeof module === "object")
module.exports = factory(require("./other-dep"));
else if (typeof define === "function" && define.amd) {
// Should not be used, unresolvable
define(["./something-invalid"], factory);
} else if (typeof exports === "object") {
// Should not be used
exports["my-lib"] = factory(require("./something-invalid"));
} else {
// Should not be used
root["my-lib"] = factory(root["something-invalid"]);
}
})(
this,
function (otherDep) {
return /******/ (function (modules) {
// webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if (installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/
}
/******/ // Create a new module (and put it into the cache)
/******/ var module = (installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {},
/******/
});
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(
module.exports,
module,
module.exports,
__webpack_require__,
);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/
}
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function (exports, name, getter) {
/******/ if (!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
enumerable: true,
get: getter,
});
/******/
}
/******/
};
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function (exports) {
/******/ if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, {
value: "Module",
});
/******/
}
/******/ Object.defineProperty(exports, "__esModule", { value: true });
/******/
};
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function (value, mode) {
/******/ if (mode & 1) value = __webpack_require__(value);
/******/ if (mode & 8) return value;
/******/ if (
mode & 4 &&
typeof value === "object" &&
value &&
value.__esModule
)
return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, "default", {
enumerable: true,
value: value,
});
/******/ if (mode & 2 && typeof value != "string")
for (var key in value)
__webpack_require__.d(
ns,
key,
function (key) {
return value[key];
}.bind(null, key),
);
/******/ return ns;
/******/
};
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function (module) {
/******/ var getter =
module && module.__esModule
? /******/ function getDefault() {
return module["default"];
}
: /******/ function getModuleExports() {
return module;
};
/******/ __webpack_require__.d(getter, "a", getter);
/******/ return getter;
/******/
};
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function (object, property) {
return Object.prototype.hasOwnProperty.call(object, property);
};
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__((__webpack_require__.s = 0));
/******/
})(
/************************************************************************/
/******/ [
/* 4 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(
__webpack_exports__,
"default",
function () {
return test;
},
);
function test() {
return `${otherDep} 1234`;
}
/***/
},
],
);
},
);
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment