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
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@
//! creation, aliasing, mutation, freezing, and error conditions for each
//! instruction and terminal in the HIR.

use indexmap::{IndexMap, IndexSet};
use indexmap::IndexMap;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};

use react_compiler_diagnostics::CompilerDiagnostic;
Expand DownExpand Up@@ -69,7 +69,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Context,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ctx_place.identifier, value_id);
Expand All@@ -78,12 +78,12 @@ pub fn infer_mutation_aliasing_effects(
let param_kind: AbstractValue = if is_function_expression {
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
}
} else {
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(ValueReason::ReactiveFunctionArgument),
reason: ValueReasonSet::single(ValueReason::ReactiveFunctionArgument),
}
};

Expand All@@ -103,7 +103,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ref_place.identifier, value_id);
Expand DownExpand Up@@ -185,7 +185,7 @@ pub fn infer_mutation_aliasing_effects(
};

states_by_block.insert(block_id, incoming_state.clone());
let mut state = incoming_state.clone();
let mut state = incoming_state;

infer_block(&mut context, &mut state, block_id, func, env)?;

Expand DownExpand Up@@ -258,16 +258,88 @@ impl ValueId {
// AbstractValue
// =============================================================================

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Copy)]
struct AbstractValue {
kind: ValueKind,
reason: IndexSet<ValueReason, FxBuildHasher>,
reason: ValueReasonSet,
}

/// Capacity of [`ValueReasonSet`]. A set holds at most one of each `ValueReason`
/// variant, of which there are currently 12; the extra slots are headroom so
/// that adding variants upstream cannot overflow the set.
const VALUE_REASON_CAPACITY: usize = 16;

/// An insertion-ordered set of [`ValueReason`]s, stored inline.
///
/// This is a deliberate replacement for `IndexSet`, enabling insertion-order
/// memory while avoiding any heap allocation. At `AbstractValue`'s scale, this
/// has a dramatic impact on heap memory and wall time.
/// This takes advantage of the format of the data it's actually storing. A set
/// can hold at most one of each variant, so the members fit into a fixed inline
/// array. `ValueReason` is implemented as a single byte, so this struct is
/// ~18 bytes on the stack.
///
/// Insertion order is preserved deliberately: [`primary_reason`] returns the
/// first non-`Other` member, matching the iteration order of the `Set` used by
/// the TypeScript implementation this is ported from.
#[derive(Debug, Clone, Copy)]
struct ValueReasonSet {
/// Members in insertion order. Only the first `len` entries are meaningful.
members: [ValueReason; VALUE_REASON_CAPACITY],
len: u8,
}

fn hashset_of(r: ValueReason) -> IndexSet<ValueReason, FxBuildHasher> {
let mut s = IndexSet::default();
s.insert(r);
s
impl Default for ValueReasonSet {
fn default() -> Self {
ValueReasonSet {
members: [ValueReason::Other; VALUE_REASON_CAPACITY],
len: 0,
}
}
}

impl ValueReasonSet {
fn single(reason: ValueReason) -> Self {
let mut set = Self::default();
set.insert(reason);
set
}

fn contains(&self, reason: ValueReason) -> bool {
self.members[..self.len as usize].contains(&reason)
}

fn iter(&self) -> impl Iterator<Item = ValueReason> + '_ {
self.members[..self.len as usize].iter().copied()
}

/// Appends `reason` if not already present, preserving insertion order.
fn insert(&mut self, reason: ValueReason) {
if self.contains(reason) {
return;
}
debug_assert!(
(self.len as usize) < VALUE_REASON_CAPACITY,
"ValueReasonSet capacity must cover every ValueReason variant"
);
if (self.len as usize) < VALUE_REASON_CAPACITY {
self.members[self.len as usize] = reason;
self.len += 1;
}
}

/// True when every member of `other` is also a member of `self`.
fn is_superset_of(&self, other: &ValueReasonSet) -> bool {
other.iter().all(|reason| self.contains(reason))
}

/// Adds every member of `other`, keeping `self`'s existing order and
/// appending newcomers in `other`'s order — matching `IndexSet::insert`.
fn union_with(&mut self, other: &ValueReasonSet) {
for reason in other.iter() {
self.insert(reason);
}
}
}

// =============================================================================
Expand DownExpand Up@@ -315,7 +387,7 @@ impl InferenceState {
}
return AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
};
}
};
Expand All@@ -332,7 +404,7 @@ impl InferenceState {
}
merged_kind.unwrap_or_else(|| AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
})
}

Expand DownExpand Up@@ -360,7 +432,7 @@ impl InferenceState {
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
}
Expand DownExpand Up@@ -438,7 +510,7 @@ impl InferenceState {
value_id,
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
// Note: In TS, this also transitively freezes FunctionExpression captures
Expand DownExpand Up@@ -493,7 +565,7 @@ impl InferenceState {
if let Some(other_value) = other.values.get(id) {
let merged = merge_abstract_values(this_value, other_value);
if merged.kind != this_value.kind
|| !is_superset(&this_value.reason, &merged.reason)
|| !this_value.reason.is_superset_of(&merged.reason)
{
let nv = next_values.get_or_insert_with(|| self.values.clone());
nv.insert(*id, merged);
Expand DownExpand Up@@ -566,13 +638,6 @@ impl InferenceState {
}
}

fn is_superset(
a: &IndexSet<ValueReason, FxBuildHasher>,
b: &IndexSet<ValueReason, FxBuildHasher>,
) -> bool {
b.iter().all(|x| a.contains(x))
}

#[derive(Debug, Clone, Copy)]
enum MutateVariant {
Mutate,
Expand DownExpand Up@@ -738,13 +803,11 @@ fn hash_effect(effect: &AliasingEffect) -> String {

fn merge_abstract_values(a: &AbstractValue, b: &AbstractValue) -> AbstractValue {
let kind = merge_value_kinds(a.kind, b.kind);
if kind == a.kind && kind == b.kind && is_superset(&a.reason, &b.reason) {
if kind == a.kind && kind == b.kind && a.reason.is_superset_of(&b.reason) {
return a.clone();
}
let mut reason = a.reason.clone();
for r in &b.reason {
reason.insert(*r);
}
let mut reason = a.reason;
reason.union_with(&b.reason);
AbstractValue { kind, reason }
}

Expand DownExpand Up@@ -1233,7 +1296,7 @@ fn apply_signature(
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
state.define(instr.lvalue.identifier, vid);
Expand DownExpand Up@@ -1341,7 +1404,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1370,7 +1433,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1487,7 +1550,7 @@ fn apply_effect(
} else {
ValueKind::Frozen
},
reason: IndexSet::default(),
reason: ValueReasonSet::default(),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1599,7 +1662,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand All@@ -1615,7 +1678,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -3410,8 +3473,8 @@ fn compute_effects_for_aliasing_signature(
/// since the primary reason is always inserted first, this effectively
/// picks the most specific non-Other reason. We replicate this by
/// preferring any non-Other reason over Other.
fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason {
for &r in reasons {
fn primary_reason(reasons: &ValueReasonSet) -> ValueReason {
for r in reasons.iter() {
if r != ValueReason::Other {
return r;
}
Expand All@@ -3420,32 +3483,32 @@ fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason
}

fn get_write_error_reason(abstract_value: &AbstractValue) -> String {
if abstract_value.reason.contains(&ValueReason::Global) {
if abstract_value.reason.contains(ValueReason::Global) {
"Modifying a variable defined outside a component or hook is not allowed. Consider using an effect".to_string()
} else if abstract_value.reason.contains(&ValueReason::JsxCaptured) {
} else if abstract_value.reason.contains(ValueReason::JsxCaptured) {
"Modifying a value used previously in JSX is not allowed. Consider moving the modification before the JSX".to_string()
} else if abstract_value.reason.contains(&ValueReason::Context) {
} else if abstract_value.reason.contains(ValueReason::Context) {
"Modifying a value returned from 'useContext()' is not allowed.".to_string()
} else if abstract_value
.reason
.contains(&ValueReason::KnownReturnSignature)
.contains(ValueReason::KnownReturnSignature)
{
"Modifying a value returned from a function whose return value should not be mutated"
.to_string()
} else if abstract_value
.reason
.contains(&ValueReason::ReactiveFunctionArgument)
.contains(ValueReason::ReactiveFunctionArgument)
{
"Modifying component props or hook arguments is not allowed. Consider using a local variable instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::State) {
} else if abstract_value.reason.contains(ValueReason::State) {
"Modifying a value returned from 'useState()', which should not be modified directly. Use the setter function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::ReducerState) {
} else if abstract_value.reason.contains(ValueReason::ReducerState) {
"Modifying a value returned from 'useReducer()', which should not be modified directly. Use the dispatch function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::Effect) {
} else if abstract_value.reason.contains(ValueReason::Effect) {
"Modifying a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the modification before calling useEffect()".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookCaptured) {
} else if abstract_value.reason.contains(ValueReason::HookCaptured) {
"Modifying a value previously passed as an argument to a hook is not allowed. Consider moving the modification before calling the hook".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookReturn) {
} else if abstract_value.reason.contains(ValueReason::HookReturn) {
"Modifying a value returned from a hook is not allowed. Consider moving the modification into the hook where the value is constructed".to_string()
} else {
"This modifies a variable that React considers immutable".to_string()
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -1472,32 +1472,36 @@ fn recursively_propagate_non_null(
}

// Compute intersection of 'done' neighbors only (filter out 'active' = cycle nodes)
let done_neighbor_sets: Vec<BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n).cloned())
.collect();
let neighbor_intersection = {
let done_neighbor_sets: Vec<&BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n))
.collect();

let neighbor_intersection = if done_neighbor_sets.is_empty() {
BTreeSet::new()
} else {
let mut iter = done_neighbor_sets.into_iter();
let first = iter.next().unwrap();
iter.fold(first, |acc, s| acc.intersection(&s).copied().collect())
match done_neighbor_sets.split_first() {
None => BTreeSet::new(),
Some((first, rest)) => rest.iter().fold((*first).clone(), |acc, s| {
acc.intersection(s).copied().collect()
}),
}
};

let prev_objects = working.get(&node_id).cloned().unwrap_or_default();
// Temporarily remove the previous set out of the map so it can be safely
// borrowed and compared without a heavy deep clone.
let prev_objects = working.remove(&node_id).unwrap_or_default();
let mut merged: BTreeSet<usize> = prev_objects
.union(&neighbor_intersection)
.copied()
.collect();
reduce_maybe_optional_chains(&mut merged, registry);

working.insert(node_id, merged.clone());
traversal_state.insert(node_id, TraversalState::Done);

// Compare with previous value — can't just check size due to reduce_maybe_optional_chains
changed |= prev_objects != merged;

working.insert(node_id, merged);
traversal_state.insert(node_id, TraversalState::Done);

changed
}

Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
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
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@
//! creation, aliasing, mutation, freezing, and error conditions for each
//! instruction and terminal in the HIR.

use indexmap::{IndexMap, IndexSet};
use indexmap::IndexMap;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};

use react_compiler_diagnostics::CompilerDiagnostic;
Expand DownExpand Up@@ -69,7 +69,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Context,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ctx_place.identifier, value_id);
Expand All@@ -78,12 +78,12 @@ pub fn infer_mutation_aliasing_effects(
let param_kind: AbstractValue = if is_function_expression {
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
}
} else {
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(ValueReason::ReactiveFunctionArgument),
reason: ValueReasonSet::single(ValueReason::ReactiveFunctionArgument),
}
};

Expand All@@ -103,7 +103,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ref_place.identifier, value_id);
Expand DownExpand Up@@ -185,7 +185,7 @@ pub fn infer_mutation_aliasing_effects(
};

states_by_block.insert(block_id, incoming_state.clone());
let mut state = incoming_state.clone();
let mut state = incoming_state;

infer_block(&mut context, &mut state, block_id, func, env)?;

Expand DownExpand Up@@ -258,16 +258,88 @@ impl ValueId {
// AbstractValue
// =============================================================================

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Copy)]
struct AbstractValue {
kind: ValueKind,
reason: IndexSet<ValueReason, FxBuildHasher>,
reason: ValueReasonSet,
}

/// Capacity of [`ValueReasonSet`]. A set holds at most one of each `ValueReason`
/// variant, of which there are currently 12; the extra slots are headroom so
/// that adding variants upstream cannot overflow the set.
const VALUE_REASON_CAPACITY: usize = 16;

/// An insertion-ordered set of [`ValueReason`]s, stored inline.
///
/// This is a deliberate replacement for `IndexSet`, enabling insertion-order
/// memory while avoiding any heap allocation. At `AbstractValue`'s scale, this
/// has a dramatic impact on heap memory and wall time.
/// This takes advantage of the format of the data it's actually storing. A set
/// can hold at most one of each variant, so the members fit into a fixed inline
/// array. `ValueReason` is implemented as a single byte, so this struct is
/// ~18 bytes on the stack.
///
/// Insertion order is preserved deliberately: [`primary_reason`] returns the
/// first non-`Other` member, matching the iteration order of the `Set` used by
/// the TypeScript implementation this is ported from.
#[derive(Debug, Clone, Copy)]
struct ValueReasonSet {
/// Members in insertion order. Only the first `len` entries are meaningful.
members: [ValueReason; VALUE_REASON_CAPACITY],
len: u8,
}

fn hashset_of(r: ValueReason) -> IndexSet<ValueReason, FxBuildHasher> {
let mut s = IndexSet::default();
s.insert(r);
s
impl Default for ValueReasonSet {
fn default() -> Self {
ValueReasonSet {
members: [ValueReason::Other; VALUE_REASON_CAPACITY],
len: 0,
}
}
}

impl ValueReasonSet {
fn single(reason: ValueReason) -> Self {
let mut set = Self::default();
set.insert(reason);
set
}

fn contains(&self, reason: ValueReason) -> bool {
self.members[..self.len as usize].contains(&reason)
}

fn iter(&self) -> impl Iterator<Item = ValueReason> + '_ {
self.members[..self.len as usize].iter().copied()
}

/// Appends `reason` if not already present, preserving insertion order.
fn insert(&mut self, reason: ValueReason) {
if self.contains(reason) {
return;
}
debug_assert!(
(self.len as usize) < VALUE_REASON_CAPACITY,
"ValueReasonSet capacity must cover every ValueReason variant"
);
if (self.len as usize) < VALUE_REASON_CAPACITY {
self.members[self.len as usize] = reason;
self.len += 1;
}
}

/// True when every member of `other` is also a member of `self`.
fn is_superset_of(&self, other: &ValueReasonSet) -> bool {
other.iter().all(|reason| self.contains(reason))
}

/// Adds every member of `other`, keeping `self`'s existing order and
/// appending newcomers in `other`'s order — matching `IndexSet::insert`.
fn union_with(&mut self, other: &ValueReasonSet) {
for reason in other.iter() {
self.insert(reason);
}
}
}

// =============================================================================
Expand DownExpand Up@@ -315,7 +387,7 @@ impl InferenceState {
}
return AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
};
}
};
Expand All@@ -332,7 +404,7 @@ impl InferenceState {
}
merged_kind.unwrap_or_else(|| AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
})
}

Expand DownExpand Up@@ -360,7 +432,7 @@ impl InferenceState {
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
}
Expand DownExpand Up@@ -438,7 +510,7 @@ impl InferenceState {
value_id,
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
// Note: In TS, this also transitively freezes FunctionExpression captures
Expand DownExpand Up@@ -493,7 +565,7 @@ impl InferenceState {
if let Some(other_value) = other.values.get(id) {
let merged = merge_abstract_values(this_value, other_value);
if merged.kind != this_value.kind
|| !is_superset(&this_value.reason, &merged.reason)
|| !this_value.reason.is_superset_of(&merged.reason)
{
let nv = next_values.get_or_insert_with(|| self.values.clone());
nv.insert(*id, merged);
Expand DownExpand Up@@ -566,13 +638,6 @@ impl InferenceState {
}
}

fn is_superset(
a: &IndexSet<ValueReason, FxBuildHasher>,
b: &IndexSet<ValueReason, FxBuildHasher>,
) -> bool {
b.iter().all(|x| a.contains(x))
}

#[derive(Debug, Clone, Copy)]
enum MutateVariant {
Mutate,
Expand DownExpand Up@@ -738,13 +803,11 @@ fn hash_effect(effect: &AliasingEffect) -> String {

fn merge_abstract_values(a: &AbstractValue, b: &AbstractValue) -> AbstractValue {
let kind = merge_value_kinds(a.kind, b.kind);
if kind == a.kind && kind == b.kind && is_superset(&a.reason, &b.reason) {
if kind == a.kind && kind == b.kind && a.reason.is_superset_of(&b.reason) {
return a.clone();
}
let mut reason = a.reason.clone();
for r in &b.reason {
reason.insert(*r);
}
let mut reason = a.reason;
reason.union_with(&b.reason);
AbstractValue { kind, reason }
}

Expand DownExpand Up@@ -1233,7 +1296,7 @@ fn apply_signature(
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
state.define(instr.lvalue.identifier, vid);
Expand DownExpand Up@@ -1341,7 +1404,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1370,7 +1433,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1487,7 +1550,7 @@ fn apply_effect(
} else {
ValueKind::Frozen
},
reason: IndexSet::default(),
reason: ValueReasonSet::default(),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1599,7 +1662,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand All@@ -1615,7 +1678,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -3410,8 +3473,8 @@ fn compute_effects_for_aliasing_signature(
/// since the primary reason is always inserted first, this effectively
/// picks the most specific non-Other reason. We replicate this by
/// preferring any non-Other reason over Other.
fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason {
for &r in reasons {
fn primary_reason(reasons: &ValueReasonSet) -> ValueReason {
for r in reasons.iter() {
if r != ValueReason::Other {
return r;
}
Expand All@@ -3420,32 +3483,32 @@ fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason
}

fn get_write_error_reason(abstract_value: &AbstractValue) -> String {
if abstract_value.reason.contains(&ValueReason::Global) {
if abstract_value.reason.contains(ValueReason::Global) {
"Modifying a variable defined outside a component or hook is not allowed. Consider using an effect".to_string()
} else if abstract_value.reason.contains(&ValueReason::JsxCaptured) {
} else if abstract_value.reason.contains(ValueReason::JsxCaptured) {
"Modifying a value used previously in JSX is not allowed. Consider moving the modification before the JSX".to_string()
} else if abstract_value.reason.contains(&ValueReason::Context) {
} else if abstract_value.reason.contains(ValueReason::Context) {
"Modifying a value returned from 'useContext()' is not allowed.".to_string()
} else if abstract_value
.reason
.contains(&ValueReason::KnownReturnSignature)
.contains(ValueReason::KnownReturnSignature)
{
"Modifying a value returned from a function whose return value should not be mutated"
.to_string()
} else if abstract_value
.reason
.contains(&ValueReason::ReactiveFunctionArgument)
.contains(ValueReason::ReactiveFunctionArgument)
{
"Modifying component props or hook arguments is not allowed. Consider using a local variable instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::State) {
} else if abstract_value.reason.contains(ValueReason::State) {
"Modifying a value returned from 'useState()', which should not be modified directly. Use the setter function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::ReducerState) {
} else if abstract_value.reason.contains(ValueReason::ReducerState) {
"Modifying a value returned from 'useReducer()', which should not be modified directly. Use the dispatch function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::Effect) {
} else if abstract_value.reason.contains(ValueReason::Effect) {
"Modifying a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the modification before calling useEffect()".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookCaptured) {
} else if abstract_value.reason.contains(ValueReason::HookCaptured) {
"Modifying a value previously passed as an argument to a hook is not allowed. Consider moving the modification before calling the hook".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookReturn) {
} else if abstract_value.reason.contains(ValueReason::HookReturn) {
"Modifying a value returned from a hook is not allowed. Consider moving the modification into the hook where the value is constructed".to_string()
} else {
"This modifies a variable that React considers immutable".to_string()
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -1472,32 +1472,36 @@ fn recursively_propagate_non_null(
}

// Compute intersection of 'done' neighbors only (filter out 'active' = cycle nodes)
let done_neighbor_sets: Vec<BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n).cloned())
.collect();
let neighbor_intersection = {
let done_neighbor_sets: Vec<&BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n))
.collect();

let neighbor_intersection = if done_neighbor_sets.is_empty() {
BTreeSet::new()
} else {
let mut iter = done_neighbor_sets.into_iter();
let first = iter.next().unwrap();
iter.fold(first, |acc, s| acc.intersection(&s).copied().collect())
match done_neighbor_sets.split_first() {
None => BTreeSet::new(),
Some((first, rest)) => rest.iter().fold((*first).clone(), |acc, s| {
acc.intersection(s).copied().collect()
}),
}
};

let prev_objects = working.get(&node_id).cloned().unwrap_or_default();
// Temporarily remove the previous set out of the map so it can be safely
// borrowed and compared without a heavy deep clone.
let prev_objects = working.remove(&node_id).unwrap_or_default();
let mut merged: BTreeSet<usize> = prev_objects
.union(&neighbor_intersection)
.copied()
.collect();
reduce_maybe_optional_chains(&mut merged, registry);

working.insert(node_id, merged.clone());
traversal_state.insert(node_id, TraversalState::Done);

// Compare with previous value — can't just check size due to reduce_maybe_optional_chains
changed |= prev_objects != merged;

working.insert(node_id, merged);
traversal_state.insert(node_id, TraversalState::Done);

changed
}

Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@
//! creation, aliasing, mutation, freezing, and error conditions for each
//! instruction and terminal in the HIR.

use indexmap::{IndexMap, IndexSet};
use indexmap::IndexMap;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};

use react_compiler_diagnostics::CompilerDiagnostic;
Expand DownExpand Up@@ -69,7 +69,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Context,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ctx_place.identifier, value_id);
Expand All@@ -78,12 +78,12 @@ pub fn infer_mutation_aliasing_effects(
let param_kind: AbstractValue = if is_function_expression {
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
}
} else {
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(ValueReason::ReactiveFunctionArgument),
reason: ValueReasonSet::single(ValueReason::ReactiveFunctionArgument),
}
};

Expand All@@ -103,7 +103,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ref_place.identifier, value_id);
Expand DownExpand Up@@ -185,7 +185,7 @@ pub fn infer_mutation_aliasing_effects(
};

states_by_block.insert(block_id, incoming_state.clone());
let mut state = incoming_state.clone();
let mut state = incoming_state;

infer_block(&mut context, &mut state, block_id, func, env)?;

Expand DownExpand Up@@ -258,16 +258,88 @@ impl ValueId {
// AbstractValue
// =============================================================================

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Copy)]
struct AbstractValue {
kind: ValueKind,
reason: IndexSet<ValueReason, FxBuildHasher>,
reason: ValueReasonSet,
}

/// Capacity of [`ValueReasonSet`]. A set holds at most one of each `ValueReason`
/// variant, of which there are currently 12; the extra slots are headroom so
/// that adding variants upstream cannot overflow the set.
const VALUE_REASON_CAPACITY: usize = 16;

/// An insertion-ordered set of [`ValueReason`]s, stored inline.
///
/// This is a deliberate replacement for `IndexSet`, enabling insertion-order
/// memory while avoiding any heap allocation. At `AbstractValue`'s scale, this
/// has a dramatic impact on heap memory and wall time.
/// This takes advantage of the format of the data it's actually storing. A set
/// can hold at most one of each variant, so the members fit into a fixed inline
/// array. `ValueReason` is implemented as a single byte, so this struct is
/// ~18 bytes on the stack.
///
/// Insertion order is preserved deliberately: [`primary_reason`] returns the
/// first non-`Other` member, matching the iteration order of the `Set` used by
/// the TypeScript implementation this is ported from.
#[derive(Debug, Clone, Copy)]
struct ValueReasonSet {
/// Members in insertion order. Only the first `len` entries are meaningful.
members: [ValueReason; VALUE_REASON_CAPACITY],
len: u8,
}

fn hashset_of(r: ValueReason) -> IndexSet<ValueReason, FxBuildHasher> {
let mut s = IndexSet::default();
s.insert(r);
s
impl Default for ValueReasonSet {
fn default() -> Self {
ValueReasonSet {
members: [ValueReason::Other; VALUE_REASON_CAPACITY],
len: 0,
}
}
}

impl ValueReasonSet {
fn single(reason: ValueReason) -> Self {
let mut set = Self::default();
set.insert(reason);
set
}

fn contains(&self, reason: ValueReason) -> bool {
self.members[..self.len as usize].contains(&reason)
}

fn iter(&self) -> impl Iterator<Item = ValueReason> + '_ {
self.members[..self.len as usize].iter().copied()
}

/// Appends `reason` if not already present, preserving insertion order.
fn insert(&mut self, reason: ValueReason) {
if self.contains(reason) {
return;
}
debug_assert!(
(self.len as usize) < VALUE_REASON_CAPACITY,
"ValueReasonSet capacity must cover every ValueReason variant"
);
if (self.len as usize) < VALUE_REASON_CAPACITY {
self.members[self.len as usize] = reason;
self.len += 1;
}
}

/// True when every member of `other` is also a member of `self`.
fn is_superset_of(&self, other: &ValueReasonSet) -> bool {
other.iter().all(|reason| self.contains(reason))
}

/// Adds every member of `other`, keeping `self`'s existing order and
/// appending newcomers in `other`'s order — matching `IndexSet::insert`.
fn union_with(&mut self, other: &ValueReasonSet) {
for reason in other.iter() {
self.insert(reason);
}
}
}

// =============================================================================
Expand DownExpand Up@@ -315,7 +387,7 @@ impl InferenceState {
}
return AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
};
}
};
Expand All@@ -332,7 +404,7 @@ impl InferenceState {
}
merged_kind.unwrap_or_else(|| AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
})
}

Expand DownExpand Up@@ -360,7 +432,7 @@ impl InferenceState {
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
}
Expand DownExpand Up@@ -438,7 +510,7 @@ impl InferenceState {
value_id,
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
// Note: In TS, this also transitively freezes FunctionExpression captures
Expand DownExpand Up@@ -493,7 +565,7 @@ impl InferenceState {
if let Some(other_value) = other.values.get(id) {
let merged = merge_abstract_values(this_value, other_value);
if merged.kind != this_value.kind
|| !is_superset(&this_value.reason, &merged.reason)
|| !this_value.reason.is_superset_of(&merged.reason)
{
let nv = next_values.get_or_insert_with(|| self.values.clone());
nv.insert(*id, merged);
Expand DownExpand Up@@ -566,13 +638,6 @@ impl InferenceState {
}
}

fn is_superset(
a: &IndexSet<ValueReason, FxBuildHasher>,
b: &IndexSet<ValueReason, FxBuildHasher>,
) -> bool {
b.iter().all(|x| a.contains(x))
}

#[derive(Debug, Clone, Copy)]
enum MutateVariant {
Mutate,
Expand DownExpand Up@@ -738,13 +803,11 @@ fn hash_effect(effect: &AliasingEffect) -> String {

fn merge_abstract_values(a: &AbstractValue, b: &AbstractValue) -> AbstractValue {
let kind = merge_value_kinds(a.kind, b.kind);
if kind == a.kind && kind == b.kind && is_superset(&a.reason, &b.reason) {
if kind == a.kind && kind == b.kind && a.reason.is_superset_of(&b.reason) {
return a.clone();
}
let mut reason = a.reason.clone();
for r in &b.reason {
reason.insert(*r);
}
let mut reason = a.reason;
reason.union_with(&b.reason);
AbstractValue { kind, reason }
}

Expand DownExpand Up@@ -1233,7 +1296,7 @@ fn apply_signature(
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
state.define(instr.lvalue.identifier, vid);
Expand DownExpand Up@@ -1341,7 +1404,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1370,7 +1433,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1487,7 +1550,7 @@ fn apply_effect(
} else {
ValueKind::Frozen
},
reason: IndexSet::default(),
reason: ValueReasonSet::default(),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1599,7 +1662,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand All@@ -1615,7 +1678,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -3410,8 +3473,8 @@ fn compute_effects_for_aliasing_signature(
/// since the primary reason is always inserted first, this effectively
/// picks the most specific non-Other reason. We replicate this by
/// preferring any non-Other reason over Other.
fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason {
for &r in reasons {
fn primary_reason(reasons: &ValueReasonSet) -> ValueReason {
for r in reasons.iter() {
if r != ValueReason::Other {
return r;
}
Expand All@@ -3420,32 +3483,32 @@ fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason
}

fn get_write_error_reason(abstract_value: &AbstractValue) -> String {
if abstract_value.reason.contains(&ValueReason::Global) {
if abstract_value.reason.contains(ValueReason::Global) {
"Modifying a variable defined outside a component or hook is not allowed. Consider using an effect".to_string()
} else if abstract_value.reason.contains(&ValueReason::JsxCaptured) {
} else if abstract_value.reason.contains(ValueReason::JsxCaptured) {
"Modifying a value used previously in JSX is not allowed. Consider moving the modification before the JSX".to_string()
} else if abstract_value.reason.contains(&ValueReason::Context) {
} else if abstract_value.reason.contains(ValueReason::Context) {
"Modifying a value returned from 'useContext()' is not allowed.".to_string()
} else if abstract_value
.reason
.contains(&ValueReason::KnownReturnSignature)
.contains(ValueReason::KnownReturnSignature)
{
"Modifying a value returned from a function whose return value should not be mutated"
.to_string()
} else if abstract_value
.reason
.contains(&ValueReason::ReactiveFunctionArgument)
.contains(ValueReason::ReactiveFunctionArgument)
{
"Modifying component props or hook arguments is not allowed. Consider using a local variable instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::State) {
} else if abstract_value.reason.contains(ValueReason::State) {
"Modifying a value returned from 'useState()', which should not be modified directly. Use the setter function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::ReducerState) {
} else if abstract_value.reason.contains(ValueReason::ReducerState) {
"Modifying a value returned from 'useReducer()', which should not be modified directly. Use the dispatch function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::Effect) {
} else if abstract_value.reason.contains(ValueReason::Effect) {
"Modifying a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the modification before calling useEffect()".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookCaptured) {
} else if abstract_value.reason.contains(ValueReason::HookCaptured) {
"Modifying a value previously passed as an argument to a hook is not allowed. Consider moving the modification before calling the hook".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookReturn) {
} else if abstract_value.reason.contains(ValueReason::HookReturn) {
"Modifying a value returned from a hook is not allowed. Consider moving the modification into the hook where the value is constructed".to_string()
} else {
"This modifies a variable that React considers immutable".to_string()
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -1472,32 +1472,36 @@ fn recursively_propagate_non_null(
}

// Compute intersection of 'done' neighbors only (filter out 'active' = cycle nodes)
let done_neighbor_sets: Vec<BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n).cloned())
.collect();
let neighbor_intersection = {
let done_neighbor_sets: Vec<&BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n))
.collect();

let neighbor_intersection = if done_neighbor_sets.is_empty() {
BTreeSet::new()
} else {
let mut iter = done_neighbor_sets.into_iter();
let first = iter.next().unwrap();
iter.fold(first, |acc, s| acc.intersection(&s).copied().collect())
match done_neighbor_sets.split_first() {
None => BTreeSet::new(),
Some((first, rest)) => rest.iter().fold((*first).clone(), |acc, s| {
acc.intersection(s).copied().collect()
}),
}
};

let prev_objects = working.get(&node_id).cloned().unwrap_or_default();
// Temporarily remove the previous set out of the map so it can be safely
// borrowed and compared without a heavy deep clone.
let prev_objects = working.remove(&node_id).unwrap_or_default();
let mut merged: BTreeSet<usize> = prev_objects
.union(&neighbor_intersection)
.copied()
.collect();
reduce_maybe_optional_chains(&mut merged, registry);

working.insert(node_id, merged.clone());
traversal_state.insert(node_id, TraversalState::Done);

// Compare with previous value — can't just check size due to reduce_maybe_optional_chains
changed |= prev_objects != merged;

working.insert(node_id, merged);
traversal_state.insert(node_id, TraversalState::Done);

changed
}

Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@
//! creation, aliasing, mutation, freezing, and error conditions for each
//! instruction and terminal in the HIR.

use indexmap::{IndexMap, IndexSet};
use indexmap::IndexMap;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};

use react_compiler_diagnostics::CompilerDiagnostic;
Expand DownExpand Up@@ -69,7 +69,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Context,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ctx_place.identifier, value_id);
Expand All@@ -78,12 +78,12 @@ pub fn infer_mutation_aliasing_effects(
let param_kind: AbstractValue = if is_function_expression {
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
}
} else {
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(ValueReason::ReactiveFunctionArgument),
reason: ValueReasonSet::single(ValueReason::ReactiveFunctionArgument),
}
};

Expand All@@ -103,7 +103,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ref_place.identifier, value_id);
Expand DownExpand Up@@ -185,7 +185,7 @@ pub fn infer_mutation_aliasing_effects(
};

states_by_block.insert(block_id, incoming_state.clone());
let mut state = incoming_state.clone();
let mut state = incoming_state;

infer_block(&mut context, &mut state, block_id, func, env)?;

Expand DownExpand Up@@ -258,16 +258,88 @@ impl ValueId {
// AbstractValue
// =============================================================================

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Copy)]
struct AbstractValue {
kind: ValueKind,
reason: IndexSet<ValueReason, FxBuildHasher>,
reason: ValueReasonSet,
}

/// Capacity of [`ValueReasonSet`]. A set holds at most one of each `ValueReason`
/// variant, of which there are currently 12; the extra slots are headroom so
/// that adding variants upstream cannot overflow the set.
const VALUE_REASON_CAPACITY: usize = 16;

/// An insertion-ordered set of [`ValueReason`]s, stored inline.
///
/// This is a deliberate replacement for `IndexSet`, enabling insertion-order
/// memory while avoiding any heap allocation. At `AbstractValue`'s scale, this
/// has a dramatic impact on heap memory and wall time.
/// This takes advantage of the format of the data it's actually storing. A set
/// can hold at most one of each variant, so the members fit into a fixed inline
/// array. `ValueReason` is implemented as a single byte, so this struct is
/// ~18 bytes on the stack.
///
/// Insertion order is preserved deliberately: [`primary_reason`] returns the
/// first non-`Other` member, matching the iteration order of the `Set` used by
/// the TypeScript implementation this is ported from.
#[derive(Debug, Clone, Copy)]
struct ValueReasonSet {
/// Members in insertion order. Only the first `len` entries are meaningful.
members: [ValueReason; VALUE_REASON_CAPACITY],
len: u8,
}

fn hashset_of(r: ValueReason) -> IndexSet<ValueReason, FxBuildHasher> {
let mut s = IndexSet::default();
s.insert(r);
s
impl Default for ValueReasonSet {
fn default() -> Self {
ValueReasonSet {
members: [ValueReason::Other; VALUE_REASON_CAPACITY],
len: 0,
}
}
}

impl ValueReasonSet {
fn single(reason: ValueReason) -> Self {
let mut set = Self::default();
set.insert(reason);
set
}

fn contains(&self, reason: ValueReason) -> bool {
self.members[..self.len as usize].contains(&reason)
}

fn iter(&self) -> impl Iterator<Item = ValueReason> + '_ {
self.members[..self.len as usize].iter().copied()
}

/// Appends `reason` if not already present, preserving insertion order.
fn insert(&mut self, reason: ValueReason) {
if self.contains(reason) {
return;
}
debug_assert!(
(self.len as usize) < VALUE_REASON_CAPACITY,
"ValueReasonSet capacity must cover every ValueReason variant"
);
if (self.len as usize) < VALUE_REASON_CAPACITY {
self.members[self.len as usize] = reason;
self.len += 1;
}
}

/// True when every member of `other` is also a member of `self`.
fn is_superset_of(&self, other: &ValueReasonSet) -> bool {
other.iter().all(|reason| self.contains(reason))
}

/// Adds every member of `other`, keeping `self`'s existing order and
/// appending newcomers in `other`'s order — matching `IndexSet::insert`.
fn union_with(&mut self, other: &ValueReasonSet) {
for reason in other.iter() {
self.insert(reason);
}
}
}

// =============================================================================
Expand DownExpand Up@@ -315,7 +387,7 @@ impl InferenceState {
}
return AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
};
}
};
Expand All@@ -332,7 +404,7 @@ impl InferenceState {
}
merged_kind.unwrap_or_else(|| AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
})
}

Expand DownExpand Up@@ -360,7 +432,7 @@ impl InferenceState {
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
}
Expand DownExpand Up@@ -438,7 +510,7 @@ impl InferenceState {
value_id,
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
// Note: In TS, this also transitively freezes FunctionExpression captures
Expand DownExpand Up@@ -493,7 +565,7 @@ impl InferenceState {
if let Some(other_value) = other.values.get(id) {
let merged = merge_abstract_values(this_value, other_value);
if merged.kind != this_value.kind
|| !is_superset(&this_value.reason, &merged.reason)
|| !this_value.reason.is_superset_of(&merged.reason)
{
let nv = next_values.get_or_insert_with(|| self.values.clone());
nv.insert(*id, merged);
Expand DownExpand Up@@ -566,13 +638,6 @@ impl InferenceState {
}
}

fn is_superset(
a: &IndexSet<ValueReason, FxBuildHasher>,
b: &IndexSet<ValueReason, FxBuildHasher>,
) -> bool {
b.iter().all(|x| a.contains(x))
}

#[derive(Debug, Clone, Copy)]
enum MutateVariant {
Mutate,
Expand DownExpand Up@@ -738,13 +803,11 @@ fn hash_effect(effect: &AliasingEffect) -> String {

fn merge_abstract_values(a: &AbstractValue, b: &AbstractValue) -> AbstractValue {
let kind = merge_value_kinds(a.kind, b.kind);
if kind == a.kind && kind == b.kind && is_superset(&a.reason, &b.reason) {
if kind == a.kind && kind == b.kind && a.reason.is_superset_of(&b.reason) {
return a.clone();
}
let mut reason = a.reason.clone();
for r in &b.reason {
reason.insert(*r);
}
let mut reason = a.reason;
reason.union_with(&b.reason);
AbstractValue { kind, reason }
}

Expand DownExpand Up@@ -1233,7 +1296,7 @@ fn apply_signature(
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
state.define(instr.lvalue.identifier, vid);
Expand DownExpand Up@@ -1341,7 +1404,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1370,7 +1433,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1487,7 +1550,7 @@ fn apply_effect(
} else {
ValueKind::Frozen
},
reason: IndexSet::default(),
reason: ValueReasonSet::default(),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1599,7 +1662,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand All@@ -1615,7 +1678,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -3410,8 +3473,8 @@ fn compute_effects_for_aliasing_signature(
/// since the primary reason is always inserted first, this effectively
/// picks the most specific non-Other reason. We replicate this by
/// preferring any non-Other reason over Other.
fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason {
for &r in reasons {
fn primary_reason(reasons: &ValueReasonSet) -> ValueReason {
for r in reasons.iter() {
if r != ValueReason::Other {
return r;
}
Expand All@@ -3420,32 +3483,32 @@ fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason
}

fn get_write_error_reason(abstract_value: &AbstractValue) -> String {
if abstract_value.reason.contains(&ValueReason::Global) {
if abstract_value.reason.contains(ValueReason::Global) {
"Modifying a variable defined outside a component or hook is not allowed. Consider using an effect".to_string()
} else if abstract_value.reason.contains(&ValueReason::JsxCaptured) {
} else if abstract_value.reason.contains(ValueReason::JsxCaptured) {
"Modifying a value used previously in JSX is not allowed. Consider moving the modification before the JSX".to_string()
} else if abstract_value.reason.contains(&ValueReason::Context) {
} else if abstract_value.reason.contains(ValueReason::Context) {
"Modifying a value returned from 'useContext()' is not allowed.".to_string()
} else if abstract_value
.reason
.contains(&ValueReason::KnownReturnSignature)
.contains(ValueReason::KnownReturnSignature)
{
"Modifying a value returned from a function whose return value should not be mutated"
.to_string()
} else if abstract_value
.reason
.contains(&ValueReason::ReactiveFunctionArgument)
.contains(ValueReason::ReactiveFunctionArgument)
{
"Modifying component props or hook arguments is not allowed. Consider using a local variable instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::State) {
} else if abstract_value.reason.contains(ValueReason::State) {
"Modifying a value returned from 'useState()', which should not be modified directly. Use the setter function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::ReducerState) {
} else if abstract_value.reason.contains(ValueReason::ReducerState) {
"Modifying a value returned from 'useReducer()', which should not be modified directly. Use the dispatch function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::Effect) {
} else if abstract_value.reason.contains(ValueReason::Effect) {
"Modifying a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the modification before calling useEffect()".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookCaptured) {
} else if abstract_value.reason.contains(ValueReason::HookCaptured) {
"Modifying a value previously passed as an argument to a hook is not allowed. Consider moving the modification before calling the hook".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookReturn) {
} else if abstract_value.reason.contains(ValueReason::HookReturn) {
"Modifying a value returned from a hook is not allowed. Consider moving the modification into the hook where the value is constructed".to_string()
} else {
"This modifies a variable that React considers immutable".to_string()
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -1472,32 +1472,36 @@ fn recursively_propagate_non_null(
}

// Compute intersection of 'done' neighbors only (filter out 'active' = cycle nodes)
let done_neighbor_sets: Vec<BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n).cloned())
.collect();
let neighbor_intersection = {
let done_neighbor_sets: Vec<&BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n))
.collect();

let neighbor_intersection = if done_neighbor_sets.is_empty() {
BTreeSet::new()
} else {
let mut iter = done_neighbor_sets.into_iter();
let first = iter.next().unwrap();
iter.fold(first, |acc, s| acc.intersection(&s).copied().collect())
match done_neighbor_sets.split_first() {
None => BTreeSet::new(),
Some((first, rest)) => rest.iter().fold((*first).clone(), |acc, s| {
acc.intersection(s).copied().collect()
}),
}
};

let prev_objects = working.get(&node_id).cloned().unwrap_or_default();
// Temporarily remove the previous set out of the map so it can be safely
// borrowed and compared without a heavy deep clone.
let prev_objects = working.remove(&node_id).unwrap_or_default();
let mut merged: BTreeSet<usize> = prev_objects
.union(&neighbor_intersection)
.copied()
.collect();
reduce_maybe_optional_chains(&mut merged, registry);

working.insert(node_id, merged.clone());
traversal_state.insert(node_id, TraversalState::Done);

// Compare with previous value — can't just check size due to reduce_maybe_optional_chains
changed |= prev_objects != merged;

working.insert(node_id, merged);
traversal_state.insert(node_id, TraversalState::Done);

changed
}

Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
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
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@
//! creation, aliasing, mutation, freezing, and error conditions for each
//! instruction and terminal in the HIR.

use indexmap::{IndexMap, IndexSet};
use indexmap::IndexMap;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};

use react_compiler_diagnostics::CompilerDiagnostic;
Expand DownExpand Up@@ -69,7 +69,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Context,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ctx_place.identifier, value_id);
Expand All@@ -78,12 +78,12 @@ pub fn infer_mutation_aliasing_effects(
let param_kind: AbstractValue = if is_function_expression {
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
}
} else {
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(ValueReason::ReactiveFunctionArgument),
reason: ValueReasonSet::single(ValueReason::ReactiveFunctionArgument),
}
};

Expand All@@ -103,7 +103,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ref_place.identifier, value_id);
Expand DownExpand Up@@ -185,7 +185,7 @@ pub fn infer_mutation_aliasing_effects(
};

states_by_block.insert(block_id, incoming_state.clone());
let mut state = incoming_state.clone();
let mut state = incoming_state;

infer_block(&mut context, &mut state, block_id, func, env)?;

Expand DownExpand Up@@ -258,16 +258,88 @@ impl ValueId {
// AbstractValue
// =============================================================================

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Copy)]
struct AbstractValue {
kind: ValueKind,
reason: IndexSet<ValueReason, FxBuildHasher>,
reason: ValueReasonSet,
}

/// Capacity of [`ValueReasonSet`]. A set holds at most one of each `ValueReason`
/// variant, of which there are currently 12; the extra slots are headroom so
/// that adding variants upstream cannot overflow the set.
const VALUE_REASON_CAPACITY: usize = 16;

/// An insertion-ordered set of [`ValueReason`]s, stored inline.
///
/// This is a deliberate replacement for `IndexSet`, enabling insertion-order
/// memory while avoiding any heap allocation. At `AbstractValue`'s scale, this
/// has a dramatic impact on heap memory and wall time.
/// This takes advantage of the format of the data it's actually storing. A set
/// can hold at most one of each variant, so the members fit into a fixed inline
/// array. `ValueReason` is implemented as a single byte, so this struct is
/// ~18 bytes on the stack.
///
/// Insertion order is preserved deliberately: [`primary_reason`] returns the
/// first non-`Other` member, matching the iteration order of the `Set` used by
/// the TypeScript implementation this is ported from.
#[derive(Debug, Clone, Copy)]
struct ValueReasonSet {
/// Members in insertion order. Only the first `len` entries are meaningful.
members: [ValueReason; VALUE_REASON_CAPACITY],
len: u8,
}

fn hashset_of(r: ValueReason) -> IndexSet<ValueReason, FxBuildHasher> {
let mut s = IndexSet::default();
s.insert(r);
s
impl Default for ValueReasonSet {
fn default() -> Self {
ValueReasonSet {
members: [ValueReason::Other; VALUE_REASON_CAPACITY],
len: 0,
}
}
}

impl ValueReasonSet {
fn single(reason: ValueReason) -> Self {
let mut set = Self::default();
set.insert(reason);
set
}

fn contains(&self, reason: ValueReason) -> bool {
self.members[..self.len as usize].contains(&reason)
}

fn iter(&self) -> impl Iterator<Item = ValueReason> + '_ {
self.members[..self.len as usize].iter().copied()
}

/// Appends `reason` if not already present, preserving insertion order.
fn insert(&mut self, reason: ValueReason) {
if self.contains(reason) {
return;
}
debug_assert!(
(self.len as usize) < VALUE_REASON_CAPACITY,
"ValueReasonSet capacity must cover every ValueReason variant"
);
if (self.len as usize) < VALUE_REASON_CAPACITY {
self.members[self.len as usize] = reason;
self.len += 1;
}
}

/// True when every member of `other` is also a member of `self`.
fn is_superset_of(&self, other: &ValueReasonSet) -> bool {
other.iter().all(|reason| self.contains(reason))
}

/// Adds every member of `other`, keeping `self`'s existing order and
/// appending newcomers in `other`'s order — matching `IndexSet::insert`.
fn union_with(&mut self, other: &ValueReasonSet) {
for reason in other.iter() {
self.insert(reason);
}
}
}

// =============================================================================
Expand DownExpand Up@@ -315,7 +387,7 @@ impl InferenceState {
}
return AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
};
}
};
Expand All@@ -332,7 +404,7 @@ impl InferenceState {
}
merged_kind.unwrap_or_else(|| AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
})
}

Expand DownExpand Up@@ -360,7 +432,7 @@ impl InferenceState {
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
}
Expand DownExpand Up@@ -438,7 +510,7 @@ impl InferenceState {
value_id,
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
// Note: In TS, this also transitively freezes FunctionExpression captures
Expand DownExpand Up@@ -493,7 +565,7 @@ impl InferenceState {
if let Some(other_value) = other.values.get(id) {
let merged = merge_abstract_values(this_value, other_value);
if merged.kind != this_value.kind
|| !is_superset(&this_value.reason, &merged.reason)
|| !this_value.reason.is_superset_of(&merged.reason)
{
let nv = next_values.get_or_insert_with(|| self.values.clone());
nv.insert(*id, merged);
Expand DownExpand Up@@ -566,13 +638,6 @@ impl InferenceState {
}
}

fn is_superset(
a: &IndexSet<ValueReason, FxBuildHasher>,
b: &IndexSet<ValueReason, FxBuildHasher>,
) -> bool {
b.iter().all(|x| a.contains(x))
}

#[derive(Debug, Clone, Copy)]
enum MutateVariant {
Mutate,
Expand DownExpand Up@@ -738,13 +803,11 @@ fn hash_effect(effect: &AliasingEffect) -> String {

fn merge_abstract_values(a: &AbstractValue, b: &AbstractValue) -> AbstractValue {
let kind = merge_value_kinds(a.kind, b.kind);
if kind == a.kind && kind == b.kind && is_superset(&a.reason, &b.reason) {
if kind == a.kind && kind == b.kind && a.reason.is_superset_of(&b.reason) {
return a.clone();
}
let mut reason = a.reason.clone();
for r in &b.reason {
reason.insert(*r);
}
let mut reason = a.reason;
reason.union_with(&b.reason);
AbstractValue { kind, reason }
}

Expand DownExpand Up@@ -1233,7 +1296,7 @@ fn apply_signature(
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
state.define(instr.lvalue.identifier, vid);
Expand DownExpand Up@@ -1341,7 +1404,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1370,7 +1433,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1487,7 +1550,7 @@ fn apply_effect(
} else {
ValueKind::Frozen
},
reason: IndexSet::default(),
reason: ValueReasonSet::default(),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1599,7 +1662,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand All@@ -1615,7 +1678,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -3410,8 +3473,8 @@ fn compute_effects_for_aliasing_signature(
/// since the primary reason is always inserted first, this effectively
/// picks the most specific non-Other reason. We replicate this by
/// preferring any non-Other reason over Other.
fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason {
for &r in reasons {
fn primary_reason(reasons: &ValueReasonSet) -> ValueReason {
for r in reasons.iter() {
if r != ValueReason::Other {
return r;
}
Expand All@@ -3420,32 +3483,32 @@ fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason
}

fn get_write_error_reason(abstract_value: &AbstractValue) -> String {
if abstract_value.reason.contains(&ValueReason::Global) {
if abstract_value.reason.contains(ValueReason::Global) {
"Modifying a variable defined outside a component or hook is not allowed. Consider using an effect".to_string()
} else if abstract_value.reason.contains(&ValueReason::JsxCaptured) {
} else if abstract_value.reason.contains(ValueReason::JsxCaptured) {
"Modifying a value used previously in JSX is not allowed. Consider moving the modification before the JSX".to_string()
} else if abstract_value.reason.contains(&ValueReason::Context) {
} else if abstract_value.reason.contains(ValueReason::Context) {
"Modifying a value returned from 'useContext()' is not allowed.".to_string()
} else if abstract_value
.reason
.contains(&ValueReason::KnownReturnSignature)
.contains(ValueReason::KnownReturnSignature)
{
"Modifying a value returned from a function whose return value should not be mutated"
.to_string()
} else if abstract_value
.reason
.contains(&ValueReason::ReactiveFunctionArgument)
.contains(ValueReason::ReactiveFunctionArgument)
{
"Modifying component props or hook arguments is not allowed. Consider using a local variable instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::State) {
} else if abstract_value.reason.contains(ValueReason::State) {
"Modifying a value returned from 'useState()', which should not be modified directly. Use the setter function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::ReducerState) {
} else if abstract_value.reason.contains(ValueReason::ReducerState) {
"Modifying a value returned from 'useReducer()', which should not be modified directly. Use the dispatch function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::Effect) {
} else if abstract_value.reason.contains(ValueReason::Effect) {
"Modifying a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the modification before calling useEffect()".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookCaptured) {
} else if abstract_value.reason.contains(ValueReason::HookCaptured) {
"Modifying a value previously passed as an argument to a hook is not allowed. Consider moving the modification before calling the hook".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookReturn) {
} else if abstract_value.reason.contains(ValueReason::HookReturn) {
"Modifying a value returned from a hook is not allowed. Consider moving the modification into the hook where the value is constructed".to_string()
} else {
"This modifies a variable that React considers immutable".to_string()
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -1472,32 +1472,36 @@ fn recursively_propagate_non_null(
}

// Compute intersection of 'done' neighbors only (filter out 'active' = cycle nodes)
let done_neighbor_sets: Vec<BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n).cloned())
.collect();
let neighbor_intersection = {
let done_neighbor_sets: Vec<&BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n))
.collect();

let neighbor_intersection = if done_neighbor_sets.is_empty() {
BTreeSet::new()
} else {
let mut iter = done_neighbor_sets.into_iter();
let first = iter.next().unwrap();
iter.fold(first, |acc, s| acc.intersection(&s).copied().collect())
match done_neighbor_sets.split_first() {
None => BTreeSet::new(),
Some((first, rest)) => rest.iter().fold((*first).clone(), |acc, s| {
acc.intersection(s).copied().collect()
}),
}
};

let prev_objects = working.get(&node_id).cloned().unwrap_or_default();
// Temporarily remove the previous set out of the map so it can be safely
// borrowed and compared without a heavy deep clone.
let prev_objects = working.remove(&node_id).unwrap_or_default();
let mut merged: BTreeSet<usize> = prev_objects
.union(&neighbor_intersection)
.copied()
.collect();
reduce_maybe_optional_chains(&mut merged, registry);

working.insert(node_id, merged.clone());
traversal_state.insert(node_id, TraversalState::Done);

// Compare with previous value — can't just check size due to reduce_maybe_optional_chains
changed |= prev_objects != merged;

working.insert(node_id, merged);
traversal_state.insert(node_id, TraversalState::Done);

changed
}

Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@
//! creation, aliasing, mutation, freezing, and error conditions for each
//! instruction and terminal in the HIR.

use indexmap::{IndexMap, IndexSet};
use indexmap::IndexMap;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};

use react_compiler_diagnostics::CompilerDiagnostic;
Expand DownExpand Up@@ -69,7 +69,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Context,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ctx_place.identifier, value_id);
Expand All@@ -78,12 +78,12 @@ pub fn infer_mutation_aliasing_effects(
let param_kind: AbstractValue = if is_function_expression {
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
}
} else {
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(ValueReason::ReactiveFunctionArgument),
reason: ValueReasonSet::single(ValueReason::ReactiveFunctionArgument),
}
};

Expand All@@ -103,7 +103,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ref_place.identifier, value_id);
Expand DownExpand Up@@ -185,7 +185,7 @@ pub fn infer_mutation_aliasing_effects(
};

states_by_block.insert(block_id, incoming_state.clone());
let mut state = incoming_state.clone();
let mut state = incoming_state;

infer_block(&mut context, &mut state, block_id, func, env)?;

Expand DownExpand Up@@ -258,16 +258,88 @@ impl ValueId {
// AbstractValue
// =============================================================================

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Copy)]
struct AbstractValue {
kind: ValueKind,
reason: IndexSet<ValueReason, FxBuildHasher>,
reason: ValueReasonSet,
}

/// Capacity of [`ValueReasonSet`]. A set holds at most one of each `ValueReason`
/// variant, of which there are currently 12; the extra slots are headroom so
/// that adding variants upstream cannot overflow the set.
const VALUE_REASON_CAPACITY: usize = 16;

/// An insertion-ordered set of [`ValueReason`]s, stored inline.
///
/// This is a deliberate replacement for `IndexSet`, enabling insertion-order
/// memory while avoiding any heap allocation. At `AbstractValue`'s scale, this
/// has a dramatic impact on heap memory and wall time.
/// This takes advantage of the format of the data it's actually storing. A set
/// can hold at most one of each variant, so the members fit into a fixed inline
/// array. `ValueReason` is implemented as a single byte, so this struct is
/// ~18 bytes on the stack.
///
/// Insertion order is preserved deliberately: [`primary_reason`] returns the
/// first non-`Other` member, matching the iteration order of the `Set` used by
/// the TypeScript implementation this is ported from.
#[derive(Debug, Clone, Copy)]
struct ValueReasonSet {
/// Members in insertion order. Only the first `len` entries are meaningful.
members: [ValueReason; VALUE_REASON_CAPACITY],
len: u8,
}

fn hashset_of(r: ValueReason) -> IndexSet<ValueReason, FxBuildHasher> {
let mut s = IndexSet::default();
s.insert(r);
s
impl Default for ValueReasonSet {
fn default() -> Self {
ValueReasonSet {
members: [ValueReason::Other; VALUE_REASON_CAPACITY],
len: 0,
}
}
}

impl ValueReasonSet {
fn single(reason: ValueReason) -> Self {
let mut set = Self::default();
set.insert(reason);
set
}

fn contains(&self, reason: ValueReason) -> bool {
self.members[..self.len as usize].contains(&reason)
}

fn iter(&self) -> impl Iterator<Item = ValueReason> + '_ {
self.members[..self.len as usize].iter().copied()
}

/// Appends `reason` if not already present, preserving insertion order.
fn insert(&mut self, reason: ValueReason) {
if self.contains(reason) {
return;
}
debug_assert!(
(self.len as usize) < VALUE_REASON_CAPACITY,
"ValueReasonSet capacity must cover every ValueReason variant"
);
if (self.len as usize) < VALUE_REASON_CAPACITY {
self.members[self.len as usize] = reason;
self.len += 1;
}
}

/// True when every member of `other` is also a member of `self`.
fn is_superset_of(&self, other: &ValueReasonSet) -> bool {
other.iter().all(|reason| self.contains(reason))
}

/// Adds every member of `other`, keeping `self`'s existing order and
/// appending newcomers in `other`'s order — matching `IndexSet::insert`.
fn union_with(&mut self, other: &ValueReasonSet) {
for reason in other.iter() {
self.insert(reason);
}
}
}

// =============================================================================
Expand DownExpand Up@@ -315,7 +387,7 @@ impl InferenceState {
}
return AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
};
}
};
Expand All@@ -332,7 +404,7 @@ impl InferenceState {
}
merged_kind.unwrap_or_else(|| AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
})
}

Expand DownExpand Up@@ -360,7 +432,7 @@ impl InferenceState {
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
}
Expand DownExpand Up@@ -438,7 +510,7 @@ impl InferenceState {
value_id,
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
// Note: In TS, this also transitively freezes FunctionExpression captures
Expand DownExpand Up@@ -493,7 +565,7 @@ impl InferenceState {
if let Some(other_value) = other.values.get(id) {
let merged = merge_abstract_values(this_value, other_value);
if merged.kind != this_value.kind
|| !is_superset(&this_value.reason, &merged.reason)
|| !this_value.reason.is_superset_of(&merged.reason)
{
let nv = next_values.get_or_insert_with(|| self.values.clone());
nv.insert(*id, merged);
Expand DownExpand Up@@ -566,13 +638,6 @@ impl InferenceState {
}
}

fn is_superset(
a: &IndexSet<ValueReason, FxBuildHasher>,
b: &IndexSet<ValueReason, FxBuildHasher>,
) -> bool {
b.iter().all(|x| a.contains(x))
}

#[derive(Debug, Clone, Copy)]
enum MutateVariant {
Mutate,
Expand DownExpand Up@@ -738,13 +803,11 @@ fn hash_effect(effect: &AliasingEffect) -> String {

fn merge_abstract_values(a: &AbstractValue, b: &AbstractValue) -> AbstractValue {
let kind = merge_value_kinds(a.kind, b.kind);
if kind == a.kind && kind == b.kind && is_superset(&a.reason, &b.reason) {
if kind == a.kind && kind == b.kind && a.reason.is_superset_of(&b.reason) {
return a.clone();
}
let mut reason = a.reason.clone();
for r in &b.reason {
reason.insert(*r);
}
let mut reason = a.reason;
reason.union_with(&b.reason);
AbstractValue { kind, reason }
}

Expand DownExpand Up@@ -1233,7 +1296,7 @@ fn apply_signature(
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
state.define(instr.lvalue.identifier, vid);
Expand DownExpand Up@@ -1341,7 +1404,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1370,7 +1433,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1487,7 +1550,7 @@ fn apply_effect(
} else {
ValueKind::Frozen
},
reason: IndexSet::default(),
reason: ValueReasonSet::default(),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1599,7 +1662,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand All@@ -1615,7 +1678,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -3410,8 +3473,8 @@ fn compute_effects_for_aliasing_signature(
/// since the primary reason is always inserted first, this effectively
/// picks the most specific non-Other reason. We replicate this by
/// preferring any non-Other reason over Other.
fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason {
for &r in reasons {
fn primary_reason(reasons: &ValueReasonSet) -> ValueReason {
for r in reasons.iter() {
if r != ValueReason::Other {
return r;
}
Expand All@@ -3420,32 +3483,32 @@ fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason
}

fn get_write_error_reason(abstract_value: &AbstractValue) -> String {
if abstract_value.reason.contains(&ValueReason::Global) {
if abstract_value.reason.contains(ValueReason::Global) {
"Modifying a variable defined outside a component or hook is not allowed. Consider using an effect".to_string()
} else if abstract_value.reason.contains(&ValueReason::JsxCaptured) {
} else if abstract_value.reason.contains(ValueReason::JsxCaptured) {
"Modifying a value used previously in JSX is not allowed. Consider moving the modification before the JSX".to_string()
} else if abstract_value.reason.contains(&ValueReason::Context) {
} else if abstract_value.reason.contains(ValueReason::Context) {
"Modifying a value returned from 'useContext()' is not allowed.".to_string()
} else if abstract_value
.reason
.contains(&ValueReason::KnownReturnSignature)
.contains(ValueReason::KnownReturnSignature)
{
"Modifying a value returned from a function whose return value should not be mutated"
.to_string()
} else if abstract_value
.reason
.contains(&ValueReason::ReactiveFunctionArgument)
.contains(ValueReason::ReactiveFunctionArgument)
{
"Modifying component props or hook arguments is not allowed. Consider using a local variable instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::State) {
} else if abstract_value.reason.contains(ValueReason::State) {
"Modifying a value returned from 'useState()', which should not be modified directly. Use the setter function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::ReducerState) {
} else if abstract_value.reason.contains(ValueReason::ReducerState) {
"Modifying a value returned from 'useReducer()', which should not be modified directly. Use the dispatch function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::Effect) {
} else if abstract_value.reason.contains(ValueReason::Effect) {
"Modifying a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the modification before calling useEffect()".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookCaptured) {
} else if abstract_value.reason.contains(ValueReason::HookCaptured) {
"Modifying a value previously passed as an argument to a hook is not allowed. Consider moving the modification before calling the hook".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookReturn) {
} else if abstract_value.reason.contains(ValueReason::HookReturn) {
"Modifying a value returned from a hook is not allowed. Consider moving the modification into the hook where the value is constructed".to_string()
} else {
"This modifies a variable that React considers immutable".to_string()
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -1472,32 +1472,36 @@ fn recursively_propagate_non_null(
}

// Compute intersection of 'done' neighbors only (filter out 'active' = cycle nodes)
let done_neighbor_sets: Vec<BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n).cloned())
.collect();
let neighbor_intersection = {
let done_neighbor_sets: Vec<&BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n))
.collect();

let neighbor_intersection = if done_neighbor_sets.is_empty() {
BTreeSet::new()
} else {
let mut iter = done_neighbor_sets.into_iter();
let first = iter.next().unwrap();
iter.fold(first, |acc, s| acc.intersection(&s).copied().collect())
match done_neighbor_sets.split_first() {
None => BTreeSet::new(),
Some((first, rest)) => rest.iter().fold((*first).clone(), |acc, s| {
acc.intersection(s).copied().collect()
}),
}
};

let prev_objects = working.get(&node_id).cloned().unwrap_or_default();
// Temporarily remove the previous set out of the map so it can be safely
// borrowed and compared without a heavy deep clone.
let prev_objects = working.remove(&node_id).unwrap_or_default();
let mut merged: BTreeSet<usize> = prev_objects
.union(&neighbor_intersection)
.copied()
.collect();
reduce_maybe_optional_chains(&mut merged, registry);

working.insert(node_id, merged.clone());
traversal_state.insert(node_id, TraversalState::Done);

// Compare with previous value — can't just check size due to reduce_maybe_optional_chains
changed |= prev_objects != merged;

working.insert(node_id, merged);
traversal_state.insert(node_id, TraversalState::Done);

changed
}

Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@
//! creation, aliasing, mutation, freezing, and error conditions for each
//! instruction and terminal in the HIR.

use indexmap::{IndexMap, IndexSet};
use indexmap::IndexMap;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};

use react_compiler_diagnostics::CompilerDiagnostic;
Expand DownExpand Up@@ -69,7 +69,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Context,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ctx_place.identifier, value_id);
Expand All@@ -78,12 +78,12 @@ pub fn infer_mutation_aliasing_effects(
let param_kind: AbstractValue = if is_function_expression {
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
}
} else {
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(ValueReason::ReactiveFunctionArgument),
reason: ValueReasonSet::single(ValueReason::ReactiveFunctionArgument),
}
};

Expand All@@ -103,7 +103,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ref_place.identifier, value_id);
Expand DownExpand Up@@ -185,7 +185,7 @@ pub fn infer_mutation_aliasing_effects(
};

states_by_block.insert(block_id, incoming_state.clone());
let mut state = incoming_state.clone();
let mut state = incoming_state;

infer_block(&mut context, &mut state, block_id, func, env)?;

Expand DownExpand Up@@ -258,16 +258,88 @@ impl ValueId {
// AbstractValue
// =============================================================================

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Copy)]
struct AbstractValue {
kind: ValueKind,
reason: IndexSet<ValueReason, FxBuildHasher>,
reason: ValueReasonSet,
}

/// Capacity of [`ValueReasonSet`]. A set holds at most one of each `ValueReason`
/// variant, of which there are currently 12; the extra slots are headroom so
/// that adding variants upstream cannot overflow the set.
const VALUE_REASON_CAPACITY: usize = 16;

/// An insertion-ordered set of [`ValueReason`]s, stored inline.
///
/// This is a deliberate replacement for `IndexSet`, enabling insertion-order
/// memory while avoiding any heap allocation. At `AbstractValue`'s scale, this
/// has a dramatic impact on heap memory and wall time.
/// This takes advantage of the format of the data it's actually storing. A set
/// can hold at most one of each variant, so the members fit into a fixed inline
/// array. `ValueReason` is implemented as a single byte, so this struct is
/// ~18 bytes on the stack.
///
/// Insertion order is preserved deliberately: [`primary_reason`] returns the
/// first non-`Other` member, matching the iteration order of the `Set` used by
/// the TypeScript implementation this is ported from.
#[derive(Debug, Clone, Copy)]
struct ValueReasonSet {
/// Members in insertion order. Only the first `len` entries are meaningful.
members: [ValueReason; VALUE_REASON_CAPACITY],
len: u8,
}

fn hashset_of(r: ValueReason) -> IndexSet<ValueReason, FxBuildHasher> {
let mut s = IndexSet::default();
s.insert(r);
s
impl Default for ValueReasonSet {
fn default() -> Self {
ValueReasonSet {
members: [ValueReason::Other; VALUE_REASON_CAPACITY],
len: 0,
}
}
}

impl ValueReasonSet {
fn single(reason: ValueReason) -> Self {
let mut set = Self::default();
set.insert(reason);
set
}

fn contains(&self, reason: ValueReason) -> bool {
self.members[..self.len as usize].contains(&reason)
}

fn iter(&self) -> impl Iterator<Item = ValueReason> + '_ {
self.members[..self.len as usize].iter().copied()
}

/// Appends `reason` if not already present, preserving insertion order.
fn insert(&mut self, reason: ValueReason) {
if self.contains(reason) {
return;
}
debug_assert!(
(self.len as usize) < VALUE_REASON_CAPACITY,
"ValueReasonSet capacity must cover every ValueReason variant"
);
if (self.len as usize) < VALUE_REASON_CAPACITY {
self.members[self.len as usize] = reason;
self.len += 1;
}
}

/// True when every member of `other` is also a member of `self`.
fn is_superset_of(&self, other: &ValueReasonSet) -> bool {
other.iter().all(|reason| self.contains(reason))
}

/// Adds every member of `other`, keeping `self`'s existing order and
/// appending newcomers in `other`'s order — matching `IndexSet::insert`.
fn union_with(&mut self, other: &ValueReasonSet) {
for reason in other.iter() {
self.insert(reason);
}
}
}

// =============================================================================
Expand DownExpand Up@@ -315,7 +387,7 @@ impl InferenceState {
}
return AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
};
}
};
Expand All@@ -332,7 +404,7 @@ impl InferenceState {
}
merged_kind.unwrap_or_else(|| AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
})
}

Expand DownExpand Up@@ -360,7 +432,7 @@ impl InferenceState {
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
}
Expand DownExpand Up@@ -438,7 +510,7 @@ impl InferenceState {
value_id,
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
// Note: In TS, this also transitively freezes FunctionExpression captures
Expand DownExpand Up@@ -493,7 +565,7 @@ impl InferenceState {
if let Some(other_value) = other.values.get(id) {
let merged = merge_abstract_values(this_value, other_value);
if merged.kind != this_value.kind
|| !is_superset(&this_value.reason, &merged.reason)
|| !this_value.reason.is_superset_of(&merged.reason)
{
let nv = next_values.get_or_insert_with(|| self.values.clone());
nv.insert(*id, merged);
Expand DownExpand Up@@ -566,13 +638,6 @@ impl InferenceState {
}
}

fn is_superset(
a: &IndexSet<ValueReason, FxBuildHasher>,
b: &IndexSet<ValueReason, FxBuildHasher>,
) -> bool {
b.iter().all(|x| a.contains(x))
}

#[derive(Debug, Clone, Copy)]
enum MutateVariant {
Mutate,
Expand DownExpand Up@@ -738,13 +803,11 @@ fn hash_effect(effect: &AliasingEffect) -> String {

fn merge_abstract_values(a: &AbstractValue, b: &AbstractValue) -> AbstractValue {
let kind = merge_value_kinds(a.kind, b.kind);
if kind == a.kind && kind == b.kind && is_superset(&a.reason, &b.reason) {
if kind == a.kind && kind == b.kind && a.reason.is_superset_of(&b.reason) {
return a.clone();
}
let mut reason = a.reason.clone();
for r in &b.reason {
reason.insert(*r);
}
let mut reason = a.reason;
reason.union_with(&b.reason);
AbstractValue { kind, reason }
}

Expand DownExpand Up@@ -1233,7 +1296,7 @@ fn apply_signature(
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
state.define(instr.lvalue.identifier, vid);
Expand DownExpand Up@@ -1341,7 +1404,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1370,7 +1433,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1487,7 +1550,7 @@ fn apply_effect(
} else {
ValueKind::Frozen
},
reason: IndexSet::default(),
reason: ValueReasonSet::default(),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1599,7 +1662,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand All@@ -1615,7 +1678,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -3410,8 +3473,8 @@ fn compute_effects_for_aliasing_signature(
/// since the primary reason is always inserted first, this effectively
/// picks the most specific non-Other reason. We replicate this by
/// preferring any non-Other reason over Other.
fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason {
for &r in reasons {
fn primary_reason(reasons: &ValueReasonSet) -> ValueReason {
for r in reasons.iter() {
if r != ValueReason::Other {
return r;
}
Expand All@@ -3420,32 +3483,32 @@ fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason
}

fn get_write_error_reason(abstract_value: &AbstractValue) -> String {
if abstract_value.reason.contains(&ValueReason::Global) {
if abstract_value.reason.contains(ValueReason::Global) {
"Modifying a variable defined outside a component or hook is not allowed. Consider using an effect".to_string()
} else if abstract_value.reason.contains(&ValueReason::JsxCaptured) {
} else if abstract_value.reason.contains(ValueReason::JsxCaptured) {
"Modifying a value used previously in JSX is not allowed. Consider moving the modification before the JSX".to_string()
} else if abstract_value.reason.contains(&ValueReason::Context) {
} else if abstract_value.reason.contains(ValueReason::Context) {
"Modifying a value returned from 'useContext()' is not allowed.".to_string()
} else if abstract_value
.reason
.contains(&ValueReason::KnownReturnSignature)
.contains(ValueReason::KnownReturnSignature)
{
"Modifying a value returned from a function whose return value should not be mutated"
.to_string()
} else if abstract_value
.reason
.contains(&ValueReason::ReactiveFunctionArgument)
.contains(ValueReason::ReactiveFunctionArgument)
{
"Modifying component props or hook arguments is not allowed. Consider using a local variable instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::State) {
} else if abstract_value.reason.contains(ValueReason::State) {
"Modifying a value returned from 'useState()', which should not be modified directly. Use the setter function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::ReducerState) {
} else if abstract_value.reason.contains(ValueReason::ReducerState) {
"Modifying a value returned from 'useReducer()', which should not be modified directly. Use the dispatch function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::Effect) {
} else if abstract_value.reason.contains(ValueReason::Effect) {
"Modifying a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the modification before calling useEffect()".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookCaptured) {
} else if abstract_value.reason.contains(ValueReason::HookCaptured) {
"Modifying a value previously passed as an argument to a hook is not allowed. Consider moving the modification before calling the hook".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookReturn) {
} else if abstract_value.reason.contains(ValueReason::HookReturn) {
"Modifying a value returned from a hook is not allowed. Consider moving the modification into the hook where the value is constructed".to_string()
} else {
"This modifies a variable that React considers immutable".to_string()
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -1472,32 +1472,36 @@ fn recursively_propagate_non_null(
}

// Compute intersection of 'done' neighbors only (filter out 'active' = cycle nodes)
let done_neighbor_sets: Vec<BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n).cloned())
.collect();
let neighbor_intersection = {
let done_neighbor_sets: Vec<&BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n))
.collect();

let neighbor_intersection = if done_neighbor_sets.is_empty() {
BTreeSet::new()
} else {
let mut iter = done_neighbor_sets.into_iter();
let first = iter.next().unwrap();
iter.fold(first, |acc, s| acc.intersection(&s).copied().collect())
match done_neighbor_sets.split_first() {
None => BTreeSet::new(),
Some((first, rest)) => rest.iter().fold((*first).clone(), |acc, s| {
acc.intersection(s).copied().collect()
}),
}
};

let prev_objects = working.get(&node_id).cloned().unwrap_or_default();
// Temporarily remove the previous set out of the map so it can be safely
// borrowed and compared without a heavy deep clone.
let prev_objects = working.remove(&node_id).unwrap_or_default();
let mut merged: BTreeSet<usize> = prev_objects
.union(&neighbor_intersection)
.copied()
.collect();
reduce_maybe_optional_chains(&mut merged, registry);

working.insert(node_id, merged.clone());
traversal_state.insert(node_id, TraversalState::Done);

// Compare with previous value — can't just check size due to reduce_maybe_optional_chains
changed |= prev_objects != merged;

working.insert(node_id, merged);
traversal_state.insert(node_id, TraversalState::Done);

changed
}

Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
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
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,7 +11,7 @@
//! creation, aliasing, mutation, freezing, and error conditions for each
//! instruction and terminal in the HIR.

use indexmap::{IndexMap, IndexSet};
use indexmap::IndexMap;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};

use react_compiler_diagnostics::CompilerDiagnostic;
Expand DownExpand Up@@ -69,7 +69,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Context,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ctx_place.identifier, value_id);
Expand All@@ -78,12 +78,12 @@ pub fn infer_mutation_aliasing_effects(
let param_kind: AbstractValue = if is_function_expression {
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
}
} else {
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(ValueReason::ReactiveFunctionArgument),
reason: ValueReasonSet::single(ValueReason::ReactiveFunctionArgument),
}
};

Expand All@@ -103,7 +103,7 @@ pub fn infer_mutation_aliasing_effects(
value_id,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
initial_state.define(ref_place.identifier, value_id);
Expand DownExpand Up@@ -185,7 +185,7 @@ pub fn infer_mutation_aliasing_effects(
};

states_by_block.insert(block_id, incoming_state.clone());
let mut state = incoming_state.clone();
let mut state = incoming_state;

infer_block(&mut context, &mut state, block_id, func, env)?;

Expand DownExpand Up@@ -258,16 +258,88 @@ impl ValueId {
// AbstractValue
// =============================================================================

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Copy)]
struct AbstractValue {
kind: ValueKind,
reason: IndexSet<ValueReason, FxBuildHasher>,
reason: ValueReasonSet,
}

/// Capacity of [`ValueReasonSet`]. A set holds at most one of each `ValueReason`
/// variant, of which there are currently 12; the extra slots are headroom so
/// that adding variants upstream cannot overflow the set.
const VALUE_REASON_CAPACITY: usize = 16;

/// An insertion-ordered set of [`ValueReason`]s, stored inline.
///
/// This is a deliberate replacement for `IndexSet`, enabling insertion-order
/// memory while avoiding any heap allocation. At `AbstractValue`'s scale, this
/// has a dramatic impact on heap memory and wall time.
/// This takes advantage of the format of the data it's actually storing. A set
/// can hold at most one of each variant, so the members fit into a fixed inline
/// array. `ValueReason` is implemented as a single byte, so this struct is
/// ~18 bytes on the stack.
///
/// Insertion order is preserved deliberately: [`primary_reason`] returns the
/// first non-`Other` member, matching the iteration order of the `Set` used by
/// the TypeScript implementation this is ported from.
#[derive(Debug, Clone, Copy)]
struct ValueReasonSet {
/// Members in insertion order. Only the first `len` entries are meaningful.
members: [ValueReason; VALUE_REASON_CAPACITY],
len: u8,
}

fn hashset_of(r: ValueReason) -> IndexSet<ValueReason, FxBuildHasher> {
let mut s = IndexSet::default();
s.insert(r);
s
impl Default for ValueReasonSet {
fn default() -> Self {
ValueReasonSet {
members: [ValueReason::Other; VALUE_REASON_CAPACITY],
len: 0,
}
}
}

impl ValueReasonSet {
fn single(reason: ValueReason) -> Self {
let mut set = Self::default();
set.insert(reason);
set
}

fn contains(&self, reason: ValueReason) -> bool {
self.members[..self.len as usize].contains(&reason)
}

fn iter(&self) -> impl Iterator<Item = ValueReason> + '_ {
self.members[..self.len as usize].iter().copied()
}

/// Appends `reason` if not already present, preserving insertion order.
fn insert(&mut self, reason: ValueReason) {
if self.contains(reason) {
return;
}
debug_assert!(
(self.len as usize) < VALUE_REASON_CAPACITY,
"ValueReasonSet capacity must cover every ValueReason variant"
);
if (self.len as usize) < VALUE_REASON_CAPACITY {
self.members[self.len as usize] = reason;
self.len += 1;
}
}

/// True when every member of `other` is also a member of `self`.
fn is_superset_of(&self, other: &ValueReasonSet) -> bool {
other.iter().all(|reason| self.contains(reason))
}

/// Adds every member of `other`, keeping `self`'s existing order and
/// appending newcomers in `other`'s order — matching `IndexSet::insert`.
fn union_with(&mut self, other: &ValueReasonSet) {
for reason in other.iter() {
self.insert(reason);
}
}
}

// =============================================================================
Expand DownExpand Up@@ -315,7 +387,7 @@ impl InferenceState {
}
return AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
};
}
};
Expand All@@ -332,7 +404,7 @@ impl InferenceState {
}
merged_kind.unwrap_or_else(|| AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
})
}

Expand DownExpand Up@@ -360,7 +432,7 @@ impl InferenceState {
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
}
Expand DownExpand Up@@ -438,7 +510,7 @@ impl InferenceState {
value_id,
AbstractValue {
kind: ValueKind::Frozen,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
// Note: In TS, this also transitively freezes FunctionExpression captures
Expand DownExpand Up@@ -493,7 +565,7 @@ impl InferenceState {
if let Some(other_value) = other.values.get(id) {
let merged = merge_abstract_values(this_value, other_value);
if merged.kind != this_value.kind
|| !is_superset(&this_value.reason, &merged.reason)
|| !this_value.reason.is_superset_of(&merged.reason)
{
let nv = next_values.get_or_insert_with(|| self.values.clone());
nv.insert(*id, merged);
Expand DownExpand Up@@ -566,13 +638,6 @@ impl InferenceState {
}
}

fn is_superset(
a: &IndexSet<ValueReason, FxBuildHasher>,
b: &IndexSet<ValueReason, FxBuildHasher>,
) -> bool {
b.iter().all(|x| a.contains(x))
}

#[derive(Debug, Clone, Copy)]
enum MutateVariant {
Mutate,
Expand DownExpand Up@@ -738,13 +803,11 @@ fn hash_effect(effect: &AliasingEffect) -> String {

fn merge_abstract_values(a: &AbstractValue, b: &AbstractValue) -> AbstractValue {
let kind = merge_value_kinds(a.kind, b.kind);
if kind == a.kind && kind == b.kind && is_superset(&a.reason, &b.reason) {
if kind == a.kind && kind == b.kind && a.reason.is_superset_of(&b.reason) {
return a.clone();
}
let mut reason = a.reason.clone();
for r in &b.reason {
reason.insert(*r);
}
let mut reason = a.reason;
reason.union_with(&b.reason);
AbstractValue { kind, reason }
}

Expand DownExpand Up@@ -1233,7 +1296,7 @@ fn apply_signature(
vid,
AbstractValue {
kind: ValueKind::Mutable,
reason: hashset_of(ValueReason::Other),
reason: ValueReasonSet::single(ValueReason::Other),
},
);
state.define(instr.lvalue.identifier, vid);
Expand DownExpand Up@@ -1341,7 +1404,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind,
reason: hashset_of(reason),
reason: ValueReasonSet::single(reason),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1370,7 +1433,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1487,7 +1550,7 @@ fn apply_effect(
} else {
ValueKind::Frozen
},
reason: IndexSet::default(),
reason: ValueReasonSet::default(),
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -1599,7 +1662,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand All@@ -1615,7 +1678,7 @@ fn apply_effect(
value_id,
AbstractValue {
kind: from_value.kind,
reason: from_value.reason.clone(),
reason: from_value.reason,
},
);
state.define(into.identifier, value_id);
Expand DownExpand Up@@ -3410,8 +3473,8 @@ fn compute_effects_for_aliasing_signature(
/// since the primary reason is always inserted first, this effectively
/// picks the most specific non-Other reason. We replicate this by
/// preferring any non-Other reason over Other.
fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason {
for &r in reasons {
fn primary_reason(reasons: &ValueReasonSet) -> ValueReason {
for r in reasons.iter() {
if r != ValueReason::Other {
return r;
}
Expand All@@ -3420,32 +3483,32 @@ fn primary_reason(reasons: &IndexSet<ValueReason, FxBuildHasher>) -> ValueReason
}

fn get_write_error_reason(abstract_value: &AbstractValue) -> String {
if abstract_value.reason.contains(&ValueReason::Global) {
if abstract_value.reason.contains(ValueReason::Global) {
"Modifying a variable defined outside a component or hook is not allowed. Consider using an effect".to_string()
} else if abstract_value.reason.contains(&ValueReason::JsxCaptured) {
} else if abstract_value.reason.contains(ValueReason::JsxCaptured) {
"Modifying a value used previously in JSX is not allowed. Consider moving the modification before the JSX".to_string()
} else if abstract_value.reason.contains(&ValueReason::Context) {
} else if abstract_value.reason.contains(ValueReason::Context) {
"Modifying a value returned from 'useContext()' is not allowed.".to_string()
} else if abstract_value
.reason
.contains(&ValueReason::KnownReturnSignature)
.contains(ValueReason::KnownReturnSignature)
{
"Modifying a value returned from a function whose return value should not be mutated"
.to_string()
} else if abstract_value
.reason
.contains(&ValueReason::ReactiveFunctionArgument)
.contains(ValueReason::ReactiveFunctionArgument)
{
"Modifying component props or hook arguments is not allowed. Consider using a local variable instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::State) {
} else if abstract_value.reason.contains(ValueReason::State) {
"Modifying a value returned from 'useState()', which should not be modified directly. Use the setter function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::ReducerState) {
} else if abstract_value.reason.contains(ValueReason::ReducerState) {
"Modifying a value returned from 'useReducer()', which should not be modified directly. Use the dispatch function to update instead".to_string()
} else if abstract_value.reason.contains(&ValueReason::Effect) {
} else if abstract_value.reason.contains(ValueReason::Effect) {
"Modifying a value used previously in an effect function or as an effect dependency is not allowed. Consider moving the modification before calling useEffect()".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookCaptured) {
} else if abstract_value.reason.contains(ValueReason::HookCaptured) {
"Modifying a value previously passed as an argument to a hook is not allowed. Consider moving the modification before calling the hook".to_string()
} else if abstract_value.reason.contains(&ValueReason::HookReturn) {
} else if abstract_value.reason.contains(ValueReason::HookReturn) {
"Modifying a value returned from a hook is not allowed. Consider moving the modification into the hook where the value is constructed".to_string()
} else {
"This modifies a variable that React considers immutable".to_string()
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -1472,32 +1472,36 @@ fn recursively_propagate_non_null(
}

// Compute intersection of 'done' neighbors only (filter out 'active' = cycle nodes)
let done_neighbor_sets: Vec<BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n).cloned())
.collect();
let neighbor_intersection = {
let done_neighbor_sets: Vec<&BTreeSet<usize>> = neighbors
.iter()
.filter(|n| traversal_state.get(n) == Some(&TraversalState::Done))
.filter_map(|n| working.get(n))
.collect();

let neighbor_intersection = if done_neighbor_sets.is_empty() {
BTreeSet::new()
} else {
let mut iter = done_neighbor_sets.into_iter();
let first = iter.next().unwrap();
iter.fold(first, |acc, s| acc.intersection(&s).copied().collect())
match done_neighbor_sets.split_first() {
None => BTreeSet::new(),
Some((first, rest)) => rest.iter().fold((*first).clone(), |acc, s| {
acc.intersection(s).copied().collect()
}),
}
};

let prev_objects = working.get(&node_id).cloned().unwrap_or_default();
// Temporarily remove the previous set out of the map so it can be safely
// borrowed and compared without a heavy deep clone.
let prev_objects = working.remove(&node_id).unwrap_or_default();
let mut merged: BTreeSet<usize> = prev_objects
.union(&neighbor_intersection)
.copied()
.collect();
reduce_maybe_optional_chains(&mut merged, registry);

working.insert(node_id, merged.clone());
traversal_state.insert(node_id, TraversalState::Done);

// Compare with previous value — can't just check size due to reduce_maybe_optional_chains
changed |= prev_objects != merged;

working.insert(node_id, merged);
traversal_state.insert(node_id, TraversalState::Done);

changed
}

Expand Down
Loading
Loading