Breaking the grip JS has on the DOM: Difference between revisions

From MozillaWiki
Jump to navigation Jump to search
No edit summary
(We don't want to do this anymore.)
 
(38 intermediate revisions by 18 users not shown)
Line 1: Line 1:
We care more about speed now. See {{bug|570738}}.
----
We want to change the grip JS has on the DOM and on XUL.  We will do this in 2 steps:
We want to change the grip JS has on the DOM and on XUL.  We will do this in 2 steps:


Line 4: Line 8:
* Create a Python implementation.
* Create a Python implementation.


Ideally, the first step could be done without consideration for the second, in the assumption at the implementation should be truly language neutralHowever, this first real implementation is likely to impact the design decisions made, so there will be some iteration involved
This work is currently being done on a DOM_AGNOSTIC2_BRANCH cvs branch (note the 2 in the branch name!)The initial work on this, including a Python implementation is largely complete.  This document attempts to capture the current state of this work, including any issues not yet addressed.


== Original specification - stage 1 ==
== Description of changes - both already made and yet to be made ==
This is the high-level task list as specified at the start of the project:


* Extend nsScriptLoader using the XPCOM category manager to handle arbitrary <script type="...">
=== Overview ===
* MIME types, loading extension component mapped by MIME type through a category
* Abstract and multiplex nsIScriptContext, generalizing it (changing its IID of course) away from the JS API, making a nsIJavaScriptContext for JS and an nsIPythonContext for Python, fixing various places that assume nsIScriptContext "does JS"
* Fix default script language selection and event handlers, which are script-language-typed by the selected default, so that you can write Python event handlers.


== High-level design decisions ==
A [[#new interface nsILanguageRuntime]] will be implemented for each language.  It is a singleton (JS will be manually instantiated, but all other languages will be services).  <tt>nsDOMScriptObjectFactory</tt> will become the factory for these <tt>nsILanguageRuntime</tt>s, with the language runtime taking responsibility for creating the <tt>nsIScriptContext</tt>.
   
The existing <tt>nsIScriptContext</tt> interface will remain tied to a specific language.  The <tt>void *</tt> params in its interface will remain.  This means that a <tt>void *</tt> and a suitable <tt>nsIScriptContext</tt> must always be treated as a pair (ie, given just a <tt>void *</tt>, there is no way to determine an appropriate <tt>nsIScriptContext</tt> suitable for it.  See [[#nsIScriptContext]]


Decisions made/ratified by Brendan etc:
<tt>nsIProgrammingLanguage</tt> constants will internally identify a language offering an efficient array-based implementation for multiple languages.  The <tt>nsIDOMScriptObjectFactory</tt> will be able to convert language names to IDs and will be responsible for instantiating new language runtimes.


* No sharing of language namespacesOnly the "global DOM namespace" (ie, the nsIScriptGlobalObject) will be shared.
The existing <tt>nsIScriptGlobalObject</tt> interface will move towards a model where there is a global <tt>nsIScriptContext</tt> per language.  <tt>GetGlobalJSObject</tt> and <tt>GetContext</tt> hav largely been replaced with <tt>GetLanguageGlobal</tt> and <tt>GetLanguageContext</tt> methods (hard-coding <tt>nsIProgrammingLanguage::JAVASCRIPT</tt>) where necessary.  Thus, <tt>nsIScriptGlobalObject</tt> may have many <tt>nsIScriptContext</tt>s associated with it (one per supported and initialized language).  The script global itself is responsible for preparing itself to work with a specific language, but will only do so via an explicit request to <tt>EnsureScriptEnvironment()</tt> for a language. See [[#nsIScriptGlobalObject and nsGlobalWindow]]


== Identified task list ==
A new context stack may need to be invented - see [[#Context Stack]]


These are the tasks identified during the analysis and implementation phases of the project.
The special casing for js in <tt>nsDOMClassInfo</tt> will need a fair bit of work for each language - see [[#nsDOMClassInfo]]


=== Overview ===
Below are specific implementation notes:


The existing nsIScriptContext interface will remain tied to a specific language.  The "void *" params in its interface will remain.  This means that a "void *" and a suitable nsIScriptContext must always be treated as a pair (ie, given just a "void *", there is no way to determine an appropriate nsIScriptContext suitable for it - although "assume JS" is likely to remain for existing code that does exactly this)
=== Array and Variant object model changes ===


nsIScriptContext will grow new methods relating to:
* <tt>nsIArray</tt> to be used in place of <tt>jsval</tt> argc/argv used now.  There is a new <tt>nsJSArgArray</tt> object that "wraps" a <tt>jsval *argv/int argc</tt> pair into an <tt>nsIArray</tt> - but also support a private interface for getting the original <tt>jsval</tt> based arrayThus, js->js calls do not convert elements in the array - (offering both performance and no conversion issues), but they are converted when <tt>nsIArray</tt> methods are directly used (eg, when another language sees the array).
* language specific cleanup and "default language context" type codeFor example, nsGlobalWindow.cpp has a number of calls to ::JS_ClearScope/::JS_ClearWatchPointsForObject etc - these need to be hidden behind one of the interfaces.
* The "WrapNative" process.


The existing nsIScriptGlobalObject interface will move towards a model where there is a global script context per language.  GetGlobalJSObject and GetContext would be deprecated, with a new method allowing the desired language to be specified.
* Each of these <tt>nsIArray</tt> elements params are expected to hold either an <tt>nsIVariant</tt> or an <tt>nsISupportsPrimitive</tt>.


The 'context stack' will need to be enhanced to allow each language to have their own implementation for pushing and poping contextThus, when the DOM requires an item on or off the context stack, each language will be called once to do its own thing.
* Result values from calling scripts are now nsIVariantThis is currently used only for the "return value" of an event handler, and only boolean and string result values are handled.  If may be more efficient to convert this to use <tt>nsISupportsPrimitive</tt> (but xpconnect already provided <tt>nsIVariant</tt> converters).


nsDOMClassInfo will be split into a language neutral nsDOMClassInfo, and a JS specific nsIXPCScriptable.  The JS specific code in this file will need to be re-written for Python, but this should allow all DOM knowledge to be reused by the Python implementation.
=== new interface nsILanguageRuntime ===


Need to agree on a single "script language ID".  nsIProgrammingLanguage defines a set of integers, while nsIScriptElement uses a generic "char *".
This is a factory for nsIScriptContext objects and has methods for parsing "version strings" into a version integer specific to the language.


Is nsIDOMClassInfo just a poor-man's IDispatch?  Should we just invent a new interface designed for truly dynamic object models, and wrap the DOM in that? This will require someone from Mozilla driving it.
nsJSEnvironment implements this interface and becomes the JS factory (and renamed to nsJSRuntime). Public function for creating JSContext replaced with public function for the nsJSRuntime.


Below are specific implementation notes:
All memory management/object ownership related functions will exist on the language runtime.  This is so a language object can be locked or unlocked without having an nsIScriptContent - all it needs is the integer language ID so it can fetch the nsILanguageRuntime to perform the operation.  Currently these are defined in terms of the JS GC API (and hence ignored by Python), but this will change to a more language neutral technique.


=== nsIScriptContext ===
=== nsIScriptContext ===


* Existing JSObject replaced with void
* The ownership model of the <tt>void *</tt> objects returned from <tt>nsIScriptContext</tt> must be clarified and made more explicitMarkH is working on this.
 
* Existing "void *aScopeObject" (ExecuteScript/EvaluateStringWithValue/CompileScript), replaced with nsIScriptGlobalObject.  The language impl can then get the "void *" for their language via either sgo->GetLanguageContext() or (static) nsIScriptGlobalObject::GetDefaultLanguageObject()
 
* Need a "WrapNative" type function
 
* FinalizeClasses method - JS does the ClearScope/ClearWatchpointsForObject/ClearRegExpStatistics?
 
* Some kind of "SetProperty" function - as needed by nsGlobalWindow - "arguments", "navigator" etchttp://lxr.mozilla.org/seamonkey/source/dom/src/base/nsGlobalWindow.cpp#871
 
=== nsIScriptGlobalObject / nsGlobalWindow ===


http://lxr.mozilla.org/seamonkey/source/dom/public/nsIScriptGlobalObject.h
* Existing <tt>JSObject</tt> replaced with <tt>void</tt>. JS implementation still returns a <tt>JSObject</tt>, but that implementation detail is hidden inside the script context itself.


nsGlobalWindow is the main implemention of nsIScriptGlobalObject
* Existing <tt>char *version</tt> replaced with <tt>PRUint32 version</tt>.  New method on <tt>nsILanguageRuntime</tt> to convert a <tt>char * version</tt> string into the flags.


* XXXX - Still need to understand GetNativeContext
* New <tt>ClearScope</tt> method - JS implementation does the <tt>ClearScope/ClearWatchpointsForObject/ClearRegExpStatistics</tt> dance.


* nsIScriptGlobalObject probably needs to remain a single object (ie, not per language).  It will move towards keeping a list of "IScriptContext *ctx, void *global" items, one for each language.  New method:
* As described above, <tt>nsIArray</tt> and <tt>nsIVariant</tt> used to make language args and result values agnostic..
  nsresult GetLanguageContext( [in] language_id language, [out] nsIScriptContext **retLangContext, [out]void **retLangGlobal);
mJSObject and mContext will both be dropped in favour of the list.  The concept of a single context/global will be deprecated - callers will be encouraged to use the new method.
GetContext()/GetGlobalJSObject() remain for b/w compat.  They are equivalent to "GetLanguageContext('js', ...)"


* New static method GetDefaultLanguageObject(PRInt32 language, void **retLangGlobal)For JS, this will return ::JS_GetGlobalObject(ctxt)
* <tt>CompileEventHandler</tt> now takes an array of arg names - this is because the <tt>onerror</tt> event takes 3 params<tt>nsContentUtils::GetEventArgName()</tt> renamed to <tt>GetEventArgNames()</tt> with params changed accordingly, and returns 3 names for 'onerror'.


* New method to set and get "properties" - nsGlobalWindow does this for JSSetting a property should presumably set it in all languages (via the global attached to the context).  Getting is tricker - what if the property is in a different language?  Or in multiple languages?
* A new <tt>SetProperty</tt> method has been added, currently used only to set <tt>window.arguments</tt>Note that <tt>BindCompiledEventHandler()</tt> changes make these 2 functions almost identical in concept, so these could possibly be mergedAlternatively, now we use <tt>nsIArray</tt> for window arguments, we could possibly add <tt>arguments</tt> as an XPCOM property on the DOM object itself, meaning <tt>SetProperty()</tt> could go away.
** Properties set include "arguments" and "navigator".  Presumably other code also sets additional properties?
** Properties fetched seem arbitrary.


* "Arguments" will need to be specified in a language neutral wayMaybe array of nsVariants?
* <tt>SetTerminationFunction</tt> needs thinking through - this does *not* seem to be a per-language thing, but is used only for JS GC, so that the script global is notified when the JS global object is collectedThis needs more thinking through, or possibly just moved privately inside the JS implementation.


* Serializing scripts?
* New method <tt>void *GetNativeGlobal()</tt> to return the "global object" used by <tt>nsIScriptGlobalWindow</tt> (previously stored in <tt>mJSObject</tt>) for this context.  <tt>nsIScriptGlobalObject</tt> calls this method during language init to setup its environment.


* CompileScript:
* New <tt>Serialize</tt> and <tt>Deserialize</tt> methods added with <tt>nsXULPrototypeScript</tt> delegating to these.
  nsXulElement.  Line 3666:
  // XXXbe violate nsIScriptContext layering because its version parameter
  // is mis-typed as const char *
  sets mJSObject


=== Context Stack ===
=== nsIScriptGlobalObject and nsGlobalWindow ===


Existing nsIJSContextStack "@mozilla.org/js/xpc/ContextStack;1" service is replaced with language generic ContextStack.  This is almost identical to the JS version, but all functions accept a 'language_id' param, to indicate which language they are interested in.  Existing 'js' specific context stack could be re-implemented using the new one.
<tt>nsGlobalWindow</tt> is the main implemention of <tt>nsIScriptGlobalObject</tt>, but XUL and XBL have a few.


Probably need a new interface for each language to do their thingThe DOM will simply ask for a new context - something must do the delegation to the languages. XXX - but how do we know what languages we need to work with? Can we introduce new languages to the mix even after a context has been pushed?
* <tt>nsIScriptGlobalObject</tt> remains a single object (ie, not per language).  It keeps an array of <tt>nsIScriptContext</tt> objects and <tt>void *</tt> globals for each supported language.  Methods <tt>GetContext</tt> and <tt>GetGlobalJSObject</tt> have been replaced with <tt>GetLanguageContext</tt> and <tt>GetLanguageGlobal</tt>, both of which take the language ID as a paramThe places still tied to JS explicitly pass <tt>nsIProgrammingLanguage::JAVASCRIPT</tt> when necessary.


What about http://lxr.mozilla.org/seamonkey/source/dom/public/nsIScriptContext.h#356 - it
* New method <tt>EnsureScriptEnvironment(PRUint32 langID)</tt> to ensure the <tt>nsIScriptGlobalObject</tt> is initialized for a specific languageThis may be called at any time - whenever someone needs to run a script in a language.
checks flagsWill there be flags for a single stack entry, or flags for each language in a single stack entry, or both?


::JS_GetContextPrivate ???
* nsGlobalWindow still has some complicated JS specific code in place - most notably in <tt>SetNewDocument</tt>.  Some of these subtleties must also be done for other languages - but these have not yet been done in the hope of keeping the patch as small and "obviously correct" as possible.


=== nsScriptLoader ===
* A new interface <tt>nsIScriptTimeoutHandler</tt> has been created.  This abstracts most of the JS specific code related to timeouts and intervals.  The core logic in nsGlobalWindow relating to timeouts has not changed at all.  The JS specific code that remains in nsGlobalWindow should probably be relocated into a JS specific file to help keep the size of nsGlobalWindow.cpp down.


nsScriptLoader's interface is language neutral.
=== XUL Fastload Cache ===


* nsScriptLoadRequest will have either a nsIScriptContext or language ID as a member.
* XUL cache now stores and returns both a <tt>void *</tt> and a <tt>PRUint32 langID</tt>.  As described in [[#new interface nsILanguageRuntime]], this language ID is enough to perform the necessary ownership management of objects in the cache.


=== nsScriptLoaderObserver ===
* Serializing scripts is supported by first writing the language ID to the stream, then delegating to the (new) <tt>nsIScriptContext::Serialize()</tt> method.  Deserialization then reads this language ID to determine the appropriate nsIScriptContext to delegate to.


Presumably will need to become script language awareeg, scriptAvailable() method has text of the script passed - not much use without also knowing the language. Possibly replace with nsIScriptElement, which does have the language ID
* Note that fast-load is fragile in the face of errors; more work is needed to ensure things work for script languages that do not support fast-load. This is not currently a problem as Python does implement this functionalityThis fragility did previously exist - it is just more open to failing when multi-languages are considered.


=== nsDOMClassInfo ===
=== nsDOMClassInfo ===


Lots of DOM namespace magic happens here, but it is very JS specific.  We will:
nsDOMClassInfo provides 2 key functions:


* Create ns(I)DOMClassInfo.  It contains all the existing code that works with nsDOMClassInfoData - that includes most of the "tables" defined using macros.
* standard nsIClassInfo implementations for DOM.


* nsDOMXPC will have all the JS specific code, which is currently implementing nsIXPCScriptableThis is the bulk of the existing nsDOMClassInfo implementation.
* Enhanced support for DOM objects which can not be expressed using nsIClassInfoThese are the "scriptable helpers"


* This language neutral interface will allow language "helpers" to be explicitly installed, and will then be able to be fetched by the existing nsIClassInfo::GetLanguageHelper() functionThus, anyone with an nsIDOMClassInfo will still be able to get the JS helper.
The extra nsIClassInfo implementation is suitable for all languages.  However, the scriptable helpers have lots of DOM namespace magic, and are very JS specificThis functionality currently needs to be re-implemented for Python.


* Decide what to do with the various flags - eg, ALLOW_PROP_MODS_TO_PROTOTYPEPresumably these will have some meaning to languages other than JS, but they are defined in a JS specific interface (nsIXPCScriptable)
Widgets implemented in XBL do not have any class info available.  This works in JavaScript as the widgets themselves are implemented by JS, and therefore all methods and properties exist as native JS propertiesThus, JS does not use XPConnect to talk to XBL implemented widgets.  Python has currently worked around this by hardcoding mapping between a XUL tag name and a list of interfaces that should be implemented.  This should be addressed in XBL 1.5/2.0.


The Python language implementation will then need to write an equivalent to the new nsDOMXPC.  This will be the magic where attributes are got/set for objects, etc.  This Python implementation will need to lean heavily on nsDOMClassInfo.


=== Context Stack ===


=== nsXULPrototypeScript ===
[MarkH - I've managed to completely ignore this for the time being]
 
Change JSObject *mJSObject -> void *mScriptObject, and add new nsIScriptContext reference.
 
=== Event listeners ===
http://lxr.mozilla.org/seamonkey/source/content/events/src/nsEventListenerManager.cpp#1160
 
Changes required:
* AddScriptEventListener() needs a "language_id" passed in
* 'context' still comes from ScriptGlobal
* Use of "@mozilla.org/js/xpc/ContextStack;1" needs to be abstracted into the nsIScript interfaces.
 
=== Exceptions ===
 
Exceptions should be chained across languages.  This should just mean diligent use of nsIExceptionService?
 
== Identified list of things we will *not* do ==
* We will make no attempt to have abstract the security interfaces - Python has no concept of "untrusted code".  This means Python will be restricted to running from trusted XUL.
* Principals (obviously we must not change existing semantics, but Python will ignore them.)
* Allowing a language version to be specified.
 
 
== Stuff Mark still needs to grok ==
 
* Still a little gray on the relationship between a JSContext, a "scope" and a "global". 
** JSContext a DOM specific concept, so script_language -> C++ -> script_language preserves the state of the globals (correct?)
** What is in a "context" beyond the global object?
 
* WrapNative and what it really means to this
 
* What exactly does nsDOMClassInfo do???  How can we factor it?


* nsBindingManager - very JS specific and not using nsIScript interfaces
Existing code that works directly with the nsIJSContextStack "@mozilla.org/js/xpc/ContextStack;1" service must be modified to be language agnostic.  These callers may be unaware of the language being used, or the set of language available.  Therefore, the nsIScriptGlobalObject interface will grow a way to generically push and pop contexts for *all* languages.  It will probably not be possible to explicitly push a context for only a single language, as that will muddy the semantics.
Exactly what this means is still TDB, but there are a few possibilities:
* We invent a new interface for each language to do its thing.
* We simple push nsIScriptContext objects directly on a stack - we push a context for every language known to us.


* Need to understand the desired 'undefined' semantics for the return valuePython's builtin None is closer to a JS null, so may not be suitable for 'undefined'. However, a simple 'return' will return None.
If a language is initialized even after items are already on the context stack, only new items pushed will include a context item for that languageOnce the stack pops back past where a language has no entries, the language will not be able to run (but this should be impossible - there can be no stack entries for that language higher in the context stack, and attempting to start a new script in that language will simply re-push a context entry which will again include the language)


* Timeouts look tricky.
As mentioned above re nsIScriptContext, we may need to handle SetTerminationFunction functionality on this stack.


* Events look tricky
Tricky: We need to interoperate with code that is not multi-language nor nsIScriptGlobalObject aware, and may not be for some time.  Eg:
http://lxr.mozilla.org/seamonkey/source/extensions/pref/autoconfig/src/nsJSConfigTriggers.cpp#216
http://lxr.mozilla.org/seamonkey/source/extensions/webservices/security/src/nsWebScriptsAccess.cpp#767 - pushes a NULL context?


== Random Notes ==
Generic "GetCallerDocShell" or similar will avoid some JS specifics - eg, http://lxr.mozilla.org/seamonkey/source/docshell/base/nsDocShell.cpp#6092


Some notes about existing callers of certain interfaces.
Possible implementation strategy:


nsDOMParser:
==== New interface - nsIDOMContextStackItem ====
An item on the context stack - stores one nsIScriptContext for every language initialized for this item.


* Gets "native call context" to end up with nsIScriptContext - apparently all just to get the script URI nsDocShell
nsIDOMContextStackItem : nsISupports
** http://lxr.mozilla.org/seamonkey/source/extensions/xmlextras/base/src/nsDOMParser.cpp#476
{
** Will need to know the language_id that should process the data from the stream
  nsIScriptContext getLanguageContext(in PRInt32 langId);
* Security related functions
  void setLanguageContext(in PRInt32 langId, in nsIScriptContext cx);
};


nsXMLHttpRequest.cpp
==== New interface - nsIDOMContextStack ====
* GetCurrentContext uses the JS ContextStack.


mozXMLTermUtils.cpp:
interface nsIDOMContextStack : nsISupports
   * mozXMLTermUtils::ExecuteScript called nsIScriptContext::ExecuteScript -     but with NULL "void *" pointers.  Needs to have nsIScriptContext passed?
{
  readonly attribute PRInt32    count;
  nsIDOMContextStackItem      peek();
   nsIDOMContextStackItem     pop();
  void                                   push(in nsIDOMContextStackItem cx);


nsScriptSecurityManager.cpp/nsSecurityManagerFactory.cpp:
  /* what is a "safe context" anyway???
*Almost all functions convert a JSContext to an nsIScriptContext.  Most just use to GetGlobalObject - GetPrincipalAndFrame has JS assumptions
  * - a context guaranteed to be available and usable.
* nsSecurityNameSet::InitializeNameSet - Lots of JS specific code.
  */
 
  nsIScriptContext getLanguageSafeContext(in PRInt32 langId);
docshell/base/nsDocShell.cpp:
1 use nsDocShell::CheckLoadingPermissions() - use of JF ContextStack to fetch nsIScriptContext - just to GetGlobalObject
 
embedding/components/windowwatcher/src/nsWWJSUtils.cpp
* Converts JSContext to nsIScriptContext.  Mainly for GetGlobalObject, but nsIScriptGlobalObject *nsWWJSUtils::GetStaticScriptGlobal has JS deps.
 
embedding/components/windowwatcher/src/nsWindowWatcher.cpp:
 
    JSObject * nsWindowWatcher::GetWindowScriptObject
        not used???
 
    nsWindowWatcher::AttachArguments
    AddSupportsTojsvals
        2038      rv = xpc->WrapNative(cx, ::JS_GetGlobalObject(cx), data,
        2039                            *iid, getter_AddRefs(wrapper));
    
    
  /* A helper for code that wants the most recent nsIDocShell on
  the context stack - any/all languages on the stack can provide it */
  nsIDocShell GetCallerDocShell()
};


content/base/src/nsContentUtils.cpp:
=== Exceptions ===
    Convert nsIScriptContext -> JS Context
content/base/src/nsDocument.cpp:
    Convert nsIScriptContext -> JS Context -> CanRunScripts
    (can CanRunScripts take an nsIScriptContext?)
 
nsRange:
    nsRange::CreateContextualFragment - seems to push/pop a JS Context?
 
content/base/src/nsScriptLoader.cpp:
 
        nsScriptLoader::ProcessScriptElement
            Does the actual loading of the stream.
        EvaluateScript calls nsIScriptContext->EvaluateScript - with most args
 
content/events/src/nsEventListenerManager.cpp:
 
    Quite JS specific
   
content/xbl/src/
nsXBLBinding
    ::JSSetPrototype for a new context?
nsXBLDocumentInfo:
  implementation of nsIScriptGlobalObject.
  JSObject *mJSObject;    // XXX JS language rabies bigotry badness
  mJSObject = ::JS_NewObject - abstraction?
nsXBLProtoImpl:
  Lots of JS Specific code.
  Fairly generic compile function: http://lxr.mozilla.org/seamonkey/source/content/xbl/src/nsXBLProtoImpl.cpp#192
 
content/xul:
nsXULElement
    event handlers remain JS specific
    serialization too
nsXULDocument:
    Calls ExecuteScript with mScriptGlobalObject->GetGlobalJSObject() as an arg
    case nsXULPrototypeNode::eType_Script: {
      else if (scriptproto->mJSObject) {
                    // An inline script
                    rv = ExecuteScript(scriptproto->mJSObject);
                    if (NS_FAILED(rv)) return rv;
                }
 
    XUL Script cache
 
dom/src/base/nsDOMClassInfo.cpp
  Lots of JS - dynamic DOM not exposed by XPCOM class info?
 
dom/src/base/nsGlobalWindow.cpp
    JS specific "scope" code
    nsIScriptContext *currentCX = nsJSUtils::GetDynamicScriptContext(cx);
    argv handling
    Creating a window - calls WindowWatcher::OpenWindowJS
   
dom/src/events/nsJSEventListener.cpp:
 
layout/generic/nsObjectFrame.cpp
 
xpfe/appshell/src/nsAppShellService.cpp


plugins/activex/embedding/crypto: ignoring for now.
Exceptions should be chained across languages. This should just mean diligent use of nsIExceptionService? This has not been addressed yet.
[http://www.paybacksh.com/Body/aboutus.asp �?装CAD]
[http://www.paybacksh.com/Body/aboutus.asp 数字化仪]
[http://www.paybacksh.com/Body/aboutus.asp �?装设计软件]
[http://www.paybacksh.com/Body/aboutus.asp �?装绘图仪]

Latest revision as of 18:08, 8 June 2010

We care more about speed now. See bug 570738.


We want to change the grip JS has on the DOM and on XUL. We will do this in 2 steps:

This work is currently being done on a DOM_AGNOSTIC2_BRANCH cvs branch (note the 2 in the branch name!). The initial work on this, including a Python implementation is largely complete. This document attempts to capture the current state of this work, including any issues not yet addressed.

Description of changes - both already made and yet to be made

Overview

A #new interface nsILanguageRuntime will be implemented for each language. It is a singleton (JS will be manually instantiated, but all other languages will be services). nsDOMScriptObjectFactory will become the factory for these nsILanguageRuntimes, with the language runtime taking responsibility for creating the nsIScriptContext.

The existing nsIScriptContext interface will remain tied to a specific language. The void * params in its interface will remain. This means that a void * and a suitable nsIScriptContext must always be treated as a pair (ie, given just a void *, there is no way to determine an appropriate nsIScriptContext suitable for it. See #nsIScriptContext

nsIProgrammingLanguage constants will internally identify a language offering an efficient array-based implementation for multiple languages. The nsIDOMScriptObjectFactory will be able to convert language names to IDs and will be responsible for instantiating new language runtimes.

The existing nsIScriptGlobalObject interface will move towards a model where there is a global nsIScriptContext per language. GetGlobalJSObject and GetContext hav largely been replaced with GetLanguageGlobal and GetLanguageContext methods (hard-coding nsIProgrammingLanguage::JAVASCRIPT) where necessary. Thus, nsIScriptGlobalObject may have many nsIScriptContexts associated with it (one per supported and initialized language). The script global itself is responsible for preparing itself to work with a specific language, but will only do so via an explicit request to EnsureScriptEnvironment() for a language. See #nsIScriptGlobalObject and nsGlobalWindow

A new context stack may need to be invented - see #Context Stack

The special casing for js in nsDOMClassInfo will need a fair bit of work for each language - see #nsDOMClassInfo

Below are specific implementation notes:

Array and Variant object model changes

  • nsIArray to be used in place of jsval argc/argv used now. There is a new nsJSArgArray object that "wraps" a jsval *argv/int argc pair into an nsIArray - but also support a private interface for getting the original jsval based array. Thus, js->js calls do not convert elements in the array - (offering both performance and no conversion issues), but they are converted when nsIArray methods are directly used (eg, when another language sees the array).
  • Each of these nsIArray elements params are expected to hold either an nsIVariant or an nsISupportsPrimitive.
  • Result values from calling scripts are now nsIVariant. This is currently used only for the "return value" of an event handler, and only boolean and string result values are handled. If may be more efficient to convert this to use nsISupportsPrimitive (but xpconnect already provided nsIVariant converters).

new interface nsILanguageRuntime

This is a factory for nsIScriptContext objects and has methods for parsing "version strings" into a version integer specific to the language.

nsJSEnvironment implements this interface and becomes the JS factory (and renamed to nsJSRuntime). Public function for creating JSContext replaced with public function for the nsJSRuntime.

All memory management/object ownership related functions will exist on the language runtime. This is so a language object can be locked or unlocked without having an nsIScriptContent - all it needs is the integer language ID so it can fetch the nsILanguageRuntime to perform the operation. Currently these are defined in terms of the JS GC API (and hence ignored by Python), but this will change to a more language neutral technique.

nsIScriptContext

  • The ownership model of the void * objects returned from nsIScriptContext must be clarified and made more explicit. MarkH is working on this.
  • Existing JSObject replaced with void. JS implementation still returns a JSObject, but that implementation detail is hidden inside the script context itself.
  • Existing char *version replaced with PRUint32 version. New method on nsILanguageRuntime to convert a char * version string into the flags.
  • New ClearScope method - JS implementation does the ClearScope/ClearWatchpointsForObject/ClearRegExpStatistics dance.
  • As described above, nsIArray and nsIVariant used to make language args and result values agnostic..
  • CompileEventHandler now takes an array of arg names - this is because the onerror event takes 3 params. nsContentUtils::GetEventArgName() renamed to GetEventArgNames() with params changed accordingly, and returns 3 names for 'onerror'.
  • A new SetProperty method has been added, currently used only to set window.arguments. Note that BindCompiledEventHandler() changes make these 2 functions almost identical in concept, so these could possibly be merged. Alternatively, now we use nsIArray for window arguments, we could possibly add arguments as an XPCOM property on the DOM object itself, meaning SetProperty() could go away.
  • SetTerminationFunction needs thinking through - this does *not* seem to be a per-language thing, but is used only for JS GC, so that the script global is notified when the JS global object is collected. This needs more thinking through, or possibly just moved privately inside the JS implementation.
  • New method void *GetNativeGlobal() to return the "global object" used by nsIScriptGlobalWindow (previously stored in mJSObject) for this context. nsIScriptGlobalObject calls this method during language init to setup its environment.
  • New Serialize and Deserialize methods added with nsXULPrototypeScript delegating to these.

nsIScriptGlobalObject and nsGlobalWindow

nsGlobalWindow is the main implemention of nsIScriptGlobalObject, but XUL and XBL have a few.

  • nsIScriptGlobalObject remains a single object (ie, not per language). It keeps an array of nsIScriptContext objects and void * globals for each supported language. Methods GetContext and GetGlobalJSObject have been replaced with GetLanguageContext and GetLanguageGlobal, both of which take the language ID as a param. The places still tied to JS explicitly pass nsIProgrammingLanguage::JAVASCRIPT when necessary.
  • New method EnsureScriptEnvironment(PRUint32 langID) to ensure the nsIScriptGlobalObject is initialized for a specific language. This may be called at any time - whenever someone needs to run a script in a language.
  • nsGlobalWindow still has some complicated JS specific code in place - most notably in SetNewDocument. Some of these subtleties must also be done for other languages - but these have not yet been done in the hope of keeping the patch as small and "obviously correct" as possible.
  • A new interface nsIScriptTimeoutHandler has been created. This abstracts most of the JS specific code related to timeouts and intervals. The core logic in nsGlobalWindow relating to timeouts has not changed at all. The JS specific code that remains in nsGlobalWindow should probably be relocated into a JS specific file to help keep the size of nsGlobalWindow.cpp down.

XUL Fastload Cache

  • XUL cache now stores and returns both a void * and a PRUint32 langID. As described in #new interface nsILanguageRuntime, this language ID is enough to perform the necessary ownership management of objects in the cache.
  • Serializing scripts is supported by first writing the language ID to the stream, then delegating to the (new) nsIScriptContext::Serialize() method. Deserialization then reads this language ID to determine the appropriate nsIScriptContext to delegate to.
  • Note that fast-load is fragile in the face of errors; more work is needed to ensure things work for script languages that do not support fast-load. This is not currently a problem as Python does implement this functionality. This fragility did previously exist - it is just more open to failing when multi-languages are considered.

nsDOMClassInfo

nsDOMClassInfo provides 2 key functions:

  • standard nsIClassInfo implementations for DOM.
  • Enhanced support for DOM objects which can not be expressed using nsIClassInfo. These are the "scriptable helpers"

The extra nsIClassInfo implementation is suitable for all languages. However, the scriptable helpers have lots of DOM namespace magic, and are very JS specific. This functionality currently needs to be re-implemented for Python.

Widgets implemented in XBL do not have any class info available. This works in JavaScript as the widgets themselves are implemented by JS, and therefore all methods and properties exist as native JS properties. Thus, JS does not use XPConnect to talk to XBL implemented widgets. Python has currently worked around this by hardcoding mapping between a XUL tag name and a list of interfaces that should be implemented. This should be addressed in XBL 1.5/2.0.


Context Stack

[MarkH - I've managed to completely ignore this for the time being]

Existing code that works directly with the nsIJSContextStack "@mozilla.org/js/xpc/ContextStack;1" service must be modified to be language agnostic. These callers may be unaware of the language being used, or the set of language available. Therefore, the nsIScriptGlobalObject interface will grow a way to generically push and pop contexts for *all* languages. It will probably not be possible to explicitly push a context for only a single language, as that will muddy the semantics.

Exactly what this means is still TDB, but there are a few possibilities:

  • We invent a new interface for each language to do its thing.
  • We simple push nsIScriptContext objects directly on a stack - we push a context for every language known to us.

If a language is initialized even after items are already on the context stack, only new items pushed will include a context item for that language. Once the stack pops back past where a language has no entries, the language will not be able to run (but this should be impossible - there can be no stack entries for that language higher in the context stack, and attempting to start a new script in that language will simply re-push a context entry which will again include the language)

As mentioned above re nsIScriptContext, we may need to handle SetTerminationFunction functionality on this stack.

Tricky: We need to interoperate with code that is not multi-language nor nsIScriptGlobalObject aware, and may not be for some time. Eg: http://lxr.mozilla.org/seamonkey/source/extensions/pref/autoconfig/src/nsJSConfigTriggers.cpp#216 http://lxr.mozilla.org/seamonkey/source/extensions/webservices/security/src/nsWebScriptsAccess.cpp#767 - pushes a NULL context?

Generic "GetCallerDocShell" or similar will avoid some JS specifics - eg, http://lxr.mozilla.org/seamonkey/source/docshell/base/nsDocShell.cpp#6092

Possible implementation strategy:

New interface - nsIDOMContextStackItem

An item on the context stack - stores one nsIScriptContext for every language initialized for this item.

nsIDOMContextStackItem : nsISupports {

 nsIScriptContext getLanguageContext(in PRInt32 langId);
 void setLanguageContext(in PRInt32 langId, in nsIScriptContext cx);

};

New interface - nsIDOMContextStack

interface nsIDOMContextStack : nsISupports {

 readonly attribute PRInt32     count;
 nsIDOMContextStackItem      peek();
 nsIDOMContextStackItem      pop();
 void                                   push(in nsIDOMContextStackItem cx);
 /* what is a "safe context" anyway??? 
  * - a context guaranteed to be available and usable.
  */
 nsIScriptContext getLanguageSafeContext(in PRInt32 langId);
 
 /* A helper for code that wants the most recent nsIDocShell on
 the context stack - any/all languages on the stack can provide it */
 nsIDocShell GetCallerDocShell()

};

Exceptions

Exceptions should be chained across languages. This should just mean diligent use of nsIExceptionService? This has not been addressed yet.