Struct boa_engine::Context

source ·
pub struct Context<'host> { /* 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::{
    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("x", 12, Attribute::READONLY)
    .build();
context.register_global_property("arg", arg, Attribute::all());

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

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

Implementations§

source§

impl<'host> Context<'host>

source

pub fn builder() -> ContextBuilder<'static, 'static, 'static, 'static>

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

source

pub fn eval<R: Read>(&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::{
    object::ObjectInitializer,
    property::{Attribute, PropertyDescriptor},
    Context,
};

let mut context = Context::default();

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

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

pub fn register_global_callable( &mut self, name: &str, 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: &str, 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<T>(&mut self) -> JsResult<()>where T: Class,

Register a global class of type T, where T implements Class.

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

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

impl Class for MyClass {
   // ...
}

context.register_global_class::<MyClass>();
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 need to ensure that jobs are executed concurrently, you can 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 const fn root_shape(&self) -> &RootShape

Get the RootShape.

source

pub fn host_hooks(&self) -> MaybeShared<'host, dyn HostHooks>

Gets the host hooks.

source

pub fn job_queue(&self) -> MaybeShared<'host, dyn JobQueue>

Gets the job queue.

source

pub fn module_loader(&self) -> MaybeShared<'host, 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.

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

Auto Trait Implementations§

§

impl<'host> !RefUnwindSafe for Context<'host>

§

impl<'host> !Send for Context<'host>

§

impl<'host> !Sync for Context<'host>

§

impl<'host> Unpin for Context<'host>

§

impl<'host> !UnwindSafe for Context<'host>

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere 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) -> Twhere 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 Twhere 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 Twhere T: ?Sized,

source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere 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) -> Rwhere 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) -> Rwhere 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) -> Rwhere 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 ) -> Rwhere 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) -> Rwhere 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) -> Rwhere 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) -> Rwhere 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 ) -> Rwhere 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)) -> Selfwhere 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)) -> Selfwhere 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)) -> Selfwhere 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)) -> Selfwhere 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)) -> Selfwhere 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)) -> Selfwhere 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)) -> Selfwhere 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)) -> Selfwhere 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)) -> Selfwhere 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)) -> Selfwhere 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)) -> Selfwhere 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)) -> Selfwhere 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 Twhere 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 Twhere 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.
§

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

§

fn vzip(self) -> V

§

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