Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Move the empty and one-char strings to CommonStrings, and allow istr! to access them. #19465

Merged
merged 3 commits into from
Feb 9, 2025
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
20 changes: 18 additions & 2 deletions core/macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,10 @@ pub fn enum_trait_object(args: TokenStream, item: TokenStream) -> TokenStream {
/// istr!(context, "description");
/// // expands to:
/// HasStringContext::strings_ref(context).str_description;
///
/// istr!("A");
/// // expands to:
/// activation.context.strings.common().ascii_chars[65 /* 'A' */];
moulins marked this conversation as resolved.
Show resolved Hide resolved
/// ```
#[proc_macro]
pub fn atom(item: TokenStream) -> TokenStream {
Expand Down Expand Up @@ -231,9 +235,17 @@ fn atom_internal(
}

let input = parse_macro_input!(item as Input);
let string_ident = format_ident!("str_{}", input.str.value());

let atom = if let Some(context) = input.context {
let string = input.str.value();
let (string_ident, array_index) = if string.len() == 1 && string.is_ascii() {
// Special case: a single ASCII char.
let c = string.as_bytes()[0];
(format_ident!("ascii_chars"), Some(c as usize))
} else {
(format_ident!("str_{string}"), None)
};

let mut atom = if let Some(context) = input.context {
quote!(
crate::string::HasStringContext::strings_ref(#context).common().#string_ident
)
Expand All @@ -246,5 +258,9 @@ fn atom_internal(
)
};

if let Some(i) = array_index {
atom.extend(quote!([#i]));
}

transform(atom).into()
}
5 changes: 3 additions & 2 deletions core/src/avm1/activation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use crate::{avm_error, avm_warn};
use gc_arena::{Gc, GcCell, Mutation};
use indexmap::IndexMap;
use rand::Rng;
use ruffle_macros::istr;
use smallvec::SmallVec;
use std::borrow::Cow;
use std::cmp::min;
Expand Down Expand Up @@ -831,7 +832,7 @@ impl<'a, 'gc> Activation<'a, 'gc> {
let object = object_val.coerce_to_object(self);

let method_name = if method_name == Value::Undefined {
self.strings().empty()
istr!(self, "")
} else {
method_name.coerce_to_string(self)?
};
Expand Down Expand Up @@ -1717,7 +1718,7 @@ impl<'a, 'gc> Activation<'a, 'gc> {
let object = object_val.coerce_to_object(self);

let method_name = if method_name == Value::Undefined {
self.strings().empty()
istr!(self, "")
} else {
method_name.coerce_to_string(self)?
};
Expand Down
5 changes: 3 additions & 2 deletions core/src/avm1/globals/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use crate::avm1::{ArrayObject, Object, TObject, Value};
use crate::ecma_conversions::f64_to_wrapping_i32;
use crate::string::{AvmString, StringContext};
use bitflags::bitflags;
use ruffle_macros::istr;
use std::cmp::Ordering;

bitflags! {
Expand Down Expand Up @@ -252,11 +253,11 @@ pub fn join<'gc>(
let separator = if let Some(v) = args.get(0) {
v.coerce_to_string(activation)?
} else {
",".into()
istr!(",")
};

if length <= 0 {
return Ok(activation.strings().empty().into());
return Ok(istr!("").into());
}

let parts = (0..length)
Expand Down
2 changes: 1 addition & 1 deletion core/src/avm1/globals/load_vars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ fn send<'gc>(

let window = match args.get(1) {
Some(window) => window.coerce_to_string(activation)?,
None => activation.strings().empty(),
None => istr!(""),
};

let method_name = args
Expand Down
2 changes: 1 addition & 1 deletion core/src/avm1/globals/movie_clip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1550,7 +1550,7 @@ pub fn get_url<'gc>(

let window = match args.get(1) {
Some(window) => window.coerce_to_string(activation)?,
None => activation.strings().empty(),
None => istr!(""),
};

let method = match args.get(2) {
Expand Down
3 changes: 2 additions & 1 deletion core/src/avm1/globals/number.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! `Number` class impl

use gc_arena::Gc;
use ruffle_macros::istr;

use crate::avm1::activation::Activation;
use crate::avm1::clamp::Clamp;
Expand Down Expand Up @@ -134,7 +135,7 @@ fn to_string<'gc>(
Ordering::Greater => (number, false),
Ordering::Equal => {
// Bail out immediately if we're 0.
return Ok("0".into());
return Ok(istr!("0").into());
}
};

Expand Down
4 changes: 3 additions & 1 deletion core/src/avm1/globals/selection.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use ruffle_macros::istr;

use crate::avm1::activation::Activation;
use crate::avm1::error::Error;
use crate::avm1::globals::as_broadcaster::BroadcasterFunctions;
Expand Down Expand Up @@ -105,7 +107,7 @@ pub fn get_focus<'gc>(
.as_displayobject()
.object()
.coerce_to_string(activation)
.unwrap_or_else(|_| activation.strings().empty())
.unwrap_or_else(|_| istr!(""))
.into(),
None => Value::Null,
})
Expand Down
13 changes: 7 additions & 6 deletions core/src/avm1/globals/string.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! `String` class impl

use gc_arena::Gc;
use ruffle_macros::istr;

use crate::avm1::activation::Activation;
use crate::avm1::error::Error;
Expand Down Expand Up @@ -39,7 +40,7 @@ pub fn string<'gc>(
let value = match args.get(0).cloned() {
Some(Value::String(s)) => s,
Some(v) => v.coerce_to_string(activation)?,
None => activation.strings().empty(),
None => istr!(""),
};

// Called from a constructor, populate `this`.
Expand All @@ -65,7 +66,7 @@ pub fn string_function<'gc>(
let value = match args.get(0).cloned() {
Some(Value::String(s)) => s,
Some(v) => v.coerce_to_string(activation)?,
None => activation.strings().empty(),
None => istr!(""),
};

Ok(value.into())
Expand Down Expand Up @@ -116,7 +117,7 @@ fn char_at<'gc>(
.and_then(|i| string.get(i))
.map(WString::from_unit)
.map(|ret| AvmString::new(activation.gc(), ret))
.unwrap_or_else(|| activation.strings().empty());
.unwrap_or_else(|| istr!(""));

Ok(ret.into())
}
Expand Down Expand Up @@ -250,7 +251,7 @@ fn slice<'gc>(
let ret = WString::from(&this[start_index..end_index]);
Ok(AvmString::new(activation.gc(), ret).into())
} else {
Ok(activation.strings().empty().into())
Ok(istr!("").into())
}
}

Expand All @@ -268,7 +269,7 @@ fn split<'gc>(
// and the empty string behaves the same as undefined does in later SWF versions.
let is_swf5 = activation.swf_version() == 5;
if let Some(delimiter) = match args.get(0).unwrap_or(&Value::Undefined) {
&Value::Undefined => is_swf5.then_some(",".into()),
&Value::Undefined => is_swf5.then_some(istr!(",")),
v => Some(v.coerce_to_string(activation)?).filter(|s| !(is_swf5 && s.is_empty())),
} {
if delimiter.is_empty() {
Expand Down Expand Up @@ -332,7 +333,7 @@ fn substr<'gc>(
let ret = WString::from(&this[start_index..end_index]);
Ok(AvmString::new(activation.gc(), ret).into())
} else {
Ok(activation.strings().empty().into())
Ok(istr!("").into())
}
}

Expand Down
10 changes: 6 additions & 4 deletions core/src/avm1/globals/xml_node.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! XMLNode class

use ruffle_macros::istr;

use crate::avm1::activation::Activation;
use crate::avm1::error::Error;
use crate::avm1::property_decl::{define_properties_on, Declaration};
Expand Down Expand Up @@ -43,7 +45,7 @@ pub fn constructor<'gc>(
let node_value = value.coerce_to_string(activation)?;
XmlNode::new(mc, node_type, Some(node_value))
} else {
XmlNode::new(mc, TEXT_NODE, Some(activation.strings().empty()))
XmlNode::new(mc, TEXT_NODE, Some(istr!("")))
};
node.introduce_script_object(mc, this);
this.set_native(mc, NativeObject::XmlNode(node));
Expand Down Expand Up @@ -146,7 +148,7 @@ fn get_prefix_for_namespace<'gc>(
if let Some(prefix) = prefix.strip_prefix(b':') {
return Ok(AvmString::new(activation.gc(), prefix).into());
} else {
return Ok(activation.strings().empty().into());
return Ok(istr!("").into());
}
}
}
Expand Down Expand Up @@ -195,7 +197,7 @@ fn to_string<'gc>(
return Ok(AvmString::new(activation.gc(), string).into());
}

Ok(activation.strings().empty().into())
Ok(istr!("").into())
}

fn local_name<'gc>(
Expand Down Expand Up @@ -382,7 +384,7 @@ fn namespace_uri<'gc>(
if let Some(prefix) = node.prefix(activation.strings()) {
return Ok(node
.lookup_namespace_uri(&prefix)
.unwrap_or_else(|| activation.strings().empty().into()));
.unwrap_or_else(|| istr!("").into()));
}

return Ok(Value::Null);
Expand Down
9 changes: 4 additions & 5 deletions core/src/avm1/object/stage_object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use crate::display_object::{
use crate::string::{AvmString, WStr};
use crate::types::Percent;
use gc_arena::{Collect, GcCell, GcWeakCell, Mutation};
use ruffle_macros::istr;
use std::fmt;
use swf::Twips;

Expand Down Expand Up @@ -658,9 +659,7 @@ fn frames_loaded<'gc>(
}

fn name<'gc>(activation: &mut Activation<'_, 'gc>, this: DisplayObject<'gc>) -> Value<'gc> {
this.name()
.unwrap_or_else(|| activation.strings().empty())
.into()
this.name().unwrap_or_else(|| istr!("")).into()
}

fn set_name<'gc>(
Expand All @@ -677,14 +676,14 @@ fn drop_target<'gc>(activation: &mut Activation<'_, 'gc>, this: DisplayObject<'g
match this.as_movie_clip().and_then(|mc| mc.drop_target()) {
Some(target) => AvmString::new(activation.gc(), target.slash_path()).into(),
None if activation.swf_version() < 6 => Value::Undefined,
None => activation.strings().empty().into(),
None => istr!("").into(),
}
}

fn url<'gc>(activation: &mut Activation<'_, 'gc>, this: DisplayObject<'gc>) -> Value<'gc> {
match this.as_movie_clip() {
Some(mc) => AvmString::new_utf8(activation.gc(), mc.movie().url()).into(),
None => activation.strings().empty().into(),
None => istr!("").into(),
}
}

Expand Down
3 changes: 2 additions & 1 deletion core/src/avm1/object_reference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::{
};
use gc_arena::lock::Lock;
use gc_arena::{Collect, Gc, GcWeakCell, Mutation};
use ruffle_macros::istr;

#[derive(Clone, Debug, Collect)]
#[collect(no_drop)]
Expand Down Expand Up @@ -188,7 +189,7 @@ impl<'gc> MovieClipReference<'gc> {
pub fn coerce_to_string(&self, activation: &mut Activation<'_, 'gc>) -> AvmString<'gc> {
match self.resolve_reference(activation) {
// Couldn't find the reference
None => activation.strings().empty(),
None => istr!(""),
// Found the reference, cached, we can't re-use `self.path` sadly, it would be quicker if we could
// But if the clip has been re-named, since being created then `mc.path() != path`
Some((true, _, dobj)) => AvmString::new(activation.gc(), dobj.path()),
Expand Down
8 changes: 4 additions & 4 deletions core/src/avm1/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,12 +410,12 @@ impl<'gc> Value<'gc> {
activation: &mut Activation<'_, 'gc>,
) -> Result<AvmString<'gc>, Error<'gc>> {
Ok(match self {
Value::Undefined if activation.swf_version() < 7 => activation.strings().empty(),
Value::Undefined if activation.swf_version() < 7 => istr!(""),
Value::Bool(true) if activation.swf_version() < 5 => {
activation.strings().ascii_char(b'1')
istr!("1")
}
Value::Bool(false) if activation.swf_version() < 5 => {
activation.strings().ascii_char(b'0')
istr!("0")
}
Value::Object(object) => {
if let Some(object) = object
Expand Down Expand Up @@ -571,7 +571,7 @@ fn f64_to_string<'gc>(activation: &mut Activation<'_, 'gc>, mut n: f64) -> AvmSt
// FIXME is there an easy way to use istr! here?
AvmString::new_utf8_bytes(activation.gc(), b"-Infinity")
} else if n == 0.0 {
activation.strings().ascii_char(b'0')
istr!("0")
} else if n >= -2147483648.0 && n <= 2147483647.0 && n.fract() == 0.0 {
// Fast path for integers.
let n = n as i32;
Expand Down
9 changes: 5 additions & 4 deletions core/src/avm2/e4x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use quick_xml::{
name::ResolveResult,
Error as XmlError, NsReader,
};
use ruffle_macros::istr;

use std::cell::{Ref, RefMut};
use std::fmt::{self, Debug};
Expand Down Expand Up @@ -755,7 +756,7 @@ impl<'gc> E4XNode<'gc> {
) -> Result<Vec<Self>, Error<'gc>> {
let string = match &value {
// The docs claim that this throws a TypeError, but it actually doesn't
Value::Null | Value::Undefined => activation.strings().empty(),
Value::Null | Value::Undefined => istr!(""),
// The docs claim that only String, Number or Boolean are accepted, but that's also a lie
val => {
if let Some(obj) = val.as_object() {
Expand Down Expand Up @@ -962,7 +963,7 @@ impl<'gc> E4XNode<'gc> {
} else {
(
AvmString::new_utf8_bytes(activation.gc(), text.as_bytes()),
activation.strings().empty(),
istr!(""),
)
};
let node = E4XNode(GcCell::new(
Expand Down Expand Up @@ -1073,7 +1074,7 @@ impl<'gc> E4XNode<'gc> {
if &*name == b"xmlns" {
namespaces.push(E4XNamespace {
uri: value,
prefix: Some(activation.strings().empty()),
prefix: Some(istr!("")),
});
continue;
}
Expand Down Expand Up @@ -1418,7 +1419,7 @@ pub fn simple_content_to_string<'gc>(
children: impl Iterator<Item = E4XOrXml<'gc>>,
activation: &mut Activation<'_, 'gc>,
) -> AvmString<'gc> {
let mut out = activation.strings().empty();
let mut out = istr!("");
for child in children {
if matches!(
&*child.node().kind(),
Expand Down
5 changes: 3 additions & 2 deletions core/src/avm2/globals/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use crate::avm2::value::Value;
use crate::avm2::Error;
use crate::string::AvmString;
use bitflags::bitflags;
use ruffle_macros::istr;
use std::cmp::{min, Ordering};
use std::mem::swap;

Expand Down Expand Up @@ -164,7 +165,7 @@ pub fn join<'gc>(

if let Some(array) = this.as_array_storage() {
let string_separator = if matches!(separator, Value::Undefined) {
activation.strings().ascii_char(b',')
istr!(",")
} else {
separator.coerce_to_string(activation)?
};
Expand All @@ -175,7 +176,7 @@ pub fn join<'gc>(
let item = resolve_array_hole(activation, this, i, item)?;

if matches!(item, Value::Undefined) || matches!(item, Value::Null) {
accum.push(activation.strings().empty());
accum.push(istr!(""));
} else {
accum.push(item.coerce_to_string(activation)?);
}
Expand Down
Loading