diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index bce4edad74..6fda66efe1 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -25,7 +25,12 @@ //! - `app.activeDocument` with no document open throws `No active document`. //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. -//! - Members the help pages list that are not here yet throw an error that says so. +//! - Members the help pages list that are not here yet throw an error that says so, and `reflect` +//! leaves them out. +//! - `reflect` on an object or a class gives each member's type from the declaration that installs +//! the member ([`classes`]): a class name, `boolean`, `number`, `string`, `Array` for a list of +//! numbers, the enumeration's name for an enumerated value, and `*` where the value can be of +//! more than one type. use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -33,7 +38,9 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_geom::{Point, Rect}; -use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts}; +use vectorcraft_js::{ + ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts, +}; use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; @@ -151,9 +158,23 @@ fn method(link: &Link, f: Member) -> HostMember { HostMember::Method(function(link, f)) } +/// A member of a class with what `reflect` tells of it. +type Described = (String, HostMember, MemberInfo); + +/// A property's or a method's result's type for `reflect`. +fn typed(data_type: &str) -> MemberInfo { + MemberInfo { data_type: data_type.into(), ..MemberInfo::default() } +} + +/// A method's result's type and its arguments' names and types, for `reflect`. +fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo { + let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect(); + MemberInfo { arguments, ..typed(data_type) } +} + /// A member the help pages list that is not available yet: reading or assigning it throws, after /// the check that a document or page item `this` is still there. -fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { +fn later(link: &Link, class: &'static str, name: &'static str) -> Described { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -170,7 +191,7 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM } Err(HostError::Error(message.clone())) }); - (name.to_string(), HostMember::Property { get: f.clone(), set: f }) + (name.to_string(), HostMember::Property { get: f.clone(), set: f }, MemberInfo { unavailable: true, ..MemberInfo::default() }) } fn text(s: impl Into) -> Data { @@ -1765,12 +1786,30 @@ fn typename_of(name: &'static str) -> HostMember { HostMember::Get(Rc::new(move |_| Ok(text(name)))) } -fn class(name: &str, parent: Option<&str>, members: Vec<(String, HostMember)>, index: Option) -> HostClass { - HostClass { name: name.into(), parent: parent.map(Into::into), members, index, construct: None } +fn class(name: &str, parent: Option<&str>, members: Vec, index: Option) -> HostClass { + let info = members.iter().map(|(n, _, i)| (n.clone(), i.clone())).collect(); + let members = members.into_iter().map(|(n, m, _)| (n, m)).collect(); + HostClass { name: name.into(), parent: parent.map(Into::into), members, info, index, construct: None } } -fn named(items: Vec<(&str, HostMember)>) -> Vec<(String, HostMember)> { - items.into_iter().map(|(n, m)| (n.to_string(), m)).collect() +fn named(items: Vec<(&str, HostMember, MemberInfo)>) -> Vec { + items.into_iter().map(|(n, m, i)| (n.to_string(), m, i)).collect() +} + +/// The type of a `DocumentPreset` field's value. +fn preset_type(field: &str) -> &'static str { + match field { + "artboardLayout" => "DocumentArtboardLayout", + "colorMode" => "DocumentColorSpace", + "documentBleedLink" => "boolean", + "documentBleedOffsetRect" => "Array", + "previewMode" => "DocumentPreviewMode", + "rasterResolution" => "DocumentRasterResolution", + "title" => "string", + "transparencyGrid" => "DocumentTransparencyGrid", + "units" => "RulerUnits", + _ => "number", + } } /// The enumerations, as frozen objects whose members are `"Name.MEMBER"` strings. @@ -1807,14 +1846,20 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; } + realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))]) +} + +/// The classes of the object model, each member with the type `reflect` gives for it. +fn classes(link: &Link) -> Vec { let l = link; + let placement = [("relativeObject", "*"), ("insertionLocation", "ElementPlacement")]; let mut application = named(vec![ - ("typename", typename_of("Application")), - ("documents", get(l, app_documents)), - ("activeDocument", property(l, app_active, app_set_active)), - ("selection", get(l, app_selection)), - ("coordinateSystem", property(l, app_coords, app_set_coords)), - ("getIsFileOpen", method(l, app_is_open)), + ("typename", typename_of("Application"), typed("string")), + ("documents", get(l, app_documents), MemberInfo { collection: true, ..typed("Documents") }), + ("activeDocument", property(l, app_active, app_set_active), typed("Document")), + ("selection", get(l, app_selection), typed("*")), + ("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")), + ("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])), ]); application.push(later(l, "Application", "beep")); let preset = { @@ -1824,9 +1869,9 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), h.charge_call(64)?; new_preset(&h) }); - let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"))]; - members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k)))); - HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) } + let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"), typed("string"))]; + members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k), typed(preset_type(k))))); + HostClass { construct: Some(f), ..class("DocumentPreset", None, members, None) } }; let mut classes = vec![ class("Application", None, application, None), @@ -1835,29 +1880,52 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "Documents", None, named(vec![ - ("typename", typename_of("Documents")), - ("length", get(l, docs_length)), - ("parent", get(l, app_ref)), - ("index", method(l, docs_index)), - ("getByName", method(l, docs_by_name)), - ("add", method(l, docs_add)), - ("addDocument", method(l, docs_add_document)), + ("typename", typename_of("Documents"), typed("string")), + ("length", get(l, docs_length), typed("number")), + ("parent", get(l, app_ref), typed("Application")), + ("index", method(l, docs_index), returns("Document", &[("itemKey", "*")])), + ("getByName", method(l, docs_by_name), returns("Document", &[("name", "string")])), + ( + "add", + method(l, docs_add), + returns( + "Document", + &[ + ("colorSpace", "DocumentColorSpace"), + ("width", "number"), + ("height", "number"), + ("numArtBoards", "number"), + ("artboardLayout", "DocumentArtboardLayout"), + ("artboardSpacing", "number"), + ("artboardRowsOrCols", "number"), + ], + ), + ), + ( + "addDocument", + method(l, docs_add_document), + returns("Document", &[("startupPreset", "string"), ("presetSettings", "DocumentPreset"), ("showOptionsDialog", "boolean")]), + ), ]), Some(function(l, docs_at)), ), ]; let mut document = named(vec![ - ("typename", get(l, doc_typename)), - ("parent", get(l, doc_parent)), - ("name", get(l, doc_name)), - ("width", get(l, doc_width)), - ("height", get(l, doc_height)), - ("rulerUnits", get(l, doc_units)), - ("documentColorSpace", get(l, doc_color_space)), - ("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin)), - ("convertCoordinate", method(l, doc_convert)), - ("pageItems", get(l, doc_page_items)), - ("selection", property(l, doc_selection, doc_set_selection)), + ("typename", get(l, doc_typename), typed("string")), + ("parent", get(l, doc_parent), typed("Application")), + ("name", get(l, doc_name), typed("string")), + ("width", get(l, doc_width), typed("number")), + ("height", get(l, doc_height), typed("number")), + ("rulerUnits", get(l, doc_units), typed("RulerUnits")), + ("documentColorSpace", get(l, doc_color_space), typed("DocumentColorSpace")), + ("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin), typed("Array")), + ( + "convertCoordinate", + method(l, doc_convert), + returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]), + ), + ("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }), + ("selection", property(l, doc_selection, doc_set_selection), typed("*")), ]); document.extend( ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] @@ -1869,38 +1937,44 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), "PageItems", None, named(vec![ - ("typename", get(l, items_typename)), - ("length", get(l, items_length)), - ("parent", get(l, items_parent)), - ("index", method(l, items_index)), - ("getByName", method(l, items_by_name)), - ("removeAll", method(l, items_remove_all)), + ("typename", get(l, items_typename), typed("string")), + ("length", get(l, items_length), typed("number")), + ("parent", get(l, items_parent), typed("Document")), + ("index", method(l, items_index), returns("PageItem", &[("itemKey", "*")])), + ("getByName", method(l, items_by_name), returns("PageItem", &[("name", "string")])), + ("removeAll", method(l, items_remove_all), returns("undefined", &[])), ]), Some(function(l, items_at)), )); let mut page_item = named(vec![ - ("typename", get(l, item_typename)), - ("parent", get(l, item_parent)), - ("name", property(l, item_name, item_set_name)), - ("note", property(l, item_note, item_set_note)), - ("hidden", property(l, item_hidden, item_set_hidden)), - ("locked", property(l, item_locked, item_set_locked)), - ("selected", property(l, item_selected, item_set_selected)), - ("opacity", property(l, item_opacity, item_set_opacity)), - ("position", property(l, item_position, item_set_position)), - ("left", property(l, item_left, item_set_left)), - ("top", property(l, item_top, item_set_top)), - ("width", property(l, item_width, item_set_width)), - ("height", property(l, item_height, item_set_height)), - ("geometricBounds", get(l, item_geometric)), - ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), - ("editable", get(l, item_editable)), - ("zOrderPosition", get(l, item_z_order_position)), - ("duplicate", method(l, item_duplicate)), - ("move", method(l, item_move)), - ("remove", method(l, item_remove)), - ("zOrder", method(l, item_z_order)), + ("typename", get(l, item_typename), typed("string")), + ("parent", get(l, item_parent), typed("*")), + ("name", property(l, item_name, item_set_name), typed("string")), + ("note", property(l, item_note, item_set_note), typed("string")), + ("hidden", property(l, item_hidden, item_set_hidden), typed("boolean")), + ("locked", property(l, item_locked, item_set_locked), typed("boolean")), + ("selected", property(l, item_selected, item_set_selected), typed("boolean")), + ("opacity", property(l, item_opacity, item_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }), + ("position", property(l, item_position, item_set_position), typed("Array")), + ("left", property(l, item_left, item_set_left), typed("number")), + ("top", property(l, item_top, item_set_top), typed("number")), + ("width", property(l, item_width, item_set_width), typed("number")), + ("height", property(l, item_height, item_set_height), typed("number")), + ("geometricBounds", get(l, item_geometric), typed("Array")), + ("visibleBounds", get(l, item_visible), typed("Array")), + ("controlBounds", get(l, item_visible), typed("Array")), + ("editable", get(l, item_editable), typed("boolean")), + ("zOrderPosition", get(l, item_z_order_position), typed("number")), + ("duplicate", method(l, item_duplicate), returns("PageItem", &placement)), + ("move", method(l, item_move), { + let mut info = returns("PageItem", &placement); + if let Some(at) = info.arguments.get_mut(1) { + at.default = Some(text("ElementPlacement.PLACEATBEGINNING")); + } + info + }), + ("remove", method(l, item_remove), returns("undefined", &[])), + ("zOrder", method(l, item_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])), ]); page_item.extend( [ @@ -1928,8 +2002,13 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ); classes.push(class("PageItem", None, page_item, None)); classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); - classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); - realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) + classes.push(class( + "Layer", + None, + named(vec![("typename", get(l, layer_typename), typed("string")), ("name", get(l, layer_name), typed("string"))]), + None, + )); + classes } #[cfg(test)] @@ -1944,4 +2023,107 @@ mod tests { assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into()))); assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into()))); } + + /// A script function that writes a reflection as one line, in the form [`expected_line`] gives. + const LINE: &str = "function line(r) {\ + function args(a) { var s = []; for (var i = 0; i < a.length; i++) s.push([a[i].name, a[i].type, a[i].dataType, a[i].defaultValue].join('=')); return s.join(','); }\ + function list(a) { var s = []; for (var i = 0; i < a.length; i++) { var e = a[i];\ + s.push([e.name, e.type, e.dataType, e.isCollection, e.min, e.max, e.defaultValue, args(e.arguments)].join(':')); } return s.join(' '); }\ + return r.name + '|' + list(r.properties) + '|' + list(r.methods); }"; + + fn shown(d: Option<&Data>) -> String { + match d { + None | Some(Data::Undefined) => String::new(), + Some(Data::String(s)) => s.clone(), + Some(Data::Number(n)) => n.to_string(), + Some(other) => panic!("no form for {other:?}"), + } + } + + /// The line [`LINE`] should write for `class`: its parents' members, then its own, a member it + /// declares again in its parent's place, without the members that are not available. + fn expected_line(classes: &[HostClass], class: &HostClass) -> String { + let mut chain = vec![class]; + while let Some(p) = chain.last().and_then(|c| c.parent.as_ref()) { + chain.push(classes.iter().find(|c| &c.name == p).unwrap_or_else(|| panic!("no class {p}"))); + } + let mut members: Vec<(String, &'static str, MemberInfo)> = Vec::new(); + for c in chain.iter().rev() { + for (name, member) in &c.members { + let info = c.info.iter().find(|(n, _)| n == name).map(|(_, i)| i.clone()).unwrap_or_default(); + let kind = match member { + HostMember::Get(_) => "readonly", + HostMember::Property { .. } => "readwrite", + HostMember::Method(_) => "method", + }; + match members.iter_mut().find(|(n, ..)| n == name) { + Some(slot) => *slot = (name.clone(), kind, info), + None => members.push((name.clone(), kind, info)), + } + } + } + members.retain(|(.., i)| !i.unavailable); + let one = |(name, kind, i): &(String, &str, MemberInfo)| { + let args: Vec = + i.arguments.iter().map(|a| format!("{}=parameter={}={}", a.name, a.data_type, shown(a.default.as_ref()))).collect(); + let number = |n: Option| n.map(|n| n.to_string()).unwrap_or_default(); + format!( + "{name}:{kind}:{}:{}:{}:{}:{}:{}", + i.data_type, + i.collection, + number(i.min), + number(i.max), + shown(i.default.as_ref()), + args.join(",") + ) + }; + let properties: Vec = members.iter().filter(|m| m.1 != "method").map(one).collect(); + let methods: Vec = members.iter().filter(|m| m.1 == "method").map(one).collect(); + format!("{}|{}|{}", class.name, properties.join(" "), methods.join(" ")) + } + + fn logged(s: &mut Session, source: &str) -> Vec { + let r = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().unwrap_or_else(|| panic!("{r}")).iter().map(|v| v.as_str().unwrap_or_default().to_string()).collect() + } + + #[test] + fn reflect_of_every_class_equals_its_declaration() { + let link = Link::default(); + let classes = classes(&link); + // Every member that is available declares its type, so `reflect` never answers `unknown`. + for c in &classes { + for (name, _) in &c.members { + let info = c.info.iter().find(|(n, _)| n == name).map(|(_, i)| i); + assert!(info.is_some_and(|i| i.unavailable || !i.data_type.is_empty()), "{}.{name} declares no type", c.name); + } + } + let mut s = Session::new(); + let logs: Vec = classes.iter().map(|c| format!("vc.log(line({}.reflect));", c.name)).collect(); + let script = format!("{LINE} {}", logs.join(" ")); + let got = logged(&mut s, &script); + let want: Vec = classes.iter().map(|c| expected_line(&classes, c)).collect(); + assert_eq!(got, want); + assert!(want.iter().any(|w| w.contains("insertionLocation=parameter=ElementPlacement=ElementPlacement.PLACEATBEGINNING"))); + } + + #[test] + fn reflect_of_an_object_equals_its_class_and_calls_no_member() { + let link = Link::default(); + let classes = classes(&link); + let want = |name: &str| expected_line(&classes, classes.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("no class {name}"))); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap_or_else(|e| panic!("{e}")); + s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap_or_else(|e| panic!("{e}")); + let script = format!( + "{LINE} var d = app.activeDocument, p = d.pageItems[0]; vc.log(line(app.reflect)); vc.log(line(app.documents.reflect));\ + vc.log(line(d.reflect)); vc.log(line(d.pageItems.reflect)); vc.log(line(p.reflect)); vc.log(line(new DocumentPreset().reflect));\ + p.remove(); vc.log(line(p.reflect)); vc.log(String(p.reflect.find('opacity').max));" + ); + let got = logged(&mut s, &script); + let path = want("PathItem"); + let expected = + [want("Application"), want("Documents"), want("Document"), want("PageItems"), path.clone(), want("DocumentPreset"), path, "100".into()]; + assert_eq!(got, expected); + } } diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index d9b6b87103..4b3b95e517 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -45,7 +45,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// documents; `Document.saveAs` and `close` throw "not available yet". const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder alert confirm localize prompt toSource"), - ("Object.prototype.", "toSource"), + ("Object.prototype.", "reflect toSource"), ("localize.", "length"), ("toSource.", "length"), ( diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs index 94ee226d57..68eca8d657 100644 --- a/crates/js/src/builtins/extensions.rs +++ b/crates/js/src/builtins/extensions.rs @@ -1,6 +1,6 @@ //! The script extensions a host adds with [`crate::Realm::add_script_extensions`]: the global -//! `localize`, the global `toSource` and `Object.prototype.toSource`, and the getters behind -//! [`crate::ScriptItem`]. `localize` and `Object.prototype.toString` read the locale of +//! `localize`, the global `toSource` and `Object.prototype.toSource`, `Object.prototype.reflect` +//! ([`crate::reflect`]), and the getters behind [`crate::ScriptItem`]. `localize` and `Object.prototype.toString` read the locale of //! [`Localization`]. //! //! `toSource` writes primitives, arrays and plain objects as the text of a JavaScript expression @@ -96,7 +96,8 @@ pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { method(interp, global, "localize", localize, 1)?; method(interp, global, "toSource", to_source, 1)?; let object_proto = interp.intrinsics.object_proto; - method(interp, object_proto, "toSource", to_source_method, 0) + method(interp, object_proto, "toSource", to_source_method, 0)?; + crate::reflect::install(interp) } /// The text of the localization object `id` for the current locale: the string value of the first diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..2af2fc130f 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -17,6 +17,11 @@ //! setter gets `this` and the value assigned. A class with an indexer answers `object[i]` for each //! array index `i` with it, called with `this` and the index, and `i in object` is true when it //! gives a value other than `undefined`; other names are looked up as usual. +//! +//! A script's `reflect` ([`crate::reflect`]) describes an object of a host class, and the class's +//! constructor, from the members installed here and their [`HostClass::info`], so what a script is +//! told always matches what the class has. A class that names a member twice, or describes a member +//! it does not have, is refused. use std::rc::Rc; @@ -40,6 +45,39 @@ pub enum HostMember { Method(HostFunction), } +/// What a script's `reflect` tells of a member of a host class ([`HostClass::info`]). The member's +/// name and whether it is read-only, read-write or a method come from the [`HostMember`] itself. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MemberInfo { + /// The type of the member's value, or of a method's result: `boolean`, `number`, `string`, a + /// class name, `*` for any type, `null` or `undefined`. Empty reads as `unknown`. + pub data_type: String, + pub description: Option, + pub help: Option, + /// The value an omitted value means. + pub default: Option, + pub min: Option, + pub max: Option, + /// The value, or a method's result, is a collection. + pub collection: bool, + /// A method's arguments, in order. + pub arguments: Vec, + /// The member is installed but throws when used: `reflect` leaves it out. + pub unavailable: bool, +} + +/// What a script's `reflect` tells of an argument of a host class's method ([`MemberInfo::arguments`]). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ArgInfo { + pub name: String, + /// As [`MemberInfo::data_type`]. + pub data_type: String, + pub description: Option, + pub default: Option, + pub min: Option, + pub max: Option, +} + /// A class [`crate::Realm::define_host_classes`] adds. #[derive(Clone)] pub struct HostClass { @@ -48,6 +86,9 @@ pub struct HostClass { /// class's prototype inherits from. pub parent: Option, pub members: Vec<(String, HostMember)>, + /// What `reflect` tells of the members, each under the name of one of `members`. A member + /// without an entry has the type `unknown` and nothing else. + pub info: Vec<(String, MemberInfo)>, /// What `object[i]` gives for an array index `i`. pub index: Option, /// What `new Name(...)` and `Name(...)` give; without it both throw a `TypeError`. @@ -72,6 +113,26 @@ pub(crate) struct Entry { /// The class without a parent this class descends from (itself for such a class), as an index /// into the realm's classes. family: u32, + /// The parent class, as an index into the realm's classes. + parent: Option, + /// The class's own members as `reflect` lists them. + members: Rc<[Reflected]>, +} + +/// How a script may use a member of a host class. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Access { + ReadOnly, + ReadWrite, + Method, +} + +/// A member of a host class as `reflect` lists it. +#[derive(Clone, Debug)] +pub(crate) struct Reflected { + pub(crate) name: Rc, + pub(crate) access: Access, + pub(crate) info: MemberInfo, } impl Entry { @@ -168,6 +229,41 @@ impl Interp { self.host_classes.iter().any(|e| e.ctor == id) } + /// The name of the host class of `id`, when it is an object of a host class. + pub(crate) fn host_class_name(&self, id: ObjId) -> JsResult>> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + Ok(self.host_classes.get(h.class as usize).map(|e| e.name.clone())) + } + + /// The name and members of the host class of `id`, an object of the class or its constructor: + /// the members of its parents first, then its own, a member a class declares again in the place + /// of its parent's. Members marked [`MemberInfo::unavailable`] are left out. `None` when `id` is + /// neither. + pub(crate) fn host_class_members(&self, id: ObjId) -> JsResult, Vec)>> { + let class = match &self.object(id)?.class { + Class::Host(h) => Some(h.class as usize), + _ => self.host_classes.iter().position(|e| e.ctor == id), + }; + let Some(class) = class else { return Ok(None) }; + let Some(entry) = self.host_classes.get(class) else { return Err(Abrupt::Internal("host class out of range".into())) }; + let mut chain = vec![entry]; + while let Some(p) = chain.last().and_then(|e| e.parent) { + let Some(parent) = self.host_classes.get(p as usize) else { return Err(Abrupt::Internal("host class out of range".into())) }; + chain.push(parent); + } + let mut out: Vec = Vec::new(); + for e in chain.iter().rev() { + for m in e.members.iter() { + match out.iter_mut().find(|r| r.name == m.name) { + Some(slot) => *slot = m.clone(), + None => out.push(m.clone()), + } + } + } + out.retain(|m| !m.info.unavailable); + Ok(Some((entry.name.clone(), out))) + } + /// The indexer of the host class of `id`, when it is an object of a host class that has one. pub(crate) fn host_indexer(&self, id: ObjId) -> JsResult> { let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; @@ -223,24 +319,57 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { return Err(i.throw(ErrorType::Type, &format!("the host class {} is defined twice", class.name))); } let own = u32::try_from(i.host_classes.len()).unwrap_or(u32::MAX); - let (parent, family) = match &class.parent { - None => (i.intrinsics.object_proto, own), - Some(p) => match i.host_classes.iter().find(|e| *e.name == **p) { - Some(e) => (e.proto, e.family), + let (parent, family, parent_index) = match &class.parent { + None => (i.intrinsics.object_proto, own, None), + Some(p) => match i.host_classes.iter().enumerate().find(|(_, e)| *e.name == **p) { + Some((n, e)) => (e.proto, e.family, Some(u32::try_from(n).unwrap_or(u32::MAX))), None => return Err(i.throw(ErrorType::Type, &format!("the host class {p} is not defined"))), }, }; + let members = match reflected_members(&class) { + Ok(m) => m, + Err(message) => return Err(i.throw(ErrorType::Type, &message)), + }; let proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(parent))); let mark = i.temp_roots.len(); i.temp_roots.push(Value::Object(proto)); let r = fill_class(i, proto, &class); i.temp_roots.truncate(mark); let ctor = r?; - i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family }); + i.host_classes.push(Entry { name: class.name.as_str().into(), proto, ctor, index: class.index, family, parent: parent_index, members }); let global = i.global; i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) } +/// The members of `class` as `reflect` lists them, each with its [`HostClass::info`] entry. → the +/// error's message when a member is named twice, or an entry names no member or is given twice. +fn reflected_members(class: &HostClass) -> Result, String> { + let mut out: Vec = Vec::with_capacity(class.members.len()); + for (name, member) in &class.members { + if out.iter().any(|r| *r.name == **name) { + return Err(format!("the host class {} names the member {name} twice", class.name)); + } + let access = match member { + HostMember::Get(_) => Access::ReadOnly, + HostMember::Property { .. } => Access::ReadWrite, + HostMember::Method(_) => Access::Method, + }; + out.push(Reflected { name: name.as_str().into(), access, info: MemberInfo::default() }); + } + let mut seen: Vec<&str> = Vec::with_capacity(class.info.len()); + for (name, info) in &class.info { + if seen.contains(&name.as_str()) { + return Err(format!("the host class {} describes the member {name} twice", class.name)); + } + seen.push(name); + let Some(slot) = out.iter_mut().find(|r| *r.name == **name) else { + return Err(format!("the host class {} describes {name}, which is not one of its members", class.name)); + }; + slot.info = info.clone(); + } + Ok(out.into()) +} + /// Puts the members of `class` on `proto` and makes its constructor. → the constructor. fn fill_class(i: &mut Interp, proto: ObjId, class: &HostClass) -> JsResult { let path = &class.name; diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..040361d460 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -644,7 +644,7 @@ fn with_thing(r: &mut Realm, make: Option) { let fetch: HostFunction = Rc::new(move |_| if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) }); let id: HostFunction = Rc::new(|a| Ok(a.first().and_then(host_ref_parts).and_then(|(_, h)| h.first().copied()).map_or(Data::Null, Data::Number))); let members = vec![("fetch".to_string(), HostMember::Method(fetch)), ("id".to_string(), HostMember::Get(id))]; - let class = HostClass { name: "Thing".into(), parent: None, members, index: None, construct: make }; + let class = HostClass { name: "Thing".into(), parent: None, members, info: Vec::new(), index: None, construct: make }; r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap(); } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1d7af9e4fb..8d61712e36 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -65,6 +65,7 @@ mod number; mod number_builtins; mod parser; mod realm; +mod reflect; mod regexp; mod regexp_builtins; mod regexp_vm; @@ -82,10 +83,11 @@ pub use ast::{ pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; -pub use host_classes::{HOST_REF_KEY, HostClass, HostMember, host_ref, host_ref_parts}; +pub use host_classes::{ArgInfo, HOST_REF_KEY, HostClass, HostMember, MemberInfo, host_ref, host_ref_parts}; pub use lexer::{Goal, Lexer}; pub use number::to_string as number_to_string; pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; +pub use reflect::MAX_REFLECTED_MEMBERS; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; /// How a script is read. @@ -211,6 +213,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod reflect_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod text_tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index f1ca6b570d..745c2b9364 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -539,7 +539,9 @@ impl Realm { /// Adds the script extensions: the global `localize(object, ...values)`, which gives a /// localization object's text for the locale of [`Realm::localization`], the global /// `toSource(value)` and `Object.prototype.toSource()`, which write plain data as source text, - /// and the localized `Object.prototype.toString` while [`crate::Localization::enabled`]. + /// `Object.prototype.reflect`, which describes an object's properties and methods (a host + /// class's from its [`crate::HostClass`]), and the localized `Object.prototype.toString` while + /// [`crate::Localization::enabled`]. pub fn add_script_extensions(&mut self) -> Result<(), RunError> { match crate::builtins::extensions::install(&mut self.interp) { Ok(()) => Ok(()), diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs new file mode 100644 index 0000000000..a84c221d3a --- /dev/null +++ b/crates/js/src/reflect.rs @@ -0,0 +1,331 @@ +//! The script extension `reflect` ([`crate::Realm::add_script_extensions`]): a read-only property +//! of `Object.prototype` that gives, on each read, a new reflection object describing the object it +//! is read on. +//! +//! A reflection object has `name` (the object's class), `description` and `help` (`undefined`), +//! `properties` and `methods` (arrays of ReflectionInfo objects), and `find(name)`, which gives the +//! ReflectionInfo of the property or method with that name, or `null`. A ReflectionInfo has `name` +//! (a string, or a number for an array index), `description`, `help`, `type` (`readonly`, +//! `readwrite`, `method`, or `parameter` for a method's argument), `dataType`, `defaultValue`, +//! `min`, `max`, `isCollection` and `arguments` (an array of ReflectionInfo objects, empty for a +//! property). Each entry of `properties`, `methods` and `arguments` is also under its name when +//! that name is not an array index or `length`. +//! +//! An object of a host class and the class's constructor are described by the class's members +//! ([`crate::HostClass::members`] and [`crate::HostClass::info`]), its parents' included. Any other +//! object is described by its own properties: a property whose value is a function is a method, +//! with the parameter names of a function written in JavaScript as its arguments; a data property +//! is read-write when it is writable and gives the type of its value; an accessor is read-write +//! when it has a setter and its type is `unknown`. A string, number or boolean is described by its +//! prototype's own properties. No getter or other script code runs. +//! +//! Every object made is frozen, so a script cannot change one; `reflect` itself has no setter. +//! Each member described takes fuel, and an object with more than [`MAX_REFLECTED_MEMBERS`] +//! members and arguments throws a `RangeError`. + +use crate::builtins::native; +use crate::heap::{Class, ENUMERABLE, Func, Key, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, WRITABLE, key}; +use crate::host::Data; +use crate::host_classes::{Access, Reflected}; +use crate::interp::{ErrorType, Interp, JsResult}; +use crate::value::{Str, Value, array_index, index_key, number_to_str}; + +/// The most members and arguments `reflect` describes for one object. +pub const MAX_REFLECTED_MEMBERS: usize = 10_000; + +/// The properties of a ReflectionInfo object. +const INFO_PROPS: usize = 10; + +/// A member or argument as a ReflectionInfo object describes it. +struct Info { + name: Value, + kind: &'static str, + data_type: String, + description: Option, + help: Option, + default: Option, + min: Option, + max: Option, + collection: bool, + arguments: Vec, +} + +impl Info { + fn new(name: Value, kind: &'static str, data_type: &str) -> Self { + Self { + name, + kind, + data_type: data_type.to_string(), + description: None, + help: None, + default: None, + min: None, + max: None, + collection: false, + arguments: Vec::new(), + } + } +} + +/// The type a [`crate::MemberInfo`] gives, `unknown` when it gives none. +fn declared(data_type: &str) -> &str { + if data_type.is_empty() { "unknown" } else { data_type } +} + +pub(crate) fn install(interp: &mut Interp) -> JsResult<()> { + let get = native(interp, "reflect", reflect, 0, NativeKind::Plain, false)?; + let object_proto = interp.intrinsics.object_proto; + interp.define(object_proto, key("reflect"), Prop::Accessor { get: Some(get), set: None, flags: 0 }) +} + +/// Counts one more member or argument against [`MAX_REFLECTED_MEMBERS`], with a unit of fuel. +fn count(interp: &mut Interp, total: &mut usize) -> JsResult<()> { + interp.use_fuel()?; + *total += 1; + if *total > MAX_REFLECTED_MEMBERS { + return Err(interp.throw(ErrorType::Range, &format!("reflect: the object has more than {MAX_REFLECTED_MEMBERS} members"))); + } + Ok(()) +} + +/// The getter of `Object.prototype.reflect`. +fn reflect(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (id, primitive) = match &this { + Value::Undefined | Value::Null => return Err(interp.type_error("reflect needs an object")), + Value::String(_) => (interp.intrinsics.string_proto, Some("String")), + Value::Number(_) => (interp.intrinsics.number_proto, Some("Number")), + Value::Bool(_) => (interp.intrinsics.boolean_proto, Some("Boolean")), + Value::Object(o) => (*o, None), + }; + let (name, properties, methods) = match interp.host_class_members(id)? { + Some((name, members)) if primitive.is_none() => { + let (properties, methods) = host_infos(interp, &members)?; + (name.to_string(), properties, methods) + } + _ => { + let name = primitive.unwrap_or(interp.object(id)?.class.name()).to_string(); + let (properties, methods) = own_infos(interp, id)?; + (name, properties, methods) + } + }; + interp.rooted(&[this], |i| { + let mark = i.temp_roots.len(); + let r = reflection(i, &name, &properties, &methods); + i.temp_roots.truncate(mark); + r + }) +} + +/// The properties and methods of a host class's `members`. +fn host_infos(interp: &mut Interp, members: &[Reflected]) -> JsResult<(Vec, Vec)> { + let (mut properties, mut methods) = (Vec::new(), Vec::new()); + let mut total = 0; + for m in members { + count(interp, &mut total)?; + let kind = match m.access { + Access::ReadOnly => "readonly", + Access::ReadWrite => "readwrite", + Access::Method => "method", + }; + let mut info = Info::new(Value::str(&m.name), kind, declared(&m.info.data_type)); + info.description = m.info.description.clone(); + info.help = m.info.help.clone(); + info.default = m.info.default.clone(); + info.min = m.info.min; + info.max = m.info.max; + info.collection = m.info.collection; + for a in &m.info.arguments { + count(interp, &mut total)?; + let mut arg = Info::new(Value::str(&a.name), "parameter", declared(&a.data_type)); + arg.description = a.description.clone(); + arg.default = a.default.clone(); + arg.min = a.min; + arg.max = a.max; + info.arguments.push(arg); + } + if m.access == Access::Method { methods.push(info) } else { properties.push(info) } + } + Ok((properties, methods)) +} + +/// The properties and methods of the own properties of `id`. No getter runs. +fn own_infos(interp: &mut Interp, id: ObjId) -> JsResult<(Vec, Vec)> { + let o = interp.object(id)?; + let extra = match &o.class { + Class::String(s) => s.len().saturating_add(1), + Class::Array { .. } => 1, + _ => 0, + }; + // Checked before the names are listed, so a huge object costs no more than a small one. + if o.props.len().saturating_add(extra) > MAX_REFLECTED_MEMBERS { + return Err(interp.throw(ErrorType::Range, &format!("reflect: the object has more than {MAX_REFLECTED_MEMBERS} members"))); + } + let keys = interp.own_keys(id)?; + let (mut properties, mut methods) = (Vec::new(), Vec::new()); + let mut total = 0; + for k in keys { + count(interp, &mut total)?; + let Some(prop) = interp.get_own_property(id, &k)? else { continue }; + let name = member_name(&k); + match prop { + Prop::Data { value, .. } if interp.is_callable(&value) => { + let mut info = Info::new(name, "method", "unknown"); + if let Some(params) = parameters(interp, &value)? { + for p in params { + count(interp, &mut total)?; + info.arguments.push(Info::new(Value::String(Str::from_rc(p)), "parameter", "*")); + } + } + methods.push(info); + } + Prop::Data { value, flags } => { + let kind = if flags & WRITABLE != 0 { "readwrite" } else { "readonly" }; + let data_type = value_type(interp, &value)?; + properties.push(Info::new(name, kind, &data_type)); + } + Prop::Accessor { set, .. } => properties.push(Info::new(name, if set.is_some() { "readwrite" } else { "readonly" }, "unknown")), + } + } + Ok((properties, methods)) +} + +/// A property name as a ReflectionInfo's `name`: a number for an array index. +fn member_name(k: &Key) -> Value { + match array_index(k) { + Some(i) => Value::Number(f64::from(i)), + None => Value::String(Str::from_rc(k.clone())), + } +} + +/// The parameter names of the function `f` when it is written in JavaScript. +fn parameters(interp: &Interp, f: &Value) -> JsResult>> { + let Some(id) = f.as_object() else { return Ok(None) }; + Ok(match &interp.object(id)?.class { + Class::Function(Func::Closure { code, .. }) => Some(code.params.clone()), + _ => None, + }) +} + +/// The `dataType` of a data property holding `v`. +fn value_type(interp: &Interp, v: &Value) -> JsResult { + Ok(match v { + Value::Undefined => "undefined".into(), + Value::Null => "null".into(), + Value::Bool(_) => "boolean".into(), + Value::Number(_) => "number".into(), + Value::String(_) => "string".into(), + Value::Object(o) => match interp.host_class_name(*o)? { + Some(name) => name.to_string(), + None => interp.object(*o)?.class.name().into(), + }, + }) +} + +/// The reflection object. Every object it makes is kept in `interp.temp_roots`. +fn reflection(interp: &mut Interp, name: &str, properties: &[Info], methods: &[Info]) -> JsResult { + let properties = info_array(interp, properties)?; + let methods = info_array(interp, methods)?; + interp.reserve_heap(2 * OBJECT_BYTES + 8 * PROP_BYTES)?; + let find = native(interp, "find", find, 1, NativeKind::Plain, false)?; + interp.temp_roots.push(Value::Object(find)); + let r = interp.new_object(); + interp.temp_roots.push(Value::Object(r)); + for (k, v) in [ + ("name", Value::str(name)), + ("description", Value::Undefined), + ("help", Value::Undefined), + ("properties", Value::Object(properties)), + ("methods", Value::Object(methods)), + ] { + interp.define(r, key(k), Prop::Data { value: v, flags: ENUMERABLE })?; + } + interp.define(r, key("find"), Prop::Data { value: Value::Object(find), flags: 0 })?; + interp.object_mut(r)?.extensible = false; + Ok(Value::Object(r)) +} + +/// A frozen array of ReflectionInfo objects for `infos`, each also under its name when that name +/// is not an array index or `length`. +fn info_array(interp: &mut Interp, infos: &[Info]) -> JsResult { + interp.reserve_heap(OBJECT_BYTES.saturating_add(infos.len().saturating_mul(2 * PROP_BYTES)))?; + let proto = interp.intrinsics.array_proto; + let a = interp.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: false }, Some(proto))); + interp.temp_roots.push(Value::Object(a)); + for (n, info) in infos.iter().enumerate() { + let o = info_object(interp, info)?; + interp.define(a, index_key(u32::try_from(n).unwrap_or(u32::MAX)), Prop::Data { value: Value::Object(o), flags: ENUMERABLE })?; + } + for (n, info) in infos.iter().enumerate() { + let Value::String(s) = &info.name else { continue }; + let k = s.flat(); + if array_index(&k).is_some() || *k == *key("length") || interp.object(a)?.props.contains(&k) { + continue; + } + let Some(Prop::Data { value, .. }) = interp.get_own_property(a, &index_key(u32::try_from(n).unwrap_or(u32::MAX)))? else { continue }; + interp.define(a, k, Prop::Data { value, flags: 0 })?; + } + interp.object_mut(a)?.extensible = false; + Ok(a) +} + +/// A frozen ReflectionInfo object for `info`. +fn info_object(interp: &mut Interp, info: &Info) -> JsResult { + let arguments = info_array(interp, &info.arguments)?; + interp.reserve_heap(OBJECT_BYTES + INFO_PROPS * PROP_BYTES)?; + let o = interp.new_object(); + interp.temp_roots.push(Value::Object(o)); + let text = |s: &Option| s.as_deref().map_or(Value::Undefined, Value::str); + let number = |n: Option| n.map_or(Value::Undefined, Value::Number); + let default = match &info.default { + Some(d) => interp.write_data(d.clone(), 0, true)?, + None => Value::Undefined, + }; + let fields = [ + ("name", info.name.clone()), + ("description", text(&info.description)), + ("help", text(&info.help)), + ("type", Value::str(info.kind)), + ("dataType", Value::str(&info.data_type)), + ("defaultValue", default), + ("min", number(info.min)), + ("max", number(info.max)), + ("isCollection", Value::Bool(info.collection)), + ("arguments", Value::Object(arguments)), + ]; + for (k, v) in fields { + interp.define(o, key(k), Prop::Data { value: v, flags: ENUMERABLE })?; + } + interp.object_mut(o)?.extensible = false; + Ok(o) +} + +/// `reflect.find(name)`: the ReflectionInfo of the property, or else the method, named `name` (a +/// string, or a number for an array index), or `null`. +fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let wanted = match args.first() { + Some(Value::String(s)) => s.flat(), + Some(Value::Number(n)) => number_to_str(*n).flat(), + _ => return Err(interp.type_error("reflect.find: give the member's name, as a string or a number")), + }; + let not_reflection = "reflect.find must be called on a reflection object"; + let Value::Object(r) = this else { return Err(interp.type_error(not_reflection)) }; + for list in ["properties", "methods"] { + let Some(Prop::Data { value: Value::Object(a), .. }) = interp.get_own_property(r, &key(list))? else { + return Err(interp.type_error(not_reflection)); + }; + let Class::Array { length, .. } = interp.object(a)?.class else { return Err(interp.type_error(not_reflection)) }; + for i in 0..length { + interp.use_fuel()?; + let Some(Prop::Data { value: Value::Object(e), .. }) = interp.get_own_property(a, &index_key(i))? else { continue }; + let name = match interp.get_own_property(e, &key("name"))? { + Some(Prop::Data { value: Value::String(s), .. }) => s.flat(), + Some(Prop::Data { value: Value::Number(n), .. }) => number_to_str(n).flat(), + _ => continue, + }; + if *name == *wanted { + return Ok(Value::Object(e)); + } + } + } + Ok(Value::Null) +} diff --git a/crates/js/src/reflect_tests.rs b/crates/js/src/reflect_tests.rs new file mode 100644 index 0000000000..3e8827cf4f --- /dev/null +++ b/crates/js/src/reflect_tests.rs @@ -0,0 +1,242 @@ +//! `reflect`: the description of an object's properties and methods, from a host class's members +//! or from an object's own properties. + +use std::rc::Rc; + +use super::*; + +fn realm() -> Realm { + let mut r = Realm::new(); + r.add_script_extensions().unwrap(); + r +} + +fn text(r: &mut Realm, source: &str) -> String { + match r.run(source) { + Ok(JsValue::String(s)) => s, + other => panic!("{source}: {other:?}"), + } +} + +fn thrown(r: &mut Realm, source: &str) -> String { + match r.run(source) { + Err(e) if e.kind == RunErrorKind::Thrown => e.message, + other => panic!("{source}: {other:?}"), + } +} + +/// `name:type:dataType` of each entry of a list, joined with spaces. +const LIST: &str = "function list(a) { var s = []; for (var i = 0; i < a.length; i++) s.push(a[i].name + ':' + a[i].type + ':' + a[i].dataType); \ + return s.join(' '); }"; + +#[test] +fn a_script_object_lists_its_own_properties_and_methods_without_running_getters() { + let mut r = realm(); + let setup = "var o = {a: 1, b: 'x', c: null, d: [1], f: function (p, q) {}, get g() { throw new Error('ran'); }, set h(v) {}};\ + Object.defineProperty(o, 'k', {value: true, writable: false});"; + r.run(setup).unwrap(); + r.run(LIST).unwrap(); + assert_eq!(text(&mut r, "o.reflect.name"), "Object"); + assert_eq!( + text(&mut r, "list(o.reflect.properties)"), + "a:readwrite:number b:readwrite:string c:readwrite:null d:readwrite:Array g:readonly:unknown h:readwrite:unknown k:readonly:boolean" + ); + assert_eq!(text(&mut r, "list(o.reflect.methods)"), "f:method:unknown"); + assert_eq!(text(&mut r, "list(o.reflect.methods[0].arguments)"), "p:parameter:* q:parameter:*"); + assert_eq!(text(&mut r, "list(o.reflect.properties[0].arguments) + '|' + o.reflect.description + '|' + o.reflect.help"), "|undefined|undefined"); + // A value replaced by a function becomes a method on the next read; each read is a new snapshot. + assert_eq!( + text(&mut r, "var before = o.reflect; o.a = function () {}; delete o.b; list(before.methods) + '|' + list(o.reflect.methods)"), + "f:method:unknown|a:method:unknown f:method:unknown" + ); + assert_eq!(text(&mut r, "String(o.reflect.find('b'))"), "null"); +} + +#[test] +fn find_and_names_look_up_properties_then_methods() { + let mut r = realm(); + r.run("var o = {width: 2, draw: function () {}};").unwrap(); + assert_eq!(text(&mut r, "o.reflect.find('width').dataType + ' ' + o.reflect.find('draw').type"), "number method"); + assert_eq!(text(&mut r, "String(o.reflect.find('nothing'))"), "null"); + assert_eq!(text(&mut r, "o.reflect.properties.width.name + ' ' + o.reflect.methods.draw.name"), "width draw"); + // Array indexes are numbers, found by number or by their text. + assert_eq!( + text( + &mut r, + "var a = [5, 'x']; a[3] = true; var f = a.reflect.find(1); typeof f.name + ' ' + f.dataType + ' ' + a.reflect.find('3').dataType" + ), + "number string boolean" + ); + assert_eq!(text(&mut r, "[5].reflect.properties.length + ' ' + [5].reflect.find('length').type"), "2 readwrite"); + // A name that is missing or of another type is refused. + assert!(thrown(&mut r, "o.reflect.find();").starts_with("TypeError")); + assert!(thrown(&mut r, "o.reflect.find({});").starts_with("TypeError")); + assert!(thrown(&mut r, "o.reflect.find.call({}, 'width');").starts_with("TypeError")); +} + +#[test] +fn a_reflection_info_has_every_field() { + let mut r = realm(); + let fields = "var i = ({a: 1}).reflect.properties[0]; var k = []; for (var n in i) k.push(n); k.join(' ')"; + assert_eq!(text(&mut r, fields), "name description help type dataType defaultValue min max isCollection arguments"); + let values = + "var i = ({a: 1}).reflect.properties[0]; [i.description, i.help, i.defaultValue, i.min, i.max, i.isCollection, i.arguments.length].join()"; + assert_eq!(text(&mut r, values), ",,,,,false,0"); + assert_eq!(text(&mut r, "var k = []; for (var n in ({}).reflect) k.push(n); k.join(' ')"), "name description help properties methods"); +} + +#[test] +fn functions_primitives_and_built_ins_are_described() { + let mut r = realm(); + r.run(LIST).unwrap(); + assert_eq!( + text(&mut r, "function f(a, b) {} f.reflect.name + ' ' + list(f.reflect.properties)"), + "Function length:readonly:number prototype:readwrite:Object" + ); + assert_eq!(text(&mut r, "Math.reflect.name + ' ' + Math.reflect.find('PI').type + ' ' + Math.reflect.find('max').type"), "Math readonly method"); + assert_eq!(text(&mut r, "'abc'.reflect.name + ' ' + 'abc'.reflect.find('charAt').type"), "String method"); + assert_eq!(text(&mut r, "(5).reflect.name + ' ' + true.reflect.name"), "Number Boolean"); + assert!(thrown(&mut r, "var n = null; n.reflect;").starts_with("TypeError")); + let getter = "Object.getOwnPropertyDescriptor(Object.prototype, 'reflect').get"; + assert!(thrown(&mut r, &format!("{getter}.call(undefined);")).starts_with("TypeError")); + // Neither a getter nor `toString` runs, so a cyclic object is described as it is. + assert_eq!(text(&mut r, "var c = {}; c.self = c; c.toString = function () { throw 1; }; c.reflect.find('self').dataType"), "Object"); +} + +#[test] +fn a_reflection_cannot_be_changed() { + let mut r = realm(); + r.run("var o = {a: 1}; var x = o.reflect;").unwrap(); + // Outside strict mode the writes are ignored. + let tries = "o.reflect = 5; x.name = 'y'; x.properties[0].dataType = 'y'; x.properties[1] = 2; x.extra = 1; delete x.methods;\ + [typeof o.reflect, x.name, x.properties[0].dataType, x.properties.length, x.extra, typeof x.methods].join()"; + assert_eq!(text(&mut r, tries), "object,Object,number,1,,object"); + // In strict mode each one throws a TypeError. + for write in ["o.reflect = 5", "x.name = 'y'", "x.properties[0].type = 'y'", "x.properties.push(1)", "x.extra = 1", "delete x.find"] { + assert!(thrown(&mut r, &format!("(function () {{ 'use strict'; {write}; }})();")).starts_with("TypeError"), "{write}"); + } + assert_eq!( + text(&mut r, "Object.isFrozen(x) + ' ' + Object.isFrozen(x.properties) + ' ' + Object.isFrozen(x.properties[0].arguments)"), + "true true true" + ); +} + +#[test] +fn a_very_wide_object_is_refused() { + let mut r = realm(); + let wide = |n: usize| format!("var w = {{}}; for (var i = 0; i < {n}; i++) w['p' + i] = i;"); + r.run(&wide(MAX_REFLECTED_MEMBERS)).unwrap(); + assert_eq!(text(&mut r, "String(w.reflect.properties.length)"), MAX_REFLECTED_MEMBERS.to_string()); + r.run(&wide(MAX_REFLECTED_MEMBERS + 1)).unwrap(); + assert!(thrown(&mut r, "w.reflect;").starts_with("RangeError")); + // A function with too many parameters is counted with the members. + let params = (0..MAX_REFLECTED_MEMBERS).map(|i| format!("a{i}")).collect::>().join(","); + assert!(thrown(&mut r, &format!("({{f: function ({params}) {{}}}}).reflect;")).starts_with("RangeError")); +} + +fn constant(value: f64) -> HostFunction { + Rc::new(move |_| Ok(Data::Number(value))) +} + +/// `Item` with `size` (read-write, 1 to 10, default 5), `kind` and the method `fit(target, +/// margin?)`; and `Box`, a child that declares `kind` again as a method and adds `cut`, which is +/// not available. +fn classes() -> Vec { + let item = HostClass { + name: "Item".into(), + parent: None, + members: vec![ + ("size".into(), HostMember::Property { get: constant(5.0), set: constant(0.0) }), + ("kind".into(), HostMember::Get(constant(1.0))), + ("fit".into(), HostMember::Method(constant(2.0))), + ], + info: vec![ + ( + "size".into(), + MemberInfo { + data_type: "number".into(), + description: Some("The size.".into()), + help: Some("How large the item is.".into()), + default: Some(Data::Number(5.0)), + min: Some(1.0), + max: Some(10.0), + ..MemberInfo::default() + }, + ), + ( + "fit".into(), + MemberInfo { + data_type: "boolean".into(), + collection: true, + arguments: vec![ + ArgInfo { name: "target".into(), data_type: "Item".into(), ..ArgInfo::default() }, + ArgInfo { + name: "margin".into(), + data_type: "number".into(), + default: Some(Data::Number(0.0)), + min: Some(0.0), + ..ArgInfo::default() + }, + ], + ..MemberInfo::default() + }, + ), + ], + index: None, + construct: None, + }; + let child = HostClass { + name: "Box".into(), + parent: Some("Item".into()), + members: vec![("kind".into(), HostMember::Method(constant(3.0))), ("cut".into(), HostMember::Method(constant(4.0)))], + info: vec![("cut".into(), MemberInfo { unavailable: true, ..MemberInfo::default() })], + index: None, + construct: None, + }; + vec![item, child] +} + +#[test] +fn a_host_class_is_described_by_its_members_and_their_info() { + let mut r = realm(); + r.define_host_classes(classes(), vec![("item".into(), host_ref("Item", &[1.0])), ("box".into(), host_ref("Box", &[2.0]))]).unwrap(); + r.run(LIST).unwrap(); + for target in ["item", "Item"] { + assert_eq!(text(&mut r, &format!("{target}.reflect.name")), "Item"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.properties)")), "size:readwrite:number kind:readonly:unknown"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.methods)")), "fit:method:boolean"); + } + let size = "var s = item.reflect.find('size'); [s.description, s.help, s.defaultValue, s.min, s.max, s.isCollection].join('|')"; + assert_eq!(text(&mut r, size), "The size.|How large the item is.|5|1|10|false"); + let fit = "var f = item.reflect.find('fit'); f.isCollection + ' ' + list(f.arguments) + ' ' + f.arguments.margin.defaultValue + ' ' + f.arguments[1].min"; + assert_eq!(text(&mut r, fit), "true target:parameter:Item margin:parameter:number 0 0"); + // The child lists its parent's members first, its own declaration of one in its place, and + // leaves out the member that is not available. + for target in ["box", "Box"] { + assert_eq!(text(&mut r, &format!("{target}.reflect.name")), "Box"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.properties)")), "size:readwrite:number"); + assert_eq!(text(&mut r, &format!("list({target}.reflect.methods)")), "kind:method:unknown fit:method:boolean"); + assert_eq!(text(&mut r, &format!("String({target}.reflect.find('cut'))")), "null"); + } + // No member's function ran: a data property of the class's type names it. + assert_eq!(text(&mut r, "({b: box}).reflect.find('b').dataType"), "Box"); +} + +#[test] +fn info_for_a_member_a_class_does_not_have_is_refused() { + for (info, message) in [ + (vec![("nothing".to_string(), MemberInfo::default())], "not one of its members"), + (vec![("size".to_string(), MemberInfo::default()), ("size".to_string(), MemberInfo::default())], "twice"), + ] { + let mut r = realm(); + let mut class = classes().remove(0); + class.info = info; + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert!(e.message.contains(message), "{}", e.message); + } + let mut r = realm(); + let mut class = classes().remove(0); + class.members.push(("size".into(), HostMember::Get(constant(1.0)))); + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert!(e.message.contains("names the member size twice"), "{}", e.message); +} diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 6f25fe6df3..1e61b47bf5 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -174,7 +174,7 @@ features! { Notify "notify" Language, OperatorOverloading "operatorOverloading" HostOnly, Preferences "preferences" Language, - Reflection "reflection" HostOnly, + Reflection "reflection" Language, ScriptuiDialog "scriptui.dialog" Dialogs, ScriptuiDrawing "scriptui.drawing" Dialogs, ScriptuiPalette "scriptui.palette" HostOnly, diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index cf71cefc0f..ac75fb0256 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -212,6 +212,13 @@ fn directives_are_read_at_the_start_of_a_line_in_both_forms() { assert_eq!(r.needs, [Need::Language], "VectorCraft runs #targetengine"); } +#[test] +fn reflection_needs_only_the_language() { + let r = report("var p = obj.reflect.properties;\nvar m = $.reflect.find('write');\n"); + assert_eq!(feature(&r, "reflection").map(|f| f.lines.clone()), Some(vec![1, 2])); + assert_eq!(r.needs, [Need::Language], "VectorCraft runs reflect"); +} + #[test] fn a_byte_order_mark_and_every_line_break_are_read() { // U+2028 ends line 2. diff --git a/docs/mcp.md b/docs/mcp.md index 51cd09fdbb..eff8b953f8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2540,9 +2540,9 @@ top-level `import` or `export`, such as a React `.jsx` file), `notText` (a NUL b control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script, the reply holds these lists: - `needs` lists what the script needs from the app that runs it: `language` (the script language's own objects - and directives, such as `$`, `alert`, `UnitValue`, `#target` and `#targetengine`), `dom` (the reference app's + and directives, such as `$`, `alert`, `UnitValue`, `reflect`, `#target` and `#targetengine`), `dom` (the reference app's document model), `files`, `menuCommands`, `dialogs`, and `hostOnly` (features only the reference app has: - palettes, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, reflection, actions + palettes, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, actions and `selectTool`). - `directives` lists the `#include`, `#includepath`, `#script`, `#strict`, `#target` and `#targetengine` lines, and `targets` splits each `#target` line's application specifier into `app`, `instance`, `version` and @@ -2794,6 +2794,22 @@ itself throws a `TypeError`. So does a property that is not writable or not conf would make each of them writable, configurable and extensible again (VectorCraft's own rule). A value deeper than 64 levels, with more than 1,048,576 entries or with text longer than 16,777,216 characters throws a `RangeError`. +`value.reflect` describes an object, as the reflection interface page lays out +(https://extendscript.docsforadobe.dev/extendscript-tools-features/extendscript-reflection-interface/). Each read +gives a new frozen object with `name` (the class), `description` and `help` (`undefined`), `properties` and +`methods` (arrays of entries), and `find(name)`, which gives the entry of the property, or else the method, with that +name, or `null`; a name that is not a string or a number throws a `TypeError`. Each entry has `name` (a number for an +array index), `description`, `help`, `type` (`readonly`, `readwrite`, `method`, or `parameter` for an argument), +`dataType`, `defaultValue`, `min`, `max`, `isCollection` and `arguments`; an entry is also under its name in its array +when that name is not an array index or `length`. `app`, its documents, page items and layers, `DocumentPreset` and +each class's constructor list the members of their class and its parents, with the types, bounds, defaults and method +arguments the object model declares for them (VectorCraft's own values); members that are not available yet are left +out. Any other object lists its own properties: a function value is a method, with a JavaScript function's parameter +names as its arguments, a data property gives the type of its value, and an accessor gives `unknown`. A string, number +or boolean lists its prototype's own properties. No getter runs. `reflect` has no setter, and nothing in a reflection +can be changed: a write is ignored, or throws a `TypeError` in strict mode. An object with more than 10,000 members +and arguments throws a `RangeError`. + The run is one transaction. When the script ends, each document it changed gets one undo step named Run Script. A run that changes no document adds no undo step. The journal records each command the run finished, as it records commands run one at a time. A preference the run changed takes the run's value, and a preference changed in the app diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..762fde881d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1029,6 +1029,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. - Scripts: `toSource` throws a `TypeError` for a property that is not writable or not configurable, a sealed, frozen or non-extensible object or array, and an array with a read-only `length` (VectorCraft's own rule). `crates/js/src/extension_tests.rs`. + - Scripts: every object has a read-only `reflect` property (https://extendscript.docsforadobe.dev/extendscript-tools-features/extendscript-reflection-interface/) that gives its class name, its properties and methods with their types, access, bounds, defaults and method arguments, and `find(name)`. `app`, its documents and page items and their classes are described from the declarations that install their members, and any other object from its own properties, without running a getter. `script.check` no longer counts it as host-only. `crates/js/src/reflect_tests.rs`, `crates/engine/src/script/dom.rs`. - Scripts: a canceled request stops a run that sleeps in `$.sleep`, waits at a dialog or waits for approval to grow at the run's next slice, before its wake time or an answer, and every document goes back to its state before the run. VectorCraft's own rule. `crates/engine/src/tests/script_dollar.rs`, `crates/engine/src/tests/script_dialogs.rs`, `crates/engine/src/tests/script_run.rs`. - Scripts: the Script Console panel's report line reads as `script.console` gives it, `time unavailable` included on a platform without a clock; counts of host calls, dropped lines and cut lines take the singular for one, in each language's own plural forms; and a run that is no longer available still gets its end line (`crates/engine/src/tests/script_console.rs`, `crates/ui-egui/src/panels/tests_script_console.rs`). - Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`.