WebIDL bindings

  • Revision slug: Mozilla/WebIDL_bindings
  • Revision title: WebIDL bindings
  • Revision id: 456521
  • Created:
  • Creator: kanru
  • Is current revision? No
  • Comment

Revision Content

Notes: Need to document the setup for indexed and named getters/setters/creators/deleters.

The WebIDL bindings are generated at build time based on two things: the actual WebIDL file and a configuration file that lists some metadata about how the WebIDL should be reflected into Gecko-internal code.

All WebIDL files should be placed in dom/webidl and added to the list in the WebIDL.mk file in that directory.

The configuration file, dom/bindings/Bindings.conf, is basically a Python dict that maps interface names to information about the interface, called a descriptor.  There are all sorts of possible options here that handle various edge cases, but most descriptors can be very simple.

All the generated code is placed in the mozilla::dom namespace.  For each interface, a namespace whose name is the name of the interface with Binding appended is created, and all the things pertaining to that interface's binding go in that namespace.

There are various helper objects and utility methods in dom/bindings that are also all in the mozilla::dom namespace and whose headers are all exported into mozilla/dom.

Adding WebIDL bindings to a class

Note: If your object needs to be reflected in Workers, you will need to do more work here.  XXXbz need to document.

To add a WebIDL binding for interface MyInterface to a class mozilla::dom::MyInterface that's supposed to implement that interface, you need to do the following:

  1. Inherit from nsWrapperCache and hook up the class to the cycle collector so it will trace the wrapper cache properly, and call SetIsDOMBinding() in the constructor of the derived class.  Note that you may not need to do this if your objects can only be created, never gotten from other objects.  If you also inherit from nsISupports, make sure the nsISupports comes before the nsWrapperCache in your list of parent classes.
  2. Implement a GetParentObject override that, for a given instance of your class, returns the same object every time (unless you write explicit code that handles your parent object changing by reparenting JS wrappers, as nodes do).  The idea is that walking the GetParentObject chain will eventually get you to a Window, so that every WebIDL object is associated with a particular Window.  For example, nsINode::GetParentObject returns the node's owner document.  The return value of GetParentObject must either singly-inherit from nsISupports or have a corresponding ToSupports() method that can produce an nsISupports from it.  If many instances of MyInterface are expected to be created quicky, the return value of GetParentObject should itself inherit from nsWrapperCache for optimal performance.  Returning null from GetParentObject is allowed in situations in which it's OK to associate the resulting object with a random global object for security purposes; this is not usually ok for things that are exposed to web content.  Again, if you do not need wrapper caching you don't need to do this.
  3. Add the WebIDL for MyInterface in dom/webidl and to the list in dom/webidl/WebIDL.mk.
  4. Add an entry to dom/bindings/Bindings.conf that sets some basic information about the implementation of the interface.  If the C++ type is not mozilla::dom::MyInterface, you need to set the 'nativeType' to the right type.  If the type is not in the header file one gets by replacing '::' with '/' and appending '.h' (for main thread; for workers the rules are slightly different), then add a corresponding 'headerFile' annotation (or HeaderFile annotation to the .webidl file).  If you don't have to set any annotations, then you don't need to add an entry either and the code generator will simply assume the defaults here.
  5. Add external interface entries to Bindings.conf for whatever non-WebIDL interfaces your new interface has as arguments or return values.
  6. Implement a WrapObject override on mozilla::dom::MyInterface that just calls through to mozilla::dom::MyInterfaceBinding::Wrap.  Note that if your C++ type is implementing multiple distinct Web IDL interfaces, you need to choose which mozilla::dom::MyInterfaceBinding::Wrap to call here.  See AudioContext::Wrap for example.
  7. Expose whatever methods the interface needs on mozilla::dom::MyInterface.  These can be inline, virtual, have any calling convention, and so forth, as long as they have the right argument types and return types.  You can see an example of what the function declarations should look like by running make MyInterface-example in dom/bindings in your objdir.  That will produce two files in that directory: MyInterface-example.h and MyInterface-example.cpp, which show a basic implementation of the interface, using a class that inherits from nsISupports and has a wrapper cache.

See this sample patch that migrates window.performance.* to WebIDL bindings.

Note: If your object can only be reflected into JS by creating it, not by retrieving it from somewhere, you can skip steps 1 and 2 above and instead add 'wrapperCache': False to your descriptor.  If your object already has classinfo, it should be using the nsNewDOMBindingNoWrapperCacheSH scriptable helper in this case.  You will need to flag the functions that return your object as [Creator] in the WebIDL.

C++ reflections of WebIDL constructs

C++ reflections of WebIDL operations (methods)


A WebIDL operation is turned into a method call on the underlying C++ object.  The return type and argument types are determined as described below.  In addition to those, all methods that are allowed to throw will get an ErrorResult& argument appended to their argument list.  Methods that use certain WebIDL types like any or object will get a JSContext* argument prepended to the argument list.  Static methods will be passed a const GlobalObject&, or const WorkerGlobalObject& in the worker case, for the relevant global.  This argument comes after the JSContext*, if any, but before all the other arguments.

The name of the C++ method is simply the name of the WebIDL operation with the first letter converted to uppercase.

WebIDL overloads are turned into C++ overloads: they simply call C++ methods with the same name and different signatures.

For example, this webidl:

interface MyInterface 
{
  void doSomething(long number);
  double doSomething(MyInterface? otherInstance);

  [Throws]
  MyInterface doSomethingElse(optional long maybeNumber);
  [Throws]
  void doSomethingElse(MyInterface otherInstance);

  void doTheOther(any something);

  static void staticOperation(any arg);
};

will require these method declarations:

class MyClass
{
  void DoSomething(int32_t aNumber);
  double DoSomething(MyClass* aOtherInstance);

  already_AddRefed<MyInterface> DoSomethingElse(Optional<int32_t> aMaybeNumber,
                                                ErrorResult& rv);
  void DoSomethingElse(MyClass& aOtherInstance, ErrorResult& rv);
  
  void DoTheOther(JSContext* cx, JS::Value aSomething);

  static void StaticOperation(JSContext* cx, const GlobalObject& aGlobal, JS::Value aSomething);
}

C++ reflections of WebIDL attributes

A WebIDL attribute is turned into a pair of method calls for the getter and setter on the underlying C++ object.  A readonly attribute only has a getter and no setter.

The getter's name is the name of the attribute with the first letter converted to uppercase.  This has Get prepended to it if any of these conditions hold:

  1. The type of the attribute is nullable.
  2. The getter can throw.
  3. The return value of the attribute is returned via an out parameter in the C++.

The method signature for the getter looks just like an operation with no arguments and the attribute's type as the return type.

The setter's name is Set followed by the name of the attribute with the first letter converted to uppercase.  The method signature looks just like an operation with a void return value and a single argument whose type as the attribute's type.

C++ reflections of WebIDL constructors

A WebIDL constructor is turned into a static class method named Constructor.  The arguments of this method will be the arguments of the WebIDL constructor, with a const GlobalObject&, or const WorkerGlobalObject& in the worker case, for the relevant global prepended.  For the non-worker case, the global is typically the inner window for the DOM Window the constructor function is attached to.  If a JSContext* is also needed due to some of the argument types, it will come before the global.  The return value of the constructor for MyInterface is exactly the same as that of a method returning an instance of MyInterface. Constructors are always allowed to throw.

For example, this IDL:

[Constructor,
 Constructor(unsigned long someNumber)]
interface MyInterface 
{
};

will require the following declarations in MyClass, for a non-worker binding:

class MyClass {
  // Various nsISupports stuff or whatnot
  static
  already_AddRefed<MyClass> Constructor(const GlobalObject& aGlobal,
                                        ErrorResult& rv);
  static
  already_AddRefed<MyClass> Constructor(const GlobalObject& aGlobal,
                                        uint32_t aSomeNumber,
                                        ErrorResult& rv);  
};

C++ reflections of WebIDL types

The exact C++ representation for WebIDL types can depend on the precise way that they're being used: e.g. return values, arguments, and sequence or dictionary members might all have different representations.

Unless stated otherwise, a type only has one representation.  Also, unless stated otherwise, nullable types are represented by wrapping Nullable<> around the base type.

In all cases, optional arguments which do not have a default value are represented by wrapping const Optional<>& around the representation of the argument type.  If the argument type is a C++ reference, it will also become a NonNull<> around the actual type of the object in the process.  Optional arguments which do have a default value are just represented by the argument type itself, set to the default value if the argument was not in fact passed in.

Variadic WebIDL arguments are treated as a const Sequence<>& around the actual argument type.

any

any is represented in two different ways, depending on use:

  • any arguments become JS::Handle<JS::Value>.
  • any return values, dictionary members, and sequence elements become JS::Value.  The dictionary members and sequence elements are guaranteed to be marked by whoever puts the sequence or dictionary on the stack, using SequenceRooter and DictionaryRooter.

Methods using any always get a JSContext* argument.

For example, this WebIDL:

interface Test {
  attribute any myAttr;
  any myMethod(any arg1, sequence<any> arg2, optional any arg3);
};

will correspond to these C++ function declarations:

JS::Value MyAttr(JSContext* cx);
void SetMyAttr(JSContext* cx, JS::Handle<JS::Value> value);
JS::Value MyMethod(JSContext* cx, JS::Handle<JS::Value> arg1, 
                   const Sequence<JS::Value>& arg2,
                   const Optional<JS::Handle<JS::Value> >& arg3);

boolean

The boolean WebIDL type is represented as a C++ bool.

For example, this WebIDL:

interface Test {
  attribute boolean myAttr;
  boolean myMethod(optional boolean arg);
};

will correspond to these C++ function declarations:

bool MyAttr();
void SetMyAttr(bool value);
JS::Value MyMethod(const Optional<bool>& arg);

Integer types

Integer WebIDL types are mapped to the corresponding C99 stdint types.

For example, this WebIDL:

interface Test {
  attribute short myAttr;
  long long myMethod(unsigned long? arg);
};

will correspond to these C++ function declarations:

int16_t MyAttr();
void SetMyAttr(int16_t value);
int64_t MyMethod(const Nullable<uint32_t>& arg);

Floating point types

Floating point WebIDL types are mapped to the C++ type of the same name.  So float and unrestricted float become a C++ float, while double and unrestricted double become a C++ double.

For example, this WebIDL:

interface Test {
  float myAttr;
  double myMethod(unrestricted double? arg);
};

will correspond to these C++ function declarations:

float MyAttr();
void SetMyAttr(float value);
double MyMethod(const Nullable<double>& arg);

DOMString

Strings are reflected in three different ways, depending on use:

  • String arguments become const nsAString&.
  • String return values become a mozilla::dom::DOMString& out param appended to the argument list.  This comes after all IDL arguments, but before the ErrorResult&, if any, for the method.  Note that this allows callees to declare their methods as taking an nsAString& or nsString& if desired.
  • Strings in sequences and dictionaries become nsString.

Nullable strings are represented by the same types as non-nullable ones, but the string will return true for DOMStringIsNull().  Returning null as a string value can be done using SetDOMStringToNull on the out param if it's an nsAString or calling SetNull() on a DOMString.

For example, this WebIDL:

interface Test {
  DOMString myAttr;
  [Throws]
  DOMString myMethod(sequence<DOMString> arg1, DOMString? arg2, optional DOMString arg3);
};

will correspond to these C++ function declarations:

void GetMyAttr(nsString& retval);
void SetMyAttr(const nsAString& value);
void MyMethod(const Sequence<nsString>& arg1, const nsAString& arg2,
              const Optional<nsAString>& arg3, nsString& retval, ErrorResult& rv);

ByteString

ByteString is not suported yet.

object

object is represented in two different ways, depending on use:

  • object arguments become JS::Handle<JSObject*>.
  • object return values, dictionary members, and sequence elements become JSObject*.  The dictionary members and sequence elements are guaranteed to be marked by whoever puts the sequence or dictionary on the stack, using SequenceRooter and DictionaryRooter.

Methods using object always get a JSContext* argument.

For example, this WebIDL:

interface Test {
  object myAttr;
  object myMethod(object arg1, object? arg2, sequence<object> arg3, optional object arg4,
                  optional object? arg5);
};

will correspond to these C++ function declarations:

JSObject* GetMyAttr(JSContext* cx);
void SetMyAttr(JSContext* cx, JS::Handle<JSObject*> value);
void MyMethod(JSContext* cx, JS::Handle<JSObject*> arg1, JS::Handle<JSObject*> arg2,
              const Sequence<JSObject*>& arg3,
              const Optional<JS::Handle<JSObject*> >& arg4,
              const Optional<JS::Handle<JSObject*> >& arg5);

Interface types

There are four kinds of interface types in the WebIDL bindings.  Callback interfaces are used to represent script objects that browser code can call into.  External interfaces are used to represent objects that have not been converted to the WebIDL bindings yet.  WebIDL interfaces are used to represent WebIDL binding objects.  "SpiderMonkey" interfaces are used to represent objects that are implemented natively by the JavaScript engine (e.g. typed arrays).

Callback interfaces

Callback interfaces are represented in C++ as objects inheriting from mozilla::dom::CallbackInterface, whose name, in the mozilla::dom namespace, matches the name of the callback interface in the WebIDL.  The exact representation depends on how the type is being used.

  • Nullable arguments become Foo*.
  • Non-nullable arguments become Foo&.
  • Return values become already_AddRefed<Foo> or Foo* depending on whether the method or property involved is flagged as resultNotAddRefed in Bindings.conf.
  • WebIDL callback interfaces in sequences and dictionaries are represented by nsRefPtr<Foo> if nullable and OwningNonNull<Foo> otherwise.

If the interface is a single-opertion interface, the object exposes two methods that both invoke the same underlying JS callable.  The first of these methods allows the caller to pass in a this object, while the second defaults to a null this object.  In either case, the this object is only used if the callback interface is implemented by a JS callable.  If it's implemented by an object with a property whose name matches the operation, the object itself is always used as this.

If the interface is not a single-operation interface, it just exposes a single method for every IDL method/getter/setter.

The signatures of the methods correspond to the signatures for throwing IDL methods/getters/setters with an additional trailing "mozilla::dom::CallbackObject::ExceptionHandling aExceptionHandling" argument, defaulting to eReportExceptions.  If aReportExceptions is set to eReportExceptions, the methods will report JS exceptions before returning.  If aReportExceptions is set to eRethrowExceptions, JS exceptions will be stashed in the ErrorResult and will be reported when the stack unwinds to wherever the ErrorResult was set up.

For example, this WebIDL:

callback interface MyCallback {
  attribute long someNumber;
  short someMethod(DOMString someString);
};
callback inteface MyOtherCallback {
  // single-operation interface
  short doSomething(Node someNode);
};
interface MyInterface {
  attribute MyCallback foo;
  attribute MyCallback? bar;
};

will lead to these C++ class declarations, in the mozilla::dom namespace:

class MyCallback : public CallbackInterface
{
  int32_t GetSomeNumber(ErrorResult& rv, ExceptionHandling aExceptionHandling = eReportExceptions);
  void SetSomeNumber(int32_t arg, ErrorResult& rv,
                     ExceptionHandling aExceptionHandling = eReportExceptions);
  int16_t SomeMethod(const nsAString& someString, ErrorResult& rv,
                     ExceptionHandling aExceptionHandling = eReportExceptions);
};

class MyOtherCallback : public CallbackInterface
{
public:
  int16_t
  DoSomething(nsINode& someNode, ErrorResult& rv,
              ExceptionHandling aExceptionHandling = eReportExceptions);

  template<typename T>
  int16_t
  DoSomething(const T& thisObj, nsINode& someNode, ErrorResult& rv,
              ExceptionHandling aExceptionHandling = eReportExceptions);
};

and these C++ function declarations on the implementation of MyInterface:

already_AddRefed<MyCallback> GetFoo();
void SetFoo(MyCallback&);
already_AddRefed<MyCallback> GetBar();
void SetBar(MyCallback*);
External interfaces

External interfaces are represented in C++ as objects that XPConnect knows how to unwrap to.  This can mean XPCOM interfaces (whether declared in XPIDL or not) or it can mean some type that there's a castable native unwrapping function for.  The C++ type to be used should be the nativeType listed for the external interface in the Bindings.conf file.  The exact representation depends on how the type is being used.

  • Arguments become nsIFoo*.
  • Return values become already_AddRefed<nsIFoo> or nsIFoo* depending on whether the method or property involved is flagged as resultNotAddRefed in Bindings.conf.
  • External interfaces in sequences and dictionaries are represented by nsRefPtr<nsIFoo>.
WebIDL interfaces

WebIDL interfaces are represented in C++ as C++ classes.  For non-worker bindings the class involved must either inherit from nsISupports, in which case the canonical nsISupports must be on the primary inheritance chain of the object, or must be explicitly annotated in Bindings.conf as being non-nsISupports refcounted or directly by the JS object.  If the interface has a parent interface, the C++ class corresponding to the parent must be on the primary inheritance chain of the object.  This guarantees that a void* can be stored in the JSObject which can then be reinterpret_cast to any of the classes that correspond to interfaces the object implements.  The C++ type to be used should be the nativeType listed for the interface in the Bindings.conf file, or mozilla::dom::InterfaceName if none is listed (mozilla::dom::workers::InterfaecName for worker bindings).  The exact representation depends on how the type is being used.

  • Nullable arguments become Foo*.
  • Non-nullable arguments become Foo&.
  • Return values become already_AddRefed<Foo> or Foo* depending on whether the method or property involved is flagged as resultNotAddRefed in Bindings.conf.
  • WebIDL interfaces in sequences and dictionaries are represented by nsRefPtr<Foo> if nullable and OwningNonNull<Foo> otherwise.

For example, this WebIDL:

interface MyInterface {
  attribute MyInterface myAttr;
  void passNullable(MyInterface? arg);
  MyInterface? doSomething(sequence<MyInterface> arg);
  MyInterface doTheOther(sequence<MyInterface?> arg);
  readonly attribute MyInterface? nullableAttr;
  readonly attribute MyInterface someOtherAttr; // Marked as resultNotAddRefed
};

Would correspond to these C++ function declarations:

already_AddRefed<MyClass> MyAttr();
void SetMyAttr(MyClass& value);
void PassNullable(MyClass* arg);
already_AddRefed<MyClass> doSomething(const Sequence<OwningNonNull<MyClass> >& arg);
already_AddRefed<MyClass> doTheOther(const Sequence<nsRefPtr<MyClass> >& arg);
already_Addrefed<MyClass> GetMyAttr();
MyClass* SomeOtherAttr();
"SpiderMonkey" interfaces

Typed array, array buffer, and array buffer view arguments are represented by the objects in TypedArray.h.  For example, this WebIDL:

interface Test {
  void passTypedArrayBuffer(ArrayBuffer arg);
  void passTypedArray(ArrayBufferView arg);
  void passInt16Array(Int16Array arg);
}

will correspond to these C++ function declarations:

void PassTypedArrayBuffer(ArrayBuffer& arg);
void PassTypedArray(ArrayBufferView& arg);
void PassInt16Array(Int16Array& arg);

Typed array return values are represented by JSObject*.

Dictionary types

A dictionary argument is represented by a const reference to a struct whose name is the dictionary name in the mozilla::dom namespace.  The struct has one member for each of the dictionary's members with the same name except the first letter uppercased and prefixed with "m". The members that have default values have types as described under the corresponding WebIDL type in this document.  The members that don't have default values have those types wrapped in Optional<>.

Dictionary return values are represented by an out parameter whose type is a non-const reference to the struct described above, with all the members that have default values preinitialized to those default values.

Note that optional dictionary arguments are always considered to have a default value of null so dictionary arguments are never wrapped in Optional<>.

If necessary, dictionaries can be directly initialized from a JS::Value in C++ code by invoking their Init() method.  Consumers doing this should declare their dictionary as RootedDictionary<DictionaryName>.  When this is done, passing in a null scope object and even a null JSContext* is allowed if the passed-in JS::Value is JS::NullValue().  Likewise, a dictionary struct can be converted to a JS::Value in C++ by invoking its ToObject() method.  If Init() or ToObject() return false, they will generally set a pending exception on the JSContext; reporting those is the responsibility of the caller.

For example, this WebIDL:

dictionary Dict {
  long foo = 5;
  DOMString bar;
};

interface Test {
  void initSomething(optional Dict arg);
};

will correspond to this C++ function declaration:

void InitSomething(const Dict& arg);

and the Dict struct will look like this:

struct Dict {
  bool Init(JSContext* cx, JSObject* scopeObj, const JS::Value& val);
  bool ToObject(JSContext* cx, JSObject* parentObject, JS::Value *vp);

  Optional<nsString> mBar;
  int32_t mFoo;
}

Note that the dictionary members are sorted in the struct in alphabetical order.

Enumeration types

WebIDL enumeration types are represented as C++ enums.  The values of the C++ enum are named by taking the strings in the WebIDL enumeration, replacing all non-alphanumerics with underscores, and uppercasing the first letter, with a special case for the empty string, which becomes the value _empty.

For a WebIDL enum named MyEnum, the C++ enum is named MyEnum and placed in the mozilla::dom namespace, while the values are placed in the mozilla::dom::MyEnum namespace.  There is also a mozilla::dom::MyEnumValues::strings which is an array of mozilla::dom::EnumEntry structs that gives access to the string representations of the values.

For example, this WebIDL:

enum MyEnum {
  "something",
  "something-else",
  "",
  "another"
};

would lead to this C++ enum declaration:

MOZ_BEGIN_ENUM_CLASS(MyEnum, uint32_t)
  Something,
  Something_else,
  _empty,
  Another
MOZ_END_ENUM_CLASS(MyEnum)

namespace MyEnumValues {
extern const EnumEntry strings[10];
} // namespace MyEnumValues

Callback function types

Callback functions are represented as an object, inheriting from mozilla::dom::CallbackFunction, whose name, in the mozilla::dom namespace, matches the name of the callback function in the WebIDL.  If the type is nullable, a pointer is passed in; otherwise a reference is passed in.

The object exposes two Call methods, which both invoke the underlying JS callable.  The first Call method has the same signature as a throwing method declared just like the callback function, with an additional trailing "mozilla::dom::CallbackObject::ExceptionHandling aExceptionHandling" argument, defaulting to eReportExceptions, and calling it will invoke the callable with a null this object.  The second Call method allows passing in an explicit this value as the first argument.  This second call method is a template on the type of the first argument, so the this value can be passed in in whatever form is most convenient, as long as it's either a type that can be wrapped by XPConnect or a WebIDL interface type.

If aReportExceptions is set to eReportExceptions, the Call methods will report JS exceptions before returning.  If aReportExceptions is set to eRethrowExceptions, JS exceptions will be stashed in the ErrorResult and will be reported when the stack unwinds to wherever the ErrorResult was set up.

For example, this WebIDL:

callback MyCallback = long (MyInterface arg1, boolean arg2);
interface MyInterface {
  attribute MyCallback foo;
  attribute MyCallback? bar;
};

will lead to this C++ class declaration, in the mozilla::dom namespace:

class MyCallback : public CallbackFunction
{
public:
  int32_t
  Call(MyInterface& arg1, bool arg2, ErrorResult& rv,
       ExceptionHandling aExceptionHandling = eReportExceptions);

  template<typename T>
  int32_t
  Call(const T& thisObj, MyInterface& arg1, bool arg2, ErrorResult& rv,
       ExceptionHandling aExceptionHandling = eReportExceptions);
};

and these C++ function declarations in the MyInterface class:

already_AddRefed<MyCallback> GetFoo();
void SetFoo(MyCallback&);
already_AddRefed<MyCallback> GetBar();
void SetBar(MyCallback*);

Sequences

Sequence arguments are represented by const Sequence<T>&, where T depends on the type of elements in the WebIDL sequence.

Sequence return values are represented by an nsTArray<T> out param appended to the argument list, where T is the return type for the elements of the WebIDL sequence.  This comes after all IDL arguments, but before the ErrorResult&, if any, for the method.

Arrays

IDL array objects are not supported yet.

Union types

XXXbz write me

Date

WebIDL Date types are represented by a mozilla::dom::Date struct.

Stringifiers

Named stringifiers operations in WebIDL will just invoke the corresponding C++ method.

Anonymous stringifiers in WebIDL will invoke the C++ method called Stringify.  So for example given this IDL:

interface FirstInterface {
  stringifier;
};

interface SecondInterface {
  stringifier DOMString getStringRepresentation();
};

the corresponding C++ would be:

class FirstInterface {
public:
  void Stringify(nsAString& aResult);
};

class SecondInterface {
public:
  void GetStringRepresentation(nsAString& aResult);
};

Legacy Callers

Only anonymous legacy callers are supported, and will invoke the C++ method called LegacyCall.  So for example given this IDL:

interface InterfaceWithCall {
  legacycaller long (float arg);
};

the corresponding C++ would be:

class InterfaceWithCall {
public:
  int32_t LegacyCall(float aArgument);
};

Throwing exceptions from WebIDL methods, getters, and setters

WebIDL methods, getters, and setters that are explicitly marked as allowed to throw have an ErrorResult& argument as their last argument.  To throw an exception, simply call Throw() on the ErrorResult& and return from your C++ back into the binding code.

In cases when the specification calls for throwing a TypeError, you should use ErrorResult::ThrowTypeError() instead of calling Throw().

Custom extended attributes

Our WebIDL parser and code generator recognize several extended attributes that are not present in the WebIDL spec.

[ChromeOnly]

This extended attribute can be specified on any method, attribute, or constant on an interface or on an interface as a whole.

Interface members flagged as [ChromeOnly] are only exposed in chrome Windows (and in particular, are not exposed to webpages).  From the point of view of web content, it's as if the interface member were not there at all.  These members are exposed to chrome script working with a content objects.

If specified on an interface as a whole, this functions like [PrefControlled] except that the binding code will automatically check whether the global object (Window or worker global) involved is a chrome global instead of calling into the C++ implementation to determine whether to expose the interface object on the global.   Accessing a  content global via Xrays will not show [ChromeOnly] interface objects on it.

[Pref=prefname]

This extended attribute can be specified on any method, attribute, or constant on an interface or on an interface as a whole. It takes a value, which must be the name of a boolean preference.

If specified on an interface member, the interface member involved is only exposed if the preference is set to true. An example of how this can be used:

interface MyInterface {
  attribute long alwaysHere;
  [Pref="my.pref.name"] attribute long onlyHereIfEnabled;
};

If specifed on an interface as a whole, this functions like [PrefControlled] except that the binding will check the value of the preference directly without calling into the C++ implementation of the interface at all. This is useful when the enable check is simple and it's desirable to keep the prefname with the WebIDL declaration. The implementation can call MyInterfaceBinding::PrefEnabled() to check whether it is enabled or not.  An example of how this can be used:

[Pref="my.pref.name"]
interface MyConditionalInterface {
};

[Func="funcname"]

This extended attribute can be specified on any method, attribute, or constant on an interface or on an interface as a whole.  It takes a value, which must be the name of a static function. 

If specified on an interface member, the interface member involved is only exposed if that function returns true.   An example of how this can be used:

interface MyInterface {
  attribute long alwaysHere;
  [Func="MyClass::StuffEnabled"] attribute long onlyHereIfEnabled;
};

The function is invoked with two arguments: the JSContext that the operation is happening on and the JSObject for the global of the object that the property will be defined on if the function returns true.  So in this case, the above IDL would also require the following C++:

class MyClass {
  static bool StuffEnabled(JSContext* cx, JSObject* obj);
};

If specified on an interface as a whole, this functions like [PrefControlled] except it will call the given function.  An example of how it can be used:

[Func="MyClass::MyConditionalInterfaceEnabled"]
interface MyConditionalInterface {
};

[PrefControlled]

This extended attribute can be specified on an interface.  If it is specified, then lookups for the interface object for this interface on a DOM Window will only find it if the static PrefEnabled() method on the C++ class corresponding to the interface returns true.  For objects that can only be created via a constructor, this allows disabing the functionality altogether via a preference and making it look like the feature is not implemented at all.  The PrefEnabled() function is invoked with no arguments.

If this is specified on a [NavigatorProperty] interface, it will also control whether the property appears on window.navigator.

[Creator]

Used to flag methods or attributes as guaranteeing that they create a new object each time the method or attribute getter is called.  Only methods or attribute getters flagged in this way are allowed to return objects that are marked with 'wrapperCache': False.

[Throws], [GetterThrows], [SetterThrows]

Used to flag methods or attributes as allowing the C++ callee to throw.  This causes the binding generator, and in many cases the JIT, to generate extra code to handle possible exceptions.  Possibly-throwing methods and attributes get an ErrorResult& argument.

[Throws] applies to both methods and attributes; for attributes it means both the getter and the setter can throw.  [GetterThrows] applies only to attributes.  [SetterThrows] applies only to non-readonly attributes.

For bindings that involve workers, the above can all be specified with MainThread or Workers as a value.  When doing this, if [Throws] is specified on an attribute, no matter what its value, then [GetterThrows] and [SetterThrows] will be ignored.  So to have an attribute which can throw both when getting and setting on main thread but can only throw from the setter in workers, use [SetterThrows, GetterThrows=MainThread].

For interfaces flagged with [JSImplementation], all methods and properties are assumed to be able to throw and do not need to be flagged as throwing.

[Pure]

Used to flag attributes whose getter has no side-effects and keeps returning the same value as long as no DOM methods or setters are executed.  This allows the JIT to perform loop-hoisting and common subexpression elimination on the return values of these attributes in some cases.  Note that side-effects include throwing exceptions, so any attribute that has the [Throws] or [GetterThrows] extended attribute cannot be marked [Pure].  This extended can be used on writable attributes as long as the getter obeys the above rules.

[Constant]

Used to flag readonly attributes that could have been annotated with [Pure] and also always return the same value.  This allows the JIT to do even more aggressive optimization of getters for such attributes.  This should only be used when it's absolutely guaranteed that the return value of the attribute getter will always be the same from the JS engine's point of view.  This extended attribute implies [Pure] as far as the JIT is concerned.

[NeedNewResolve]

Used to flag interfaces which have a custom resolve hook.  This annotation will cause the DoNewResolve method to be called on the underlying C++ class when a property lookup happens on the object.  The signature of this method is: DoNewResolve(JSContext*, JS::Handle<JSObject*>, JS::Handle<jsid>, JS::MutableHandle<JS::Value>).  Here the passed-in object is the object the property lookup is happening on (which may be an Xray for the actual DOM object) and the jsid is the property name.  The value that the property should have is returned in the MutableHandle<Value>, with UndefinedValue() indicating that the property does not exist.

If this extended attribute is used, then the underlying C++ class must also implement a method called GetOwnPropertyNames with the signature GetOwnPropertyNames(JSContext* aCx, nsTArray<nsString>& aNames, ErrorResult& aRv).  This method wil be called by the JS engine's enumerate hook and must provide a superset of all the property names that DoNewResolve might resolve.  Providing names that DoNewResolve won't actually resolve is OK.

[HeaderFile="path/to/headerfile.h"]

Indicates where the implementation can be found. Similar to the headerFile annotation in Bindings.conf.

[JSImplementation="@mozilla.org/some-contractid;1"]

Used on an interface to provide the contractid of the JavaScript component implementing the interface.

Setting this extended attribute to propName on an interface causes window.navigator.propName to be an instance of the interface.

Helper objects

The C++ side of the bindings uses a number of helper objects.

Nullable<T>

Nullable<> is a struct declared in Nullable.h and exported to mozilla/dom/Nullable.h that is used to represent nullable values of types that don't have a natural way to represent null.

Nullable<T> has an IsNull() getter that returns whether null is represented and a Value() getter that returns a const T& and can be used to get the value when it's not null.

Nullable<T> has a SetNull() setter that sets it as representing null and two setters that can be used to set it to a value: "void SetValue(T)" (for setting it to a given value) and "T& SetValue()" for directly modifying the underlying T&.

Optional<T>

Optional<> is a struct declared in BindingDeclarations.h and exported to mozilla/dom/BindingDeclarations.h that is used to represent optional arguments and dictionary members, but only those that have no default value.

Optional<T> has a WasPassed() getter that returns true if a value is available.  In that case, the Value() getter can be used to get a const T& for the value.

NonNull<T>

NonNull<T> is a struct declared in BindingUtils.h and exported to mozilla/dom/BindingUtils.h that is used to represent non-null C++ objects.  It has a conversion operator that produces T&.

OwningNonNull<T>

OwningNonNull<T> is a struct declared in BindingUtils.h and exported to mozilla/dom/BindingUtils.h that is used to represent non-null C++ objects and holds a strong reference to them.  It has a conversion operator that produces T&.

Typed arrays, arraybuffers, array buffer views

TypedArray.h is exported to mozilla/dom/TypedArray.h and exposes structs that correspond to the various typed array types, as well as ArrayBuffer and ArrayBufferView, all in the mozilla::dom namespace.  Each struct has an Data() method that returns a pointer to the relevant type (uint8_t for ArrayBuffer and ArrayBufferView) and a Length() method that returns the length in units of *Data().  So for example, Int32Array has a Data() returning int32_t* and a Length() that returns the number of 32-bit ints in the array..

Sequence<T>

Sequence<> is a type declared in BindingDeclarations.h and exported to mozilla/dom/BindingDeclarations.h that is used to represent sequence arguments.  It's some kind of typed array, but which exact kind is opaque to consumers.  This allows the binding code to change the exact definition (e.g. to use auto arrays of different sizes and so forth) without having to update all the callees.

CallbackFunction

CallbackFunction is a type declared in CallbackFunction.h and exported to mozilla/dom/CallbackFunction.h that is used as a common base class for all the generated callback function representations.  This class inherits from nsISupports, and consumers must make sure to cycle-collect it, since it keeps JS objects alive.

CallbackInterface

CallbackInterface is a type declared in CallbackInterface.h and exported to mozilla/dom/CallbackInterface.h that is used as a common base class for all the generated callback interface representations.  This class inherits from nsISupports, and consumers must make sure to cycle-collect it, since it keeps JS objects alive.

DOMString

DOMString is a class declared in BindingDeclarations.h and exported to mozilla/dom/BindingDeclarations.h that is used for WebIDL DOMString return values.  It has a conversion operator to nsString& so that it can be passed to methods that take that type or nsAString&, but callees that care about performance, have an nsStringBuffer available, and promise to hold on to the nsStringBuffer at least until the binding code comes off the stack can also take a DOMString directly for their string return value and call its SetStringBuffer method with the nsStringBuffer and its length.  This allows the binding code to avoid extra reference-counting of the string buffer in many cases, and allows it to take a faster codepath even if it does end up having to addref the nsStringBuffer.

GlobalObject

GlobalObject is a class declared in BindingDeclarations.h and exported to mozilla/dom/BindingDeclarations.h that is used to represent the global object for static attributes and operations (including constructors) in non-worker bindings.  It has a Get() method that returns an nsISupports* for the global, if such is available.

WorkerGlobalObject

WorkerGlobalObject is a class declared in BindingDeclarations.h and exported to mozilla/dom/BindingDeclarations.h that is used to represent the global object for static attributes and operations (including constructors) in worker bindings.  It has a Get() method that returns the JSObject*  for the global and a GetContext() method that returns the JSContext* the call is happening on.  A caveat: the compartment of the JSContext may not match the compartment of the global!

Date

Date is a class declared in BindingDeclarations.h and exported to mozilla/dom/BindingDeclarations.h that is used to represent WebIDL Dates.  It has a TimeStamp() method returning a double which represents a number of milliseconds since the epoch, as well as SetTimeStamp() methods that can be used to initialize it with a double timestamp or a JS Date object.  It also has a ToDateObject() method that can be used to create a new JS Date.

ErrorResult

ErrorResult is a class declared in ErrorResult.h and exported to mozilla/ErrorResult.h that is used to represent exceptions in WebIDL bindings.  This has the following methods:

  • Throw: allows throwing an nsresult.  The nsresult must be a failure code.
  • ThrowTypeError: allows throwing a TypeError with the given error message.  The list of allowed TypeErrors and corresponding messages is in dom/bindings/Errors.msg.
  • ThrowJSException: allows throwing a preexisting JS exception value. However, the MightThrowJSException() method must be called before any such exceptions are thrown (even if no exception is thrown).
  • Failed: checks whether an exception has been thrown on this ErrorResult.
  • ErrorCode: returns a failure nsresult representing (perhaps incompletely) the state of this ErrorResult.
  • operator=: takes an nsresult and acts like Throw if the result is an error code, and like a no-op otherwise (unless an exception has already been thrown, in which case it asserts).  This should only be used for legacy code that has nsresult everywhere; we would like to get rid of this operator at some point.

Bindings.conf details

XXXbz write me.  In particular, need to describe at least use of concrete, prefable, and addExternalInterface

How to get a JSContext passed to a given method

In some rare cases you may need a JSContext* argument to be passed to a C++ method that wouldn't otherwise get such an argument. To see how to achieve this, search for implicitJSContext in dom/bindings/Bindings.conf.

Implementing WebIDL using Javascript

There is support for implementing WebIDL interfaces in JavaScript.  When this is done, there are actually two objects created: the implementation object (running as a chrome-privileged script) and the content-exposed object (which is what the web page sees).  This allows the implementation object to have various APIs that the content-exposed object does not.

To implement a WebIDL interface in JavaScript, first add a WebIDL file, in the same way as you would for a C++-implemented interface.  To support implementation in JS, you must add an extended attribute JSImplementation="CONTRACT_ID_STRING" on your interface, where CONTRACT_ID_STRING is the XPCOM component contract ID of the JS implementation.  Here's an example:

[Constructor(optional long firstNumber), JSImplementation="@mozilla.org/my-number;1"]
interface MyNumber {
  attribute long value;
  readonly attribute long otherValue;
  void doNothing();
};

Next, create an XPCOM component that implements this interface.  Basic directions for how to do this can be found elsewhere on MDN.  Use the same contract ID as you specified in the WebIDL file.  The class ID doesn't matter, except that it should be a newly generated one.  For QueryInterface, you only need to implement nsISupports, not anything corresponding to the WebIDL interface.  The name you use for the XPCOM component should be distinct from the name of the interface, to avoid confusing error messages.

WebIDL attributes are implemented as properties on the JS object or its prototype chain, whereas WebIDL methods are implemented as methods on the object or prototype.  Note that any other instances of the interface that you are passed in as arguments are the full web-facing version of the object, and not the JS implementation, so you currently cannot access any private data.

The WebIDL constructor invocation will first create your object.  If the XPCOM component implements nsIDOMGlobalPropertyInitializer, then the object's init method will be invoked with a single argument: the content window the constructor came from.  This allows the JS implementation to know which content window it's associated with.  The init method should not return anything.  Then, if there are any constructor arguments, the object's __init method will be invoked, with the constructor arguments as its arguments.

If you want an instance of the class to be added to window.navigator, add an extended attribute NavigatorProperty="PropertyName" which will make the instance available as window.navigator.PropertyName.

Here's an example JS implementation of the above interface. The invisibleValue field will not be accessible to web content, but is usable by the doNothing() method.

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

function MyNumberInner() {
  this.value = 111;
  this.invisibleValue = 12345;
}

MyNumberInner.prototype = {
  classDescription: "Get my number XPCOM Component",
  classID: Components.ID("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"), // dummy UUID
  contractID: "@mozilla.org/my-number;1",
  QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsISupports]),
  doNothing: function() {},
  get otherValue() { return this.invisibleValue - 4; },
  __init: function(firstNumber) {
    if (arguments.length > 0) {
      this.value = firstNumber;
    }
  }
}

var components = [MyNumberInner];
var NSGetFactory = XPCOMUtils.generateNSGetFactory(components);

Finally, add a component and a contract and whatever other manifest stuff you need to implement an XPCOM component.

Guarantees provided by bindings

When implementing a WebIDL interface in JavaScript, certain guarantees will be provided by the binding implementation.  For example, string or numeric arguments will actually be primitive strings or numbers.  Dictionaries will contain only the properties that they are declared to have, and they will have the right types.  Interface arguments will actually be objects implementing that interface.

What the bindings will NOT guarantee is much of anything about object and any arguments.  They will get cross-compartment wrappers that make touching them from chrome code not be an immediate security bug, but otherwise they can have quite surprising behavior if the page is trying to be malicious.  Try to avoid using these types if possible.

Accessing the content object from the implementation

If the JS implementation of the WebIDL interface needs to access the content object, it is available as a property called __DOM_IMPL__ on the chrome implementation object.

Inheriting from interfaces implemented in C++

It's possible to have an interface implemented in JavaScript inherit from an interface implemented in C++.  To do so, simply have one interface inherit from the other and the bindings code will auto-generate a C++ object inheriting from the implementation of the parent interface.  The class implementing the parent interface will need a constructor that takes an nsPIDOMWindow* (though it doesn't have to do anything with that argument).

If the class implementing the parent interface is abstract and you want to use a specific concrete class as the implementation to inherit from, you will need to add a defaultImpl annotation to the descriptor for the parent interface in Bindings.conf.  The value of the annotation is the C++ class to use as the parent for JS-implemented descendants; if defaultImpl is not specified, the nativeType will be used.

For example, consider this interface that we wish to implement in JavaScript:

[JSImplemented="some-contract"]
interface MyEventTarget : EventTarget {
  attribute EventHandler onmyevent;
  void dispatchTheEvent(); // Sends a "myevent" event to this EventTarget
}

The implementation would look something like this, ignoring the XPCOM boilerplate:

function MyEventTargetImpl() {
}
MyEventTargetImpl.prototype = {
  init: function(contentWindow) {  // XXXbz need to document how to get this called on you!
    this.contentWindow = contentWindow;
  }

  get onmyevent() {
    return this.__DOM_IMPL__.getEventHandler("onmyevent");
  }

  set onmyevent(handler) {
    this.__DOM_IMPL__.setEventHandler("onmyevent", handler);
  }

  dispatchTheEvent: function() {
    var event = new this.contentWindow.Event("myevent");
    this.__DOM_IMPL__.dispatchEvent(event);
  }
};

The implementation would automatically support the API exposed on EventTarget (so for example addEventListener).  Calling the dispatchTheEvent method would cause dispatch of an event that content script can see via listeners it has added.

Note that in this case the chrome implementation is relying on some [ChromeOnly] methods on EventTarget that were added specifically to make it possible to easily implement event handlers.  Other cases can do similar things as needed.

Revision Source

<div class="note">
  <p>Notes: Need to document the setup for indexed and named getters/setters/creators/deleters.</p>
</div>
<p>The <a class="external" href="http://www.w3.org/TR/WebIDL/" title="http://www.w3.org/TR/WebIDL/">WebIDL</a> bindings are generated at build time based on two things: the actual WebIDL file and a configuration file that lists some metadata about how the WebIDL should be reflected into Gecko-internal code.</p>
<p>All WebIDL files should be placed in <a class="external" href="http://mxr.mozilla.org/mozilla-central/source/dom/webidl/" title="http://mxr.mozilla.org/mozilla-central/source/dom/webidl/"><code>dom/webidl</code></a> and added to the list in the <a class="external" href="http://mxr.mozilla.org/mozilla-central/source/dom/webidl/WebIDL.mk" title="http://mxr.mozilla.org/mozilla-central/source/dom/webidl/WebIDL.mk"><code>WebIDL.mk</code></a> file in that directory.</p>
<p>The configuration file, <code><a class="external" href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/Bindings.conf" title="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/Bindings.conf">dom/bindings/Bindings.conf</a>,</code> is basically a Python dict that maps interface names to information about the interface, called a <em>descriptor</em>.&nbsp; There are all sorts of possible options here that handle various edge cases, but most descriptors can be very simple.</p>
<p>All the generated code is placed in the <code>mozilla::dom</code> namespace.&nbsp; For each interface, a namespace whose name is the name of the interface with <code>Binding</code> appended is created, and all the things pertaining to that interface's binding go in that namespace.</p>
<p>There are various helper objects and utility methods in <code>dom/bindings</code> that are also all in the <code>mozilla::dom</code> namespace and whose headers are all exported into <code>mozilla/dom</code>.</p>
<h2 id="Adding_WebIDL_bindings_to_a_class">Adding WebIDL bindings to a class</h2>
<div class="warning">
  <strong>Note:</strong> If your object needs to be reflected in Workers, you will need to do more work here.&nbsp; XXXbz need to document.</div>
<p>To add a WebIDL binding for interface <code>MyInterface</code> to a class <code>mozilla::dom::MyInterface</code> that's supposed to implement that interface, you need to do the following:</p>
<ol>
  <li>Inherit from <code>nsWrapperCache</code> and hook up the class to the cycle collector so it will trace the wrapper cache properly, and call <code>SetIsDOMBinding()</code> in the constructor of the derived class.&nbsp; Note that you may not need to do this if your objects can only be created, never gotten from other objects.&nbsp; If you also inherit from <code>nsISupports</code>, make sure the <code>nsISupports</code> comes before the <code>nsWrapperCache</code> in your list of parent classes.</li>
  <li>Implement a <code>GetParentObject</code> override that, for a given instance of your class, returns the same object every time (unless you write explicit code that handles your parent object changing by reparenting JS wrappers, as nodes do).&nbsp; The idea is that walking the <code>GetParentObject</code> chain will eventually get you to a Window, so that every WebIDL object is associated with a particular Window.&nbsp; For example, <code>nsINode::GetParentObject</code> returns the node's owner document.&nbsp; The return value of <code>GetParentObject</code> must either singly-inherit from <code>nsISupports</code> or have a corresponding <code>ToSupports()</code> method that can produce an <code>nsISupports</code> from it.&nbsp; If many instances of <code>MyInterface</code> are expected to be created quicky, the return value of <code>GetParentObject</code> should itself inherit from <code>nsWrapperCache</code> for optimal performance.&nbsp; Returning null from <code>GetParentObject</code> is allowed in situations in which it's OK to associate the resulting object with a random global object for security purposes; this is not usually ok for things that are exposed to web content.&nbsp; Again, if you do not need wrapper caching you don't need to do this.</li>
  <li>Add the WebIDL for <code>MyInterface</code> in <code>dom/webidl</code> and to the list in <code>dom/webidl/WebIDL.mk</code>.</li>
  <li>Add an entry to <code>dom/bindings/Bindings.conf</code> that sets some basic information about the implementation of the interface.&nbsp; If the C++ type is not <code>mozilla::dom::MyInterface</code>, you need to set the <code>'nativeType'</code> to the right type.&nbsp; If the type is not in the header file one gets by replacing '::' with '/' and appending '<code>.h</code>' (for main thread; for workers the rules are slightly different), then add a corresponding <code>'headerFile'</code> annotation (or <a href="#HeaderFile" title="#HeaderFile"><code>HeaderFile</code></a> annotation to the .webidl file).&nbsp; If you don't have to set any annotations, then you don't need to add an entry either and the code generator will simply assume the defaults here.</li>
  <li>Add external interface entries to <code>Bindings.conf</code> for whatever non-WebIDL interfaces your new interface has as arguments or return values.</li>
  <li>Implement a <code>WrapObject</code> override on <code>mozilla::dom::MyInterface</code> that just calls through to <code>mozilla::dom::MyInterfaceBinding::Wrap</code>.&nbsp; Note that if your C++ type is implementing multiple distinct Web IDL interfaces, you need to choose which <code>mozilla::dom::MyInterfaceBinding::Wrap</code> to call here.&nbsp; See <code>AudioContext::Wrap</code> for example.</li>
  <li>Expose whatever methods the interface needs on <code>mozilla::dom::MyInterface</code>.&nbsp; These can be inline, virtual, have any calling convention, and so forth, as long as they have the right argument types and return types.&nbsp; You can see an example of what the function declarations should look like by running <code>make MyInterface-example</code> in <code>dom/bindings</code> in your objdir.&nbsp; That will produce two files in that directory: <code>MyInterface-example.h</code> and <code>MyInterface-example.cpp</code>, which show a basic implementation of the interface, using a class that inherits from <code>nsISupports</code> and has a wrapper cache.</li>
</ol>
<p>See this <a class="link-https" href="https://hg.mozilla.org/mozilla-central/rev/dd08c10193c6" title="https://hg.mozilla.org/mozilla-central/rev/dd08c10193c6">sample patch that migrates window.performance.* to WebIDL bindings</a>.</p>
<div class="note">
  <strong>Note:</strong> If your object can only be reflected into JS by creating it, not by retrieving it from somewhere, you can skip steps 1 and 2 above and instead add <code>'wrapperCache': False</code> to your descriptor.&nbsp; If your object already has classinfo, it should be using the <code>nsNewDOMBindingNoWrapperCacheSH</code> scriptable helper in this case.&nbsp; You will need to flag the functions that return your object as <a href="#Creator" title="#Creator"><code>[Creator]</code></a> in the WebIDL.</div>
<h2 id="C.2B.2B_reflections_of_WebIDL_constructs">C++ reflections of WebIDL constructs</h2>
<h3 id="C.2B.2B_reflections_of_WebIDL_operations_(methods)">C++ reflections of WebIDL operations (methods)</h3>
<p><br />
  A WebIDL operation is turned into a method call on the underlying C++ object.&nbsp; The return type and argument types are determined <a href="#typemapping" title="#typemapping">as described below</a>.&nbsp; In addition to those, all <a href="#Throws">methods that are allowed to throw</a> will get an <code>ErrorResult&amp;</code> argument appended to their argument list.&nbsp; Methods that use certain WebIDL types like <code>any</code> or <code>object</code> will get a <code>JSContext*</code> argument prepended to the argument list.&nbsp; Static methods will be passed a <a href="#GlobalObject" title="#GlobalObject"><code>const GlobalObject&amp;</code></a>, or <a href="#WorkerGlobalObject" title="#WorkerGlobalObject"><code>const WorkerGlobalObject&amp;</code></a> in the worker case, for the relevant global.&nbsp; This argument comes after the <code>JSContext*</code>, if any, but before all the other arguments.</p>
<p>The name of the C++ method is simply the name of the WebIDL operation with the first letter converted to uppercase.</p>
<p>WebIDL overloads are turned into C++ overloads: they simply call C++ methods with the same name and different signatures.</p>
<p>For example, this webidl:</p>
<pre>
interface MyInterface 
{
  void doSomething(long number);
  double doSomething(MyInterface? otherInstance);

  [Throws]
  MyInterface doSomethingElse(optional long maybeNumber);
  [Throws]
  void doSomethingElse(MyInterface otherInstance);

  void doTheOther(any something);

  static void staticOperation(any arg);
};
</pre>
<p>will require these method declarations:</p>
<pre class="brush: cpp">
class MyClass
{
  void DoSomething(int32_t aNumber);
  double DoSomething(MyClass* aOtherInstance);

  already_AddRefed&lt;MyInterface&gt; DoSomethingElse(Optional&lt;int32_t&gt; aMaybeNumber,
                                                ErrorResult&amp; rv);
  void DoSomethingElse(MyClass&amp; aOtherInstance, ErrorResult&amp; rv);
  
  void DoTheOther(JSContext* cx, JS::Value aSomething);

  static void StaticOperation(JSContext* cx, const GlobalObject&amp; aGlobal, JS::Value aSomething);
}
</pre>
<h3 id="C.2B.2B_reflections_of_WebIDL_attributes">C++ reflections of WebIDL attributes</h3>
<p>A WebIDL attribute is turned into a pair of method calls for the getter and setter on the underlying C++ object.&nbsp; A readonly attribute only has a getter and no setter.</p>
<p>The getter's name is the name of the attribute with the first letter converted to uppercase.&nbsp; This has <code>Get</code> prepended to it if any of these conditions hold:</p>
<ol>
  <li>The type of the attribute is nullable.</li>
  <li>The getter can throw.</li>
  <li>The return value of the attribute is returned via an out parameter in the C++.</li>
</ol>
<p>The method signature for the getter looks just like an operation with no arguments and the attribute's type as the return type.</p>
<p>The setter's name is <code>Set</code> followed by the name of the attribute with the first letter converted to uppercase.&nbsp; The method signature looks just like an operation with a void return value and a single argument whose type as the attribute's type.</p>
<h3 id="C.2B.2B_reflections_of_WebIDL_constructors">C++ reflections of WebIDL constructors</h3>
<p>A WebIDL constructor is turned into a static class method named <code>Constructor</code>.&nbsp; The arguments of this method will be the arguments of the WebIDL constructor, with a <a href="#GlobalObject" title="#GlobalObject"><code>const GlobalObject&amp;</code></a>, or <a href="#WorkerGlobalObject" title="#WorkerGlobalObject"><code>const WorkerGlobalObject&amp;</code></a> in the worker case, for the relevant global prepended.&nbsp; For the non-worker case, the global is typically the inner window for the DOM Window the constructor function is attached to.&nbsp; If a <code>JSContext*</code> is also needed due to some of the argument types, it will come before the global.&nbsp; The return value of the constructor for <code>MyInterface</code> is exactly the same as that of a method returning an instance of <code>MyInterface</code>. Constructors are always allowed to throw.</p>
<p>For example, this IDL:</p>
<pre>
[Constructor,
 Constructor(unsigned long someNumber)]
interface MyInterface 
{
};
</pre>
<p>will require the following declarations in <code>MyClass</code>, for a non-worker binding:</p>
<pre class="brush: cpp">
class MyClass {
  // Various nsISupports stuff or whatnot
  static
  already_AddRefed&lt;MyClass&gt; Constructor(const GlobalObject&amp; aGlobal,
                                        ErrorResult&amp; rv);
  static
  already_AddRefed&lt;MyClass&gt; Constructor(const GlobalObject&amp; aGlobal,
                                        uint32_t aSomeNumber,
                                        ErrorResult&amp; rv);  
};
</pre>
<h3 id="typemapping" name="typemapping">C++ reflections of WebIDL types</h3>
<p>The exact C++ representation for WebIDL types can depend on the precise way that they're being used: e.g. return values, arguments, and sequence or dictionary members might all have different representations.</p>
<p>Unless stated otherwise, a type only has one representation.&nbsp; Also, unless stated otherwise, nullable types are represented by wrapping <a href="#Nullable" title="#Nullable"><code>Nullable&lt;&gt;</code></a> around the base type.</p>
<p>In all cases, optional arguments which do not have a default value are represented by wrapping <a href="#Optional" title="#Optional"><code>const Optional&lt;&gt;&amp;</code></a> around the representation of the argument type.&nbsp; If the argument type is a C++ reference, it will also become a <a href="#NonNull" title="#NonNull">NonNull&lt;&gt;</a> around the actual type of the object in the process.&nbsp; Optional arguments which do have a default value are just represented by the argument type itself, set to the default value if the argument was not in fact passed in.</p>
<p>Variadic WebIDL arguments are treated as a <a href="#Sequence" title="#Sequence"><code>const Sequence&lt;&gt;&amp;</code></a> around the actual argument type.</p>
<h4 id="any"><code>any</code></h4>
<p><code>any</code> is represented in two different ways, depending on use:</p>
<ul>
  <li><code>any</code> arguments become <code>JS::Handle&lt;JS::Value&gt;</code>.</li>
  <li><code>any</code> return values, dictionary members, and sequence elements become <code>JS::Value</code>.&nbsp; The dictionary members and sequence elements are guaranteed to be marked by whoever puts the sequence or dictionary on the stack, using <code>SequenceRooter</code> and <code>DictionaryRooter</code>.</li>
</ul>
<p>Methods using <code>any</code> always get a <code>JSContext*</code> argument.</p>
<p>For example, this WebIDL:</p>
<pre>
interface Test {
  attribute any myAttr;
  any myMethod(any arg1, sequence&lt;any&gt; arg2, optional any arg3);
};
</pre>
<p>will correspond to these C++ function declarations:</p>
<pre class="brush: cpp">
JS::Value MyAttr(JSContext* cx);
void SetMyAttr(JSContext* cx, JS::Handle&lt;JS::Value&gt; value);
JS::Value MyMethod(JSContext* cx, JS::Handle&lt;JS::Value&gt; arg1, 
                   const Sequence&lt;JS::Value&gt;&amp; arg2,
                   const Optional&lt;JS::Handle&lt;JS::Value&gt; &gt;&amp; arg3);
</pre>
<h4 id="boolean"><code>boolean</code></h4>
<p>The <code>boolean</code> WebIDL type is represented as a C++ <code>bool</code>.</p>
<p>For example, this WebIDL:</p>
<pre>
interface Test {
  attribute boolean myAttr;
  boolean myMethod(optional boolean arg);
};
</pre>
<p>will correspond to these C++ function declarations:</p>
<pre class="brush: cpp">
bool MyAttr();
void SetMyAttr(bool value);
JS::Value MyMethod(const Optional&lt;bool&gt;&amp; arg);
</pre>
<h4 id="Integer_types">Integer types</h4>
<p>Integer WebIDL types are mapped to the corresponding C99 stdint types.</p>
<p>For example, this WebIDL:</p>
<pre>
interface Test {
  attribute short myAttr;
  long long myMethod(unsigned long? arg);
};
</pre>
<p>will correspond to these C++ function declarations:</p>
<pre class="brush: cpp">
int16_t MyAttr();
void SetMyAttr(int16_t value);
int64_t MyMethod(const Nullable&lt;uint32_t&gt;&amp; arg);
</pre>
<h4 id="Floating_point_types">Floating point types</h4>
<p>Floating point WebIDL types are mapped to the C++ type of the same name.&nbsp; So <code>float</code> and <code>unrestricted float</code> become a C++ <code>float</code>, while <code>double</code> and <code>unrestricted double</code> become a C++ <code>double</code>.</p>
<p>For example, this WebIDL:</p>
<pre>
interface Test {
  float myAttr;
  double myMethod(unrestricted double? arg);
};
</pre>
<p>will correspond to these C++ function declarations:</p>
<pre class="brush: cpp">
float MyAttr();
void SetMyAttr(float value);
double MyMethod(const Nullable&lt;double&gt;&amp; arg);
</pre>
<h4 id="DOMString"><code>DOMString</code></h4>
<p>Strings are reflected in three different ways, depending on use:</p>
<ul>
  <li>String arguments become <code>const nsAString&amp;</code>.</li>
  <li>String return values become a <a href="#DOMString-helper" title="#DOMString-helper"><code>mozilla::dom::DOMString&amp;</code></a> out param appended to the argument list.&nbsp; This comes after all IDL arguments, but before the <code>ErrorResult&amp;</code>, if any, for the method.&nbsp; Note that this allows callees to declare their methods as taking an <code>nsAString&amp;</code> or <code>nsString&amp;</code> if desired.</li>
  <li>Strings in sequences and dictionaries become <code>nsString</code>.</li>
</ul>
<p>Nullable strings are represented by the same types as non-nullable ones, but the string will return true for <code>DOMStringIsNull()</code>.&nbsp; Returning null as a string value can be done using <code>SetDOMStringToNull</code> on the out param if it's an <code>nsAString</code> or calling <code>SetNull()</code> on a <code>DOMString</code>.</p>
<p>For example, this WebIDL:</p>
<pre>
interface Test {
  DOMString myAttr;
  [Throws]
  DOMString myMethod(sequence&lt;DOMString&gt; arg1, DOMString? arg2, optional DOMString arg3);
};
</pre>
<p>will correspond to these C++ function declarations:</p>
<pre class="brush: cpp">
void GetMyAttr(nsString&amp; retval);
void SetMyAttr(const nsAString&amp; value);
void MyMethod(const Sequence&lt;nsString&gt;&amp; arg1, const nsAString&amp; arg2,
              const Optional&lt;nsAString&gt;&amp; arg3, nsString&amp; retval, ErrorResult&amp; rv);
</pre>
<h4 id="ByteString"><code>ByteString</code></h4>
<p><code>ByteString</code> is not suported yet.</p>
<h4 id="object"><code>object</code></h4>
<p><code>object</code> is represented in two different ways, depending on use:</p>
<ul>
  <li><code>object</code> arguments become <code>JS::Handle&lt;JSObject*&gt;</code>.</li>
  <li><code>object</code> return values, dictionary members, and sequence elements become <code>JSObject*</code>.&nbsp; The dictionary members and sequence elements are guaranteed to be marked by whoever puts the sequence or dictionary on the stack, using <code>SequenceRooter</code> and <code>DictionaryRooter</code>.</li>
</ul>
<p>Methods using <code>object</code> always get a <code>JSContext*</code> argument.</p>
<p>For example, this WebIDL:</p>
<pre>
interface Test {
  object myAttr;
  object myMethod(object arg1, object? arg2, sequence&lt;object&gt; arg3, optional object arg4,
                  optional object? arg5);
};</pre>
<p>will correspond to these C++ function declarations:</p>
<pre class="brush: cpp">
JSObject* GetMyAttr(JSContext* cx);
void SetMyAttr(JSContext* cx, JS::Handle&lt;JSObject*&gt; value);
void MyMethod(JSContext* cx, JS::Handle&lt;JSObject*&gt; arg1, JS::Handle&lt;JSObject*&gt; arg2,
              const Sequence&lt;JSObject*&gt;&amp; arg3,
              const Optional&lt;JS::Handle&lt;JSObject*&gt; &gt;&amp; arg4,
              const Optional&lt;JS::Handle&lt;JSObject*&gt; &gt;&amp; arg5);
</pre>
<h4 id="Interface_types">Interface types</h4>
<p>There are four kinds of interface types in the WebIDL bindings.&nbsp; Callback interfaces are used to represent script objects that browser code can call into.&nbsp; External interfaces are used to represent objects that have not been converted to the WebIDL bindings yet.&nbsp; WebIDL interfaces are used to represent WebIDL binding objects.&nbsp; "SpiderMonkey" interfaces are used to represent objects that are implemented natively by the JavaScript engine (e.g. typed arrays).</p>
<h5 id="Callback_interfaces">Callback interfaces</h5>
<p>Callback interfaces are represented in C++ as objects inheriting from <a href="#CallbackInterface" title="#CallbackInterface"><code>mozilla::dom::CallbackInterface</code></a>, whose name, in the <code>mozilla::dom</code> namespace, matches the name of the callback interface in the WebIDL.&nbsp; The exact representation depends on how the type is being used.</p>
<ul>
  <li>Nullable arguments become <code>Foo*</code>.</li>
  <li>Non-nullable arguments become <code>Foo&amp;</code>.</li>
  <li>Return values become <code>already_AddRefed&lt;Foo&gt;</code> or <code>Foo*</code> depending on whether the method or property involved is flagged as <code>resultNotAddRefed</code> in <a href="#Bindings.conf" title="#Bindings.conf"><code>Bindings.conf</code></a>.</li>
  <li>WebIDL callback interfaces in sequences and dictionaries are represented by <code>nsRefPtr&lt;Foo&gt;</code> if nullable and <a href="#OwningNonNull" title="#OwningNonNull"><code>OwningNonNull&lt;Foo&gt;</code></a> otherwise.</li>
</ul>
<p>If the interface is a single-opertion interface, the object exposes two methods that both invoke the same underlying JS callable.&nbsp; The first of these methods allows the caller to pass in a <code>this</code> object, while the second defaults to a null <code>this</code> object.&nbsp; In either case, the <code>this</code> object is only used if the callback interface is implemented by a JS callable.&nbsp; If it's implemented by an object with a property whose name matches the operation, the object itself is always used as <code>this</code>.</p>
<p>If the interface is not a single-operation interface, it just exposes a single method for every IDL method/getter/setter.</p>
<p>The signatures of the methods correspond to the signatures for throwing IDL methods/getters/setters with an additional trailing "<code>mozilla::dom::CallbackObject::ExceptionHandling</code> <code>aExceptionHandling</code>" argument, defaulting to <code>eReportExceptions</code>.&nbsp; If <code>aReportExceptions</code> is set to <code>eReportExceptions</code>, the methods will report JS exceptions before returning.&nbsp; If <code>aReportExceptions</code> is set to <code>eRethrowExceptions</code>, JS exceptions will be stashed in the <code>ErrorResult</code> and will be reported when the stack unwinds to wherever the <code>ErrorResult</code> was set up.</p>
<p>For example, this WebIDL:</p>
<pre>
callback interface MyCallback {
  attribute long someNumber;
  short someMethod(DOMString someString);
};
callback inteface MyOtherCallback {
  // single-operation interface
  short doSomething(Node someNode);
};
interface MyInterface {
  attribute MyCallback foo;
  attribute MyCallback? bar;
};</pre>
<p>will lead to these C++ class declarations, in the <code>mozilla::dom</code> namespace:</p>
<pre class="brush: cpp">
class MyCallback : public CallbackInterface
{
  int32_t GetSomeNumber(ErrorResult&amp; rv, ExceptionHandling aExceptionHandling = eReportExceptions);
  void SetSomeNumber(int32_t arg, ErrorResult&amp; rv,
                     ExceptionHandling aExceptionHandling = eReportExceptions);
  int16_t SomeMethod(const nsAString&amp; someString, ErrorResult&amp; rv,
                     ExceptionHandling aExceptionHandling = eReportExceptions);
};

class MyOtherCallback : public CallbackInterface
{
public:
  int16_t
  DoSomething(nsINode&amp; someNode, ErrorResult&amp; rv,
              ExceptionHandling aExceptionHandling = eReportExceptions);

  template&lt;typename T&gt;
  int16_t
  DoSomething(const T&amp; thisObj, nsINode&amp; someNode, ErrorResult&amp; rv,
              ExceptionHandling aExceptionHandling = eReportExceptions);
};</pre>
<p>and these C++ function declarations on the implementation of <code>MyInterface</code>:</p>
<pre>
already_AddRefed&lt;MyCallback&gt; GetFoo();
void SetFoo(MyCallback&amp;);
already_AddRefed&lt;MyCallback&gt; GetBar();
void SetBar(MyCallback*);
</pre>
<h5 id="External_interfaces">External interfaces</h5>
<p>External interfaces are represented in C++ as objects that XPConnect knows how to unwrap to.&nbsp; This can mean XPCOM interfaces (whether declared in XPIDL or not) or it can mean some type that there's a castable native unwrapping function for.&nbsp; The C++ type to be used should be the <code>nativeType</code> listed for the external interface in the <a href="#Bindings.conf" title="#Bindings.conf"><code>Bindings.conf</code></a> file.&nbsp; The exact representation depends on how the type is being used.</p>
<ul>
  <li>Arguments become <code>nsIFoo*</code>.</li>
  <li>Return values become <code>already_AddRefed&lt;nsIFoo&gt;</code> or <code>nsIFoo*</code> depending on whether the method or property involved is flagged as <code>resultNotAddRefed</code> in <a href="#Bindings.conf" title="#Bindings.conf"><code>Bindings.conf</code></a>.</li>
  <li>External interfaces in sequences and dictionaries are represented by <code>nsRefPtr&lt;nsIFoo&gt;.</code></li>
</ul>
<h5 id="WebIDL_interfaces">WebIDL interfaces</h5>
<p>WebIDL interfaces are represented in C++ as C++ classes.&nbsp; For non-worker bindings the class involved must either inherit from <code>nsISupports</code>, in which case the canonical <code>nsISupports</code> must be on the primary inheritance chain of the object, or must be explicitly annotated in <code>Bindings.conf</code> as being non-nsISupports refcounted or directly by the JS object.&nbsp; If the interface has a parent interface, the C++ class corresponding to the parent must be on the primary inheritance chain of the object.&nbsp; This guarantees that a <code>void*</code> can be stored in the JSObject which can then be <code>reinterpret_cast</code> to any of the classes that correspond to interfaces the object implements.&nbsp; The C++ type to be used should be the <code>nativeType</code> listed for the interface in the <a href="#Bindings.conf" title="#Bindings.conf"><code>Bindings.conf</code></a> file, or <code>mozilla::dom::InterfaceName</code> if none is listed (<code>mozilla::dom::workers::InterfaecName</code> for worker bindings).&nbsp; The exact representation depends on how the type is being used.</p>
<ul>
  <li>Nullable arguments become <code>Foo*</code>.</li>
  <li>Non-nullable arguments become <code>Foo&amp;</code>.</li>
  <li>Return values become <code>already_AddRefed&lt;Foo&gt;</code> or <code>Foo*</code> depending on whether the method or property involved is flagged as <code>resultNotAddRefed</code> in <a href="#Bindings.conf" title="#Bindings.conf"><code>Bindings.conf</code></a>.</li>
  <li>WebIDL interfaces in sequences and dictionaries are represented by <code>nsRefPtr&lt;Foo&gt;</code> if nullable and <a href="#OwningNonNull" title="#OwningNonNull"><code>OwningNonNull&lt;Foo&gt;</code></a> otherwise.</li>
</ul>
<p>For example, this WebIDL:</p>
<pre>
interface MyInterface {
  attribute MyInterface myAttr;
  void passNullable(MyInterface? arg);
  MyInterface? doSomething(sequence&lt;MyInterface&gt; arg);
  MyInterface doTheOther(sequence&lt;MyInterface?&gt; arg);
  readonly attribute MyInterface? nullableAttr;
  readonly attribute MyInterface someOtherAttr; // Marked as resultNotAddRefed
};
</pre>
<p>Would correspond to these C++ function declarations:</p>
<pre class="brush: cpp">
already_AddRefed&lt;MyClass&gt; MyAttr();
void SetMyAttr(MyClass&amp; value);
void PassNullable(MyClass* arg);
already_AddRefed&lt;MyClass&gt; doSomething(const Sequence&lt;OwningNonNull&lt;MyClass&gt; &gt;&amp; arg);
already_AddRefed&lt;MyClass&gt; doTheOther(const Sequence&lt;nsRefPtr&lt;MyClass&gt; &gt;&amp; arg);
already_Addrefed&lt;MyClass&gt; GetMyAttr();
MyClass* SomeOtherAttr();
</pre>
<h5 id=".22SpiderMonkey.22_interfaces">"SpiderMonkey" interfaces</h5>
<p>Typed array, array buffer, and array buffer view arguments are represented by the objects in <a href="#TypedArray" title="#TypedArray"><code>TypedArray.h</code></a>.&nbsp; For example, this WebIDL:</p>
<pre>
interface Test {
  void passTypedArrayBuffer(ArrayBuffer arg);
  void passTypedArray(ArrayBufferView arg);
  void passInt16Array(Int16Array arg);
}
</pre>
<p>will correspond to these C++ function declarations:</p>
<pre class="brush: cpp">
void PassTypedArrayBuffer(ArrayBuffer&amp; arg);
void PassTypedArray(ArrayBufferView&amp; arg);
void PassInt16Array(Int16Array&amp; arg);
</pre>
<p>Typed array return values are represented by <code>JSObject*</code>.</p>
<h4 id="Dictionary_types">Dictionary types</h4>
<p>A dictionary argument is represented by a const reference to a struct whose name is the dictionary name in the <code>mozilla::dom</code> namespace.&nbsp; The struct has one member for each of the dictionary's members with the same name except the first letter uppercased and prefixed with "m". The members that have default values have types as described under the corresponding WebIDL type in this document.&nbsp; The members that don't have default values have those types wrapped in <a href="#Optional" title="#Optional"><code>Optional&lt;&gt;</code></a>.</p>
<p>Dictionary return values are represented by an out parameter whose type is a non-const reference to the struct described above, with all the members that have default values preinitialized to those default values.</p>
<p>Note that optional dictionary arguments are always considered to have a default value of <code>null</code> so dictionary arguments are never wrapped in <code>Optional&lt;&gt;</code>.</p>
<p>If necessary, dictionaries can be directly initialized from a <code>JS::Value</code> in C++ code by invoking their <code>Init()</code> method.&nbsp; Consumers doing this should declare their dictionary as <code>RootedDictionary&lt;DictionaryName&gt;</code>.&nbsp; When this is done, passing in a null scope object and even a null <code>JSContext*</code> is allowed if the passed-in <code>JS::Value</code> is <code>JS::NullValue()</code>.&nbsp; Likewise, a dictionary struct can be converted to a <code>JS::Value</code> in C++ by invoking its <code>ToObject()</code> method.&nbsp; If <code>Init()</code> or <code>ToObject()</code> return false, they will generally set a pending exception on the JSContext; reporting those is the responsibility of the caller.</p>
<p>For example, this WebIDL:</p>
<pre>
dictionary Dict {
  long foo = 5;
  DOMString bar;
};

interface Test {
  void initSomething(optional Dict arg);
};
</pre>
<p>will correspond to this C++ function declaration:</p>
<pre class="brush: cpp">
void InitSomething(const Dict&amp; arg);
</pre>
<p>and the <code>Dict</code> struct will look like this:</p>
<pre class="brush: cpp">
struct Dict {
  bool Init(JSContext* cx, JSObject* scopeObj, const JS::Value&amp; val);
  bool ToObject(JSContext* cx, JSObject* parentObject, JS::Value *vp);

  Optional&lt;nsString&gt; mBar;
  int32_t mFoo;
}
</pre>
<p>Note that the dictionary members are sorted in the struct in alphabetical order.</p>
<h4 id="Enumeration_types">Enumeration types</h4>
<p>WebIDL enumeration types are represented as C++ enums.&nbsp; The values of the C++ enum are named by taking the strings in the WebIDL enumeration, replacing all non-alphanumerics with underscores, and uppercasing the first letter, with a special case for the empty string, which becomes the value <code>_empty</code>.</p>
<p>For a WebIDL enum named <code>MyEnum</code>, the C++ enum is named <code>MyEnum</code> and placed in the <code>mozilla::dom</code> namespace, while the values are placed in the <code>mozilla::dom::MyEnum</code> namespace.&nbsp; There is also a <code>mozilla::dom::MyEnumValues::strings</code> which is an array of <code>mozilla::dom::EnumEntry</code> structs that gives access to the string representations of the values.</p>
<p>For example, this WebIDL:</p>
<pre>
enum MyEnum {
  "something",
  "something-else",
  "",
  "another"
};
</pre>
<p>would lead to this C++ enum declaration:</p>
<pre class="brush: cpp">
MOZ_BEGIN_ENUM_CLASS(MyEnum, uint32_t)
  Something,
  Something_else,
  _empty,
  Another
MOZ_END_ENUM_CLASS(MyEnum)

namespace MyEnumValues {
extern const EnumEntry strings[10];
} // namespace MyEnumValues
</pre>
<h4 id="Callback_function_types">Callback function types</h4>
<p>Callback functions are represented as an object, inheriting from <a href="#CallbackFunction" title="#CallbackFunction"><code>mozilla::dom::CallbackFunction</code></a>, whose name, in the <code>mozilla::dom</code> namespace, matches the name of the callback function in the WebIDL.&nbsp; If the type is nullable, a pointer is passed in; otherwise a reference is passed in.</p>
<p>The object exposes two <code>Call</code> methods, which both invoke the underlying JS callable.&nbsp; The first <code>Call</code> method has the same signature as a throwing method declared just like the callback function, with an additional trailing "<code>mozilla::dom::CallbackObject::ExceptionHandling</code> <code>aExceptionHandling</code>" argument, defaulting to <code>eReportExceptions</code>, and calling it will invoke the callable with a null <code>this</code> object.&nbsp; The second <code>Call</code> method allows passing in an explicit <code>this</code> value as the first argument.&nbsp; This second call method is a template on the type of the first argument, so the <code>this</code> value can be passed in in whatever form is most convenient, as long as it's either a type that can be wrapped by XPConnect or a WebIDL interface type.</p>
<p>If <code>aReportExceptions</code> is set to <code>eReportExceptions</code>, the <code>Call</code> methods will report JS exceptions before returning.&nbsp; If <code>aReportExceptions</code> is set to <code>eRethrowExceptions</code>, JS exceptions will be stashed in the <code>ErrorResult</code> and will be reported when the stack unwinds to wherever the <code>ErrorResult</code> was set up.</p>
<p>For example, this WebIDL:</p>
<pre>
callback MyCallback = long (MyInterface arg1, boolean arg2);
interface MyInterface {
  attribute MyCallback foo;
  attribute MyCallback? bar;
};</pre>
<p>will lead to this C++ class declaration, in the <code>mozilla::dom</code> namespace:</p>
<pre class="brush: cpp">
class MyCallback : public CallbackFunction
{
public:
  int32_t
  Call(MyInterface&amp; arg1, bool arg2, ErrorResult&amp; rv,
      &nbsp;ExceptionHandling aExceptionHandling = eReportExceptions);

  template&lt;typename T&gt;
  int32_t
  Call(const T&amp; thisObj, MyInterface&amp; arg1, bool arg2, ErrorResult&amp; rv,
      &nbsp;ExceptionHandling aExceptionHandling = eReportExceptions);
};</pre>
<p>and these C++ function declarations in the <code>MyInterface</code> class:</p>
<pre>
already_AddRefed&lt;MyCallback&gt; GetFoo();
void SetFoo(MyCallback&amp;);
already_AddRefed&lt;MyCallback&gt; GetBar();
void SetBar(MyCallback*);
</pre>
<h4 id="Sequences">Sequences</h4>
<p>Sequence arguments are represented by <a href="#Sequence" title="#Sequence"><code>const Sequence&lt;T&gt;&amp;</code></a>, where <code>T</code> depends on the type of elements in the WebIDL sequence.</p>
<p>Sequence return values are represented by an <code>nsTArray&lt;T&gt;</code> out param appended to the argument list, where <code>T</code> is the return type for the elements of the WebIDL sequence.&nbsp; This comes after all IDL arguments, but before the <code>ErrorResult&amp;</code>, if any, for the method.</p>
<h4 id="Arrays">Arrays</h4>
<p>IDL array objects are not supported yet.</p>
<h4 id="Union_types">Union types</h4>
<p>XXXbz write me</p>
<h4 id="Date"><code>Date</code></h4>
<p>WebIDL <code>Date</code> types are represented by a <code>mozilla::dom::Date</code> struct.</p>
<h3 id="Stringifiers">Stringifiers</h3>
<p>Named stringifiers operations in WebIDL will just invoke the corresponding C++ method.</p>
<p>Anonymous stringifiers in WebIDL will invoke the C++ method called <code>Stringify</code>.&nbsp; So for example given this IDL:</p>
<pre>
interface FirstInterface {
  stringifier;
};

interface SecondInterface {
  stringifier DOMString getStringRepresentation();
};
</pre>
<p>the corresponding C++ would be:</p>
<pre>
class FirstInterface {
public:
  void Stringify(nsAString&amp; aResult);
};

class SecondInterface {
public:
  void GetStringRepresentation(nsAString&amp; aResult);
};
</pre>
<h3 id="Legacy_Callers">Legacy Callers</h3>
<p>Only anonymous legacy callers are supported, and will invoke the C++ method called <code>LegacyCall</code>.&nbsp; So for example given this IDL:</p>
<pre>
interface InterfaceWithCall {
  legacycaller long (float arg);
};
</pre>
<p>the corresponding C++ would be:</p>
<pre>
class InterfaceWithCall {
public:
  int32_t LegacyCall(float aArgument);
};
</pre>
<h2 id="Throwing_exceptions_from_WebIDL_methods.2C_getters.2C_and_setters">Throwing exceptions from WebIDL methods, getters, and setters</h2>
<p>WebIDL methods, getters, and setters that are <a href="#Throws">explicitly marked as allowed to throw</a> have an <code>ErrorResult&amp;</code> argument as their last argument.&nbsp; To throw an exception, simply call <code>Throw()</code> on the <code>ErrorResult&amp;</code> and return from your C++ back into the binding code.</p>
<p>In cases when the specification calls for throwing a <code>TypeError</code>, you should use <code>ErrorResult::ThrowTypeError()</code> instead of calling <code>Throw()</code>.</p>
<h2 class="note" id="Custom_extended_attributes">Custom extended attributes</h2>
<p>Our WebIDL parser and code generator recognize several extended attributes that are not present in the WebIDL spec.</p>
<h3 id="ChromeOnly" name="ChromeOnly"><code>[ChromeOnly]</code></h3>
<p>This extended attribute can be specified on any method, attribute, or constant on an interface or on an interface as a whole.</p>
<p>Interface members flagged as <code>[ChromeOnly]</code> are only exposed in chrome Windows (and in particular, are not exposed to webpages).&nbsp; From the point of view of web content, it's as if the interface member were not there at all.&nbsp; These members <em>are</em> exposed to chrome script working with a content objects.</p>
<p>If specified on an interface as a whole, this functions like <a href="#PrefControlled" title="#PrefControlled"><code>[PrefControlled]</code></a> except that the binding code will automatically check whether the global object (Window or worker global) involved is a chrome global instead of calling into the C++ implementation to determine whether to expose the interface object on the global.&nbsp;&nbsp; Accessing a&nbsp; content global via Xrays will not show <code>[ChromeOnly]</code> interface objects on it.</p>
<h3 id=".5BPref.3Dprefname.5D"><code>[Pref=prefname]</code></h3>
<p>This extended attribute can be specified on any method, attribute, or constant on an interface or on an interface as a whole. It takes a value, which must be the name of a boolean preference.</p>
<p>If specified on an interface member, the interface member involved is only exposed if the preference is set to <code>true</code>. An example of how this can be used:</p>
<pre>
interface MyInterface {
  attribute long alwaysHere;
  [Pref="my.pref.name"] attribute long onlyHereIfEnabled;
};
</pre>
<p>If specifed on an interface as a whole, this functions like <a href="#PrefControlled" title="#PrefControlled"><code>[PrefControlled]</code></a> except that the binding will check&nbsp;the value of the preference directly without calling into the C++ implementation of the interface at all. This is useful when the enable check is simple and it's desirable to keep the prefname with the WebIDL declaration. The implementation can call <code>MyInterfaceBinding::PrefEnabled()</code> to check whether it is enabled or not.&nbsp; An example of how this can be used:</p>
<pre>
[Pref="my.pref.name"]
interface MyConditionalInterface {
};
</pre>
<h3 id=".5BFunc.3D.22funcname.22.5D"><code>[Func="funcname"]</code></h3>
<p>This extended attribute can be specified on any method, attribute, or constant on an interface or on an interface as a whole.&nbsp; It takes a value, which must be the name of a static function.&nbsp;</p>
<p>If specified on an interface member, the interface member involved is only exposed if that function returns <code>true</code>.&nbsp;&nbsp; An example of how this can be used:</p>
<pre>
interface MyInterface {
  attribute long alwaysHere;
  [Func="MyClass::StuffEnabled"] attribute long onlyHereIfEnabled;
};
</pre>
<p>The function is invoked with two arguments: the <code>JSContext</code> that the operation is happening on and the <code>JSObject</code> for the global of the object that the property will be defined on if the function returns true.&nbsp; So in this case, the above IDL would also require the following C++:</p>
<pre>
class MyClass {
  static bool StuffEnabled(JSContext* cx, JSObject* obj);
};
</pre>
<p>If specified on an interface as a whole, this functions like <a href="#PrefControlled" title="#PrefControlled"><code>[PrefControlled]</code></a> except it will call the given function.&nbsp; An example of how it can be used:</p>
<pre>
[Func="MyClass::MyConditionalInterfaceEnabled"]
interface MyConditionalInterface {
};
</pre>
<h3 id="PrefControlled" name="PrefControlled"><code>[PrefControlled]</code></h3>
<p>This extended attribute can be specified on an interface.&nbsp; If it is specified, then lookups for the interface object for this interface on a DOM Window will only find it if the static <code>PrefEnabled()</code> method on the C++ class corresponding to the interface returns true.&nbsp; For objects that can only be created via a constructor, this allows disabing the functionality altogether via a preference and making it look like the feature is not implemented at all.&nbsp; The <code>PrefEnabled()</code> function is invoked with no arguments.</p>
<p>If this is specified on a <code>[NavigatorProperty]</code> interface, it will also control whether the property appears on <code>window.navigator</code>.</p>
<h3 id="Creator" name="Creator"><code>[Creator]</code></h3>
<p>Used to flag methods or attributes as guaranteeing that they create a new object each time the method or attribute getter is called.&nbsp; Only methods or attribute getters flagged in this way are allowed to return objects that are marked with <code>'wrapperCache': False</code>.</p>
<h3 id="Throws" name="Throws"><!--Anchor for backwards compat--><code>[Throws]</code>, <code>[GetterThrows]</code>, <code>[SetterThrows]</code></h3>
<p>Used to flag methods or attributes as allowing the C++ callee to throw.&nbsp; This causes the binding generator, and in many cases the JIT, to generate extra code to handle possible exceptions.&nbsp; Possibly-throwing methods and attributes get an <code>ErrorResult&amp;</code> argument.</p>
<p><code>[Throws]</code> applies to both methods and attributes; for attributes it means both the getter and the setter can throw.&nbsp; <code>[GetterThrows]</code> applies only to attributes.&nbsp; <code>[SetterThrows]</code> applies only to non-readonly attributes.</p>
<p>For bindings that involve workers, the above can all be specified with <code>MainThread</code> or <code>Workers</code> as a value.&nbsp; When doing this, if <code>[Throws]</code> is specified on an attribute, no matter what its value, then <code>[GetterThrows]</code> and <code>[SetterThrows]</code> will be ignored.&nbsp; So to have an attribute which can throw both when getting and setting on main thread but can only throw from the setter in workers, use <code>[SetterThrows, GetterThrows=MainThread]</code>.</p>
<p>For interfaces flagged with <code>[JSImplementation]</code>, all methods and properties are assumed to be able to throw and do not need to be flagged as throwing.</p>
<h3 id=".5BPure.5D"><code>[Pure]</code></h3>
<p>Used to flag attributes whose getter has no side-effects and keeps returning the same value as long as no DOM methods or setters are executed.&nbsp; This allows the JIT to perform loop-hoisting and common subexpression elimination on the return values of these attributes in some cases.&nbsp; Note that side-effects include throwing exceptions, so any attribute that has the <code>[Throws]</code> or <code>[GetterThrows]</code> extended attribute cannot be marked <code>[Pure]</code>.&nbsp; This extended can be used on writable attributes as long as the getter obeys the above rules.</p>
<h3 id=".5BConstant.5D"><code>[Constant]</code></h3>
<p>Used to flag readonly attributes that could have been annotated with <code>[Pure]</code> and also always return the same value.&nbsp; This allows the JIT to do even more aggressive optimization of getters for such attributes.&nbsp; This should only be used when it's absolutely guaranteed that the return value of the attribute getter will always be the same from the JS engine's point of view.&nbsp; This extended attribute implies <code>[Pure]</code> as far as the JIT is concerned.</p>
<h3 id="NeedNewResolve" name="NeedNewResolve"><code>[NeedNewResolve]</code></h3>
<p>Used to flag interfaces which have a custom resolve hook.&nbsp; This annotation will cause the <code>DoNewResolve</code> method to be called on the underlying C++ class when a property lookup happens on the object.&nbsp; The signature of this method is: <code>DoNewResolve(JSContext*, JS::Handle&lt;JSObject*&gt;, JS::Handle&lt;jsid&gt;, JS::MutableHandle&lt;JS::Value&gt;)</code>.&nbsp; Here the passed-in object is the object the property lookup is happening on (which may be an Xray for the actual DOM object) and the jsid is the property name.&nbsp; The value that the property should have is returned in the <code>MutableHandle&lt;Value&gt;</code>, with <code>UndefinedValue()</code> indicating that the property does not exist.</p>
<p>If this extended attribute is used, then the underlying C++ class must also implement a method called <code>GetOwnPropertyNames</code> with the signature <code>GetOwnPropertyNames(JSContext* aCx, nsTArray&lt;nsString&gt;&amp; aNames, ErrorResult&amp; aRv)</code>.&nbsp; This method wil be called by the JS engine's enumerate hook and must provide a superset of all the property names that <code>DoNewResolve</code> might resolve.&nbsp; Providing names that <code>DoNewResolve</code> won't actually resolve is OK.</p>
<h3 id="HeaderFile" name="HeaderFile"><code>[HeaderFile="path/to/headerfile.h"]</code></h3>
<p>Indicates where the implementation can be found. Similar to the headerFile annotation in Bindings.conf.</p>
<h3 id="JSImplementation" name="JSImplementation"><code>[JSImplementation="@mozilla.org/some-contractid;1"]</code></h3>
<p>Used on an interface to provide the contractid of the <a href="#Implementing_WebIDL_using_Javascript" title="#Implementing_WebIDL_using_Javascript">JavaScript component implementing the interface</a>.</p>
<h3 id="NavigatorProperty" name="NavigatorProperty"><code>[NavigatorProperty="propName"]</code></h3>
<p>Setting this extended attribute to <code>propName</code> on an interface causes <code>window.navigator.propName</code> to be an instance of the interface.</p>
<h2 class="note" id="Helper_objects">Helper objects</h2>
<p>The C++ side of the bindings uses a number of helper objects.</p>
<h3 id="Nullable" name="Nullable"><code>Nullable&lt;T&gt;</code></h3>
<p><code>Nullable&lt;&gt;</code> is a struct declared in <a class="external" href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/Nullable.h" title="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/Nullable.h"><code>Nullable.h</code></a> and exported to <code>mozilla/dom/Nullable.h</code> that is used to represent nullable values of types that don't have a natural way to represent null.</p>
<p><code>Nullable&lt;T&gt;</code> has an <code>IsNull()</code> getter that returns whether null is represented and a <code>Value()</code> getter that returns a <code>const T&amp;</code> and can be used to get the value when it's not null.</p>
<p><code>Nullable&lt;T&gt;</code> has a <code>SetNull()</code> setter that sets it as representing null and two setters that can be used to set it to a value: <code>"void SetValue(T)"</code> (for setting it to a given value) and <code>"T&amp; SetValue()"</code> for directly modifying the underlying <code>T&amp;</code>.</p>
<h3 id="Optional" name="Optional"><code>Optional&lt;T&gt;</code></h3>
<p><code>Optional&lt;&gt;</code> is a struct declared in <a class="external" href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/BindingDeclarations.h" title="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/BindingUtils.h"><code>BindingDeclarations.h</code></a> and exported to <code>mozilla/dom/BindingDeclarations.h</code> that is used to represent optional arguments and dictionary members, but only those that have no default value.</p>
<p><code>Optional&lt;T&gt;</code> has a <code>WasPassed()</code> getter that returns true if a value is available.&nbsp; In that case, the <code>Value()</code> getter can be used to get a <code>const T&amp;</code> for the value.</p>
<h3 id="NonNull" name="NonNull"><code>NonNull&lt;T&gt;</code></h3>
<p><code>NonNull&lt;T&gt;</code> is a struct declared in <a class="external" href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/BindingUtils.h" title="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/BindingUtils.h"><code>BindingUtils.h</code></a> and exported to <code>mozilla/dom/BindingUtils.h</code> that is used to represent non-null C++ objects.&nbsp; It has a conversion operator that produces <code>T&amp;</code>.</p>
<h3 id="OwningNonNull" name="OwningNonNull"><code>OwningNonNull&lt;T&gt;</code></h3>
<p><code>OwningNonNull&lt;T&gt;</code> is a struct declared in <a class="external" href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/BindingUtils.h" title="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/BindingUtils.h"><code>BindingUtils.h</code></a> and exported to <code>mozilla/dom/BindingUtils.h</code> that is used to represent non-null C++ objects and holds a strong reference to them.&nbsp; It has a conversion operator that produces <code>T&amp;</code>.</p>
<h3 id="TypedArrays" name="TypedArrays">Typed arrays, arraybuffers, array buffer views</h3>
<p><code><a class="external" href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/TypedArray.h" title="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/TypedArray.h">TypedArray.h</a></code> is exported to <code>mozilla/dom/TypedArray.h</code> and exposes structs that correspond to the various typed array types, as well as <code>ArrayBuffer</code> and <code>ArrayBufferView</code>, all in the <code>mozilla::dom</code> namespace.&nbsp; Each struct has an <code>Data()</code> method that returns a pointer to the relevant type (<code>uint8_t</code> for <code>ArrayBuffer</code> and <code>ArrayBufferView</code>) and a <code>Length()</code> method that returns the length in units of <code>*Data()</code>.&nbsp; So for example, <code>Int32Array</code> has a <code>Data()</code> returning i<code>nt32_t</code><code>*</code> and a <code>Length()</code> that returns the number of 32-bit ints in the array..</p>
<h3 id="Sequence" name="Sequence"><code>Sequence&lt;T&gt;</code></h3>
<p><code>Sequence&lt;&gt;</code> is a type declared in <a class="external" href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/BindingDeclarations.h" title="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/BindingUtils.h"><code>BindingDeclarations.h</code></a> and exported to <code>mozilla/dom/BindingDeclarations.h</code> that is used to represent sequence arguments.&nbsp; It's some kind of typed array, but which exact kind is opaque to consumers.&nbsp; This allows the binding code to change the exact definition (e.g. to use auto arrays of different sizes and so forth) without having to update all the callees.</p>
<h3 id="CallbackFunction" name="CallbackFunction"><code>CallbackFunction</code></h3>
<p><code>CallbackFunction</code> is a type declared in <a href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/CallbackFunction.h">CallbackFunction.h</a> and exported to <code>mozilla/dom/CallbackFunction.h</code> that is used as a common base class for all the generated callback function representations.&nbsp; This class inherits from <code>nsISupports</code>, and consumers must make sure to cycle-collect it, since it keeps JS objects alive.</p>
<h3 id="CallbackInterface" name="CallbackInterface"><code>CallbackInterface</code></h3>
<p><code>CallbackInterface</code> is a type declared in <a href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/CallbackInterface.h">CallbackInterface.h</a> and exported to <code>mozilla/dom/CallbackInterface.h</code> that is used as a common base class for all the generated callback interface representations.&nbsp; This class inherits from <code>nsISupports</code>, and consumers must make sure to cycle-collect it, since it keeps JS objects alive.</p>
<h3 id="DOMString-helper" name="DOMString-helper"><code>DOMString</code></h3>
<p><code>DOMString</code> is a class declared in <a href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/BindingDeclarations.h">BindingDeclarations.h</a> and exported to <code>mozilla/dom/BindingDeclarations.h</code> that is used for WebIDL <code>DOMString</code> return values.&nbsp; It has a conversion operator to <code>nsString&amp;</code> so that it can be passed to methods that take that type or <code>nsAString&amp;</code>, but callees that care about performance, have an <code>nsStringBuffer</code> available, and promise to hold on to the <code>nsStringBuffer</code> at least until the binding code comes off the stack can also take a <code>DOMString</code> directly for their string return value and call its <code>SetStringBuffer</code> method with the <code>nsStringBuffer</code> and its length.&nbsp; This allows the binding code to avoid extra reference-counting of the string buffer in many cases, and allows it to take a faster codepath even if it does end up having to addref the <code>nsStringBuffer</code>.</p>
<h3 id="GlobalObject" name="GlobalObject"><code>GlobalObject</code></h3>
<p><code>GlobalObject</code> is a class declared in <a href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/BindingDeclarations.h">BindingDeclarations.h</a> and exported to <code>mozilla/dom/BindingDeclarations.h</code> that is used to represent the global object for static attributes and operations (including constructors) in non-worker bindings.&nbsp; It has a <code>Get()</code> method that returns an <code>nsISupports*</code> for the global, if such is available.</p>
<h3 id="WorkerGlobalObject" name="WorkerGlobalObject"><code>WorkerGlobalObject</code></h3>
<p><code>WorkerGlobalObject</code> is a class declared in <a href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/BindingDeclarations.h">BindingDeclarations.h</a> and exported to <code>mozilla/dom/BindingDeclarations.h</code> that is used to represent the global object for static attributes and operations (including constructors) in worker bindings.&nbsp; It has a <code>Get()</code> method that returns the <code>JSObject*</code>&nbsp; for the global and a <code>GetContext()</code> method that returns the <code>JSContext*</code> the call is happening on.&nbsp; A caveat: the compartment of the <code>JSContext</code> may not match the compartment of the global!</p>
<h3 id="Date-struct" name="Date-struct"><code>Date</code></h3>
<p><code>Date</code> is a class declared in <a href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/BindingDeclarations.h">BindingDeclarations.h</a> and exported to <code>mozilla/dom/BindingDeclarations.h</code> that is used to represent WebIDL Dates.&nbsp; It has a <code>TimeStamp()</code> method returning a double which represents a number of milliseconds since the epoch, as well as <code>SetTimeStamp()</code> methods that can be used to initialize it with a double timestamp or a JS <code>Date</code> object.&nbsp; It also has a <code>ToDateObject()</code> method that can be used to create a new JS <code>Date</code>.</p>
<h3 id="ErrorResult" name="ErrorResult"><code>ErrorResult</code></h3>
<p><code>ErrorResult</code> is a class declared in <a href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/ErrorResult.h">ErrorResult.h</a> and exported to <code>mozilla/ErrorResult.h</code> that is used to represent exceptions in WebIDL bindings.&nbsp; This has the following methods:</p>
<ul>
  <li><code>Throw</code>: allows throwing an <code>nsresult</code>.&nbsp; The <code>nsresult</code> must be a failure code.</li>
  <li><code>ThrowTypeError</code>: allows throwing a <code>TypeError</code> with the given error message.&nbsp; The list of allowed <code>TypeError</code>s and corresponding messages is in <a href="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/Errors.msg" title="http://mxr.mozilla.org/mozilla-central/source/dom/bindings/Errors.msg"><code>dom/bindings/Errors.msg</code></a>.</li>
  <li><code>ThrowJSException</code>: allows throwing a preexisting JS exception value. However, the <code>MightThrowJSException()</code> method must be called before any such exceptions are thrown (even if no exception is thrown).</li>
  <li><code>Failed</code>: checks whether an exception has been thrown on this <code>ErrorResult</code>.</li>
  <li><code>ErrorCode</code>: returns a failure <code>nsresult</code> representing (perhaps incompletely) the state of this <code>ErrorResult</code>.</li>
  <li><code>operator=</code>: takes an <code>nsresult</code> and acts like <code>Throw</code> if the result is an error code, and like a no-op otherwise (unless an exception has already been thrown, in which case it asserts).&nbsp; This should only be used for legacy code that has nsresult everywhere; we would like to get rid of this operator at some point.</li>
</ul>
<h2 id="Bindings.conf" name="Bindings.conf"><code>Bindings.conf</code> details</h2>
<p>XXXbz write me.&nbsp; In particular, need to describe at least use of <code>concrete</code>, <code>prefable</code>, and <code>addExternalInterface</code></p>
<h3 id="How_to_get_a_JSContext_passed_to_a_given_method">How to get a JSContext passed to a given method</h3>
<p>In some rare cases you may need a <code>JSContext*</code> argument to be passed to a C++ method that wouldn't otherwise get such an argument. To see how to achieve this, search for <code>implicitJSContext</code> in <a href="https://developer.mozilla.org/en-US/docs/Mozilla/WebIDL_bindings#Bindings.conf" title="https://developer.mozilla.org/en-US/docs/Mozilla/WebIDL_bindings#Bindings.conf">dom/bindings/Bindings.conf</a>.</p>
<h2 id="Implementing_WebIDL_using_Javascript">Implementing WebIDL using Javascript</h2>
<p>There is support for implementing WebIDL interfaces in JavaScript.&nbsp; When this is done, there are actually two objects created: the implementation object (running as a chrome-privileged script) and the content-exposed object (which is what the web page sees).&nbsp; This allows the implementation object to have various APIs that the content-exposed object does not.</p>
<p>To implement a WebIDL interface in JavaScript, first add a WebIDL file, in the same way as you would for a C++-implemented interface.&nbsp; To support implementation in JS, you must add an extended attribute <code>JSImplementation="CONTRACT_ID_STRING"</code> on your interface, where CONTRACT_ID_STRING is the XPCOM component contract ID of the JS implementation.&nbsp; Here's an example:</p>
<pre>
[Constructor(optional long firstNumber), JSImplementation="@mozilla.org/my-number;1"]
interface MyNumber {
  attribute long value;
  readonly attribute long otherValue;
  void doNothing();
};</pre>
<p>Next, create an XPCOM component that implements this interface.&nbsp; <a href="/en-US/docs/How_to_Build_an_XPCOM_Component_in_Javascript" title="/en-US/docs/How_to_Build_an_XPCOM_Component_in_Javascript">Basic directions</a> for how to do this can be found elsewhere on MDN.&nbsp; Use the same contract ID as you specified in the WebIDL file.&nbsp; The class ID doesn't matter, except that it should be a newly generated one.&nbsp; For <code>QueryInterface</code>, you only need to implement <code>nsISupports</code>, not anything corresponding to the WebIDL interface.&nbsp; The name you use for the XPCOM component should be distinct from the name of the interface, to avoid confusing error messages.</p>
<p>WebIDL attributes are implemented as properties on the JS object or its prototype chain, whereas WebIDL methods are implemented as methods on the object or prototype.&nbsp; Note that any other instances of the interface that you are passed in as arguments are the full web-facing version of the object, and not the JS implementation, so you currently cannot access any private data.</p>
<p>The WebIDL constructor invocation will first create your object.&nbsp; If the XPCOM component implements <code>nsIDOMGlobalPropertyInitializer</code><span id="summary_alias_container"><span id="short_desc_nonedit_display">, then the object's </span></span><code>init</code><span id="summary_alias_container"><span id="short_desc_nonedit_display"> method will be invoked with a single argument: the content window the constructor came from.&nbsp; This allows the JS implementation to know which content window it's associated with.&nbsp; The </span></span><code>init</code><span id="summary_alias_container"><span id="short_desc_nonedit_display"> method should not return anything.&nbsp; Then, </span></span>if there are any constructor arguments, the object's <code>__init</code> method will be invoked, with the constructor arguments as its arguments.</p>
<p>If you want an instance of the class to be added to <code>window.navigator</code>, add an extended attribute<span class="difflineplus"> </span><code>NavigatorProperty="PropertyName"</code> which will make the instance available as <code>window.navigator.PropertyName</code>.</p>
<p>Here's an example JS implementation of the above interface. The <code>invisibleValue</code> field will not be accessible to web content, but is usable by the doNothing() method.</p>
<pre>
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

function MyNumberInner() {
  this.value = 111;
  this.invisibleValue = 12345;
}

MyNumberInner.prototype = {
  classDescription: "Get my number XPCOM Component",
  classID: Components.ID("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"), // dummy UUID
  contractID: "@mozilla.org/my-number;1",
  QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsISupports]),
  doNothing: function() {},
  get otherValue() { return this.invisibleValue - 4; },
  __init: function(firstNumber) {
    if (arguments.length &gt; 0) {
      this.value = firstNumber;
    }
  }
}

var components = [MyNumberInner];
var NSGetFactory = XPCOMUtils.generateNSGetFactory(components);</pre>
<p>Finally, add a component and a contract and whatever other manifest stuff you need to implement an XPCOM component.</p>
<h3 id="Guarantees_provided_by_bindings">Guarantees provided by bindings</h3>
<p>When implementing a WebIDL interface in JavaScript, certain guarantees will be provided by the binding implementation.&nbsp; For example, string or numeric arguments will actually be primitive strings or numbers.&nbsp; Dictionaries will contain only the properties that they are declared to have, and they will have the right types.&nbsp; Interface arguments will actually be objects implementing that interface.</p>
<p>What the bindings will NOT guarantee is much of anything about <code>object</code> and <code>any</code> arguments.&nbsp; They will get cross-compartment wrappers that make touching them from chrome code not be an immediate security bug, but otherwise they can have quite surprising behavior if the page is trying to be malicious.&nbsp; Try to avoid using these types if possible.</p>
<h3 id="Accessing_the_content_object_from_the_implementation">Accessing the content object from the implementation</h3>
<p>If the JS implementation of the WebIDL interface needs to access the content object, it is available as a property called <code>__DOM_IMPL__</code> on the chrome implementation object.</p>
<h3 id="Inheriting_from_interfaces_implemented_in_C.2B.2B">Inheriting from interfaces implemented in C++</h3>
<p>It's possible to have an interface implemented in JavaScript inherit from an interface implemented in C++.&nbsp; To do so, simply have one interface inherit from the other and the bindings code will auto-generate a C++ object inheriting from the implementation of the parent interface.&nbsp; The class implementing the parent interface will need a constructor that takes an <code>nsPIDOMWindow*</code> (though it doesn't have to do anything with that argument).</p>
<p>If the class implementing the parent interface is abstract and you want to use a specific concrete class as the implementation to inherit from, you will need to add a <code>defaultImpl</code> annotation to the descriptor for the parent interface in <code>Bindings.conf</code>.&nbsp; The value of the annotation is the C++ class to use as the parent for JS-implemented descendants; if <code>defaultImpl</code> is not specified, the <code>nativeType</code> will be used.</p>
<p>For example, consider this interface that we wish to implement in JavaScript:</p>
<pre>
[JSImplemented="some-contract"]
interface MyEventTarget : EventTarget {
  attribute EventHandler onmyevent;
  void dispatchTheEvent(); // Sends a "myevent" event to this EventTarget
}
</pre>
<p>The implementation would look something like this, ignoring the XPCOM boilerplate:</p>
<pre>
function MyEventTargetImpl() {
}
MyEventTargetImpl.prototype = {
  init: function(contentWindow) {  // XXXbz need to document how to get this called on you!
    this.contentWindow = contentWindow;
  }

  get onmyevent() {
    return this.__DOM_IMPL__.getEventHandler("onmyevent");
  }

  set onmyevent(handler) {
    this.__DOM_IMPL__.setEventHandler("onmyevent", handler);
  }

  dispatchTheEvent: function() {
    var event = new this.contentWindow.Event("myevent");
    this.__DOM_IMPL__.dispatchEvent(event);
  }
};
</pre>
<p>The implementation would automatically support the API exposed on <code>EventTarget</code> (so for example <code>addEventListener</code>).&nbsp; Calling the <code>dispatchTheEvent</code> method would cause dispatch of an event that content script can see via listeners it has added.</p>
<p>Note that in this case the chrome implementation is relying on some <code>[ChromeOnly]</code> methods on EventTarget that were added specifically to make it possible to easily implement event handlers.&nbsp; Other cases can do similar things as needed.</p>
Revert to this revision