PageRenderTime 79ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/dom/bindings/Codegen.py

https://bitbucket.org/bgirard/tiling
Python | 3057 lines | 2926 code | 50 blank | 81 comment | 60 complexity | 9eac3658c943bf5d8497682d9eb5c60a MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, BSD-2-Clause, LGPL-3.0, AGPL-1.0, MPL-2.0-no-copyleft-exception, GPL-2.0, JSON, Apache-2.0, 0BSD, MIT
  1. # This Source Code Form is subject to the terms of the Mozilla Public
  2. # License, v. 2.0. If a copy of the MPL was not distributed with this file,
  3. # You can obtain one at http://mozilla.org/MPL/2.0/.
  4. # Common codegen classes.
  5. import os
  6. import string
  7. from WebIDL import *
  8. AUTOGENERATED_WARNING_COMMENT = \
  9. "/* THIS FILE IS AUTOGENERATED - DO NOT EDIT */\n\n"
  10. ADDPROPERTY_HOOK_NAME = '_AddProperty'
  11. FINALIZE_HOOK_NAME = '_Finalize'
  12. TRACE_HOOK_NAME = '_Trace'
  13. CONSTRUCT_HOOK_NAME = '_Construct'
  14. HASINSTANCE_HOOK_NAME = '_HasInstance'
  15. def replaceFileIfChanged(filename, newContents):
  16. """
  17. Read a copy of the old file, so that we don't touch it if it hasn't changed.
  18. Returns True if the file was updated, false otherwise.
  19. """
  20. oldFileContents = ""
  21. try:
  22. oldFile = open(filename, 'rb')
  23. oldFileContents = ''.join(oldFile.readlines())
  24. oldFile.close()
  25. except:
  26. pass
  27. if newContents == oldFileContents:
  28. return False
  29. f = open(filename, 'wb')
  30. f.write(newContents)
  31. f.close()
  32. def toStringBool(arg):
  33. return str(not not arg).lower()
  34. def toBindingNamespace(arg):
  35. return re.sub("((_workers)?$)", "Binding\\1", arg);
  36. class CGThing():
  37. """
  38. Abstract base class for things that spit out code.
  39. """
  40. def __init__(self):
  41. pass # Nothing for now
  42. def declare(self):
  43. """Produce code for a header file."""
  44. assert(False) # Override me!
  45. def define(self):
  46. """Produce code for a cpp file."""
  47. assert(False) # Override me!
  48. class CGNativePropertyHooks(CGThing):
  49. """
  50. Generate a NativePropertyHooks for a given descriptor
  51. """
  52. def __init__(self, descriptor):
  53. CGThing.__init__(self)
  54. self.descriptor = descriptor
  55. def declare(self):
  56. return " extern const NativePropertyHooks NativeHooks;\n"
  57. def define(self):
  58. parent = self.descriptor.interface.parent
  59. parentHooks = ("&" + toBindingNamespace(parent.identifier.name) + "::NativeHooks"
  60. if parent else 'NULL')
  61. return """
  62. const NativePropertyHooks NativeHooks = { ResolveProperty, EnumerateProperties, %s };
  63. """ % parentHooks
  64. class CGDOMJSClass(CGThing):
  65. """
  66. Generate a DOMJSClass for a given descriptor
  67. """
  68. def __init__(self, descriptor):
  69. CGThing.__init__(self)
  70. self.descriptor = descriptor
  71. def declare(self):
  72. return " extern DOMJSClass Class;\n"
  73. def define(self):
  74. traceHook = TRACE_HOOK_NAME if self.descriptor.customTrace else 'NULL'
  75. protoList = ['prototypes::id::' + proto for proto in self.descriptor.prototypeChain]
  76. # Pad out the list to the right length with _ID_Count so we
  77. # guarantee that all the lists are the same length. _ID_Count
  78. # is never the ID of any prototype, so it's safe to use as
  79. # padding.
  80. while len(protoList) < self.descriptor.config.maxProtoChainLength:
  81. protoList.append('prototypes::id::_ID_Count')
  82. prototypeChainString = ', '.join(protoList)
  83. return """
  84. DOMJSClass Class = {
  85. { "%s",
  86. JSCLASS_IS_DOMJSCLASS | JSCLASS_HAS_RESERVED_SLOTS(1),
  87. %s, /* addProperty */
  88. JS_PropertyStub, /* delProperty */
  89. JS_PropertyStub, /* getProperty */
  90. JS_StrictPropertyStub, /* setProperty */
  91. JS_EnumerateStub,
  92. JS_ResolveStub,
  93. JS_ConvertStub,
  94. %s, /* finalize */
  95. NULL, /* checkAccess */
  96. NULL, /* call */
  97. NULL, /* construct */
  98. NULL, /* hasInstance */
  99. %s, /* trace */
  100. JSCLASS_NO_INTERNAL_MEMBERS
  101. },
  102. { %s },
  103. -1, %s, DOM_OBJECT_SLOT,
  104. &NativeHooks
  105. };
  106. """ % (self.descriptor.interface.identifier.name,
  107. ADDPROPERTY_HOOK_NAME if self.descriptor.concrete and not self.descriptor.workers else 'JS_PropertyStub',
  108. FINALIZE_HOOK_NAME, traceHook, prototypeChainString,
  109. str(self.descriptor.nativeIsISupports).lower())
  110. class CGPrototypeJSClass(CGThing):
  111. def __init__(self, descriptor):
  112. CGThing.__init__(self)
  113. self.descriptor = descriptor
  114. def declare(self):
  115. # We're purely for internal consumption
  116. return ""
  117. def define(self):
  118. return """
  119. static JSClass PrototypeClass = {
  120. "%s Prototype", 0,
  121. JS_PropertyStub, /* addProperty */
  122. JS_PropertyStub, /* delProperty */
  123. JS_PropertyStub, /* getProperty */
  124. JS_StrictPropertyStub, /* setProperty */
  125. JS_EnumerateStub,
  126. JS_ResolveStub,
  127. JS_ConvertStub,
  128. NULL, /* finalize */
  129. NULL, /* checkAccess */
  130. NULL, /* call */
  131. NULL, /* construct */
  132. NULL, /* hasInstance */
  133. NULL, /* trace */
  134. JSCLASS_NO_INTERNAL_MEMBERS
  135. };
  136. """ % (self.descriptor.interface.identifier.name)
  137. class CGInterfaceObjectJSClass(CGThing):
  138. def __init__(self, descriptor):
  139. CGThing.__init__(self)
  140. self.descriptor = descriptor
  141. def declare(self):
  142. # We're purely for internal consumption
  143. return ""
  144. def define(self):
  145. if not self.descriptor.hasInstanceInterface:
  146. return ""
  147. ctorname = "NULL" if not self.descriptor.interface.ctor() else CONSTRUCT_HOOK_NAME
  148. hasinstance = HASINSTANCE_HOOK_NAME
  149. return """
  150. static JSClass InterfaceObjectClass = {
  151. "Function", 0,
  152. JS_PropertyStub, /* addProperty */
  153. JS_PropertyStub, /* delProperty */
  154. JS_PropertyStub, /* getProperty */
  155. JS_StrictPropertyStub, /* setProperty */
  156. JS_EnumerateStub,
  157. JS_ResolveStub,
  158. JS_ConvertStub,
  159. NULL, /* finalize */
  160. NULL, /* checkAccess */
  161. %s, /* call */
  162. %s, /* construct */
  163. %s, /* hasInstance */
  164. NULL, /* trace */
  165. JSCLASS_NO_INTERNAL_MEMBERS
  166. };
  167. """ % (ctorname, ctorname, hasinstance)
  168. class CGList(CGThing):
  169. """
  170. Generate code for a list of GCThings. Just concatenates them together, with
  171. an optional joiner string. "\n" is a common joiner.
  172. """
  173. def __init__(self, children, joiner=""):
  174. CGThing.__init__(self)
  175. self.children = children
  176. self.joiner = joiner
  177. def append(self, child):
  178. self.children.append(child)
  179. def prepend(self, child):
  180. self.children.insert(0, child)
  181. def declare(self):
  182. return self.joiner.join([child.declare() for child in self.children
  183. if child is not None])
  184. def define(self):
  185. return self.joiner.join([child.define() for child in self.children
  186. if child is not None])
  187. class CGGeneric(CGThing):
  188. """
  189. A class that spits out a fixed string into the codegen. Can spit out a
  190. separate string for the declaration too.
  191. """
  192. def __init__(self, define="", declare=""):
  193. self.declareText = declare
  194. self.defineText = define
  195. def declare(self):
  196. return self.declareText
  197. def define(self):
  198. return self.defineText
  199. # We'll want to insert the indent at the beginnings of lines, but we
  200. # don't want to indent empty lines. So only indent lines that have a
  201. # non-newline character on them.
  202. lineStartDetector = re.compile("^(?=[^\n#])", re.MULTILINE)
  203. class CGIndenter(CGThing):
  204. """
  205. A class that takes another CGThing and generates code that indents that
  206. CGThing by some number of spaces. The default indent is two spaces.
  207. """
  208. def __init__(self, child, indentLevel=2):
  209. CGThing.__init__(self)
  210. self.child = child
  211. self.indent = " " * indentLevel
  212. def declare(self):
  213. decl = self.child.declare()
  214. if decl is not "":
  215. return re.sub(lineStartDetector, self.indent, decl)
  216. else:
  217. return ""
  218. def define(self):
  219. defn = self.child.define()
  220. if defn is not "":
  221. return re.sub(lineStartDetector, self.indent, defn)
  222. else:
  223. return ""
  224. class CGWrapper(CGThing):
  225. """
  226. Generic CGThing that wraps other CGThings with pre and post text.
  227. """
  228. def __init__(self, child, pre="", post="", declarePre=None,
  229. declarePost=None, definePre=None, definePost=None,
  230. declareOnly=False, defineOnly=False, reindent=False):
  231. CGThing.__init__(self)
  232. self.child = child
  233. self.declarePre = declarePre or pre
  234. self.declarePost = declarePost or post
  235. self.definePre = definePre or pre
  236. self.definePost = definePost or post
  237. self.declareOnly = declareOnly
  238. self.defineOnly = defineOnly
  239. self.reindent = reindent
  240. def declare(self):
  241. if self.defineOnly:
  242. return ''
  243. decl = self.child.declare()
  244. if self.reindent:
  245. # We don't use lineStartDetector because we don't want to
  246. # insert whitespace at the beginning of our _first_ line.
  247. decl = stripTrailingWhitespace(
  248. decl.replace("\n", "\n" + (" " * len(self.declarePre))))
  249. return self.declarePre + decl + self.declarePost
  250. def define(self):
  251. if self.declareOnly:
  252. return ''
  253. defn = self.child.define()
  254. if self.reindent:
  255. # We don't use lineStartDetector because we don't want to
  256. # insert whitespace at the beginning of our _first_ line.
  257. defn = stripTrailingWhitespace(
  258. defn.replace("\n", "\n" + (" " * len(self.definePre))))
  259. return self.definePre + defn + self.definePost
  260. class CGNamespace(CGWrapper):
  261. def __init__(self, namespace, child, declareOnly=False):
  262. pre = "namespace %s {\n" % namespace
  263. post = "} // namespace %s\n" % namespace
  264. CGWrapper.__init__(self, child, pre=pre, post=post,
  265. declareOnly=declareOnly)
  266. @staticmethod
  267. def build(namespaces, child, declareOnly=False):
  268. """
  269. Static helper method to build multiple wrapped namespaces.
  270. """
  271. if not namespaces:
  272. return child
  273. return CGNamespace(namespaces[0], CGNamespace.build(namespaces[1:],
  274. child),
  275. declareOnly=declareOnly)
  276. class CGIncludeGuard(CGWrapper):
  277. """
  278. Generates include guards for a header.
  279. """
  280. def __init__(self, prefix, child):
  281. """|prefix| is the filename without the extension."""
  282. define = 'mozilla_dom_%s_h__' % prefix
  283. CGWrapper.__init__(self, child,
  284. declarePre='#ifndef %s\n#define %s\n\n' % (define, define),
  285. declarePost='\n#endif // %s\n' % define)
  286. class CGHeaders(CGWrapper):
  287. """
  288. Generates the appropriate include statements.
  289. """
  290. def __init__(self, descriptors, declareIncludes, defineIncludes, child):
  291. """
  292. Builds a set of includes to cover |descriptors|.
  293. Also includes the files in |declareIncludes| in the header
  294. file and the files in |defineIncludes| in the .cpp.
  295. """
  296. # Determine the filenames for which we need headers.
  297. interfaceDeps = [d.interface for d in descriptors]
  298. ancestors = []
  299. for iface in interfaceDeps:
  300. while iface.parent:
  301. ancestors.append(iface.parent)
  302. iface = iface.parent
  303. interfaceDeps.extend(ancestors)
  304. bindingIncludes = set(self.getInterfaceFilename(d) for d in interfaceDeps)
  305. # Grab all the implementation declaration files we need.
  306. implementationIncludes = set(d.headerFile for d in descriptors)
  307. # Now find all the things we'll need as arguments because we
  308. # need to wrap or unwrap them.
  309. bindingHeaders = set()
  310. for d in descriptors:
  311. members = [m for m in d.interface.members]
  312. signatures = [s for m in members if m.isMethod() for s in m.signatures()]
  313. types = []
  314. for s in signatures:
  315. assert len(s) == 2
  316. (returnType, arguments) = s
  317. types.append(returnType)
  318. types.extend([a.type for a in arguments])
  319. attrs = [a for a in members if a.isAttr()]
  320. types.extend([a.type for a in attrs])
  321. for t in types:
  322. if t.unroll().isInterface():
  323. if t.unroll().isArrayBuffer():
  324. bindingHeaders.add("jsfriendapi.h")
  325. else:
  326. typeDesc = d.getDescriptor(t.unroll().inner.identifier.name)
  327. if typeDesc is not None:
  328. implementationIncludes.add(typeDesc.headerFile)
  329. bindingHeaders.add(self.getInterfaceFilename(typeDesc.interface))
  330. # Let the machinery do its thing.
  331. def _includeString(includes):
  332. return ''.join(['#include "%s"\n' % i for i in includes]) + '\n'
  333. CGWrapper.__init__(self, child,
  334. declarePre=_includeString(declareIncludes),
  335. definePre=_includeString(sorted(set(defineIncludes) |
  336. bindingIncludes |
  337. bindingHeaders |
  338. implementationIncludes)))
  339. @staticmethod
  340. def getInterfaceFilename(interface):
  341. basename = os.path.basename(interface.filename())
  342. return 'mozilla/dom/' + \
  343. basename.replace('.webidl', 'Binding.h')
  344. class Argument():
  345. """
  346. A class for outputting the type and name of an argument
  347. """
  348. def __init__(self, argType, name):
  349. self.argType = argType
  350. self.name = name
  351. def __str__(self):
  352. return self.argType + ' ' + self.name
  353. class CGAbstractMethod(CGThing):
  354. """
  355. An abstract class for generating code for a method. Subclasses
  356. should override definition_body to create the actual code.
  357. descriptor is the descriptor for the interface the method is associated with
  358. name is the name of the method as a string
  359. returnType is the IDLType of the return value
  360. args is a list of Argument objects
  361. inline should be True to generate an inline method, whose body is
  362. part of the declaration.
  363. static should be True to generate a static method, which only has
  364. a definition.
  365. """
  366. def __init__(self, descriptor, name, returnType, args, inline=False, static=False):
  367. CGThing.__init__(self)
  368. self.descriptor = descriptor
  369. self.name = name
  370. self.returnType = returnType
  371. self.args = args
  372. self.inline = inline
  373. self.static = static
  374. def _argstring(self):
  375. return ', '.join([str(a) for a in self.args])
  376. def _decorators(self):
  377. decorators = []
  378. if self.inline:
  379. decorators.append('inline')
  380. if self.static:
  381. decorators.append('static')
  382. decorators.append(self.returnType)
  383. return ' '.join(decorators)
  384. def declare(self):
  385. if self.inline:
  386. return self._define()
  387. return "\n %s %s(%s);\n" % (self._decorators(), self.name, self._argstring())
  388. def _define(self):
  389. return self.definition_prologue() + "\n" + self.definition_body() + self.definition_epilogue()
  390. def define(self):
  391. return "" if self.inline else self._define()
  392. def definition_prologue(self):
  393. maybeNewline = " " if self.inline else "\n"
  394. return "\n%s%s%s(%s)\n{" % (self._decorators(), maybeNewline,
  395. self.name, self._argstring())
  396. def definition_epilogue(self):
  397. return "\n}\n"
  398. def definition_body(self):
  399. assert(False) # Override me!
  400. class CGAbstractStaticMethod(CGAbstractMethod):
  401. """
  402. Abstract base class for codegen of implementation-only (no
  403. declaration) static methods.
  404. """
  405. def __init__(self, descriptor, name, returnType, args):
  406. CGAbstractMethod.__init__(self, descriptor, name, returnType, args,
  407. inline=False, static=True)
  408. def declare(self):
  409. # We only have implementation
  410. return ""
  411. class CGAbstractClassHook(CGAbstractStaticMethod):
  412. """
  413. Meant for implementing JSClass hooks, like Finalize or Trace. Does very raw
  414. 'this' unwrapping as it assumes that the unwrapped type is always known.
  415. """
  416. def __init__(self, descriptor, name, returnType, args):
  417. CGAbstractStaticMethod.__init__(self, descriptor, name, returnType,
  418. args)
  419. def definition_body_prologue(self):
  420. return """
  421. MOZ_ASSERT(js::GetObjectJSClass(obj) == Class.ToJSClass());
  422. %s* self = UnwrapDOMObject<%s>(obj, Class.ToJSClass());
  423. """ % (self.descriptor.nativeType, self.descriptor.nativeType)
  424. def definition_body(self):
  425. return self.definition_body_prologue() + self.generate_code()
  426. def generate_code(self):
  427. # Override me
  428. assert(False)
  429. class CGAddPropertyHook(CGAbstractClassHook):
  430. """
  431. A hook for addProperty, used to preserve our wrapper from GC.
  432. """
  433. def __init__(self, descriptor):
  434. args = [Argument('JSContext*', 'cx'), Argument('JSObject*', 'obj'),
  435. Argument('jsid', 'id'), Argument('jsval*', 'vp')]
  436. CGAbstractClassHook.__init__(self, descriptor, ADDPROPERTY_HOOK_NAME,
  437. 'JSBool', args)
  438. def generate_code(self):
  439. return """
  440. JSCompartment* compartment = js::GetObjectCompartment(obj);
  441. xpc::CompartmentPrivate* priv =
  442. static_cast<xpc::CompartmentPrivate*>(JS_GetCompartmentPrivate(compartment));
  443. if (!priv->RegisterDOMExpandoObject(obj)) {
  444. return false;
  445. }
  446. self->SetPreservingWrapper(true);
  447. return true;"""
  448. class CGClassFinalizeHook(CGAbstractClassHook):
  449. """
  450. A hook for finalize, used to release our native object.
  451. """
  452. def __init__(self, descriptor):
  453. args = [Argument('JSFreeOp*', 'fop'), Argument('JSObject*', 'obj')]
  454. CGAbstractClassHook.__init__(self, descriptor, FINALIZE_HOOK_NAME,
  455. 'void', args)
  456. def generate_code(self):
  457. if self.descriptor.customFinalize:
  458. return """ if (self) {
  459. self->%s(%s);
  460. }""" % (self.name, self.args[0].name)
  461. if self.descriptor.workers:
  462. release = "self->Release();"
  463. else:
  464. assert self.descriptor.nativeIsISupports
  465. release = """
  466. XPCJSRuntime *rt = nsXPConnect::GetRuntimeInstance();
  467. if (rt) {
  468. rt->DeferredRelease(NativeToSupports(self));
  469. } else {
  470. NS_RELEASE(self);
  471. }"""
  472. return """
  473. self->ClearWrapper();
  474. %s""" % (release)
  475. class CGClassTraceHook(CGAbstractClassHook):
  476. """
  477. A hook to trace through our native object; used for GC and CC
  478. """
  479. def __init__(self, descriptor):
  480. args = [Argument('JSTracer*', 'trc'), Argument('JSObject*', 'obj')]
  481. CGAbstractClassHook.__init__(self, descriptor, TRACE_HOOK_NAME, 'void',
  482. args)
  483. def generate_code(self):
  484. return """ if (self) {
  485. self->%s(%s);
  486. }""" % (self.name, self.args[0].name)
  487. class CGClassConstructHook(CGAbstractStaticMethod):
  488. """
  489. JS-visible constructor for our objects
  490. """
  491. def __init__(self, descriptor):
  492. args = [Argument('JSContext*', 'cx'), Argument('unsigned', 'argc'), Argument('JS::Value*', 'vp')]
  493. CGAbstractStaticMethod.__init__(self, descriptor, CONSTRUCT_HOOK_NAME,
  494. 'JSBool', args)
  495. self._ctor = self.descriptor.interface.ctor()
  496. def define(self):
  497. if not self._ctor:
  498. return ""
  499. return CGAbstractStaticMethod.define(self)
  500. def definition_body(self):
  501. return self.generate_code()
  502. def generate_code(self):
  503. preamble = """
  504. JSObject* obj = JS_GetGlobalForObject(cx, JSVAL_TO_OBJECT(JS_CALLEE(cx, vp)));
  505. """
  506. preArgs = ""
  507. if self.descriptor.workers:
  508. preArgs = "cx, obj, "
  509. else:
  510. preamble += """
  511. nsISupports* global;
  512. xpc_qsSelfRef globalRef;
  513. {
  514. nsresult rv;
  515. JS::Value val = OBJECT_TO_JSVAL(obj);
  516. rv = xpc_qsUnwrapArg<nsISupports>(cx, val, &global, &globalRef.ptr, &val);
  517. if (NS_FAILED(rv)) {
  518. return Throw<true>(cx, NS_ERROR_XPC_BAD_CONVERT_JS);
  519. }
  520. }
  521. """
  522. preArgs = "global, "
  523. name = "_" + self._ctor.identifier.name
  524. nativeName = "_" + MakeNativeName(self._ctor.identifier.name)
  525. nativeName = self.descriptor.binaryNames.get(name, nativeName)
  526. callGenerator = CGMethodCall(preArgs, nativeName, True,
  527. self.descriptor, self._ctor, {})
  528. return preamble + callGenerator.define();
  529. class CGClassHasInstanceHook(CGAbstractStaticMethod):
  530. def __init__(self, descriptor):
  531. args = [Argument('JSContext*', 'cx'), Argument('JSObject*', 'obj'),
  532. Argument('const jsval*', 'v'), Argument('JSBool*', 'bp')]
  533. CGAbstractStaticMethod.__init__(self, descriptor, HASINSTANCE_HOOK_NAME,
  534. 'JSBool', args)
  535. def define(self):
  536. if not self.descriptor.hasInstanceInterface:
  537. return ""
  538. return CGAbstractStaticMethod.define(self)
  539. def definition_body(self):
  540. return self.generate_code()
  541. def generate_code(self):
  542. return """ if (!v->isObject()) {
  543. *bp = false;
  544. return true;
  545. }
  546. jsval protov;
  547. if (!JS_GetProperty(cx, obj, "prototype", &protov))
  548. return false;
  549. if (!protov.isObject()) {
  550. JS_ReportErrorNumber(cx, js_GetErrorMessage, NULL, JSMSG_BAD_PROTOTYPE,
  551. "%s");
  552. return false;
  553. }
  554. obj = &protov.toObject();
  555. JSObject* instance = &v->toObject();
  556. JSObject* proto = JS_GetPrototype(instance);
  557. while (proto) {
  558. if (proto == obj) {
  559. *bp = true;
  560. return true;
  561. }
  562. proto = JS_GetPrototype(proto);
  563. }
  564. nsISupports* native =
  565. nsContentUtils::XPConnect()->GetNativeOfWrapper(cx, instance);
  566. nsCOMPtr<%s> qiResult = do_QueryInterface(native);
  567. *bp = !!qiResult;
  568. return true;
  569. """ % (self.descriptor.name, self.descriptor.hasInstanceInterface)
  570. def isChromeOnly(m):
  571. return m.getExtendedAttribute("ChromeOnly")
  572. class PropertyDefiner:
  573. """
  574. A common superclass for defining things on prototype objects.
  575. Subclasses should implement generateArray to generate the actual arrays of
  576. things we're defining. They should also set self.chrome to the list of
  577. things exposed to chrome and self.regular to the list of things exposed to
  578. web pages. self.chrome must be a superset of self.regular but also include
  579. all the ChromeOnly stuff.
  580. """
  581. def __init__(self, descriptor, name):
  582. self.descriptor = descriptor
  583. self.name = name
  584. def hasChromeOnly(self):
  585. return len(self.chrome) > len(self.regular)
  586. def hasNonChromeOnly(self):
  587. return len(self.regular) > 0
  588. def variableName(self, chrome):
  589. if chrome and self.hasChromeOnly():
  590. return "sChrome" + self.name
  591. if self.hasNonChromeOnly():
  592. return "s" + self.name
  593. return "NULL"
  594. def __str__(self):
  595. str = self.generateArray(self.regular, self.variableName(False))
  596. if self.hasChromeOnly():
  597. str += self.generateArray(self.chrome, self.variableName(True))
  598. return str
  599. # The length of a method is the maximum of the lengths of the
  600. # argument lists of all its overloads.
  601. def methodLength(method):
  602. signatures = method.signatures()
  603. return max([len(arguments) for (retType, arguments) in signatures])
  604. class MethodDefiner(PropertyDefiner):
  605. """
  606. A class for defining methods on a prototype object.
  607. """
  608. def __init__(self, descriptor, name, static):
  609. PropertyDefiner.__init__(self, descriptor, name)
  610. methods = [m for m in descriptor.interface.members if
  611. m.isMethod() and m.isStatic() == static]
  612. self.chrome = [{"name": m.identifier.name,
  613. "length": methodLength(m),
  614. "flags": "JSPROP_ENUMERATE"} for m in methods]
  615. self.regular = [{"name": m.identifier.name,
  616. "length": methodLength(m),
  617. "flags": "JSPROP_ENUMERATE"}
  618. for m in methods if not isChromeOnly(m)]
  619. if not descriptor.interface.parent and not static and not descriptor.workers:
  620. self.chrome.append({"name": 'QueryInterface',
  621. "length": 1,
  622. "flags": "0"})
  623. self.regular.append({"name": 'QueryInterface',
  624. "length": 1,
  625. "flags": "0"})
  626. if static:
  627. if not descriptor.interface.hasInterfaceObject():
  628. # static methods go on the interface object
  629. assert not self.hasChromeOnly() and not self.hasNonChromeOnly()
  630. else:
  631. if not descriptor.interface.hasInterfacePrototypeObject():
  632. # non-static methods go on the interface prototype object
  633. assert not self.hasChromeOnly() and not self.hasNonChromeOnly()
  634. @staticmethod
  635. def generateArray(array, name):
  636. if len(array) == 0:
  637. return ""
  638. funcdecls = [' JS_FN("%s", %s, %s, %s)' %
  639. (m["name"], m["name"], m["length"], m["flags"])
  640. for m in array]
  641. # And add our JS_FS_END
  642. funcdecls.append(' JS_FS_END')
  643. return ("static JSFunctionSpec %s[] = {\n" +
  644. ',\n'.join(funcdecls) + "\n" +
  645. "};\n\n" +
  646. "static jsid %s_ids[%i] = { JSID_VOID };\n\n") % (name, name, len(array))
  647. class AttrDefiner(PropertyDefiner):
  648. def __init__(self, descriptor, name):
  649. PropertyDefiner.__init__(self, descriptor, name)
  650. self.name = name
  651. self.chrome = [m for m in descriptor.interface.members if m.isAttr()]
  652. self.regular = [m for m in self.chrome if not isChromeOnly(m)]
  653. @staticmethod
  654. def generateArray(array, name):
  655. if len(array) == 0:
  656. return ""
  657. def flags(attr):
  658. flags = "JSPROP_SHARED | JSPROP_ENUMERATE"
  659. if generateNativeAccessors:
  660. flags = "JSPROP_NATIVE_ACCESSORS | " + flags
  661. elif attr.readonly:
  662. return "JSPROP_READONLY | " + flags
  663. return flags
  664. def getter(attr):
  665. return "get_" + attr.identifier.name
  666. def setter(attr):
  667. if attr.readonly:
  668. return "NULL"
  669. return "set_" + attr.identifier.name
  670. attrdecls = [' { "%s", 0, %s, (JSPropertyOp)%s, (JSStrictPropertyOp)%s }' %
  671. (attr.identifier.name, flags(attr), getter(attr),
  672. setter(attr)) for attr in array]
  673. attrdecls.append(' { 0, 0, 0, 0, 0 }')
  674. return ("static JSPropertySpec %s[] = {\n" +
  675. ',\n'.join(attrdecls) + "\n" +
  676. "};\n\n" +
  677. "static jsid %s_ids[%i] = { JSID_VOID };\n\n") % (name, name, len(array))
  678. class ConstDefiner(PropertyDefiner):
  679. """
  680. A class for definining constants on the interface object
  681. """
  682. def __init__(self, descriptor, name):
  683. PropertyDefiner.__init__(self, descriptor, name)
  684. self.name = name
  685. self.chrome = [m for m in descriptor.interface.members if m.isConst()]
  686. self.regular = [m for m in self.chrome if not isChromeOnly(m)]
  687. @staticmethod
  688. def generateArray(array, name):
  689. if len(array) == 0:
  690. return ""
  691. constdecls = [' { "%s", %s }' %
  692. (const.identifier.name,
  693. convertConstIDLValueToJSVal(const.value))
  694. for const in array]
  695. constdecls.append(' { 0, JSVAL_VOID }')
  696. return ("static ConstantSpec %s[] = {\n" +
  697. ',\n'.join(constdecls) + "\n" +
  698. "};\n\n" +
  699. "static jsid %s_ids[%i] = { JSID_VOID };\n\n") % (name, name, len(array))
  700. class PropertyArrays():
  701. def __init__(self, descriptor):
  702. self.staticMethods = MethodDefiner(descriptor, "StaticMethods", True)
  703. self.methods = MethodDefiner(descriptor, "Methods", False)
  704. self.attrs = AttrDefiner(descriptor, "Attributes")
  705. self.consts = ConstDefiner(descriptor, "Constants")
  706. @staticmethod
  707. def arrayNames():
  708. return [ "staticMethods", "methods", "attrs", "consts" ]
  709. def hasChromeOnly(self):
  710. return reduce(lambda b, a: b or getattr(self, a).hasChromeOnly(),
  711. self.arrayNames(), False)
  712. def variableNames(self, chrome):
  713. names = {}
  714. for array in self.arrayNames():
  715. names[array] = getattr(self, array).variableName(chrome)
  716. return names
  717. def __str__(self):
  718. define = ""
  719. for array in self.arrayNames():
  720. define += str(getattr(self, array))
  721. return define
  722. class CGCreateInterfaceObjectsMethod(CGAbstractMethod):
  723. """
  724. Generate the CreateInterfaceObjects method for an interface descriptor.
  725. properties should be a PropertyArrays instance.
  726. """
  727. def __init__(self, descriptor, properties):
  728. args = [Argument('JSContext*', 'aCx'), Argument('JSObject*', 'aGlobal'),
  729. Argument('JSObject*', 'aReceiver')]
  730. CGAbstractMethod.__init__(self, descriptor, 'CreateInterfaceObjects', 'JSObject*', args)
  731. self.properties = properties
  732. def definition_body(self):
  733. protoChain = self.descriptor.prototypeChain
  734. if len(protoChain) == 1:
  735. getParentProto = "JS_GetObjectPrototype(aCx, aGlobal)"
  736. else:
  737. parentProtoName = self.descriptor.prototypeChain[-2]
  738. getParentProto = ("%s::GetProtoObject(aCx, aGlobal, aReceiver)" %
  739. toBindingNamespace(parentProtoName))
  740. needInterfaceObject = self.descriptor.interface.hasInterfaceObject()
  741. needInterfacePrototypeObject = self.descriptor.interface.hasInterfacePrototypeObject()
  742. # if we don't need to create anything, why are we generating this?
  743. assert needInterfaceObject or needInterfacePrototypeObject
  744. idsToInit = []
  745. for var in self.properties.arrayNames():
  746. props = getattr(self.properties, var)
  747. if props.hasNonChromeOnly():
  748. idsToInit.append(props.variableName(False))
  749. if props.hasChromeOnly() and not self.descriptor.workers:
  750. idsToInit.append(props.variableName(True))
  751. if len(idsToInit) > 0:
  752. initIds = CGList(
  753. [CGGeneric("!InitIds(aCx, %s, %s_ids)" % (varname, varname)) for
  754. varname in idsToInit], ' ||\n')
  755. if len(idsToInit) > 1:
  756. initIds = CGWrapper(initIds, pre="(", post=")", reindent=True)
  757. initIds = CGList(
  758. [CGGeneric("%s_ids[0] == JSID_VOID &&" % idsToInit[0]), initIds],
  759. "\n")
  760. initIds = CGWrapper(initIds, pre="if (", post=") {", reindent=True)
  761. initIds = CGList(
  762. [initIds,
  763. CGGeneric((" %s_ids[0] = JSID_VOID;\n"
  764. " return NULL;") % idsToInit[0]),
  765. CGGeneric("}")],
  766. "\n")
  767. else:
  768. initIds = None
  769. getParentProto = ("JSObject* parentProto = %s;\n"
  770. "if (!parentProto) {\n"
  771. " return NULL;\n"
  772. "}") % getParentProto
  773. needInterfaceObjectClass = (needInterfaceObject and
  774. self.descriptor.hasInstanceInterface)
  775. needConstructor = (needInterfaceObject and
  776. not self.descriptor.hasInstanceInterface)
  777. if self.descriptor.interface.ctor():
  778. constructHook = CONSTRUCT_HOOK_NAME
  779. constructArgs = methodLength(self.descriptor.interface.ctor())
  780. else:
  781. constructHook = "ThrowingConstructorWorkers" if self.descriptor.workers else "ThrowingConstructor"
  782. constructArgs = 0
  783. call = CGGeneric(("return dom::CreateInterfaceObjects(aCx, aGlobal, aReceiver, parentProto,\n"
  784. " %s, %s, %s, %d,\n"
  785. " %%(methods)s, %%(attrs)s, %%(consts)s, %%(staticMethods)s,\n"
  786. " %s);") % (
  787. "&PrototypeClass" if needInterfacePrototypeObject else "NULL",
  788. "&InterfaceObjectClass" if needInterfaceObjectClass else "NULL",
  789. constructHook if needConstructor else "NULL",
  790. constructArgs,
  791. '"' + self.descriptor.interface.identifier.name + '"' if needInterfaceObject else "NULL"))
  792. if self.properties.hasChromeOnly():
  793. if self.descriptor.workers:
  794. accessCheck = "mozilla::dom::workers::GetWorkerPrivateFromContext(aCx)->IsChromeWorker()"
  795. else:
  796. accessCheck = "xpc::AccessCheck::isChrome(js::GetObjectCompartment(aGlobal))"
  797. accessCheck = "if (" + accessCheck + ") {\n"
  798. chrome = CGWrapper(CGGeneric((CGIndenter(call).define() % self.properties.variableNames(True))),
  799. pre=accessCheck, post="\n}")
  800. else:
  801. chrome = None
  802. functionBody = CGList(
  803. [CGGeneric(getParentProto), initIds, chrome,
  804. CGGeneric(call.define() % self.properties.variableNames(False))],
  805. "\n\n")
  806. return CGIndenter(functionBody).define()
  807. class CGGetPerInterfaceObject(CGAbstractMethod):
  808. """
  809. A method for getting a per-interface object (a prototype object or interface
  810. constructor object).
  811. """
  812. def __init__(self, descriptor, name, idPrefix=""):
  813. args = [Argument('JSContext*', 'aCx'), Argument('JSObject*', 'aGlobal'),
  814. Argument('JSObject*', 'aReceiver')]
  815. CGAbstractMethod.__init__(self, descriptor, name,
  816. 'JSObject*', args, inline=True)
  817. self.id = idPrefix + "id::" + self.descriptor.name
  818. def definition_body(self):
  819. return """
  820. /* aGlobal and aReceiver are usually the same, but they can be different
  821. too. For example a sandbox often has an xray wrapper for a window as the
  822. prototype of the sandbox's global. In that case aReceiver is the xray
  823. wrapper and aGlobal is the sandbox's global.
  824. */
  825. /* Make sure our global is sane. Hopefully we can remove this sometime */
  826. if (!(js::GetObjectClass(aGlobal)->flags & JSCLASS_DOM_GLOBAL)) {
  827. return NULL;
  828. }
  829. /* Check to see whether the interface objects are already installed */
  830. JSObject** protoOrIfaceArray = GetProtoOrIfaceArray(aGlobal);
  831. JSObject* cachedObject = protoOrIfaceArray[%s];
  832. if (!cachedObject) {
  833. protoOrIfaceArray[%s] = cachedObject = CreateInterfaceObjects(aCx, aGlobal, aReceiver);
  834. }
  835. /* cachedObject might _still_ be null, but that's OK */
  836. return cachedObject;""" % (self.id, self.id)
  837. class CGGetProtoObjectMethod(CGGetPerInterfaceObject):
  838. """
  839. A method for getting the interface prototype object.
  840. """
  841. def __init__(self, descriptor):
  842. CGGetPerInterfaceObject.__init__(self, descriptor, "GetProtoObject",
  843. "prototypes::")
  844. def definition_body(self):
  845. return """
  846. /* Get the interface prototype object for this class. This will create the
  847. object as needed. */""" + CGGetPerInterfaceObject.definition_body(self)
  848. class CGGetConstructorObjectMethod(CGGetPerInterfaceObject):
  849. """
  850. A method for getting the interface constructor object.
  851. """
  852. def __init__(self, descriptor):
  853. CGGetPerInterfaceObject.__init__(self, descriptor, "GetConstructorObject",
  854. "constructors::")
  855. def definition_body(self):
  856. return """
  857. /* Get the interface object for this class. This will create the object as
  858. needed. */""" + CGGetPerInterfaceObject.definition_body(self)
  859. def CheckPref(descriptor, globalName, varName, retval, wrapperCache = None):
  860. """
  861. Check whether bindings should be enabled for this descriptor. If not, set
  862. varName to false and return retval.
  863. """
  864. if not descriptor.prefable:
  865. return ""
  866. if wrapperCache:
  867. wrapperCache = " %s->ClearIsDOMBinding();\n" % (wrapperCache)
  868. else:
  869. wrapperCache = ""
  870. return """
  871. {
  872. XPCWrappedNativeScope* scope =
  873. XPCWrappedNativeScope::FindInJSObjectScope(aCx, %s);
  874. if (!scope) {
  875. return %s;
  876. }
  877. if (!scope->ExperimentalBindingsEnabled()) {
  878. %s %s = false;
  879. return %s;
  880. }
  881. }
  882. """ % (globalName, retval, wrapperCache, varName, retval)
  883. class CGDefineDOMInterfaceMethod(CGAbstractMethod):
  884. """
  885. A method for resolve hooks to try to lazily define the interface object for
  886. a given interface.
  887. """
  888. def __init__(self, descriptor):
  889. args = [Argument('JSContext*', 'aCx'), Argument('JSObject*', 'aReceiver'),
  890. Argument('bool*', 'aEnabled')]
  891. CGAbstractMethod.__init__(self, descriptor, 'DefineDOMInterface', 'bool', args)
  892. def declare(self):
  893. if self.descriptor.workers:
  894. return ''
  895. return CGAbstractMethod.declare(self)
  896. def define(self):
  897. if self.descriptor.workers:
  898. return ''
  899. return CGAbstractMethod.define(self)
  900. def definition_body(self):
  901. if self.descriptor.interface.hasInterfacePrototypeObject():
  902. # We depend on GetProtoObject defining an interface constructor
  903. # object as needed.
  904. getter = "GetProtoObject"
  905. else:
  906. getter = "GetConstructorObject"
  907. return (" JSObject* global = JS_GetGlobalForObject(aCx, aReceiver);\n" +
  908. CheckPref(self.descriptor, "global", "*aEnabled", "false") +
  909. """
  910. *aEnabled = true;
  911. return !!%s(aCx, global, aReceiver);""" % (getter))
  912. class CGNativeToSupportsMethod(CGAbstractStaticMethod):
  913. """
  914. A method to cast our native to an nsISupports. We do it by casting up the
  915. interface chain in hopes of getting to something that singly-inherits from
  916. nsISupports.
  917. """
  918. def __init__(self, descriptor):
  919. args = [Argument(descriptor.nativeType + '*', 'aNative')]
  920. CGAbstractStaticMethod.__init__(self, descriptor, 'NativeToSupports', 'nsISupports*', args)
  921. def definition_body(self):
  922. cur = CGGeneric("aNative")
  923. for proto in reversed(self.descriptor.prototypeChain[:-1]):
  924. d = self.descriptor.getDescriptor(proto)
  925. cast = "static_cast<%s*>(\n" % d.nativeType;
  926. cur = CGWrapper(CGIndenter(cur), pre=cast, post=")")
  927. return CGIndenter(CGWrapper(cur, pre="return ", post=";")).define();
  928. class CGWrapMethod(CGAbstractMethod):
  929. def __init__(self, descriptor):
  930. # XXX can we wrap if we don't have an interface prototype object?
  931. assert descriptor.interface.hasInterfacePrototypeObject()
  932. args = [Argument('JSContext*', 'aCx'), Argument('JSObject*', 'aScope'),
  933. Argument(descriptor.nativeType + '*', 'aObject'),
  934. Argument('bool*', 'aTriedToWrap')]
  935. CGAbstractMethod.__init__(self, descriptor, 'Wrap', 'JSObject*', args)
  936. def definition_body(self):
  937. if self.descriptor.workers:
  938. return """
  939. *aTriedToWrap = true;
  940. return aObject->GetJSObject();"""
  941. return """
  942. *aTriedToWrap = true;
  943. JSObject* parent = WrapNativeParent(aCx, aScope, aObject->GetParentObject());
  944. if (!parent) {
  945. return NULL;
  946. }
  947. JSAutoEnterCompartment ac;
  948. if (js::GetGlobalForObjectCrossCompartment(parent) != aScope) {
  949. if (!ac.enter(aCx, parent)) {
  950. return NULL;
  951. }
  952. }
  953. JSObject* global = JS_GetGlobalForObject(aCx, parent);
  954. %s
  955. JSObject* proto = GetProtoObject(aCx, global, global);
  956. if (!proto) {
  957. return NULL;
  958. }
  959. JSObject* obj = JS_NewObject(aCx, &Class.mBase, proto, parent);
  960. if (!obj) {
  961. return NULL;
  962. }
  963. js::SetReservedSlot(obj, DOM_OBJECT_SLOT, PRIVATE_TO_JSVAL(aObject));
  964. NS_ADDREF(aObject);
  965. aObject->SetWrapper(obj);
  966. return obj;""" % (CheckPref(self.descriptor, "global", "*aTriedToWrap", "NULL", "aObject"))
  967. builtinNames = {
  968. IDLType.Tags.bool: 'bool',
  969. IDLType.Tags.int8: 'int8_t',
  970. IDLType.Tags.int16: 'int16_t',
  971. IDLType.Tags.int32: 'int32_t',
  972. IDLType.Tags.int64: 'int64_t',
  973. IDLType.Tags.uint8: 'uint8_t',
  974. IDLType.Tags.uint16: 'uint16_t',
  975. IDLType.Tags.uint32: 'uint32_t',
  976. IDLType.Tags.uint64: 'uint64_t',
  977. IDLType.Tags.float: 'float',
  978. IDLType.Tags.double: 'double'
  979. }
  980. class CastableObjectUnwrapper():
  981. """
  982. A class for unwrapping an object named by the "source" argument
  983. based on the passed-in descriptor and storing it in a variable
  984. called by the name in the "target" argument.
  985. codeOnFailure is the code to run if unwrapping fails.
  986. """
  987. def __init__(self, descriptor, source, target, codeOnFailure):
  988. assert descriptor.castable
  989. self.substitution = { "type" : descriptor.nativeType,
  990. "protoID" : "prototypes::id::" + descriptor.name,
  991. "source" : source,
  992. "target" : target,
  993. "codeOnFailure" : codeOnFailure }
  994. def __str__(self):
  995. return string.Template(
  996. """ {
  997. nsresult rv = UnwrapObject<${protoID}>(cx, ${source}, &${target});
  998. if (NS_FAILED(rv)) {
  999. ${codeOnFailure}
  1000. }
  1001. }""").substitute(self.substitution)
  1002. class FailureFatalCastableObjectUnwrapper(CastableObjectUnwrapper):
  1003. """
  1004. As CastableObjectUnwrapper, but defaulting to throwing if unwrapping fails
  1005. """
  1006. def __init__(self, descriptor, source, target):
  1007. CastableObjectUnwrapper.__init__(self, descriptor, source, target,
  1008. "return Throw<%s>(cx, rv);" %
  1009. toStringBool(not descriptor.workers))
  1010. class CallbackObjectUnwrapper:
  1011. """
  1012. A class for unwrapping objects implemented in JS.
  1013. |source| is the JSObject we want to use in native code.
  1014. |target| is an nsCOMPtr of the appropriate type in which we store the result.
  1015. """
  1016. def __init__(self, descriptor, source, target, codeOnFailure=None):
  1017. if codeOnFailure is None:
  1018. codeOnFailure = ("return Throw<%s>(cx, rv);" %
  1019. toStringBool(not descriptor.workers))
  1020. self.descriptor = descriptor
  1021. self.substitution = { "nativeType" : descriptor.nativeType,
  1022. "source" : source,
  1023. "target" : target,
  1024. "codeOnFailure" : codeOnFailure }
  1025. def __str__(self):
  1026. if self.descriptor.workers:
  1027. return string.Template("""
  1028. ${target} = ${source};""").substitute(self.substitution)
  1029. return string.Template("""
  1030. nsresult rv;
  1031. XPCCallContext ccx(JS_CALLER, cx);
  1032. if (!ccx.IsValid()) {
  1033. rv = NS_ERROR_XPC_BAD_CONVERT_JS;
  1034. ${codeOnFailure}
  1035. }
  1036. const nsIID& iid = NS_GET_IID(${nativeType});
  1037. nsRefPtr<nsXPCWrappedJS> wrappedJS;
  1038. rv = nsXPCWrappedJS::GetNewOrUsed(ccx, ${source}, iid,
  1039. NULL, getter_AddRefs(wrappedJS));
  1040. if (NS_FAILED(rv) || !wrappedJS) {
  1041. ${codeOnFailure}
  1042. }
  1043. ${target} = do_QueryObject(wrappedJS.get());
  1044. if (!${target}) {
  1045. ${codeOnFailure}
  1046. }""").substitute(self.substitution)
  1047. def getArgumentConversionTemplate(type, descriptor):
  1048. if type.isSequence() or type.isArray():
  1049. raise TypeError("Can't handle sequence or array arguments yet")
  1050. if descriptor is not None:
  1051. assert(type.isInterface())
  1052. # This is an interface that we implement as a concrete class
  1053. # or an XPCOM interface.
  1054. argIsPointer = type.nullable() or type.unroll().inner.isExternal()
  1055. if argIsPointer:
  1056. nameSuffix = ""
  1057. else:
  1058. nameSuffix = "_ptr"
  1059. # If we're going to QI, we want an nsCOMPtr. But note that XPConnect
  1060. # unwrapping may or may not QI, and we don't know whether it will. So
  1061. # we use a raw pointer for the isExternal() case, and if a ref is needed
  1062. # it'll be handled by the xpc_qsSelfRef we put on the stack later.
  1063. if descriptor.castable or type.unroll().inner.isExternal() or descriptor.workers:
  1064. declType = " ${typeName}*"
  1065. else:
  1066. declType = " nsCOMPtr<${typeName}>"
  1067. template = declType + " ${name}%s;\n" % nameSuffix
  1068. # We have to be very careful here to put anything that might need to
  1069. # hold references across the C++ call in |template| and not
  1070. # |templateBody|, since things in |templateBody| will go out of scope
  1071. # before the call happens.
  1072. templateBody = " if (${argVal}.isObject()) {"
  1073. if descriptor.castable:
  1074. templateBody += str(FailureFatalCastableObjectUnwrapper(
  1075. descriptor,
  1076. "&${argVal}.toObject()",
  1077. "${name}"+nameSuffix)).replace("\n", "\n ") + "\n"
  1078. elif descriptor.interface.isCallback():
  1079. templateBody += str(CallbackObjectUnwrapper(
  1080. descriptor,
  1081. "&${argVal}.toObject()",
  1082. "${name}"+nameSuffix)) + "\n"
  1083. elif descriptor.workers:
  1084. templateBody += """
  1085. ${name}%s = &${argVal}.toObject();
  1086. MOZ_ASSERT(${name}%s);
  1087. """ % (nameSuffix, nameSuffix)
  1088. else:
  1089. template += " xpc_qsSelfRef tmpRef_${name};\n"
  1090. template += " jsval tmpVal_${name} = ${argVal};\n"
  1091. templateBody += """
  1092. ${typeName}* tmp;
  1093. if (NS_FAILED(xpc_qsUnwrapArg<${typeName}>(cx, ${argVal}, &tmp, &tmpRef_${name}.ptr,
  1094. &tmpVal_${name}))) {
  1095. return Throw<%s>(cx, NS_ERROR_XPC_BAD_CONVERT_JS);
  1096. }
  1097. MOZ_ASSERT(tmp);
  1098. ${name}%s = tmp;
  1099. """ % (toStringBool(not descriptor.workers), nameSuffix)
  1100. if type.nullable():
  1101. templateBody += (
  1102. " } else if (${argVal}.isNullOrUndefined()) {\n"
  1103. " ${name}%s = NULL;\n" % nameSuffix)
  1104. templateBody += (
  1105. " } else {\n"
  1106. " return Throw<%s>(cx, NS_ERROR_XPC_BAD_CONVERT_JS);\n"
  1107. " }\n" % toStringBool(not descriptor.workers))
  1108. template += templateBody
  1109. if not argIsPointer:
  1110. template += " ${typeName} &${name} = *${name}_ptr;\n"
  1111. return template
  1112. if type.isArrayBuffer():
  1113. template = (
  1114. " JSObject* ${name};\n"
  1115. " if (${argVal}.isObject() && JS_IsArrayBufferObject(&${argVal}.toObject(), cx)) {\n"
  1116. " ${name} = &${argVal}.toObject();\n"
  1117. " }")
  1118. if type.nullable():
  1119. template += (
  1120. " else if (${argVal}.isNullOrUndefined()) {\n"
  1121. " ${name} = NULL;\n"
  1122. " }")
  1123. template += (
  1124. # XXXbz We don't know whether we're on workers, so play it safe
  1125. " else {\n"
  1126. " return Throw<false>(cx, NS_ERROR_XPC_BAD_CONVERT_JS);\n"
  1127. " }")
  1128. return template
  1129. if type.isInterface():
  1130. raise TypeError("Interface type with no descriptor: " + type)
  1131. if type.isString():
  1132. # XXXbz Need to figure out string behavior based on extended args? Also, how to
  1133. # detect them?
  1134. # For nullable strings that are not otherwise annotated, null
  1135. # and undefined become null strings.
  1136. if type.nullable():
  1137. nullBehavior = "eNull"
  1138. undefinedBehavior = "eNull"
  1139. else:
  1140. nullBehavior = "eStringify"
  1141. undefinedBehavior = "eStringify"
  1142. return (
  1143. " const xpc_qsDOMString ${name}(cx, ${argVal}, ${argPtr},\n"
  1144. " xpc_qsDOMString::%s,\n"
  1145. " xpc_qsDOMString::%s);\n"
  1146. " if (!${name}.IsValid()) {\n"
  1147. " return false;\n"
  1148. " }\n" % (nullBehavior, undefinedBehavior))
  1149. if type.isEnum():
  1150. if type.nullable():
  1151. raise TypeError("We don't support nullable enumerated arguments "
  1152. "yet")
  1153. enum = type.inner.identifier.name
  1154. return (
  1155. " %(enumtype)s ${name};\n"
  1156. " {\n"
  1157. " bool ok;\n"
  1158. " ${name} = static_cast<%(enumtype)s>(FindEnumStringIndex(cx, ${argVal}, %(values)s, &ok));\n"
  1159. " if (!ok) {\n"
  1160. " return false;\n"
  1161. " }\n"
  1162. " }" % { "enumtype" : enum,
  1163. "values" : enum + "Values::strings" })
  1164. if type.isCallback():
  1165. # XXXbz we're going to assume that callback types are always
  1166. # nullable and always have [TreatNonCallableAsNull] for now.
  1167. return (
  1168. " JSObject* ${name};\n"
  1169. " if (${argVal}.isObject() && JS_ObjectIsCallable(cx, &${argVal}.toObject())) {\n"
  1170. " ${name} = &${argVal}.toObject();\n"
  1171. " } else {\n"
  1172. " ${name} = NULL;\n"
  1173. " }\n")
  1174. if type.isAny():
  1175. return " JS::Value ${name} = ${argVal};\n"
  1176. if not type.isPrimitive():
  1177. raise TypeError("Need conversion for argument type '%s'" % type)
  1178. tag = type.tag()
  1179. replacements = dict()
  1180. if type.nullable():
  1181. replacements["declareArg"] = (
  1182. " Nullable<${typeName}> ${name};\n"
  1183. " if (${argVal}.isNullOrUndefined()) {\n"
  1184. " ${name}.SetNull();\n"
  1185. " } else"
  1186. )
  1187. replacements["finalValueSetter"] = "${name}.SetValue"
  1188. else:
  1189. replacements["declareArg"] = " ${typeName} ${name};\n"
  1190. replacements["finalValueSetter"] = "${name} = "
  1191. replacements["intermediateCast"] = ""
  1192. if tag == IDLType.Tags.bool:
  1193. replacements["jstype"] = "JSBool"
  1194. replacements["converter"] = "JS_ValueToBoolean"
  1195. elif tag in [IDLType.Tags.int8, IDLType.Tags.uint8, IDLType.Tags.int16,
  1196. IDLType.Tags.uint16, IDLType.Tags.int32, IDLType.Tags.uint32]:
  1197. # XXXbz need to add support for [EnforceRange] and [Clamp]
  1198. # The output of JS_ValueToECMAInt32 is determined as follows:
  1199. # 1) The value is converted to a double
  1200. # 2) Anything that's not a finite double returns 0
  1201. # 3) The double is rounded towards zero to the nearest integer
  1202. # 4) The resulting integer is reduced mod 2^32. The output of this
  1203. # operation is an integer in the range [0, 2^32).
  1204. # 5) If the resulting number is >= 2^31, 2^32 is subtracted from it.
  1205. #
  1206. # The result of all this is a number in the range [-2^31, 2^31)
  1207. #
  1208. # WebIDL conversions for the 8-bit, 16-bit, and 32-bit integer types
  1209. # are defined in the same way, except that step 4 uses reduction mod
  1210. # 2^8 and 2^16 for the 8-bit and 16-bit types respectively, and step 5
  1211. # is only done for the signed types.
  1212. #
  1213. # C/C++ define integer conversion semantics to unsigned types as taking
  1214. # your input integer mod (1 + largest value representable in the
  1215. # unsigned type). Since 2^32 is zero mod 2^8, 2^16, and 2^32,
  1216. # converting to the unsigned int of the relevant width will correctly
  1217. # perform step 4; in particular, the 2^32 possibly subtracted in step 5
  1218. # will become 0.
  1219. #
  1220. # Once we have step 4 done, we're just going to assume 2s-complement
  1221. # representation and cast directly to the type we really want.
  1222. #
  1223. # So we can cast directly for all unsigned types and for int32_t; for
  1224. # the smaller-width signed types we need to cast through the
  1225. # corresponding unsigned type.
  1226. replacements["jstype"] = "int32_t"
  1227. replacements["converter"] = "JS::ToInt32"
  1228. if tag is IDLType.Tags.int8:
  1229. replacements["intermediateCast"] = "(uint8_t)"
  1230. elif tag is IDLType.Tags.int16:
  1231. replacements["intermediateCast"] = "(uint16_t)"
  1232. else:
  1233. replacements["intermediateCast"] = ""
  1234. elif tag is IDLType.Tags.int64:
  1235. # XXXbz this may not match what WebIDL says to do in terms of reducing
  1236. # mod 2^64. Should we check?
  1237. replacements["jstype"] = "int64_t"
  1238. replacements["converter"] = "xpc::ValueToInt64"
  1239. elif tag is IDLType.Tags.uint64:
  1240. # XXXbz this may not match what WebIDL says to do in terms of reducing
  1241. # mod 2^64. Should we check?
  1242. replacements["jstype"] = "uint64_t"
  1243. replacements["converter"] = "xpc::ValueToUint64"
  1244. elif tag in [IDLType.Tags.float, IDLType.Tags.double]:
  1245. replacements["jstype"] = "double"
  1246. replacements["converter"] = "JS::ToNumber"
  1247. else:
  1248. raise TypeError("Unknown primitive type '%s'" % type);
  1249. # We substitute the %(name)s things here. Our caller will
  1250. # substitute the ${name} things.
  1251. return (" %(jstype)s ${name}_jstype;\n"
  1252. "%(declareArg)s" # No leading whitespace or newline here, on purpose
  1253. " if (%(converter)s(cx, ${argVal}, &${name}_jstype)) {\n"
  1254. " %(finalValueSetter)s((${typeName})%(intermediateCast)s${name}_jstype);\n"
  1255. " } else {\n"
  1256. " return false;\n"
  1257. " }\n" % replacements)
  1258. def convertConstIDLValueToJSVal(value):
  1259. if isinstance(value, IDLNullValue):
  1260. return "JSVAL_NULL"
  1261. tag = value.type.tag()
  1262. if tag in [IDLType.Tags.int8, IDLType.Tags.uint8, IDLType.Tags.int16,
  1263. IDLType.Tags.uint16, IDLType.Tags.int32]:
  1264. return "INT_TO_JSVAL(%s)" % (value.value)
  1265. if tag == IDLType.Tags.uint32:
  1266. return "UINT_TO_JSVAL(%s)" % (value.value)
  1267. if tag in [IDLType.Tags.int64, IDLType.Tags.uint64]:
  1268. return "DOUBLE_TO_JSVAL(%s)" % (value.value)
  1269. if tag == IDLType.Tags.bool:
  1270. return "JSVAL_TRUE" if value.value else "JSVAL_FALSE"
  1271. if tag in [IDLType.Tags.float, IDLType.Tags.double]:
  1272. return "DOUBLE_TO_JSVAL(%s)" % (value.value)
  1273. raise TypeError("Const value of unhandled type: " + value.type)
  1274. def convertIDLDefaultValueToJSVal(value):
  1275. if value.type:
  1276. tag = value.type.tag()
  1277. if tag == IDLType.Tags.domstring:
  1278. assert False # Not implemented!
  1279. return convertConstIDLValueToJSVal(value)
  1280. unindenter = re.compile("^ ", re.MULTILINE)
  1281. class CGArgumentConverter(CGThing):
  1282. """
  1283. A class that takes an IDL argument object, its index in the
  1284. argument list, and the argv and argc strings and generates code to
  1285. unwrap the argument to the right native type.
  1286. """
  1287. def __init__(self, argument, index, argv, argc, descriptorProvider):
  1288. CGThing.__init__(self)
  1289. self.argument = argument
  1290. # XXXbz should optional jsval args get JSVAL_VOID? What about
  1291. # others?
  1292. self.replacementVariables = {
  1293. "index" : index,
  1294. "argc" : argc,
  1295. "argv" : argv,
  1296. "defaultValue" : "JSVAL_VOID",
  1297. "name" : "arg%d" % index
  1298. }
  1299. if argument.optional:
  1300. if argument.defaultValue:
  1301. self.replacementVariables["defaultValue"] = convertIDLDefaultValueToJSVal(argument.defaultValue)
  1302. self.replacementVariables["argVal"] = string.Template(
  1303. "(${index} < ${argc} ? ${argv}[${index}] : ${defaultValue})"
  1304. ).substitute(self.replacementVariables)
  1305. self.replacementVariables["argPtr"] = string.Template(
  1306. "(${index} < ${argc} ? &${argv}[${index}] : NULL)"
  1307. ).substitute(self.replacementVariables)
  1308. else:
  1309. self.replacementVariables["argVal"] = string.Template(
  1310. "${argv}[${index}]"
  1311. ).substitute(self.replacementVariables)
  1312. self.replacementVariables["argPtr"] = (
  1313. "&" + self.replacementVariables["argVal"])
  1314. self.descriptor = None
  1315. if argument.type.isPrimitive():
  1316. self.replacementVariables["typeName"] = builtinNames[argument.type.tag()]
  1317. elif argument.type.isInterface() and not argument.type.isArrayBuffer():
  1318. descriptor = descriptorProvider.getDescriptor(
  1319. argument.type.unroll().inner.identifier.name)
  1320. self.descriptor = descriptor
  1321. self.replacementVariables["typeName"] = descriptor.nativeType
  1322. def define(self):
  1323. return string.Template(
  1324. re.sub(unindenter,
  1325. "",
  1326. getArgumentConversionTemplate(self.argument.type,
  1327. self.descriptor))
  1328. ).substitute(self.replacementVariables)
  1329. def getWrapTemplateForTypeImpl(type, result, descriptorProvider,
  1330. resultAlreadyAddRefed):
  1331. if type is None or type.isVoid():
  1332. return """
  1333. ${jsvalRef} = JSVAL_VOID;
  1334. return true;"""
  1335. if type.isSequence() or type.isArray():
  1336. raise TypeError("Can't handle sequence or array return values yet")
  1337. if type.isInterface() and not type.isArrayBuffer():
  1338. descriptor = descriptorProvider.getDescriptor(type.unroll().inner.identifier.name)
  1339. wrappingCode = ("""
  1340. if (!%s) {
  1341. ${jsvalRef} = JSVAL_NULL;
  1342. return true;
  1343. }""" % result) if type.nullable() else ""
  1344. if descriptor.castable and not type.unroll().inner.isExternal():
  1345. wrappingCode += """
  1346. if (WrapNewBindingObject(cx, obj, %s, ${jsvalPtr})) {
  1347. return true;
  1348. }""" % result
  1349. # We don't support prefable stuff in workers.
  1350. assert(not descriptor.prefable or not descriptor.workers)
  1351. if not descriptor.prefable:
  1352. # Non-prefable bindings can only fail to wrap as a new-binding object
  1353. # if they already threw an exception. Same thing for
  1354. # non-prefable bindings.
  1355. wrappingCode += """
  1356. MOZ_ASSERT(JS_IsExceptionPending(cx));
  1357. return false;"""
  1358. else:
  1359. # Try old-style wrapping for bindings which might be preffed off.
  1360. wrappingCode += """
  1361. return HandleNewBindingWrappingFailure(cx, obj, %s, ${jsvalPtr});""" % result
  1362. else:
  1363. if descriptor.notflattened:
  1364. getIID = "&NS_GET_IID(%s), " % descriptor.nativeType
  1365. else:
  1366. getIID = ""
  1367. wrappingCode += """
  1368. return WrapObject(cx, obj, %s, %s${jsvalPtr});""" % (result, getIID)
  1369. return wrappingCode
  1370. if type.isString():
  1371. if type.nullable():
  1372. return """
  1373. return xpc::StringToJsval(cx, %s, ${jsvalPtr});""" % result
  1374. else:
  1375. return """
  1376. return xpc::NonVoidStringToJsval(cx, %s, ${jsvalPtr});""" % result
  1377. if type.isEnum():
  1378. if type.nullable():
  1379. raise TypeError("We don't support nullable enumerated return types "
  1380. "yet")
  1381. return """
  1382. MOZ_ASSERT(uint32_t(%(result)s) < ArrayLength(%(strings)s));
  1383. JSString* result_str = JS_NewStringCopyN(cx, %(strings)s[uint32_t(%(result)s)].value, %(strings)s[uint32_t(%(result)s)].length);
  1384. if (!result_str) {
  1385. return false;
  1386. }
  1387. ${jsvalRef} = JS::StringValue(result_str);
  1388. return true;""" % { "result" : result,
  1389. "strings" : type.inner.identifier.name + "Values::strings" }
  1390. if type.isCallback() and not type.isInterface():
  1391. # XXXbz we're going to assume that callback types are always
  1392. # nullable and always have [TreatNonCallableAsNull] for now.
  1393. # See comments in WrapNewBindingObject explaining why we need
  1394. # to wrap here.
  1395. return """
  1396. ${jsvalRef} = JS::ObjectOrNullValue(%s);
  1397. return JS_WrapValue(cx, ${jsvalPtr});""" % result
  1398. if type.tag() == IDLType.Tags.any:
  1399. # See comments in WrapNewBindingObject explaining why we need
  1400. # to wrap here.
  1401. return """
  1402. ${jsvalRef} = %s;\n
  1403. return JS_WrapValue(cx, ${jsvalPtr});""" % result
  1404. if not type.isPrimitive():
  1405. raise TypeError("Need to learn to wrap %s" % type)
  1406. if type.nullable():
  1407. return """
  1408. if (%s.IsNull()) {
  1409. ${jsvalRef} = JSVAL_NULL;
  1410. return true;
  1411. }
  1412. %s""" % (result, getWrapTemplateForTypeImpl(type.inner, "%s.Value()" % result,
  1413. descriptorProvider,
  1414. resultAlreadyAddRefed))
  1415. tag = type.tag()
  1416. if tag in [IDLType.Tags.int8, IDLType.Tags.uint8, IDLType.Tags.int16,
  1417. IDLType.Tags.uint16, IDLType.Tags.int32]:
  1418. return """
  1419. ${jsvalRef} = INT_TO_JSVAL(int32_t(%s));
  1420. return true;""" % result
  1421. elif tag in [IDLType.Tags.int64, IDLType.Tags.uint64, IDLType.Tags.float,
  1422. IDLType.Tags.double]:
  1423. # XXXbz will cast to double do the "even significand" thing that webidl
  1424. # calls for for 64-bit ints? Do we care?
  1425. return """
  1426. return JS_NewNumberValue(cx, double(%s), ${jsvalPtr});""" % result
  1427. elif tag == IDLType.Tags.uint32:
  1428. return """
  1429. ${jsvalRef} = UINT_TO_JSVAL(%s);
  1430. return true;""" % result
  1431. elif tag == IDLType.Tags.bool:
  1432. return """
  1433. ${jsvalRef} = BOOLEAN_TO_JSVAL(%s);
  1434. return true;""" % result
  1435. else:
  1436. raise TypeError("Need to learn to wrap primitive: %s" % type)
  1437. def getWrapTemplateForType(type, descriptorProvider, resultAlreadyAddRefed):
  1438. return getWrapTemplateForTypeImpl(type, "result", descriptorProvider,
  1439. resultAlreadyAddRefed)
  1440. class CGCallGenerator(CGThing):
  1441. """
  1442. A class to generate an actual call to a C++ object. Assumes that the C++
  1443. object is stored in a variable named "self".
  1444. """
  1445. def __init__(self, errorReport, argCount, argsPre, returnType,
  1446. resultAlreadyAddRefed, descriptorProvider, nativeMethodName, static):
  1447. CGThing.__init__(self)
  1448. isFallible = errorReport is not None
  1449. args = CGList([CGGeneric("arg" + str(i)) for i in range(argCount)], ", ")
  1450. resultOutParam = returnType is not None and returnType.isString()
  1451. # Return values that go in outparams go here
  1452. if resultOutParam:
  1453. args.append(CGGeneric("result"))
  1454. if isFallible:
  1455. args.append(CGGeneric("rv"))
  1456. if returnType is None or returnType.isVoid():
  1457. # Nothing to declare
  1458. result = None
  1459. elif returnType.isPrimitive() and returnType.tag() in builtinNames:
  1460. result = CGGeneric(builtinNames[returnType.tag()])
  1461. if returnType.nullable():
  1462. result = CGWrapper(result, pre="Nullable<", post=">")
  1463. elif returnType.isString():
  1464. result = CGGeneric("nsString")
  1465. elif returnType.isEnum():
  1466. if returnType.nullable():
  1467. raise TypeError("We don't support nullable enum return values")
  1468. result = CGGeneric(returnType.inner.identifier.name)
  1469. elif returnType.isInterface() and not returnType.isArrayBuffer():
  1470. result = CGGeneric(descriptorProvider.getDescriptor(
  1471. returnType.unroll().inner.identifier.name).nativeType)
  1472. if resultAlreadyAddRefed:
  1473. result = CGWrapper(result, pre="nsRefPtr<", post=">")
  1474. else:
  1475. result = CGWrapper(result, post="*")
  1476. elif returnType.isCallback():
  1477. # XXXbz we're going to assume that callback types are always
  1478. # nullable for now.
  1479. result = CGGeneric("JSObject*")
  1480. elif returnType.tag() is IDLType.Tags.any:
  1481. result = CGGeneric("JS::Value")
  1482. else:
  1483. raise TypeError("Don't know how to declare return value for %s" %
  1484. returnType)
  1485. # Build up our actual call
  1486. self.cgRoot = CGList([], "\n")
  1487. call = CGGeneric(nativeMethodName)
  1488. if static:
  1489. call = CGWrapper(call, pre="%s::" % (descriptorProvider.getDescriptor(
  1490. returnType.unroll().inner.identifier.name).nativeType))
  1491. else:
  1492. call = CGWrapper(call, pre="self->")
  1493. call = CGList([call, CGWrapper(args, pre="(" + argsPre, post=");")])
  1494. if result is not None:
  1495. result = CGWrapper(result, post=" result;")
  1496. self.cgRoot.prepend(result)
  1497. if not resultOutParam:
  1498. call = CGWrapper(call, pre="result = ")
  1499. call = CGWrapper(call)
  1500. self.cgRoot.append(call)
  1501. if isFallible:
  1502. self.cgRoot.prepend(CGGeneric("nsresult rv = NS_OK;"))
  1503. self.cgRoot.append(CGGeneric("if (NS_FAILED(rv)) {"))
  1504. self.cgRoot.append(CGIndenter(CGGeneric(errorReport)))
  1505. self.cgRoot.append(CGGeneric("}"))
  1506. def define(self):
  1507. return self.cgRoot.define()
  1508. class CGPerSignatureCall(CGThing):
  1509. """
  1510. This class handles the guts of generating code for a particular
  1511. call signature. A call signature consists of four things:
  1512. 1) A return type, which can be None to indicate that there is no
  1513. actual return value (e.g. this is an attribute setter) or an
  1514. IDLType if there's an IDL type involved (including |void|).
  1515. 2) An argument list, which is allowed to be empty.
  1516. 3) A name of a native method to call.
  1517. 4) Whether or not this method is static.
  1518. We also need to know whether this is a method or a getter/setter
  1519. to do error reporting correctly.
  1520. The idlNode parameter can be either a method or an attr. We can query
  1521. |idlNode.identifier| in both cases, so we can be agnostic between the two.
  1522. """
  1523. # XXXbz For now each entry in the argument list is either an
  1524. # IDLArgument or a FakeArgument, but longer-term we may want to
  1525. # have ways of flagging things like JSContext* or optional_argc in
  1526. # there.
  1527. def __init__(self, returnType, argsPre, arguments, nativeMethodName, static,
  1528. descriptor, idlNode, extendedAttributes, argConversionStartsAt=0):
  1529. CGThing.__init__(self)
  1530. self.returnType = returnType
  1531. self.descriptor = descriptor
  1532. self.idlNode = idlNode
  1533. self.extendedAttributes = extendedAttributes
  1534. # Default to already_AddRefed on the main thread, raw pointer in workers
  1535. self.resultAlreadyAddRefed = not descriptor.workers and not 'resultNotAddRefed' in self.extendedAttributes
  1536. self.argsPre = "cx, " if 'implicitJSContext' in self.extendedAttributes else ""
  1537. self.argsPre += argsPre
  1538. self.argCount = len(arguments)
  1539. if self.argCount > argConversionStartsAt:
  1540. # Insert our argv in there
  1541. cgThings = [CGGeneric(self.getArgvDecl())]
  1542. else:
  1543. cgThings = []
  1544. cgThings.extend([CGArgumentConverter(arguments[i], i, self.getArgv(),
  1545. self.getArgc(), self.descriptor) for
  1546. i in range(argConversionStartsAt, self.argCount)])
  1547. cgThings.append(CGCallGenerator(
  1548. self.getErrorReport() if self.isFallible() else None,
  1549. self.argCount, self.argsPre, returnType,
  1550. self.resultAlreadyAddRefed, descriptor, nativeMethodName,
  1551. static))
  1552. self.cgRoot = CGList(cgThings, "\n")
  1553. def getArgv(self):
  1554. return "argv" if self.argCount > 0 else ""
  1555. def getArgvDecl(self):
  1556. return "\nJS::Value* argv = JS_ARGV(cx, vp);\n"
  1557. def getArgc(self):
  1558. return "argc"
  1559. def isFallible(self):
  1560. return not 'infallible' in self.extendedAttributes
  1561. def wrap_return_value(self):
  1562. resultTemplateValues = {'jsvalRef': '*vp', 'jsvalPtr': 'vp'}
  1563. return string.Template(
  1564. re.sub(unindenter,
  1565. "",
  1566. getWrapTemplateForType(self.returnType, self.descriptor,
  1567. self.resultAlreadyAddRefed))
  1568. ).substitute(resultTemplateValues)
  1569. def getErrorReport(self):
  1570. return 'return ThrowMethodFailedWithDetails<%s>(cx, rv, "%s", "%s");'\
  1571. % (toStringBool(not self.descriptor.workers),
  1572. self.descriptor.interface.identifier.name,
  1573. self.idlNode.identifier.name)
  1574. def define(self):
  1575. return (self.cgRoot.define() + self.wrap_return_value())
  1576. class CGSwitch(CGList):
  1577. """
  1578. A class to generate code for a switch statement.
  1579. Takes three constructor arguments: an expression, a list of cases,
  1580. and an optional default.
  1581. Each case is a CGCase. The default is a CGThing for the body of
  1582. the default case, if any.
  1583. """
  1584. def __init__(self, expression, cases, default=None):
  1585. CGList.__init__(self, [CGIndenter(c) for c in cases], "\n")
  1586. self.prepend(CGWrapper(CGGeneric(expression),
  1587. pre="switch (", post=") {"));
  1588. if default is not None:
  1589. self.append(
  1590. CGIndenter(
  1591. CGWrapper(
  1592. CGIndenter(default),
  1593. pre="default: {\n",
  1594. post="\n break;\n}"
  1595. )
  1596. )
  1597. )
  1598. self.append(CGGeneric("}"))
  1599. class CGCase(CGList):
  1600. """
  1601. A class to generate code for a case statement.
  1602. Takes three constructor arguments: an expression, a CGThing for
  1603. the body (allowed to be None if there is no body), and an optional
  1604. argument (defaulting to False) for whether to fall through.
  1605. """
  1606. def __init__(self, expression, body, fallThrough=False):
  1607. CGList.__init__(self, [], "\n")
  1608. self.append(CGWrapper(CGGeneric(expression), pre="case ", post=": {"))
  1609. bodyList = CGList([body], "\n")
  1610. if fallThrough:
  1611. bodyList.append(CGGeneric("/* Fall through */"))
  1612. else:
  1613. bodyList.append(CGGeneric("break;"))
  1614. self.append(CGIndenter(bodyList));
  1615. self.append(CGGeneric("}"))
  1616. class CGMethodCall(CGThing):
  1617. """
  1618. A class to generate selection of a method signature from a set of
  1619. signatures and generation of a call to that signature.
  1620. """
  1621. def __init__(self, argsPre, nativeMethodName, static, descriptor, method,
  1622. extendedAttributes):
  1623. CGThing.__init__(self)
  1624. def requiredArgCount(signature):
  1625. arguments = signature[1]
  1626. if len(arguments) == 0:
  1627. return 0
  1628. requiredArgs = len(arguments)
  1629. while requiredArgs and arguments[requiredArgs-1].optional:
  1630. requiredArgs -= 1
  1631. return requiredArgs
  1632. def maxSigLength(signatures):
  1633. return max([len(s[1]) for s in signatures])
  1634. def signaturesForArgCount(i, signatures):
  1635. return filter(
  1636. lambda s: len(s[1]) == i or (len(s[1]) > i and
  1637. s[1][i].optional),
  1638. signatures)
  1639. def findDistinguishingIndex(argCount, signatures):
  1640. def isValidDistinguishingIndex(idx, signatures):
  1641. for firstSigIndex in range(0, len(signatures)):
  1642. for secondSigIndex in range(0, firstSigIndex):
  1643. firstType = signatures[firstSigIndex][1][idx].type
  1644. secondType = signatures[secondSigIndex][1][idx].type
  1645. if not firstType.isDistinguishableFrom(secondType):
  1646. return False
  1647. return True
  1648. for idx in range(0, argCount):
  1649. if isValidDistinguishingIndex(idx, signatures):
  1650. return idx
  1651. return -1
  1652. def getPerSignatureCall(signature, argConversionStartsAt=0):
  1653. return CGPerSignatureCall(signature[0], argsPre, signature[1],
  1654. nativeMethodName, static, descriptor,
  1655. method, extendedAttributes,
  1656. argConversionStartsAt)
  1657. signatures = method.signatures()
  1658. if len(signatures) == 1:
  1659. # Special case: we can just do a per-signature method call
  1660. # here for our one signature and not worry about switching
  1661. # on anything.
  1662. signature = signatures[0]
  1663. self.cgRoot = CGList([ CGIndenter(getPerSignatureCall(signature)) ])
  1664. requiredArgs = requiredArgCount(signature)
  1665. if requiredArgs > 0:
  1666. self.cgRoot.prepend(
  1667. CGWrapper(
  1668. CGIndenter(
  1669. CGGeneric(
  1670. "if (argc < %d) {\n"
  1671. " return Throw<%s>(cx, NS_ERROR_XPC_NOT_ENOUGH_ARGS);\n"
  1672. "}" % (requiredArgs,
  1673. toStringBool(not descriptor.workers)))
  1674. ),
  1675. pre="\n", post="\n")
  1676. )
  1677. return
  1678. # Need to find the right overload
  1679. maxSigArgs = maxSigLength(signatures)
  1680. allowedArgCounts = [ i for i in range(0, maxSigArgs+1)
  1681. if len(signaturesForArgCount(i, signatures)) != 0 ]
  1682. argCountCases = []
  1683. for argCount in allowedArgCounts:
  1684. possibleSignatures = signaturesForArgCount(argCount, signatures)
  1685. if len(possibleSignatures) == 1:
  1686. # easy case!
  1687. signature = possibleSignatures[0]
  1688. # (possibly) important optimization: if signature[1] has >
  1689. # argCount arguments and signature[1][argCount] is optional and
  1690. # there is only one signature for argCount+1, then the
  1691. # signature for argCount+1 is just ourselves and we can fall
  1692. # through.
  1693. if (len(signature[1]) > argCount and
  1694. signature[1][argCount].optional and
  1695. (argCount+1) in allowedArgCounts and
  1696. len(signaturesForArgCount(argCount+1, signatures)) == 1):
  1697. argCountCases.append(
  1698. CGCase(str(argCount), None, True))
  1699. else:
  1700. argCountCases.append(
  1701. CGCase(str(argCount), getPerSignatureCall(signature)))
  1702. continue
  1703. distinguishingIndex = findDistinguishingIndex(argCount,
  1704. possibleSignatures)
  1705. if distinguishingIndex == -1:
  1706. raise TypeError(("Signatures with %s arguments for " +
  1707. descriptor.interface.identifier.name + "." +
  1708. method.identifier.name +
  1709. " are not distinguishable") % argCount)
  1710. for idx in range(0, distinguishingIndex):
  1711. firstSigType = possibleSignatures[0][1][idx].type
  1712. for sigIdx in range(1, len(possibleSignatures)):
  1713. if possibleSignatures[sigIdx][1][idx].type != firstSigType:
  1714. raise TypeError(("Signatures with %d arguments for " +
  1715. descriptor.interface.identifier.name +
  1716. "." + method.identifier.name +
  1717. " have different types at index %d" +
  1718. " which is before distinguishing" +
  1719. " index %d") % (argCount,
  1720. idx,
  1721. distinguishingIndex))
  1722. # Convert all our arguments up to the distinguishing index.
  1723. # Doesn't matter which of the possible signatures we use, since
  1724. # they all have the same types up to that point; just use
  1725. # possibleSignatures[0]
  1726. caseBody = [CGGeneric("JS::Value* argv_start = JS_ARGV(cx, vp);")]
  1727. caseBody.extend([ CGArgumentConverter(possibleSignatures[0][1][i],
  1728. i, "argv_start", "argc",
  1729. descriptor) for i in
  1730. range(0, distinguishingIndex) ])
  1731. # Select the right overload from our set.
  1732. distinguishingArg = "argv_start[%d]" % distinguishingIndex
  1733. def pickFirstSignature(condition, filterLambda):
  1734. sigs = filter(filterLambda, possibleSignatures)
  1735. assert len(sigs) < 2
  1736. if len(sigs) > 0:
  1737. if condition is None:
  1738. caseBody.append(
  1739. getPerSignatureCall(sigs[0], distinguishingIndex))
  1740. else:
  1741. caseBody.append(CGGeneric("if (" + condition + ") {"))
  1742. caseBody.append(CGIndenter(
  1743. getPerSignatureCall(sigs[0], distinguishingIndex)))
  1744. caseBody.append(CGGeneric("}"))
  1745. return True
  1746. return False
  1747. # First check for null or undefined
  1748. pickFirstSignature("%s.isNullOrUndefined()" % distinguishingArg,
  1749. lambda s: s[1][distinguishingIndex].type.nullable())
  1750. # Now check for distinguishingArg being a platform object.
  1751. # We can actually check separately for array buffers and
  1752. # other things.
  1753. # XXXbz Do we need to worry about security
  1754. # wrappers around the array buffer?
  1755. pickFirstSignature("%s.isObject() && JS_IsArrayBufferObject(&%s.toObject(), cx)" %
  1756. (distinguishingArg, distinguishingArg),
  1757. lambda s: (s[1][distinguishingIndex].type.isArrayBuffer() or
  1758. s[1][distinguishingIndex].type.isObject()))
  1759. interfacesSigs = [
  1760. s for s in possibleSignatures
  1761. if (s[1][distinguishingIndex].type.isObject() or
  1762. (s[1][distinguishingIndex].type.isInterface() and
  1763. not s[1][distinguishingIndex].type.isArrayBuffer() and
  1764. not s[1][distinguishingIndex].type.isCallback())) ]
  1765. # There might be more than one of these; we need to check
  1766. # which ones we unwrap to.
  1767. if len(interfacesSigs) > 0:
  1768. caseBody.append(CGGeneric("if (%s.isObject() &&\n"
  1769. " IsPlatformObject(cx, &%s.toObject())) {" %
  1770. (distinguishingArg, distinguishingArg)))
  1771. for sig in interfacesSigs:
  1772. caseBody.append(CGIndenter(CGGeneric("do {")));
  1773. type = sig[1][distinguishingIndex].type
  1774. # XXXbz this duplicates some argument-unwrapping code!
  1775. interfaceDesc = descriptor.getDescriptor(
  1776. type.unroll().inner.identifier.name)
  1777. argIsPointer = (type.nullable() or
  1778. type.unroll().inner.isExternal())
  1779. if argIsPointer:
  1780. nameSuffix = ""
  1781. else:
  1782. nameSuffix = "_ptr"
  1783. if (interfaceDesc.castable or
  1784. type.unroll().inner.isExternal() or
  1785. interfaceDesc.workers):
  1786. declType = " ${typeName}*"
  1787. else:
  1788. declType = " nsCOMPtr<${typeName}>"
  1789. template = declType + " ${name}%s;\n" % nameSuffix
  1790. if interfaceDesc.castable:
  1791. template += str(CastableObjectUnwrapper(
  1792. interfaceDesc,
  1793. "&${argVal}.toObject()",
  1794. "${name}"+nameSuffix,
  1795. "break;")) + "\n"
  1796. elif interfaceDesc.workers:
  1797. template += """
  1798. ${name}%s = &${argVal}.toObject();
  1799. MOZ_ASSERT(${name}%s);
  1800. """ % (nameSuffix, nameSuffix)
  1801. else:
  1802. template += " xpc_qsSelfRef tmpRef_${name};\n"
  1803. template += " jsval tmpVal_${name} = ${argVal};\n"
  1804. template += """
  1805. ${typeName}* tmp;
  1806. if (NS_FAILED(xpc_qsUnwrapArg<${typeName}>(cx, ${argVal}, &tmp, &tmpRef_${name}.ptr,
  1807. &tmpVal_${name}))) {
  1808. break;
  1809. }
  1810. MOZ_ASSERT(tmp);
  1811. ${name}%s = tmp;
  1812. """ % nameSuffix
  1813. if not argIsPointer:
  1814. template += " ${typeName} &${name} = *${name}_ptr;\n"
  1815. testCode = string.Template(template).substitute(
  1816. {
  1817. "typeName": interfaceDesc.nativeType,
  1818. "name" : "arg%d" % distinguishingIndex,
  1819. "argVal" : distinguishingArg
  1820. }
  1821. )
  1822. caseBody.append(CGIndenter(CGGeneric(testCode)));
  1823. # If we got this far, we know we unwrapped to the right
  1824. # interface, so just do the call. Start conversion with
  1825. # distinguishingIndex + 1, since we already converted
  1826. # distinguishingIndex.
  1827. caseBody.append(CGIndenter(CGIndenter(
  1828. getPerSignatureCall(sig, distinguishingIndex + 1))))
  1829. caseBody.append(CGIndenter(CGGeneric("} while (0);")))
  1830. caseBody.append(CGGeneric("}"))
  1831. # XXXbz Now we're supposed to check for distinguishingArg being
  1832. # an array or a platform object that supports indexed
  1833. # properties... skip that last for now. It's a bit of a pain.
  1834. pickFirstSignature("%s.isObject() && IsArrayLike(cx, &%s.toObject()" %
  1835. (distinguishingArg, distinguishingArg),
  1836. lambda s:
  1837. (s[1][distinguishingIndex].type.isArray() or
  1838. s[1][distinguishingIndex].type.isSequence() or
  1839. s[1][distinguishingIndex].type.isObject()))
  1840. # Check for Date objects
  1841. # XXXbz Do we need to worry about security wrappers around the Date?
  1842. pickFirstSignature("%s.isObject() && JS_ObjectIsDate(cx, &%s.toObject())" %
  1843. (distinguishingArg, distinguishingArg),
  1844. lambda s: (s[1][distinguishingIndex].type.isDate() or
  1845. s[1][distinguishingIndex].type.isObject()))
  1846. # Check for vanilla JS objects
  1847. # XXXbz Do we need to worry about security wrappers?
  1848. pickFirstSignature("%s.isObject() && !IsPlatformObject(cx, &%s.toObject())" %
  1849. (distinguishingArg, distinguishingArg),
  1850. lambda s: (s[1][distinguishingIndex].type.isCallback() or
  1851. s[1][distinguishingIndex].type.isDictionary() or
  1852. s[1][distinguishingIndex].type.isObject()))
  1853. # The remaining cases are mutually exclusive. The
  1854. # pickFirstSignature calls are what change caseBody
  1855. # Check for strings or enums
  1856. if pickFirstSignature(None,
  1857. lambda s: (s[1][distinguishingIndex].type.isString() or
  1858. s[1][distinguishingIndex].type.isEnum())):
  1859. pass
  1860. # Check for primitives
  1861. elif pickFirstSignature(None,
  1862. lambda s: s[1][distinguishingIndex].type.isPrimitive()):
  1863. pass
  1864. # Check for "any"
  1865. elif pickFirstSignature(None,
  1866. lambda s: s[1][distinguishingIndex].type.isAny()):
  1867. pass
  1868. else:
  1869. # Just throw; we have no idea what we're supposed to
  1870. # do with this.
  1871. caseBody.append(CGGeneric("return Throw<%s>(cx, NS_ERROR_XPC_BAD_CONVERT_JS);" %
  1872. toStringBool(not descriptor.workers)))
  1873. argCountCases.append(CGCase(str(argCount),
  1874. CGList(caseBody, "\n")))
  1875. overloadCGThings = []
  1876. overloadCGThings.append(
  1877. CGGeneric("unsigned argcount = NS_MIN(argc, %du);" %
  1878. maxSigArgs))
  1879. overloadCGThings.append(
  1880. CGSwitch("argcount",
  1881. argCountCases,
  1882. CGGeneric("return Throw<%s>(cx, NS_ERROR_XPC_NOT_ENOUGH_ARGS);" %
  1883. toStringBool(not descriptor.workers))))
  1884. overloadCGThings.append(
  1885. CGGeneric('MOZ_NOT_REACHED("We have an always-returning default case");\n'
  1886. 'return false;'))
  1887. self.cgRoot = CGWrapper(CGIndenter(CGList(overloadCGThings, "\n")),
  1888. pre="\n")
  1889. def define(self):
  1890. return self.cgRoot.define()
  1891. class CGGetterSetterCall(CGPerSignatureCall):
  1892. """
  1893. A class to generate a native object getter or setter call for a
  1894. particular IDL getter or setter.
  1895. """
  1896. def __init__(self, returnType, arguments, nativeMethodName, descriptor,
  1897. attr, extendedAttributes):
  1898. CGPerSignatureCall.__init__(self, returnType, "", arguments,
  1899. nativeMethodName, False, descriptor, attr,
  1900. extendedAttributes)
  1901. def getArgv(self):
  1902. if generateNativeAccessors:
  1903. return CGPerSignatureCall.getArgv(self)
  1904. return "vp"
  1905. class CGGetterCall(CGGetterSetterCall):
  1906. """
  1907. A class to generate a native object getter call for a particular IDL
  1908. getter.
  1909. """
  1910. def __init__(self, returnType, nativeMethodName, descriptor, attr,
  1911. extendedAttributes):
  1912. CGGetterSetterCall.__init__(self, returnType, [], nativeMethodName,
  1913. descriptor, attr, extendedAttributes)
  1914. def getArgc(self):
  1915. if generateNativeAccessors:
  1916. return CGGetterSetterCall.getArgc()
  1917. return "0"
  1918. def getArgvDecl(self):
  1919. if generateNativeAccessors:
  1920. return CGPerSignatureCall.getArgvDecl(self)
  1921. # We just get our stuff from vp
  1922. return ""
  1923. class FakeArgument():
  1924. def __init__(self, type):
  1925. self.type = type
  1926. self.optional = False
  1927. class CGSetterCall(CGGetterSetterCall):
  1928. """
  1929. A class to generate a native object setter call for a particular IDL
  1930. setter.
  1931. """
  1932. def __init__(self, argType, nativeMethodName, descriptor, attr,
  1933. extendedAttributes):
  1934. CGGetterSetterCall.__init__(self, None, [FakeArgument(argType)],
  1935. nativeMethodName, descriptor, attr,
  1936. extendedAttributes)
  1937. def wrap_return_value(self):
  1938. if generateNativeAccessors:
  1939. return CGGetterSetterCall.wrap_return_value(self)
  1940. # We have no return value
  1941. return "\nreturn true;"
  1942. def getArgc(self):
  1943. if generateNativeAccessors:
  1944. return CGGetterSetterCall.getArgc(self)
  1945. return "1"
  1946. def getArgvDecl(self):
  1947. if generateNativeAccessors:
  1948. return (CGPerSignatureCall.getArgvDecl(self) +
  1949. "jsval undef = JS::UndefinedValue();\n"
  1950. "if (argc == 0) {\n"
  1951. " argv = &undef;\n"
  1952. " argc = 1;\n"
  1953. "}")
  1954. # We just get our stuff from vp
  1955. return ""
  1956. class CGAbstractBindingMethod(CGAbstractStaticMethod):
  1957. """
  1958. Common class to generate the JSNatives for all our methods, getters, and
  1959. setters. This will generate the function declaration and unwrap the
  1960. |this| object. Subclasses are expected to override the generate_code
  1961. function to do the rest of the work. This function should return a
  1962. CGThing which is already properly indented.
  1963. """
  1964. def __init__(self, descriptor, name, args, extendedAttributes):
  1965. self.extendedAttributes = extendedAttributes
  1966. CGAbstractStaticMethod.__init__(self, descriptor, name, "JSBool", args)
  1967. def definition_body(self):
  1968. unwrapThis = CGGeneric(
  1969. str(FailureFatalCastableObjectUnwrapper(self.descriptor, "obj", "self")))
  1970. return CGList([ self.getThis(), unwrapThis,
  1971. self.generate_code() ], "\n").define()
  1972. def getThis(self):
  1973. return CGIndenter(
  1974. CGGeneric("JSObject* obj = JS_THIS_OBJECT(cx, vp);\n"
  1975. "if (!obj) {\n"
  1976. " return false;\n"
  1977. "}\n"
  1978. "\n"
  1979. "%s* self;" % self.descriptor.nativeType))
  1980. def generate_code(self):
  1981. assert(False) # Override me
  1982. def MakeNativeName(name):
  1983. return name[0].upper() + name[1:]
  1984. class CGNativeMethod(CGAbstractBindingMethod):
  1985. """
  1986. A class for generating the C++ code for an IDL method..
  1987. """
  1988. def __init__(self, descriptor, method):
  1989. self.method = method
  1990. baseName = method.identifier.name
  1991. args = [Argument('JSContext*', 'cx'), Argument('unsigned', 'argc'),
  1992. Argument('JS::Value*', 'vp')]
  1993. CGAbstractBindingMethod.__init__(self, descriptor, baseName, args,
  1994. descriptor.getExtendedAttributes(method))
  1995. def generate_code(self):
  1996. name = self.method.identifier.name
  1997. nativeName = self.descriptor.binaryNames.get(name, MakeNativeName(name))
  1998. return CGMethodCall("", nativeName, self.method.isStatic(),
  1999. self.descriptor, self.method,
  2000. self.extendedAttributes)
  2001. class CGNativeGetter(CGAbstractBindingMethod):
  2002. """
  2003. A class for generating the C++ code for an IDL attribute getter.
  2004. """
  2005. def __init__(self, descriptor, attr):
  2006. self.attr = attr
  2007. name = 'get_' + attr.identifier.name
  2008. if generateNativeAccessors:
  2009. args = [Argument('JSContext*', 'cx'), Argument('unsigned', 'argc'),
  2010. Argument('JS::Value*', 'vp')]
  2011. else:
  2012. args = [Argument('JSContext*', 'cx'), Argument('JSObject*', 'obj'),
  2013. Argument('jsid', 'id'), Argument('JS::Value*', 'vp')]
  2014. CGAbstractBindingMethod.__init__(self, descriptor, name, args,
  2015. descriptor.getExtendedAttributes(self.attr, getter=True))
  2016. def getThis(self):
  2017. if generateNativeAccessors:
  2018. return CGAbstractBindingMethod.getThis(self)
  2019. return CGIndenter(
  2020. CGGeneric("%s* self;" % self.descriptor.nativeType))
  2021. def generate_code(self):
  2022. nativeMethodName = "Get" + MakeNativeName(self.attr.identifier.name)
  2023. return CGIndenter(CGGetterCall(self.attr.type, nativeMethodName, self.descriptor,
  2024. self.attr, self.extendedAttributes))
  2025. class CGNativeSetter(CGAbstractBindingMethod):
  2026. """
  2027. A class for generating the C++ code for an IDL attribute setter.
  2028. """
  2029. def __init__(self, descriptor, attr):
  2030. self.attr = attr
  2031. baseName = attr.identifier.name
  2032. name = 'set_' + attr.identifier.name
  2033. if generateNativeAccessors:
  2034. args = [Argument('JSContext*', 'cx'), Argument('unsigned', 'argc'),
  2035. Argument('JS::Value*', 'vp')]
  2036. else:
  2037. args = [Argument('JSContext*', 'cx'), Argument('JSObject*', 'obj'),
  2038. Argument('jsid', 'id'), Argument('JSBool', 'strict'),
  2039. Argument('JS::Value*', 'vp')]
  2040. CGAbstractBindingMethod.__init__(self, descriptor, name, args,
  2041. descriptor.getExtendedAttributes(self.attr, setter=True))
  2042. def getThis(self):
  2043. if generateNativeAccessors:
  2044. return CGAbstractBindingMethod.getThis(self)
  2045. return CGIndenter(
  2046. CGGeneric("%s* self;" % self.descriptor.nativeType))
  2047. def generate_code(self):
  2048. nativeMethodName = "Set" + MakeNativeName(self.attr.identifier.name)
  2049. return CGIndenter(CGSetterCall(self.attr.type, nativeMethodName, self.descriptor,
  2050. self.attr, self.extendedAttributes))
  2051. def getEnumValueName(value):
  2052. # Some enum values can be empty strings. Others might have weird
  2053. # characters in them. Deal with the former by returning "_empty",
  2054. # deal with possible name collisions from that by throwing if the
  2055. # enum value is actually "_empty", and throw on any value
  2056. # containing chars other than [a-z] or '-' for now. Replace '-' with '_'.
  2057. value = value.replace('-', '_')
  2058. if value == "_empty":
  2059. raise SyntaxError('"_empty" is not an IDL enum value we support yet')
  2060. if value == "":
  2061. return "_empty"
  2062. if not re.match("^[a-z_]+$", value):
  2063. raise SyntaxError('Enum value "' + value + '" contains characters '
  2064. 'outside [a-z_]')
  2065. return value
  2066. class CGEnum(CGThing):
  2067. def __init__(self, enum):
  2068. CGThing.__init__(self)
  2069. self.enum = enum
  2070. def declare(self):
  2071. return """
  2072. enum valuelist {
  2073. %s
  2074. };
  2075. extern const EnumEntry strings[%d];
  2076. """ % (",\n ".join(map(getEnumValueName, self.enum.values())),
  2077. len(self.enum.values()) + 1)
  2078. def define(self):
  2079. return """
  2080. const EnumEntry strings[%d] = {
  2081. %s,
  2082. { NULL, 0 }
  2083. };
  2084. """ % (len(self.enum.values()) + 1,
  2085. ",\n ".join(['{"' + val + '", ' + str(len(val)) + '}' for val in self.enum.values()]))
  2086. class ClassItem:
  2087. """ Use with CGClass """
  2088. def __init__(self, name, visibility):
  2089. self.name = name
  2090. self.visibility = visibility
  2091. def declare(self, cgClass):
  2092. assert False
  2093. def define(self, cgClass):
  2094. assert False
  2095. class ClassBase(ClassItem):
  2096. def __init__(self, name, visibility='public'):
  2097. ClassItem.__init__(self, name, visibility)
  2098. def declare(self, cgClass):
  2099. return '%s %s' % (self.visibility, self.name)
  2100. def define(self, cgClass):
  2101. # Only in the header
  2102. return ''
  2103. class ClassMethod(ClassItem):
  2104. def __init__(self, name, returnType, args, inline=False, static=False,
  2105. virtual=False, const=False, bodyInHeader=False,
  2106. templateArgs=None, visibility='public', body=None):
  2107. self.returnType = returnType
  2108. self.args = args
  2109. self.inline = inline or bodyInHeader
  2110. self.static = static
  2111. self.virtual = virtual
  2112. self.const = const
  2113. self.bodyInHeader = bodyInHeader
  2114. self.templateArgs = templateArgs
  2115. self.body = body
  2116. ClassItem.__init__(self, name, visibility)
  2117. def getDecorators(self, declaring):
  2118. decorators = []
  2119. if self.inline:
  2120. decorators.append('inline')
  2121. if declaring:
  2122. if self.static:
  2123. decorators.append('static')
  2124. if self.virtual:
  2125. decorators.append('virtual')
  2126. if decorators:
  2127. return ' '.join(decorators) + ' '
  2128. return ''
  2129. def getBody(self):
  2130. # Override me or pass a string to constructor
  2131. assert self.body is not None
  2132. return self.body
  2133. def declare(self, cgClass):
  2134. templateClause = 'template <%s>\n' % ', '.join(self.templateArgs) \
  2135. if self.bodyInHeader and self.templateArgs else ''
  2136. args = ', '.join([str(a) for a in self.args])
  2137. if self.bodyInHeader:
  2138. body = ' ' + self.getBody();
  2139. body = body.replace('\n', '\n ').rstrip(' ')
  2140. body = '\n{\n' + body + '\n}'
  2141. else:
  2142. body = ';'
  2143. return string.Template("""${templateClause}${decorators}${returnType}
  2144. ${name}(${args})${const}${body}
  2145. """).substitute({ 'templateClause': templateClause,
  2146. 'decorators': self.getDecorators(True),
  2147. 'returnType': self.returnType,
  2148. 'name': self.name,
  2149. 'const': ' const' if self.const else '',
  2150. 'args': args,
  2151. 'body': body })
  2152. def define(self, cgClass):
  2153. if self.bodyInHeader:
  2154. return ''
  2155. templateArgs = cgClass.templateArgs
  2156. if templateArgs:
  2157. if cgClass.templateSpecialization:
  2158. templateArgs = \
  2159. templateArgs[len(cgClass.templateSpecialization):]
  2160. if templateArgs:
  2161. templateClause = \
  2162. 'template <%s>\n' % ', '.join([str(a) for a in templateArgs])
  2163. else:
  2164. templateClause = ''
  2165. args = ', '.join([str(a) for a in self.args])
  2166. body = ' ' + self.getBody()
  2167. body = body.replace('\n', '\n ').rstrip(' ')
  2168. return string.Template("""${templateClause}${decorators}${returnType}
  2169. ${className}::${name}(${args})${const}
  2170. {
  2171. ${body}
  2172. }\n
  2173. """).substitute({ 'templateClause': templateClause,
  2174. 'decorators': self.getDecorators(False),
  2175. 'returnType': self.returnType,
  2176. 'className': cgClass.getNameString(),
  2177. 'name': self.name,
  2178. 'args': args,
  2179. 'const': ' const' if self.const else '',
  2180. 'body': body })
  2181. class ClassMember(ClassItem):
  2182. def __init__(self, name, type, visibility="private", static=False,
  2183. body=None):
  2184. self.type = type;
  2185. self.static = static
  2186. self.body = body
  2187. ClassItem.__init__(self, name, visibility)
  2188. def getBody(self):
  2189. assert self.body is not None
  2190. return self.body
  2191. def declare(self, cgClass):
  2192. return '%s%s %s;\n' % ('static ' if self.static else '', self.type,
  2193. self.name)
  2194. def define(self, cgClass):
  2195. if not self.static:
  2196. return ''
  2197. return '%s %s::%s = %s;\n' % (self.type, cgClass.getNameString(),
  2198. self.name, self.getBody())
  2199. class ClassTypedef(ClassItem):
  2200. def __init__(self, name, type, visibility="public"):
  2201. self.type = type
  2202. ClassItem.__init__(self, name, visibility)
  2203. def declare(self, cgClass):
  2204. return 'typedef %s %s;\n' % (self.type, self.name)
  2205. def define(self, cgClass):
  2206. # Only goes in the header
  2207. return ''
  2208. class ClassEnum(ClassItem):
  2209. def __init__(self, name, entries, values=None, visibility="public"):
  2210. self.entries = entries
  2211. self.values = values
  2212. ClassItem.__init__(self, name, visibility)
  2213. def declare(self, cgClass):
  2214. entries = []
  2215. for i in range(0, len(self.entries)):
  2216. if i >= len(self.values):
  2217. entry = '%s' % self.entries[i]
  2218. else:
  2219. entry = '%s = %s' % (self.entries[i], self.values[i])
  2220. entries.append(entry)
  2221. name = '' if not self.name else ' ' + self.name
  2222. return 'enum%s\n{\n %s\n};\n' % (name, ',\n '.join(entries))
  2223. def define(self, cgClass):
  2224. # Only goes in the header
  2225. return ''
  2226. class CGClass(CGThing):
  2227. def __init__(self, name, bases=[], members=[], methods=[], typedefs = [],
  2228. enums=[], templateArgs=[], templateSpecialization=[],
  2229. isStruct=False, indent=''):
  2230. CGThing.__init__(self)
  2231. self.name = name
  2232. self.bases = bases
  2233. self.members = members
  2234. self.methods = methods
  2235. self.typedefs = typedefs
  2236. self.enums = enums
  2237. self.templateArgs = templateArgs
  2238. self.templateSpecialization = templateSpecialization
  2239. self.isStruct = isStruct
  2240. self.indent = indent
  2241. self.defaultVisibility ='public' if isStruct else 'private'
  2242. def getNameString(self):
  2243. className = self.name
  2244. if self.templateSpecialization:
  2245. className = className + \
  2246. '<%s>' % ', '.join([str(a) for a
  2247. in self.templateSpecialization])
  2248. return className
  2249. def declare(self):
  2250. result = ''
  2251. if self.templateArgs:
  2252. templateArgs = [str(a) for a in self.templateArgs]
  2253. templateArgs = templateArgs[len(self.templateSpecialization):]
  2254. result = result + self.indent + 'template <%s>\n' \
  2255. % ','.join([str(a) for a in templateArgs])
  2256. type = 'struct' if self.isStruct else 'class'
  2257. if self.templateSpecialization:
  2258. specialization = \
  2259. '<%s>' % ', '.join([str(a) for a in self.templateSpecialization])
  2260. else:
  2261. specialization = ''
  2262. result = result + '%s%s %s%s' \
  2263. % (self.indent, type, self.name, specialization)
  2264. if self.bases:
  2265. result = result + ' : %s' % ', '.join([d.declare(self) for d in self.bases])
  2266. result = result + '\n%s{\n' % self.indent
  2267. def declareMembers(cgClass, memberList, defaultVisibility, itemCount,
  2268. separator=''):
  2269. members = { 'private': [], 'protected': [], 'public': [] }
  2270. for member in memberList:
  2271. members[member.visibility].append(member)
  2272. if defaultVisibility == 'public':
  2273. order = [ 'public', 'protected', 'private' ]
  2274. else:
  2275. order = [ 'private', 'protected', 'public' ]
  2276. result = ''
  2277. lastVisibility = defaultVisibility
  2278. for visibility in order:
  2279. list = members[visibility]
  2280. if list:
  2281. if visibility != lastVisibility:
  2282. if itemCount:
  2283. result = result + '\n'
  2284. result = result + visibility + ':\n'
  2285. itemCount = 0
  2286. for member in list:
  2287. if itemCount == 0:
  2288. result = result + ' '
  2289. else:
  2290. result = result + separator + ' '
  2291. declaration = member.declare(cgClass)
  2292. declaration = declaration.replace('\n', '\n ')
  2293. declaration = declaration.rstrip(' ')
  2294. result = result + declaration
  2295. itemCount = itemCount + 1
  2296. lastVisibility = visibility
  2297. return (result, lastVisibility, itemCount)
  2298. order = [(self.enums, ''), (self.typedefs, ''), (self.members, ''),
  2299. (self.methods, '\n')]
  2300. lastVisibility = self.defaultVisibility
  2301. itemCount = 0
  2302. for (memberList, separator) in order:
  2303. (memberString, lastVisibility, itemCount) = \
  2304. declareMembers(self, memberList, lastVisibility, itemCount,
  2305. separator)
  2306. if self.indent:
  2307. memberString = self.indent + memberString
  2308. memberString = memberString.replace('\n', '\n' + self.indent)
  2309. memberString = memberString.rstrip(' ')
  2310. result = result + memberString
  2311. result = result + self.indent + '};\n\n'
  2312. return result
  2313. def define(self):
  2314. def defineMembers(cgClass, memberList, itemCount, separator=''):
  2315. result = ''
  2316. for member in memberList:
  2317. if itemCount != 0:
  2318. result = result + separator
  2319. result = result + member.define(cgClass)
  2320. itemCount = itemCount + 1
  2321. return (result, itemCount)
  2322. order = [(self.members, '\n'), (self.methods, '\n')]
  2323. result = ''
  2324. itemCount = 0
  2325. for (memberList, separator) in order:
  2326. (memberString, itemCount) = defineMembers(self, memberList,
  2327. itemCount, separator)
  2328. result = result + memberString
  2329. return result
  2330. class CGResolveProperty(CGAbstractMethod):
  2331. def __init__(self, descriptor, properties):
  2332. args = [Argument('JSContext*', 'cx'), Argument('JSObject*', 'wrapper'),
  2333. Argument('jsid', 'id'), Argument('bool', 'set'),
  2334. Argument('JSPropertyDescriptor*', 'desc')]
  2335. CGAbstractMethod.__init__(self, descriptor, "ResolveProperty", "bool", args)
  2336. self.properties = properties
  2337. def definition_body(self):
  2338. str = ""
  2339. varNames = self.properties.variableNames(True)
  2340. methods = self.properties.methods
  2341. if methods.hasNonChromeOnly() or methods.hasChromeOnly():
  2342. str += """ for (size_t i = 0; i < ArrayLength(%(methods)s_ids); ++i) {
  2343. if (id == %(methods)s_ids[i]) {
  2344. JSFunction *fun = JS_NewFunctionById(cx, %(methods)s[i].call, %(methods)s[i].nargs, 0, wrapper, id);
  2345. if (!fun)
  2346. return false;
  2347. JSObject *funobj = JS_GetFunctionObject(fun);
  2348. desc->value.setObject(*funobj);
  2349. desc->attrs = %(methods)s[i].flags;
  2350. desc->obj = wrapper;
  2351. desc->setter = nsnull;
  2352. desc->getter = nsnull;
  2353. return true;
  2354. }
  2355. }
  2356. """ % varNames
  2357. attrs = self.properties.attrs
  2358. if attrs.hasNonChromeOnly() or attrs.hasChromeOnly():
  2359. str += """ for (size_t i = 0; i < ArrayLength(%(attrs)s_ids); ++i) {
  2360. if (id == %(attrs)s_ids[i]) {
  2361. desc->attrs = %(attrs)s[i].flags;
  2362. desc->obj = wrapper;
  2363. desc->setter = %(attrs)s[i].setter;
  2364. desc->getter = %(attrs)s[i].getter;
  2365. return true;
  2366. }
  2367. }
  2368. """ % varNames
  2369. return str + " return true;"
  2370. class CGEnumerateProperties(CGAbstractMethod):
  2371. def __init__(self, descriptor, properties):
  2372. args = [Argument('JS::AutoIdVector&', 'props')]
  2373. CGAbstractMethod.__init__(self, descriptor, "EnumerateProperties", "bool", args)
  2374. self.properties = properties
  2375. def definition_body(self):
  2376. str = ""
  2377. varNames = self.properties.variableNames(True)
  2378. methods = self.properties.methods
  2379. if methods.hasNonChromeOnly() or methods.hasChromeOnly():
  2380. str += """ for (size_t i = 0; i < sizeof(%(methods)s_ids); ++i) {
  2381. if ((%(methods)s[i].flags & JSPROP_ENUMERATE) &&
  2382. !props.append(%(methods)s_ids[i])) {
  2383. return false;
  2384. }
  2385. }
  2386. """ % varNames
  2387. attrs = self.properties.attrs
  2388. if attrs.hasNonChromeOnly() or attrs.hasChromeOnly():
  2389. str += """ for (size_t i = 0; i < sizeof(%(attrs)s_ids); ++i) {
  2390. if ((%(attrs)s[i].flags & JSPROP_ENUMERATE) &&
  2391. !props.append(%(attrs)s_ids[i])) {
  2392. return false;
  2393. }
  2394. }
  2395. """ % varNames
  2396. return str + " return true;"
  2397. class CGPrototypeTraitsClass(CGClass):
  2398. def __init__(self, descriptor, indent=''):
  2399. templateArgs = [Argument('prototypes::ID', 'PrototypeID')]
  2400. templateSpecialization = ['prototypes::id::' + descriptor.name]
  2401. enums = [ClassEnum('', ['Depth'],
  2402. [descriptor.interface.inheritanceDepth()])]
  2403. typedefs = [ClassTypedef('NativeType', descriptor.nativeType)]
  2404. CGClass.__init__(self, 'PrototypeTraits', indent=indent,
  2405. templateArgs=templateArgs,
  2406. templateSpecialization=templateSpecialization,
  2407. enums=enums, typedefs=typedefs, isStruct=True)
  2408. class CGPrototypeIDMapClass(CGClass):
  2409. def __init__(self, descriptor, indent=''):
  2410. templateArgs = [Argument('class', 'ConcreteClass')]
  2411. templateSpecialization = [descriptor.nativeType]
  2412. enums = [ClassEnum('', ['PrototypeID'],
  2413. ['prototypes::id::' + descriptor.name])]
  2414. CGClass.__init__(self, 'PrototypeIDMap', indent=indent,
  2415. templateArgs=templateArgs,
  2416. templateSpecialization=templateSpecialization,
  2417. enums=enums, isStruct=True)
  2418. class CGClassForwardDeclare(CGThing):
  2419. def __init__(self, name, isStruct=False):
  2420. CGThing.__init__(self)
  2421. self.name = name
  2422. self.isStruct = isStruct
  2423. def declare(self):
  2424. type = 'struct' if self.isStruct else 'class'
  2425. return '%s %s;\n' % (type, self.name)
  2426. def define(self):
  2427. # Header only
  2428. return ''
  2429. def stripTrailingWhitespace(text):
  2430. lines = text.splitlines()
  2431. for i in range(len(lines)):
  2432. lines[i] = lines[i].rstrip()
  2433. return '\n'.join(lines)
  2434. class CGDescriptor(CGThing):
  2435. def __init__(self, descriptor):
  2436. CGThing.__init__(self)
  2437. assert not descriptor.concrete or descriptor.interface.hasInterfacePrototypeObject()
  2438. cgThings = []
  2439. if descriptor.interface.hasInterfacePrototypeObject():
  2440. cgThings.extend([CGNativeMethod(descriptor, m) for m in
  2441. descriptor.interface.members if
  2442. m.isMethod() and not m.isStatic()])
  2443. cgThings.extend([CGNativeGetter(descriptor, a) for a in
  2444. descriptor.interface.members if a.isAttr()])
  2445. cgThings.extend([CGNativeSetter(descriptor, a) for a in
  2446. descriptor.interface.members if
  2447. a.isAttr() and not a.readonly])
  2448. if descriptor.concrete:
  2449. if not descriptor.workers:
  2450. cgThings.append(CGAddPropertyHook(descriptor))
  2451. # Always have a finalize hook, regardless of whether the class wants a
  2452. # custom hook.
  2453. if descriptor.nativeIsISupports:
  2454. cgThings.append(CGNativeToSupportsMethod(descriptor))
  2455. cgThings.append(CGClassFinalizeHook(descriptor))
  2456. # Only generate a trace hook if the class wants a custom hook.
  2457. if (descriptor.customTrace):
  2458. cgThings.append(CGClassTraceHook(descriptor))
  2459. if descriptor.concrete or descriptor.interface.hasInterfacePrototypeObject():
  2460. cgThings.append(CGNativePropertyHooks(descriptor))
  2461. if descriptor.concrete:
  2462. cgThings.append(CGDOMJSClass(descriptor))
  2463. if descriptor.interface.hasInterfaceObject():
  2464. cgThings.append(CGClassConstructHook(descriptor))
  2465. cgThings.append(CGClassHasInstanceHook(descriptor))
  2466. cgThings.append(CGInterfaceObjectJSClass(descriptor))
  2467. if descriptor.interface.hasInterfacePrototypeObject():
  2468. cgThings.append(CGPrototypeJSClass(descriptor))
  2469. properties = PropertyArrays(descriptor)
  2470. cgThings.append(CGGeneric(define=str(properties)))
  2471. cgThings.append(CGCreateInterfaceObjectsMethod(descriptor, properties))
  2472. if descriptor.interface.hasInterfacePrototypeObject():
  2473. cgThings.append(CGIndenter(CGGetProtoObjectMethod(descriptor)))
  2474. else:
  2475. cgThings.append(CGIndenter(CGGetConstructorObjectMethod(descriptor)))
  2476. if descriptor.concrete or descriptor.interface.hasInterfacePrototypeObject():
  2477. cgThings.append(CGResolveProperty(descriptor, properties))
  2478. cgThings.append(CGEnumerateProperties(descriptor, properties))
  2479. if descriptor.interface.hasInterfaceObject():
  2480. cgThings.append(CGDefineDOMInterfaceMethod(descriptor))
  2481. if descriptor.concrete:
  2482. cgThings.append(CGWrapMethod(descriptor))
  2483. cgThings = CGList(cgThings)
  2484. cgThings = CGWrapper(cgThings, post='\n')
  2485. self.cgRoot = CGWrapper(CGNamespace(toBindingNamespace(descriptor.name),
  2486. cgThings),
  2487. post='\n')
  2488. def declare(self):
  2489. return self.cgRoot.declare()
  2490. def define(self):
  2491. return self.cgRoot.define()
  2492. class CGNamespacedEnum(CGThing):
  2493. def __init__(self, namespace, enumName, names, values, comment=""):
  2494. if not values:
  2495. values = []
  2496. # Account for explicit enum values.
  2497. entries = []
  2498. for i in range(0, len(names)):
  2499. if len(values) > i and values[i] is not None:
  2500. entry = "%s = %s" % (names[i], values[i])
  2501. else:
  2502. entry = names[i]
  2503. entries.append(entry)
  2504. # Append a Count.
  2505. entries.append('_' + enumName + '_Count')
  2506. # Indent.
  2507. entries = [' ' + e for e in entries]
  2508. # Build the enum body.
  2509. enumstr = comment + 'enum %s\n{\n%s\n};\n' % (enumName, ',\n'.join(entries))
  2510. curr = CGGeneric(declare=enumstr)
  2511. # Add some whitespace padding.
  2512. curr = CGWrapper(curr, pre='\n',post='\n')
  2513. # Add the namespace.
  2514. curr = CGNamespace(namespace, curr)
  2515. # Add the typedef
  2516. typedef = '\ntypedef %s::%s %s;\n\n' % (namespace, enumName, enumName)
  2517. curr = CGList([curr, CGGeneric(declare=typedef)])
  2518. # Save the result.
  2519. self.node = curr
  2520. def declare(self):
  2521. return self.node.declare()
  2522. def define(self):
  2523. assert False # Only for headers.
  2524. class CGRegisterProtos(CGAbstractMethod):
  2525. def __init__(self, config):
  2526. CGAbstractMethod.__init__(self, None, 'Register', 'void',
  2527. [Argument('nsScriptNameSpaceManager*', 'aNameSpaceManager')])
  2528. self.config = config
  2529. def _defineMacro(self):
  2530. return """
  2531. #define REGISTER_PROTO(_dom_class) \\
  2532. aNameSpaceManager->RegisterDefineDOMInterface(NS_LITERAL_STRING(#_dom_class), _dom_class##Binding::DefineDOMInterface);\n\n"""
  2533. def _undefineMacro(self):
  2534. return "\n#undef REGISTER_PROTO"
  2535. def _registerProtos(self):
  2536. lines = ["REGISTER_PROTO(%s);" % desc.name
  2537. for desc in self.config.getDescriptors(hasInterfaceObject=True,
  2538. isExternal=False,
  2539. workers=False)]
  2540. return '\n'.join(lines) + '\n'
  2541. def definition_body(self):
  2542. return self._defineMacro() + self._registerProtos() + self._undefineMacro()
  2543. class CGBindingRoot(CGThing):
  2544. """
  2545. Root codegen class for binding generation. Instantiate the class, and call
  2546. declare or define to generate header or cpp code (respectively).
  2547. """
  2548. def __init__(self, config, prefix, webIDLFile):
  2549. descriptors = config.getDescriptors(webIDLFile=webIDLFile,
  2550. hasInterfaceOrInterfacePrototypeObject=True)
  2551. forwardDeclares = [CGClassForwardDeclare('XPCWrappedNativeScope')]
  2552. for x in descriptors:
  2553. nativeType = x.nativeType
  2554. components = x.nativeType.split('::')
  2555. declare = CGClassForwardDeclare(components[-1])
  2556. if len(components) > 1:
  2557. declare = CGNamespace.build(components[:-1],
  2558. CGWrapper(declare, declarePre='\n',
  2559. declarePost='\n'),
  2560. declareOnly=True)
  2561. forwardDeclares.append(CGWrapper(declare, declarePost='\n'))
  2562. forwardDeclares = CGList(forwardDeclares)
  2563. descriptorsWithPrototype = filter(lambda d: d.interface.hasInterfacePrototypeObject(),
  2564. descriptors)
  2565. traitsClasses = [CGPrototypeTraitsClass(d) for d in descriptorsWithPrototype]
  2566. # We must have a 1:1 mapping here, skip for prototypes that have more
  2567. # than one concrete class implementation.
  2568. traitsClasses.extend([CGPrototypeIDMapClass(d) for d in descriptorsWithPrototype
  2569. if d.uniqueImplementation])
  2570. # Wrap all of that in our namespaces.
  2571. if len(traitsClasses) > 0:
  2572. traitsClasses = CGNamespace.build(['mozilla', 'dom'],
  2573. CGWrapper(CGList(traitsClasses),
  2574. declarePre='\n'),
  2575. declareOnly=True)
  2576. traitsClasses = CGWrapper(traitsClasses, declarePost='\n')
  2577. else:
  2578. traitsClasses = None
  2579. # Do codegen for all the descriptors and enums.
  2580. def makeEnum(e):
  2581. return CGNamespace.build([e.identifier.name + "Values"],
  2582. CGEnum(e))
  2583. def makeEnumTypedef(e):
  2584. return CGGeneric(declare=("typedef %sValues::valuelist %s;\n" %
  2585. (e.identifier.name, e.identifier.name)))
  2586. cgthings = [ fun(e) for e in config.getEnums(webIDLFile)
  2587. for fun in [makeEnum, makeEnumTypedef] ]
  2588. cgthings.extend([CGDescriptor(x) for x in descriptors])
  2589. curr = CGList(cgthings, "\n")
  2590. # Wrap all of that in our namespaces.
  2591. curr = CGNamespace.build(['mozilla', 'dom'],
  2592. CGWrapper(curr, pre="\n"))
  2593. curr = CGList([forwardDeclares,
  2594. CGWrapper(CGGeneric("using namespace mozilla::dom;"),
  2595. defineOnly=True),
  2596. traitsClasses, curr],
  2597. "\n")
  2598. # Add header includes.
  2599. curr = CGHeaders(descriptors,
  2600. ['mozilla/dom/BindingUtils.h',
  2601. 'mozilla/dom/DOMJSClass.h'],
  2602. ['mozilla/dom/Nullable.h',
  2603. 'XPCQuickStubs.h',
  2604. 'AccessCheck.h',
  2605. 'WorkerPrivate.h',
  2606. 'nsContentUtils.h'],
  2607. curr)
  2608. # Add include guards.
  2609. curr = CGIncludeGuard(prefix, curr)
  2610. # Add the auto-generated comment.
  2611. curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT)
  2612. # Store the final result.
  2613. self.root = curr
  2614. def declare(self):
  2615. return stripTrailingWhitespace(self.root.declare())
  2616. def define(self):
  2617. return stripTrailingWhitespace(self.root.define())
  2618. class GlobalGenRoots():
  2619. """
  2620. Roots for global codegen.
  2621. To generate code, call the method associated with the target, and then
  2622. call the appropriate define/declare method.
  2623. """
  2624. @staticmethod
  2625. def PrototypeList(config):
  2626. # Prototype ID enum.
  2627. protos = [d.name for d in config.getDescriptors(hasInterfacePrototypeObject=True)]
  2628. idEnum = CGNamespacedEnum('id', 'ID', protos, [0])
  2629. idEnum = CGList([idEnum])
  2630. idEnum.append(CGGeneric(declare="const unsigned MaxProtoChainLength = " +
  2631. str(config.maxProtoChainLength) + ";\n\n"))
  2632. # Wrap all of that in our namespaces.
  2633. idEnum = CGNamespace.build(['mozilla', 'dom', 'prototypes'],
  2634. CGWrapper(idEnum, pre='\n'))
  2635. idEnum = CGWrapper(idEnum, post='\n')
  2636. curr = CGList([idEnum])
  2637. # Constructor ID enum.
  2638. constructors = [d.name for d in config.getDescriptors(hasInterfaceObject=True,
  2639. hasInterfacePrototypeObject=False)]
  2640. idEnum = CGNamespacedEnum('id', 'ID', constructors, [0])
  2641. # Wrap all of that in our namespaces.
  2642. idEnum = CGNamespace.build(['mozilla', 'dom', 'constructors'],
  2643. CGWrapper(idEnum, pre='\n'))
  2644. idEnum = CGWrapper(idEnum, post='\n')
  2645. curr.append(idEnum)
  2646. traitsDecl = CGGeneric(declare="""
  2647. template <prototypes::ID PrototypeID>
  2648. struct PrototypeTraits;
  2649. template <class ConcreteClass>
  2650. struct PrototypeIDMap;
  2651. """)
  2652. traitsDecl = CGNamespace.build(['mozilla', 'dom'],
  2653. CGWrapper(traitsDecl, post='\n'))
  2654. curr.append(traitsDecl)
  2655. # Add include guards.
  2656. curr = CGIncludeGuard('PrototypeList', curr)
  2657. # Add the auto-generated comment.
  2658. curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT)
  2659. # Done.
  2660. return curr
  2661. @staticmethod
  2662. def RegisterBindings(config):
  2663. # TODO - Generate the methods we want
  2664. curr = CGRegisterProtos(config)
  2665. # Wrap all of that in our namespaces.
  2666. curr = CGNamespace.build(['mozilla', 'dom'],
  2667. CGWrapper(curr, post='\n'))
  2668. curr = CGWrapper(curr, post='\n')
  2669. # Add the includes
  2670. defineIncludes = [CGHeaders.getInterfaceFilename(desc.interface)
  2671. for desc in config.getDescriptors(hasInterfaceObject=True,
  2672. workers=False)]
  2673. defineIncludes.append('nsScriptNameSpaceManager.h')
  2674. curr = CGHeaders([], [], defineIncludes, curr)
  2675. # Add include guards.
  2676. curr = CGIncludeGuard('RegisterBindings', curr)
  2677. # Done.
  2678. return curr