PageRenderTime 72ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/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

Large files files are truncated, but you can click here to view the full file

  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"

Large files files are truncated, but you can click here to view the full file