Skip to main content

JsRuntime

Struct JsRuntime 

Source
pub struct JsRuntime {
Show 18 fields pub max_steps: u64, pub global: Rc<RefCell<Scope>>, pub out: String, pub microtasks: Rc<RefCell<VecDeque<Job>>>, pub macrotasks: Rc<RefCell<VecDeque<TimerTask>>>, pub clock_skew: Rc<Cell<u64>>, pub base_url: String, pub modules: ModuleRegistry, pub builtin_fn_cache: Rc<RefCell<BTreeMap<usize, Value>>>, pub units_cache: Rc<RefCell<UnitsCache>>, pub(crate) wm_index: Rc<RefCell<BTreeMap<usize, (Weak<RefCell<Obj>>, BTreeMap<usize, usize>)>>>, pub(crate) global_lexicals: Rc<RefCell<BTreeSet<Rc<str>>>>, pub last_syntax_errors: Vec<ParseError>, pub last_thrown: Option<Value>, pub runtime_id: u64, pub(crate) host: &'static HostHooks, pub(crate) host_state: Rc<dyn Any>, pub(crate) private_brand_seq: Rc<Cell<u64>>,
}
Expand description

ページ単位で永続するランタイム状態。

Fields§

§max_steps: u64

1 タスクあたりのステップ上限(Interp::max_steps)。

§global: Rc<RefCell<Scope>>§out: String

console.* の累積出力(ページ表示やテスト用)。

§microtasks: Rc<RefCell<VecDeque<Job>>>

Promise の then 反応を遅延実行するマイクロタスクキュー。

§macrotasks: Rc<RefCell<VecDeque<TimerTask>>>

タイマー(setTimeout / setInterval / requestAnimationFrame)。発火予定時刻付き。

§clock_skew: Rc<Cell<u64>>

タイマー用の仮想時刻のずれ(ミリ秒)。試験で時刻を早送りするのに使う。

§base_url: String

現在ページの絶対URL(fetch/XHR の相対URL解決の基準。未設定なら空)。

§modules: ModuleRegistry

登録済み ES モジュール(指定子 → ソース/評価済みエクスポート)。

§builtin_fn_cache: Rc<RefCell<BTreeMap<usize, Value>>>

組込みネイティブ関数のシングルトンキャッシュ(関数ポインタアドレスをキーにして衝突を防ぐ)。

§units_cache: Rc<RefCell<UnitsCache>>

長い文字列の UTF-16 の単位の写し(charCodeAt の繰り返しが毎回全文を変換しないように)。

§wm_index: Rc<RefCell<BTreeMap<usize, (Weak<RefCell<Obj>>, BTreeMap<usize, usize>)>>>

WeakMap の索引(エントリ配列のアドレス → (配列への弱参照, キーのアドレス → 位置))。

§global_lexicals: Rc<RefCell<BTreeSet<Rc<str>>>>

トップレベルで let/const/class/using により宣言された識別子名。 globalThis のプロパティと区別するため保持する(ECMA-262 Global Environment Record の Declarative Record 相当)。

§last_syntax_errors: Vec<ParseError>

直近の eval() で検出した構文エラー。

【2026-07-28】パーサはベストエフォートで回復して継続する設計だが、 従来は回復した事実を誰にも伝えていなかったため、壊れたスクリプトが 正常に動いていないのか、そもそも解析に失敗していたのかを区別できなかった。 実行は従来どおり継続しつつ、呼び出し側が参照できるようここへ残す。

§last_thrown: Option<Value>

直近の eval() が最上位で受けた throw の値(【2026-11-19】ホストの試験実行器 tests/js_host が、 文字列化では失われる例外の名前・メッセージを取り出すため。カーネルは読まない)。

§runtime_id: u64

実行環境の番号(1 から。起動中に重ならない)。【2026-11-17】この実行環境が作った共有の資源 (MSE の SourceBuffer)を、実行環境が捨てられたときに片付けるのに使う(TODO R2 (c) ②)。

§host: &'static HostHooks

ホスト物・ホスト資源(DOM・Web API 等)の操作の表。

§host_state: Rc<dyn Any>

ホスト側のランタイム状態(RuntimeHostState 等)。ECMAScript の核は中身を知らない。

§private_brand_seq: Rc<Cell<u64>>

クラス評価ごとのプライベートブランド ID 採番器(同一ランタイム内の eval でも衝突させない)。

Implementations§

Source§

impl JsRuntime

Source

pub fn new_ecma() -> Self

純粋 ECMAScript のみで実行環境を初期化する(DOM・Web API 無し、NULL_HOST_HOOKS 使用)。

Source

pub fn new_with_host( host: &'static HostHooks, host_state: Rc<dyn Any>, install_extra: fn(&Rc<RefCell<Scope>>), ) -> Self

指定したホストフック・ホスト状態・追加組み込み登録関数で実行環境を初期化する。

Source

fn seed_builtin_fn_cache(&mut self)

組み込みの prototype に並べたネイティブ関数を、実体からの解決(builtin_fn_val)でも同じ オブジェクトにする([].push === Array.prototype.push)。【2026-11-16】以前は prototype 側と 実体側で別々に関数オブジェクトを作り、同一性の比較(ポリフィルの「組み込みのままか」の判定など)が 偽になっていた。

Source

pub(crate) fn new_interp(&self) -> Interp

Source

pub fn define_module(&mut self, specifier: &str, source: &str)

ES モジュールをソース付きで登録する(指定子 → ソース)。 import 時に遅延評価される。同じ指定子の再登録は上書き(未評価状態に戻す)。

Source

pub fn eval_module( &mut self, specifier: &str, source: &str, ) -> Result<Value, String>

ES モジュールをトップレベルで評価する(<script type="module"> 用)。 指定子をキーとして登録・評価し、Promise/マイクロタスク等の完了までイベントループを回す。

Source

pub fn pump_timers(&mut self, budget_ms: u64) -> bool

期限の来たタイマー(setTimeout/setInterval/rAF)とマイクロタスクを最大 budget_ms 分 実行する。ホスト(描画ループ)が毎フレーム呼ぶ。何か実行したら true(DOM の再反映用)。

Source

pub fn has_due_timers(&self) -> bool

期限の来たタイマー、未消化のマイクロタスク、または到着した非同期 I/O 結果があるか(ホストの再描画判定用。軽い)。

Source

pub fn fast_forward_timers(&mut self, max_ms: u64)

試験用: 仮想時刻を最大 max_ms まで早送りしながら、期限の来たタイマーを順に流す。

Source

pub fn eval(&mut self, source: &str) -> Result<Value, String>

ソースを評価。戻り値は最後の式の値、または throw された値の文字列化。

構文エラーがあっても(従来どおり)ベストエフォートで実行を続けるが、 検出した構文エラーは必ずログへ出し、last_syntax_errors に残す。 「スクリプトが動かない」ときに、解析で諦めた箇所が分かるようにするため。

Source§

impl JsRuntime

Source

pub fn set_document_ready_state(&mut self, state: &str)

文書の読み込み状態(document.readyState)を state(loading/interactive/complete)に 進め、readystatechange(loading 以外)と DOMContentLoaded(interactive)・load (complete)の保留中のリスナと onreadystatechange/onload を呼ぶ。 【2026-10-20】従来は常に complete で、登録した時点で即時に呼んでいた。YouTube は kevlar の読み込み時に readyState が complete だと、その場で(ytd-app が組み上がる前に) monomer 部品の接続処理を済ませてしまい、ytd-page-manager が接続されなかった。

Source

pub fn set_current_script(&mut self, script_node_idx: Option<usize>)

実行中のスクリプト要素を設定・解除(document.currentScript)。 非モジュールクラシックスクリプトの同期実行中に要素ハンドルを返し、 完了後やコールバック・タイマー内では null に戻す(W3C DOM / HTML 仕様準拠)。

Source

fn call_on_handler(&mut self, obj: &Value, prop: &str, ty: &str)

obj.onXXX が関数なら呼ぶ(イベントは {type} だけの簡易なもの)。

Source

pub(crate) fn install_preludes(&mut self)

JS で書いた組み込み(prelude/*.js)を、名前が初めて読まれたときに評価するよう仕掛ける(prelude/lazy_boot.js)。

Source

pub fn set_page_url(&mut self, url: &str)

現在ページの絶対URLを設定。fetch/XHR の相対URL基準(base_url)と JS の window/document.location オブジェクトを同時に更新する。

Source

pub fn location_href(&self) -> Option<String>

スクリプトから見た今の文書の URL(location.href。history.pushState 等で変わる)。

Source

pub fn set_referrer(&mut self, referrer: &str)

document.referrer の値(この文書を読み込んだときに送った Referer。無ければ空)。

Source

pub fn set_frame_depth(&mut self, depth: u32)

フレーム階層深さ(0 = 最上位、1.. = 子 <iframe>)を設定し、子フレーム内で window.self !== window.parent / window.top と parent.postMessage を機能させる。

Source

pub fn deliver_message(&mut self, data: Value, origin: &str)

別フレーム(親または子 <iframe>)から postMessage で届いたメッセージを このフレームの window の message リスナへ配信する。

Source

pub fn dispatch_click(&mut self, node_idx: usize) -> bool

指定ノードの click イベントを発火する(バブリング対応)。ホストがクリック処理から呼ぶ。 DOM 変更があれば dom().borrow().dirty が立つので、呼び元が再レイアウトする。

Source

pub fn dispatch_event(&mut self, node_idx: usize, event_type: &str) -> bool

汎用イベントディスパッチ(追加プロパティ無し)。発火したか返す。

Source

pub fn dispatch_mouse( &mut self, node_idx: usize, event_type: &str, x: i32, y: i32, ) -> (bool, bool)

マウスイベント(click/mouseover/mouseout/mousemove 等)。座標 clientX/clientY/ pageX/pageY と button を付与。戻り値: (リスナ発火, preventDefault されたか)。

Source

pub fn dispatch_mouse_full( &mut self, node_idx: usize, event_type: &str, x: i32, y: i32, button: i32, wheel_delta: i32, ) -> (bool, bool)

マウスイベント完全版。button(0=左,1=中,2=右)と wheel_delta を指定でき、 MouseEvent 標準プロパティ(clientX/Y, pageX/Y, screenX/Y, offsetX/Y, movementX/Y, button, buttons, detail, 修飾キー shiftKey/ctrlKey/altKey/metaKey)を付与する。 wheel イベントの場合は deltaX/deltaY/deltaMode も付与する。

Source

fn push_modifier_props(extra: &mut Vec<(String, Value)>)

現在のグローバル修飾キー状態を shiftKey/ctrlKey/altKey/metaKey として extra へ追加する。

Source

pub fn dispatch_key( &mut self, node_idx: usize, event_type: &str, key: &str, ) -> (bool, bool)

キーイベント(keydown/keyup/keypress/input 等)。key/keyCode/which/code/ location/repeat と修飾キーを付与。key は呼び出し側で正規化済みの値を渡す (“a”, “Enter”, “ArrowLeft” 等)。戻り値: (リスナ発火, preventDefault されたか)。

Source

pub fn dispatch_key_full( &mut self, node_idx: usize, event_type: &str, key: &str, repeat: bool, ) -> (bool, bool)

キーイベント完全版。repeat(オートリピート)を指定できる。 keyCode/which は legacy 仕様に沿って特殊キーへ既定コードを割り当てる。

Source

fn key_attributes(key: &str) -> (u32, String, u32)

key 値から (keyCode, code, location) を導出する。 特殊キーは UI Events 仕様の標準 code と legacy keyCode に対応づける。

Source

pub fn dispatch_event_with( &mut self, node_idx: usize, event_type: &str, extra: &[(String, Value)], ) -> (bool, bool)

汎用イベントディスパッチ本体: capture(祖先→target)→ target → bubble(target→祖先)の 3フェーズで各ノードのリスナを発火。Event は type/target/currentTarget/eventPhase/bubbles/ defaultPrevented + preventDefault/stopPropagation/stopImmediatePropagation/composedPath を 持ち、extra の各プロパティも付与する。once リスナは発火後に削除する。 戻り値: (リスナが発火したか, defaultPrevented か)。

Source

pub fn take_pending_reset(&mut self) -> Option<usize>

form.reset() が積んだリセット要求を回収する。戻り値: Some(form node idx)。 ホストが JS 実行後に呼んで実リセットする。

Source

pub fn take_pending_nav(&mut self) -> i64

history.back/forward/go が積んだナビゲーション要求を回収し 0 にリセットする。 戻り値: 相対移動量(負=戻る / 正=進む / 0=要求なし)。ホストが JS 実行後に呼ぶ。

Source

pub fn take_pending_location(&mut self) -> Option<(String, String)>

location への代入や assign/replace/reload が積んだナビゲーション要求を回収する。 戻り値: Some((url, mode)) — mode は “assign”(履歴に積む) / “replace”(置換) / “hash”(同一ページ内フラグメント) / “reload”(再読込)。要求が無ければ None。 ホストが JS 実行後に呼んで実ナビゲーションする。

Source

fn window_listeners(&self, key: &str) -> Vec<Value>

window の隠し props 配列(_scroll_listeners / _popstate_listeners 等)に 登録されたリスナを複製して返す(無ければ空)。エントリは addEventListener の {signal} 対応(2026-07-14 発見・実装。 builtins::push_window_listener 参照)のため [cb, signal] 形式で 格納されており、ここで abort 済みのものを除外しつつ cb のみへ 展開する。

Source

fn fire_window_listeners( &mut self, listeners: &[Value], event_type: &str, extra: &[(String, Value)], )

指定リスナ群を共有イベントオブジェクト(type + extra props)で順に発火する。

Source

pub fn fire_popstate(&mut self)

window に登録された popstate リスナを発火する(history.back/forward/go の実ナビ後にホストが呼ぶ)。 state は history.state を引き継ぐ。

Source

pub fn has_spa_back(&self) -> bool

SPA back スタック(pushState で積んだ旧 URL/state)にエントリがあるか。

Source

pub fn spa_go_back(&mut self) -> Option<String>

SPA back スタックから1エントリ取り出す。history.state・location.href を復元し popstate を発火する。戻り値: 復元した URL(呼び元がアドレスバー更新に使う)。

Source

pub fn spa_go_forward(&mut self) -> Option<String>

SPA forward スタックから1エントリ取り出す。戻り値: 復元した URL。

Source

pub fn has_spa_forward(&self) -> bool

SPA forward スタックにエントリがあるか。

Source

pub fn fire_scroll(&mut self, scroll_y: i32)

window に登録された scroll リスナを発火する(スクロール位置が変化したときホストが呼ぶ)。 併せて window.scrollY / pageYOffset を更新し、Event に scrollY を載せる。

Source

pub fn fire_hashchange(&mut self, old_url: &str, new_url: &str)

window に登録された hashchange リスナを発火する(location.hash 変更 / アンカー(#)ナビ後にホストが呼ぶ)。 HashChangeEvent 互換で oldURL / newURL を載せる。併せて location.hash を新値へ更新する。

Source

pub fn set_viewport_size(&mut self, width: i32, height: i32)

window.innerWidth / innerHeight(と素の innerWidth/innerHeight)をこの文書の窓の大きさにする (リスナは発火しない)。【2026-10-17】ランタイム生成時のグローバルな値(VIEWPORT_HINT)を 使っていたため、iframe の文書が親ウィンドウの大きさを読んでいた。

Source

pub fn notify_layout_settled(&mut self)

DOM 変更由来の再レイアウトで要素の大きさが確定した後にホストが呼ぶ。ResizeObserver を 新しい寸法で発火し、JS が読んだ寸法が古くなっていれば window の resize リスナも呼ぶ (測り直した値は同じになるので、連鎖はそこで止まる)。 【2026-10-24】実ブラウザは clientWidth 等を読んだ時点で同期的にレイアウトするが、この処理系は 次の再レイアウトまで JS が作った要素の寸法が 0 のまま。YouTube のプレーヤーは作成直後に #movie_player の clientWidth/Height を測り、0 なら window の resize を待つため、動画の高さが 0 のまま再生されなかった。寸法が確定したことを resize で知らせて測り直させる。

Source

pub fn fire_resize(&mut self, width: i32, height: i32)

window に登録された resize リスナを発火する(ウィンドウ/ビューポートサイズ変化時にホストが呼ぶ)。 併せて window.innerWidth / innerHeight を更新し、Event に幅・高さを載せる。

Source

pub fn sync_window_frames(&mut self)

接続済み <iframe> 要素に対応する contentWindow を window[0], window[1], … および window.length に登録する。

Source§

impl JsRuntime

Source

pub fn dom(&self) -> &Rc<RefCell<DomBridge>>

DOM ブリッジへの参照(DOM 付きのランタイムであることを前提とする)。

Source§

impl JsRuntime

Source

pub fn new() -> Self

ブラウザ(DOM・Web API 一式付き)の JavaScript 実行環境を初期化する。

Trait Implementations§

Source§

impl Default for JsRuntime

Source§

fn default() -> Self

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

impl Drop for JsRuntime

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

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> 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> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

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

Source§

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.