Browse Source

replace js_str with js_string (#3836)

pull/3839/head
19年梦醒 7 months ago committed by GitHub
parent
commit
12adec5eed
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 8
      examples/src/bin/classes.rs
  2. 20
      examples/src/bin/closures.rs
  3. 4
      examples/src/bin/futures.rs
  4. 11
      examples/src/bin/jsarray.rs
  5. 4
      examples/src/bin/jsarraybuffer.rs
  6. 12
      examples/src/bin/jstypedarray.rs
  7. 10
      examples/src/bin/module_fetch.rs
  8. 12
      examples/src/bin/modulehandler.rs
  9. 11
      examples/src/bin/modules.rs
  10. 12
      examples/src/bin/synthetic.rs

8
examples/src/bin/classes.rs

@ -2,7 +2,7 @@
use boa_engine::{ use boa_engine::{
class::{Class, ClassBuilder}, class::{Class, ClassBuilder},
error::JsNativeError, error::JsNativeError,
js_str, js_string, js_string,
native_function::NativeFunction, native_function::NativeFunction,
property::Attribute, property::Attribute,
Context, JsArgs, JsData, JsResult, JsString, JsValue, Source, Context, JsArgs, JsData, JsResult, JsString, JsValue, Source,
@ -120,13 +120,13 @@ impl Class for Person {
// We add an `"inheritedProperty"` property to the prototype of `Person` with // We add an `"inheritedProperty"` property to the prototype of `Person` with
// a value of `10` and default attribute flags `READONLY`, `NON_ENUMERABLE` and `PERMANENT`. // a value of `10` and default attribute flags `READONLY`, `NON_ENUMERABLE` and `PERMANENT`.
class.property(js_str!("inheritedProperty"), 10, Attribute::default()); class.property(js_string!("inheritedProperty"), 10, Attribute::default());
// Finally, we add a `"staticProperty"` property to `Person` with a value // Finally, we add a `"staticProperty"` property to `Person` with a value
// of `"Im a static property"` and attribute flags `WRITABLE`, `ENUMERABLE` and `PERMANENT`. // of `"Im a static property"` and attribute flags `WRITABLE`, `ENUMERABLE` and `PERMANENT`.
class.static_property( class.static_property(
js_str!("staticProperty"), js_string!("staticProperty"),
js_str!("Im a static property"), js_string!("Im a static property"),
Attribute::WRITABLE | Attribute::ENUMERABLE | Attribute::PERMANENT, Attribute::WRITABLE | Attribute::ENUMERABLE | Attribute::PERMANENT,
); );

20
examples/src/bin/closures.rs

@ -4,7 +4,7 @@
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
use boa_engine::{ use boa_engine::{
js_str, js_string, js_string,
native_function::NativeFunction, native_function::NativeFunction,
object::{builtins::JsArray, FunctionObjectBuilder, JsObject}, object::{builtins::JsArray, FunctionObjectBuilder, JsObject},
property::{Attribute, PropertyDescriptor}, property::{Attribute, PropertyDescriptor},
@ -52,9 +52,9 @@ fn main() -> Result<(), JsError> {
// We create a new `JsObject` with some data // We create a new `JsObject` with some data
let object = JsObject::with_object_proto(context.intrinsics()); let object = JsObject::with_object_proto(context.intrinsics());
object.define_property_or_throw( object.define_property_or_throw(
js_str!("name"), js_string!("name"),
PropertyDescriptor::builder() PropertyDescriptor::builder()
.value(js_str!("Boa dev")) .value(js_string!("Boa dev"))
.writable(false) .writable(false)
.enumerable(false) .enumerable(false)
.configurable(false), .configurable(false),
@ -77,18 +77,18 @@ fn main() -> Result<(), JsError> {
let BigStruct { greeting, object } = &mut *captures; let BigStruct { greeting, object } = &mut *captures;
println!("Called `createMessage`"); println!("Called `createMessage`");
// We obtain the `name` property of `captures.object` // We obtain the `name` property of `captures.object`
let name = object.get(js_str!("name"), context)?; let name = object.get(js_string!("name"), context)?;
// We create a new message from our captured variable. // We create a new message from our captured variable.
let message = js_string!( let message = js_string!(
js_str!("message from `"), &js_string!("message from `"),
&name.to_string(context)?, &name.to_string(context)?,
js_str!("`: "), &js_string!("`: "),
&*greeting &*greeting
); );
// We can also mutate the moved data inside the closure. // We can also mutate the moved data inside the closure.
captures.greeting = js_string!(&*greeting, js_str!(" Hello!")); captures.greeting = js_string!(&*greeting, &js_string!(" Hello!"));
println!("{}", message.to_std_string_escaped()); println!("{}", message.to_std_string_escaped());
println!(); println!();
@ -101,7 +101,7 @@ fn main() -> Result<(), JsError> {
), ),
) )
// And here we assign `createMessage` to the `name` property of the closure. // And here we assign `createMessage` to the `name` property of the closure.
.name(js_str!("createMessage")) .name(js_string!("createMessage"))
// By default all `FunctionBuilder`s set the `length` property to `0` and // By default all `FunctionBuilder`s set the `length` property to `0` and
// the `constructable` property to `false`. // the `constructable` property to `false`.
.build(); .build();
@ -111,7 +111,7 @@ fn main() -> Result<(), JsError> {
.register_global_property( .register_global_property(
// We set the key to access the function the same as its name for // We set the key to access the function the same as its name for
// consistency, but it may be different if needed. // consistency, but it may be different if needed.
js_str!("createMessage"), js_string!("createMessage"),
// We pass `js_function` as a property value. // We pass `js_function` as a property value.
js_function, js_function,
// We assign to the "createMessage" property the desired attributes. // We assign to the "createMessage" property the desired attributes.
@ -144,7 +144,7 @@ fn main() -> Result<(), JsError> {
// We register a global closure that is not `Copy`. // We register a global closure that is not `Copy`.
context context
.register_global_callable( .register_global_callable(
js_str!("enumerate").into(), js_string!("enumerate"),
0, 0,
// Note that it is required to use `unsafe` code, since the compiler cannot verify that the // Note that it is required to use `unsafe` code, since the compiler cannot verify that the
// types captured by the closure are not traceable. // types captured by the closure are not traceable.

4
examples/src/bin/futures.rs

@ -8,7 +8,7 @@ use std::{
use boa_engine::{ use boa_engine::{
context::ContextBuilder, context::ContextBuilder,
job::{FutureJob, JobQueue, NativeJob}, job::{FutureJob, JobQueue, NativeJob},
js_str, js_string,
native_function::NativeFunction, native_function::NativeFunction,
property::Attribute, property::Attribute,
Context, JsArgs, JsResult, JsValue, Source, Context, JsArgs, JsResult, JsValue, Source,
@ -143,7 +143,7 @@ fn add_runtime(context: &mut Context) {
// Then, bind the defined async function to the ECMAScript function "delay". // Then, bind the defined async function to the ECMAScript function "delay".
context context
.register_global_builtin_callable( .register_global_builtin_callable(
js_str!("delay").into(), js_string!("delay"),
1, 1,
NativeFunction::from_async_fn(delay), NativeFunction::from_async_fn(delay),
) )

11
examples/src/bin/jsarray.rs

@ -1,7 +1,7 @@
// This example shows how to manipulate a Javascript array using Rust code. // This example shows how to manipulate a Javascript array using Rust code.
use boa_engine::{ use boa_engine::{
js_str, js_string,
native_function::NativeFunction, native_function::NativeFunction,
object::{builtins::JsArray, FunctionObjectBuilder}, object::{builtins::JsArray, FunctionObjectBuilder},
Context, JsResult, JsValue, Context, JsResult, JsValue,
@ -16,13 +16,16 @@ fn main() -> JsResult<()> {
assert!(array.is_empty(context)?); assert!(array.is_empty(context)?);
array.push(js_str!("Hello, world"), context)?; // [ "Hello, world" ] array.push(js_string!("Hello, world"), context)?; // [ "Hello, world" ]
array.push(true, context)?; // [ "Hello, world", true ] array.push(true, context)?; // [ "Hello, world", true ]
assert!(!array.is_empty(context)?); assert!(!array.is_empty(context)?);
assert_eq!(array.pop(context)?, JsValue::new(true)); // [ "Hello, world" ] assert_eq!(array.pop(context)?, JsValue::new(true)); // [ "Hello, world" ]
assert_eq!(array.pop(context)?, JsValue::new(js_str!("Hello, world"))); // [ ] assert_eq!(
array.pop(context)?,
JsValue::new(js_string!("Hello, world"))
); // [ ]
assert_eq!(array.pop(context)?, JsValue::undefined()); // [ ] assert_eq!(array.pop(context)?, JsValue::undefined()); // [ ]
array.push(1, context)?; // [ 1 ] array.push(1, context)?; // [ 1 ]
@ -113,7 +116,7 @@ fn main() -> JsResult<()> {
context context
.global_object() .global_object()
.set(js_str!("myArray"), array, true, context)?; .set(js_string!("myArray"), array, true, context)?;
Ok(()) Ok(())
} }

4
examples/src/bin/jsarraybuffer.rs

@ -1,7 +1,7 @@
// This example shows how to manipulate a Javascript array using Rust code. // This example shows how to manipulate a Javascript array using Rust code.
use boa_engine::{ use boa_engine::{
js_str, js_string,
object::builtins::{JsArrayBuffer, JsDataView, JsUint32Array, JsUint8Array}, object::builtins::{JsArrayBuffer, JsDataView, JsUint32Array, JsUint8Array},
property::Attribute, property::Attribute,
Context, JsResult, JsValue, Context, JsResult, JsValue,
@ -54,7 +54,7 @@ fn main() -> JsResult<()> {
// We can also register it as a global property // We can also register it as a global property
context context
.register_global_property( .register_global_property(
js_str!("myArrayBuffer"), js_string!("myArrayBuffer"),
array_buffer, array_buffer,
Attribute::WRITABLE | Attribute::ENUMERABLE | Attribute::CONFIGURABLE, Attribute::WRITABLE | Attribute::ENUMERABLE | Attribute::CONFIGURABLE,
) )

12
examples/src/bin/jstypedarray.rs

@ -1,7 +1,7 @@
// This example shows how to manipulate a Javascript array using Rust code. // This example shows how to manipulate a Javascript array using Rust code.
use boa_engine::{ use boa_engine::{
js_str, js_string,
native_function::NativeFunction, native_function::NativeFunction,
object::{ object::{
builtins::{JsArray, JsArrayBuffer, JsUint8Array}, builtins::{JsArray, JsArrayBuffer, JsUint8Array},
@ -168,7 +168,7 @@ fn main() -> JsResult<()> {
.buffer(context)? .buffer(context)?
.as_object() .as_object()
.unwrap() .unwrap()
.get(js_str!("byteLength"), context) .get(js_string!("byteLength"), context)
.unwrap(), .unwrap(),
JsValue::new(8) JsValue::new(8)
); );
@ -195,23 +195,23 @@ fn main() -> JsResult<()> {
// toLocaleString // toLocaleString
// let array = JsUint32Array::from_iter(vec![500, 8123, 12], context)?; // let array = JsUint32Array::from_iter(vec![500, 8123, 12], context)?;
// let locales: Option<JsValue> = Some(js_str!("de-DE").into()); // let locales: Option<JsValue> = Some(js_string!("de-DE").into());
// let options = Some(context.eval(Source::from_bytes( // let options = Some(context.eval(Source::from_bytes(
// r##"let options = { style: "currency", currency: "EUR" }; options;"##, // r##"let options = { style: "currency", currency: "EUR" }; options;"##,
// ))?); // ))?);
// assert_eq!( // assert_eq!(
// array.to_locale_string(locales, options, context)?, // array.to_locale_string(locales, options, context)?,
// js_str!("500,00 €,8.123,00 €,12,00 €").into() // js_string!("500,00 €,8.123,00 €,12,00 €").into()
// ); // );
// toStringTag // toStringTag
let array = JsUint8Array::from_iter(vec![1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8], context)?; let array = JsUint8Array::from_iter(vec![1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8], context)?;
let tag = array.to_string_tag(context)?.to_string(context)?; let tag = array.to_string_tag(context)?.to_string(context)?;
assert_eq!(tag, js_str!("Uint8Array")); assert_eq!(tag, js_string!("Uint8Array"));
context context
.register_global_property( .register_global_property(
js_str!("myUint8Array"), js_string!("myUint8Array"),
array, array,
Attribute::WRITABLE | Attribute::ENUMERABLE | Attribute::CONFIGURABLE, Attribute::WRITABLE | Attribute::ENUMERABLE | Attribute::CONFIGURABLE,
) )

10
examples/src/bin/module_fetch.rs

@ -7,7 +7,7 @@ use std::{
use boa_engine::{ use boa_engine::{
builtins::promise::PromiseState, builtins::promise::PromiseState,
job::{FutureJob, JobQueue, NativeJob}, job::{FutureJob, JobQueue, NativeJob},
js_str, js_string,
module::ModuleLoader, module::ModuleLoader,
Context, JsNativeError, JsResult, JsString, JsValue, Module, Context, JsNativeError, JsResult, JsString, JsValue, Module,
}; };
@ -148,7 +148,9 @@ fn main() -> JsResult<()> {
} }
} }
let default = module.namespace(context).get(js_str!("default"), context)?; let default = module
.namespace(context)
.get(js_string!("default"), context)?;
// `default` should contain the result of our calculations. // `default` should contain the result of our calculations.
let default = default let default = default
@ -160,14 +162,14 @@ fn main() -> JsResult<()> {
.get(0, context)? .get(0, context)?
.as_string() .as_string()
.ok_or_else(|| JsNativeError::typ().with_message("array element was not a string"))?, .ok_or_else(|| JsNativeError::typ().with_message("array element was not a string"))?,
&js_str!("aGVsbG8=") &js_string!("aGVsbG8=")
); );
assert_eq!( assert_eq!(
default default
.get(1, context)? .get(1, context)?
.as_string() .as_string()
.ok_or_else(|| JsNativeError::typ().with_message("array element was not a string"))?, .ok_or_else(|| JsNativeError::typ().with_message("array element was not a string"))?,
&js_str!("d29ybGQ=") &js_string!("d29ybGQ=")
); );
Ok(()) Ok(())

12
examples/src/bin/modulehandler.rs

@ -2,7 +2,7 @@
// the require/module.exports pattern // the require/module.exports pattern
use boa_engine::{ use boa_engine::{
js_str, native_function::NativeFunction, prelude::JsObject, property::Attribute, Context, js_string, native_function::NativeFunction, prelude::JsObject, property::Attribute, Context,
JsArgs, JsNativeError, JsResult, JsValue, Source, JsArgs, JsNativeError, JsResult, JsValue, Source,
}; };
use boa_runtime::Console; use boa_runtime::Console;
@ -33,14 +33,14 @@ fn main() -> Result<(), Box<dyn Error>> {
// Adding custom object that mimics 'module.exports' // Adding custom object that mimics 'module.exports'
let moduleobj = JsObject::default(); let moduleobj = JsObject::default();
moduleobj.set( moduleobj.set(
js_str!("exports"), js_string!("exports"),
JsValue::from(js_str!(" ")), JsValue::from(js_string!(" ")),
false, false,
&mut ctx, &mut ctx,
)?; )?;
ctx.register_global_property( ctx.register_global_property(
js_str!("module"), js_string!("module"),
JsValue::from(moduleobj), JsValue::from(moduleobj),
Attribute::default(), Attribute::default(),
)?; )?;
@ -68,9 +68,9 @@ fn require(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue
// Access module.exports and return as ResultValue // Access module.exports and return as ResultValue
let global_obj = ctx.global_object(); let global_obj = ctx.global_object();
let module = global_obj.get(js_str!("module"), ctx)?; let module = global_obj.get(js_string!("module"), ctx)?;
module module
.as_object() .as_object()
.ok_or_else(|| JsNativeError::typ().with_message("`exports` property was not an object"))? .ok_or_else(|| JsNativeError::typ().with_message("`exports` property was not an object"))?
.get(js_str!("exports"), ctx) .get(js_string!("exports"), ctx)
} }

11
examples/src/bin/modules.rs

@ -1,7 +1,7 @@
use std::{error::Error, path::Path, rc::Rc}; use std::{error::Error, path::Path, rc::Rc};
use boa_engine::{ use boa_engine::{
builtins::promise::PromiseState, js_str, module::SimpleModuleLoader, Context, JsError, builtins::promise::PromiseState, js_string, module::SimpleModuleLoader, Context, JsError,
JsNativeError, JsValue, Module, NativeFunction, JsNativeError, JsValue, Module, NativeFunction,
}; };
use boa_parser::Source; use boa_parser::Source;
@ -102,14 +102,17 @@ fn main() -> Result<(), Box<dyn Error>> {
// We can access the full namespace of the module with all its exports. // We can access the full namespace of the module with all its exports.
let namespace = module.namespace(context); let namespace = module.namespace(context);
let result = namespace.get(js_str!("result"), context)?; let result = namespace.get(js_string!("result"), context)?;
println!("result = {}", result.display()); println!("result = {}", result.display());
assert_eq!(namespace.get(js_str!("result"), context)?, JsValue::from(5)); assert_eq!(
namespace.get(js_string!("result"), context)?,
JsValue::from(5)
);
let mix = namespace let mix = namespace
.get(js_str!("mix"), context)? .get(js_string!("mix"), context)?
.as_callable() .as_callable()
.cloned() .cloned()
.ok_or_else(|| JsNativeError::typ().with_message("mix export wasn't a function!"))?; .ok_or_else(|| JsNativeError::typ().with_message("mix export wasn't a function!"))?;

12
examples/src/bin/synthetic.rs

@ -9,8 +9,7 @@ use boa_engine::builtins::promise::PromiseState;
use boa_engine::module::{SimpleModuleLoader, SyntheticModuleInitializer}; use boa_engine::module::{SimpleModuleLoader, SyntheticModuleInitializer};
use boa_engine::object::FunctionObjectBuilder; use boa_engine::object::FunctionObjectBuilder;
use boa_engine::{ use boa_engine::{
js_str, js_string, Context, JsArgs, JsError, JsNativeError, JsValue, Module, NativeFunction, js_string, Context, JsArgs, JsError, JsNativeError, JsValue, Module, NativeFunction, Source,
Source,
}; };
fn main() -> Result<(), Box<dyn Error>> { fn main() -> Result<(), Box<dyn Error>> {
@ -78,14 +77,17 @@ fn main() -> Result<(), Box<dyn Error>> {
// We can access the full namespace of the module with all its exports. // We can access the full namespace of the module with all its exports.
let namespace = module.namespace(context); let namespace = module.namespace(context);
let result = namespace.get(js_str!("result"), context)?; let result = namespace.get(js_string!("result"), context)?;
println!("result = {}", result.display()); println!("result = {}", result.display());
assert_eq!(namespace.get(js_str!("result"), context)?, JsValue::from(5)); assert_eq!(
namespace.get(js_string!("result"), context)?,
JsValue::from(5)
);
let mix = namespace let mix = namespace
.get(js_str!("mix"), context)? .get(js_string!("mix"), context)?
.as_callable() .as_callable()
.cloned() .cloned()
.ok_or_else(|| JsNativeError::typ().with_message("mix export wasn't a function!"))?; .ok_or_else(|| JsNativeError::typ().with_message("mix export wasn't a function!"))?;

Loading…
Cancel
Save