Struct boa_engine::context::Context

source ·
pub struct Context { /* private fields */ }
Expand description

ECMAScript context. It is the primary way to interact with the runtime.

Contexts constructed in a thread share the same runtime, therefore it is possible to share objects from one context to another context, but they have to be in the same thread.

§Examples

§Execute Function of Script File

use boa_engine::{
    js_string,
    object::ObjectInitializer,
    property::{Attribute, PropertyDescriptor},
    Context, Source,
};

let script = r#"
    function test(arg1) {
        if(arg1 != null) {
            return arg1.x;
        }
        return 112233;
    }
"#;

let mut context = Context::default();

// Populate the script definition to the context.
context.eval(Source::from_bytes(script)).unwrap();

// Create an object that can be used in eval calls.
let arg = ObjectInitializer::new(&mut context)
    .property(js_string!("x"), 12, Attribute::READONLY)
    .build();
context
    .register_global_property(js_string!("arg"), arg, Attribute::all())
    .expect("property shouldn't exist");

let value = context.eval(Source::from_bytes("test(arg)")).unwrap();

assert_eq!(value.as_number(), Some(12.0))

Implementations§

source§

impl Context

source

pub fn builder() -> ContextBuilder

Create a new ContextBuilder to specify the Interner and/or the icu data provider.

source

pub fn eval<R: ReadChar>(&mut self, src: Source<'_, R>) -> JsResult<JsValue>

Evaluates the given source by compiling down to bytecode, then interpreting the bytecode into a value.

§Examples
let mut context = Context::default();

let source = Source::from_bytes("1 + 3");
let value = context.eval(source).unwrap();

assert!(value.is_number());
assert_eq!(value.as_number().unwrap(), 4.0);

Note that this won’t run any scheduled promise jobs; you need to call Context::run_jobs on the context or JobQueue::run_jobs on the provided queue to run them.

source

pub fn optimize_statement_list( &mut self, statement_list: &mut StatementList ) -> OptimizerStatistics

Applies optimizations to the StatementList inplace.

source

pub fn register_global_property<K, V>( &mut self, key: K, value: V, attribute: Attribute ) -> JsResult<()>
where K: Into<PropertyKey>, V: Into<JsValue>,

Register a global property.

It will return an error if the property is already defined.

§Example
use boa_engine::{
    js_string,
    object::ObjectInitializer,
    property::{Attribute, PropertyDescriptor},
    Context,
};

let mut context = Context::default();

context
    .register_global_property(
        js_string!("myPrimitiveProperty"),
        10,
        Attribute::all(),
    )
    .expect("property shouldn't exist");

let object = ObjectInitializer::new(&mut context)
    .property(js_string!("x"), 0, Attribute::all())
    .property(js_string!("y"), 1, Attribute::all())
    .build();
context
    .register_global_property(
        js_string!("myObjectProperty"),
        object,
        Attribute::all(),
    )
    .expect("property shouldn't exist");
source

pub fn register_global_callable( &mut self, name: JsString, length: usize, body: NativeFunction ) -> JsResult<()>

Register a global native callable.

The function will be both constructable (call with new <name>()) and callable (call with <name>()).

The function will be bound to the global object with writable, non-enumerable and configurable attributes. The same as when you create a function in JavaScript.

§Note

If you wish to only create the function object without binding it to the global object, you can use the FunctionObjectBuilder API.

source

pub fn register_global_builtin_callable( &mut self, name: JsString, length: usize, body: NativeFunction ) -> JsResult<()>

Register a global native function that is not a constructor.

The function will be bound to the global object with writable, non-enumerable and configurable attributes. The same as when you create a function in JavaScript.

§Note

The difference to Context::register_global_callable is, that the function will not be constructable. Usage of the function as a constructor will produce a TypeError.

source

pub fn register_global_class<C: Class>(&mut self) -> JsResult<()>

Registers a global class C in the currently active realm.

Errors if the class has already been registered.

§Example
#[derive(Debug, Trace, Finalize)]
struct MyClass;

impl Class for MyClass {
   // ...
}

context.register_global_class::<MyClass>()?;
source

pub fn unregister_global_class<C: Class>( &mut self ) -> JsResult<Option<StandardConstructor>>

Removes the global class C from the currently active realm, returning the constructor and prototype of the class if C was registered.

§Note

This makes the constructor return an error on further calls, but note that this won’t protect static properties from being accessed within variables that stored the constructor before being unregistered. If you need that functionality, you can use a static accessor that first checks if the class is registered (Context::has_global_class) before returning the static value.

§Example
#[derive(Debug, Trace, Finalize)]
struct MyClass;

impl Class for MyClass {
   // ...
}

context.register_global_class::<MyClass>()?;
// ... code
context.unregister_global_class::<MyClass>()?;
source

pub fn has_global_class<C: Class>(&self) -> bool

Checks if the currently active realm has the global class C registered.

source

pub fn get_global_class<C: Class>(&self) -> Option<StandardConstructor>

Gets the constructor and prototype of the global class C if the currently active realm has that class registered.

source

pub const fn interner(&self) -> &Interner

Gets the string interner.

source

pub fn interner_mut(&mut self) -> &mut Interner

Gets a mutable reference to the string interner.

source

pub fn global_object(&self) -> JsObject

Returns the global object.

source

pub fn intrinsics(&self) -> &Intrinsics

Returns the currently active intrinsic constructors and objects.

source

pub const fn realm(&self) -> &Realm

Returns the currently active realm.

source

pub const fn optimizer_options(&self) -> OptimizerOptions

Get optimizer options.

source

pub fn set_optimizer_options(&mut self, optimizer_options: OptimizerOptions)

Enable or disable optimizations

source

pub fn strict(&mut self, strict: bool)

Changes the strictness mode of the context.

source

pub fn enqueue_job(&mut self, job: NativeJob)

Enqueues a NativeJob on the JobQueue.

source

pub fn run_jobs(&mut self)

Runs all the jobs in the job queue.

source

pub async fn run_jobs_async(&mut self)

Asynchronously runs all the jobs in the job queue.

§Note

Concurrent job execution cannot be guaranteed by the engine, since this depends on the specific handling of each JobQueue. If you want to execute jobs concurrently, you must provide a custom implementor of JobQueue to the context.

source

pub fn clear_kept_objects(&mut self)

Abstract operation ClearKeptObjects.

Clears all objects maintained alive by calls to the AddToKeptObjects abstract operation, used within the WeakRef constructor.

source

pub fn stack_trace(&self) -> impl Iterator<Item = &CallFrame>

Retrieves the current stack trace of the context.

source

pub fn enter_realm(&mut self, realm: Realm) -> Realm

Replaces the currently active realm with realm, and returns the old realm.

source

pub fn create_realm(&mut self) -> JsResult<Realm>

Create a new Realm with the default global bindings.

source

pub const fn root_shape(&self) -> &RootShape

Get the RootShape.

source

pub fn host_hooks(&self) -> &'static dyn HostHooks

Gets the host hooks.

source

pub fn job_queue(&self) -> Rc<dyn JobQueue>

Gets the job queue.

source

pub fn module_loader(&self) -> Rc<dyn ModuleLoader>

Gets the module loader.

source

pub const fn runtime_limits(&self) -> RuntimeLimits

Get the RuntimeLimits.

source

pub fn set_runtime_limits(&mut self, runtime_limits: RuntimeLimits)

Set the RuntimeLimits.

source

pub fn runtime_limits_mut(&mut self) -> &mut RuntimeLimits

Get a mutable reference to the RuntimeLimits.

source

pub fn can_block(&self) -> bool

Returns true if this context can be suspended by an Atomics.wait call.

Trait Implementations§

source§

impl Debug for Context

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for Context

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl Drop for Context

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Context

§

impl !Send for Context

§

impl !Sync for Context

§

impl Unpin for Context

§

impl !UnwindSafe for Context

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> Conv for T

source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Pipe for T
where T: ?Sized,

source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
source§

impl<T> Tap for T

source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
source§

impl<T> TryConv for T

source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> ErasedDestructor for T
where T: 'static,

source§

impl<T> MaybeSendSync for T