xpidl.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  1. #!/usr/bin/env python
  2. # xpidl.py - A parser for cross-platform IDL (XPIDL) files.
  3. #
  4. # This Source Code Form is subject to the terms of the Mozilla Public
  5. # License, v. 2.0. If a copy of the MPL was not distributed with this
  6. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  7. """A parser for cross-platform IDL (XPIDL) files."""
  8. import sys
  9. import os.path
  10. import re
  11. from ply import lex
  12. from ply import yacc
  13. """A type conforms to the following pattern:
  14. def isScriptable(self):
  15. 'returns True or False'
  16. def nativeType(self, calltype):
  17. 'returns a string representation of the native type
  18. calltype must be 'in', 'out', or 'inout'
  19. Interface members const/method/attribute conform to the following pattern:
  20. name = 'string'
  21. def toIDL(self):
  22. 'returns the member signature as IDL'
  23. """
  24. def attlistToIDL(attlist):
  25. if len(attlist) == 0:
  26. return ''
  27. attlist = list(attlist)
  28. attlist.sort(cmp=lambda a, b: cmp(a[0], b[0]))
  29. return '[%s] ' % ','.join(["%s%s" % (name, value is not None and '(%s)' % value or '')
  30. for name, value, aloc in attlist])
  31. _paramsHardcode = {
  32. 2: ('array', 'shared', 'iid_is', 'size_is', 'retval'),
  33. 3: ('array', 'size_is', 'const'),
  34. }
  35. def paramAttlistToIDL(attlist):
  36. if len(attlist) == 0:
  37. return ''
  38. # Hack alert: g_hash_table_foreach is pretty much unimitatable... hardcode
  39. # quirk
  40. attlist = list(attlist)
  41. sorted = []
  42. if len(attlist) in _paramsHardcode:
  43. for p in _paramsHardcode[len(attlist)]:
  44. i = 0
  45. while i < len(attlist):
  46. if attlist[i][0] == p:
  47. sorted.append(attlist[i])
  48. del attlist[i]
  49. continue
  50. i += 1
  51. sorted.extend(attlist)
  52. return '[%s] ' % ', '.join(["%s%s" % (name, value is not None and ' (%s)' % value or '')
  53. for name, value, aloc in sorted])
  54. def unaliasType(t):
  55. while t.kind == 'typedef':
  56. t = t.realtype
  57. assert t is not None
  58. return t
  59. def getBuiltinOrNativeTypeName(t):
  60. t = unaliasType(t)
  61. if t.kind == 'builtin':
  62. return t.name
  63. elif t.kind == 'native':
  64. assert t.specialtype is not None
  65. return '[%s]' % t.specialtype
  66. else:
  67. return None
  68. class BuiltinLocation(object):
  69. def get(self):
  70. return "<builtin type>"
  71. def __str__(self):
  72. return self.get()
  73. class Builtin(object):
  74. kind = 'builtin'
  75. location = BuiltinLocation
  76. def __init__(self, name, nativename, signed=False, maybeConst=False):
  77. self.name = name
  78. self.nativename = nativename
  79. self.signed = signed
  80. self.maybeConst = maybeConst
  81. def isScriptable(self):
  82. return True
  83. def nativeType(self, calltype, shared=False, const=False):
  84. if const:
  85. print >>sys.stderr, IDLError("[const] doesn't make sense on builtin types.", self.location, warning=True)
  86. const = 'const '
  87. elif calltype == 'in' and self.nativename.endswith('*'):
  88. const = 'const '
  89. elif shared:
  90. if not self.nativename.endswith('*'):
  91. raise IDLError("[shared] not applicable to non-pointer types.", self.location)
  92. const = 'const '
  93. else:
  94. const = ''
  95. return "%s%s %s" % (const, self.nativename,
  96. calltype != 'in' and '*' or '')
  97. builtinNames = [
  98. Builtin('boolean', 'bool'),
  99. Builtin('void', 'void'),
  100. Builtin('octet', 'uint8_t'),
  101. Builtin('short', 'int16_t', True, True),
  102. Builtin('long', 'int32_t', True, True),
  103. Builtin('long long', 'int64_t', True, False),
  104. Builtin('unsigned short', 'uint16_t', False, True),
  105. Builtin('unsigned long', 'uint32_t', False, True),
  106. Builtin('unsigned long long', 'uint64_t', False, False),
  107. Builtin('float', 'float', True, False),
  108. Builtin('double', 'double', True, False),
  109. Builtin('char', 'char', True, False),
  110. Builtin('string', 'char *', False, False),
  111. Builtin('wchar', 'char16_t', False, False),
  112. Builtin('wstring', 'char16_t *', False, False),
  113. ]
  114. builtinMap = {}
  115. for b in builtinNames:
  116. builtinMap[b.name] = b
  117. class Location(object):
  118. _line = None
  119. def __init__(self, lexer, lineno, lexpos):
  120. self._lineno = lineno
  121. self._lexpos = lexpos
  122. self._lexdata = lexer.lexdata
  123. self._file = getattr(lexer, 'filename', "<unknown>")
  124. def __eq__(self, other):
  125. return (self._lexpos == other._lexpos and
  126. self._file == other._file)
  127. def resolve(self):
  128. if self._line:
  129. return
  130. startofline = self._lexdata.rfind('\n', 0, self._lexpos) + 1
  131. endofline = self._lexdata.find('\n', self._lexpos, self._lexpos + 80)
  132. self._line = self._lexdata[startofline:endofline]
  133. self._colno = self._lexpos - startofline
  134. def pointerline(self):
  135. def i():
  136. for i in xrange(0, self._colno):
  137. yield " "
  138. yield "^"
  139. return "".join(i())
  140. def get(self):
  141. self.resolve()
  142. return "%s line %s:%s" % (self._file, self._lineno, self._colno)
  143. def __str__(self):
  144. self.resolve()
  145. return "%s line %s:%s\n%s\n%s" % (self._file, self._lineno, self._colno,
  146. self._line, self.pointerline())
  147. class NameMap(object):
  148. """Map of name -> object. Each object must have a .name and .location property.
  149. Setting the same name twice throws an error."""
  150. def __init__(self):
  151. self._d = {}
  152. def __getitem__(self, key):
  153. if key in builtinMap:
  154. return builtinMap[key]
  155. return self._d[key]
  156. def __iter__(self):
  157. return self._d.itervalues()
  158. def __contains__(self, key):
  159. return key in builtinMap or key in self._d
  160. def set(self, object):
  161. if object.name in builtinMap:
  162. raise IDLError("name '%s' is a builtin and cannot be redeclared" % (object.name), object.location)
  163. if object.name.startswith("_"):
  164. object.name = object.name[1:]
  165. if object.name in self._d:
  166. old = self._d[object.name]
  167. if old == object:
  168. return
  169. if isinstance(old, Forward) and isinstance(object, Interface):
  170. self._d[object.name] = object
  171. elif isinstance(old, Interface) and isinstance(object, Forward):
  172. pass
  173. else:
  174. raise IDLError("name '%s' specified twice. Previous location: %s" % (object.name, self._d[object.name].location), object.location)
  175. else:
  176. self._d[object.name] = object
  177. def get(self, id, location):
  178. try:
  179. return self[id]
  180. except KeyError:
  181. raise IDLError("Name '%s' not found", location)
  182. class IDLError(Exception):
  183. def __init__(self, message, location, warning=False):
  184. self.message = message
  185. self.location = location
  186. self.warning = warning
  187. def __str__(self):
  188. return "%s: %s, %s" % (self.warning and 'warning' or 'error',
  189. self.message, self.location)
  190. class Include(object):
  191. kind = 'include'
  192. def __init__(self, filename, location):
  193. self.filename = filename
  194. self.location = location
  195. def __str__(self):
  196. return "".join(["include '%s'\n" % self.filename])
  197. def resolve(self, parent):
  198. def incfiles():
  199. yield self.filename
  200. for dir in parent.incdirs:
  201. yield os.path.join(dir, self.filename)
  202. for file in incfiles():
  203. if not os.path.exists(file):
  204. continue
  205. self.IDL = parent.parser.parse(open(file).read(), filename=file)
  206. self.IDL.resolve(parent.incdirs, parent.parser)
  207. for type in self.IDL.getNames():
  208. parent.setName(type)
  209. parent.deps.extend(self.IDL.deps)
  210. return
  211. raise IDLError("File '%s' not found" % self.filename, self.location)
  212. class IDL(object):
  213. def __init__(self, productions):
  214. self.productions = productions
  215. self.deps = []
  216. def setName(self, object):
  217. self.namemap.set(object)
  218. def getName(self, id, location):
  219. try:
  220. return self.namemap[id]
  221. except KeyError:
  222. raise IDLError("type '%s' not found" % id, location)
  223. def hasName(self, id):
  224. return id in self.namemap
  225. def getNames(self):
  226. return iter(self.namemap)
  227. def __str__(self):
  228. return "".join([str(p) for p in self.productions])
  229. def resolve(self, incdirs, parser):
  230. self.namemap = NameMap()
  231. self.incdirs = incdirs
  232. self.parser = parser
  233. for p in self.productions:
  234. p.resolve(self)
  235. def includes(self):
  236. for p in self.productions:
  237. if p.kind == 'include':
  238. yield p
  239. def needsJSTypes(self):
  240. for p in self.productions:
  241. if p.kind == 'interface' and p.needsJSTypes():
  242. return True
  243. return False
  244. class CDATA(object):
  245. kind = 'cdata'
  246. _re = re.compile(r'\n+')
  247. def __init__(self, data, location):
  248. self.data = self._re.sub('\n', data)
  249. self.location = location
  250. def resolve(self, parent):
  251. pass
  252. def __str__(self):
  253. return "cdata: %s\n\t%r\n" % (self.location.get(), self.data)
  254. def count(self):
  255. return 0
  256. class Typedef(object):
  257. kind = 'typedef'
  258. def __init__(self, type, name, location, doccomments):
  259. self.type = type
  260. self.name = name
  261. self.location = location
  262. self.doccomments = doccomments
  263. def __eq__(self, other):
  264. return self.name == other.name and self.type == other.type
  265. def resolve(self, parent):
  266. parent.setName(self)
  267. self.realtype = parent.getName(self.type, self.location)
  268. def isScriptable(self):
  269. return self.realtype.isScriptable()
  270. def nativeType(self, calltype):
  271. return "%s %s" % (self.name,
  272. calltype != 'in' and '*' or '')
  273. def __str__(self):
  274. return "typedef %s %s\n" % (self.type, self.name)
  275. class Forward(object):
  276. kind = 'forward'
  277. def __init__(self, name, location, doccomments):
  278. self.name = name
  279. self.location = location
  280. self.doccomments = doccomments
  281. def __eq__(self, other):
  282. return other.kind == 'forward' and other.name == self.name
  283. def resolve(self, parent):
  284. # Hack alert: if an identifier is already present, move the doccomments
  285. # forward.
  286. if parent.hasName(self.name):
  287. for i in xrange(0, len(parent.productions)):
  288. if parent.productions[i] is self:
  289. break
  290. for i in xrange(i + 1, len(parent.productions)):
  291. if hasattr(parent.productions[i], 'doccomments'):
  292. parent.productions[i].doccomments[0:0] = self.doccomments
  293. break
  294. parent.setName(self)
  295. def isScriptable(self):
  296. return True
  297. def nativeType(self, calltype):
  298. return "%s %s" % (self.name,
  299. calltype != 'in' and '* *' or '*')
  300. def __str__(self):
  301. return "forward-declared %s\n" % self.name
  302. class Native(object):
  303. kind = 'native'
  304. modifier = None
  305. specialtype = None
  306. specialtypes = {
  307. 'nsid': None,
  308. 'domstring': 'nsAString',
  309. 'utf8string': 'nsACString',
  310. 'cstring': 'nsACString',
  311. 'astring': 'nsAString',
  312. 'jsval': 'JS::Value'
  313. }
  314. def __init__(self, name, nativename, attlist, location):
  315. self.name = name
  316. self.nativename = nativename
  317. self.location = location
  318. for name, value, aloc in attlist:
  319. if value is not None:
  320. raise IDLError("Unexpected attribute value", aloc)
  321. if name in ('ptr', 'ref'):
  322. if self.modifier is not None:
  323. raise IDLError("More than one ptr/ref modifier", aloc)
  324. self.modifier = name
  325. elif name in self.specialtypes.keys():
  326. if self.specialtype is not None:
  327. raise IDLError("More than one special type", aloc)
  328. self.specialtype = name
  329. if self.specialtypes[name] is not None:
  330. self.nativename = self.specialtypes[name]
  331. else:
  332. raise IDLError("Unexpected attribute", aloc)
  333. def __eq__(self, other):
  334. return (self.name == other.name and
  335. self.nativename == other.nativename and
  336. self.modifier == other.modifier and
  337. self.specialtype == other.specialtype)
  338. def resolve(self, parent):
  339. parent.setName(self)
  340. def isScriptable(self):
  341. if self.specialtype is None:
  342. return False
  343. if self.specialtype == 'nsid':
  344. return self.modifier is not None
  345. return self.modifier == 'ref'
  346. def isPtr(self, calltype):
  347. return self.modifier == 'ptr'
  348. def isRef(self, calltype):
  349. return self.modifier == 'ref'
  350. def nativeType(self, calltype, const=False, shared=False):
  351. if shared:
  352. if calltype != 'out':
  353. raise IDLError("[shared] only applies to out parameters.")
  354. const = True
  355. if self.specialtype is not None and calltype == 'in':
  356. const = True
  357. if self.specialtype == 'jsval':
  358. if calltype == 'out' or calltype == 'inout':
  359. return "JS::MutableHandleValue "
  360. return "JS::HandleValue "
  361. if self.isRef(calltype):
  362. m = '& '
  363. elif self.isPtr(calltype):
  364. m = '*' + ((self.modifier == 'ptr' and calltype != 'in') and '*' or '')
  365. else:
  366. m = calltype != 'in' and '*' or ''
  367. return "%s%s %s" % (const and 'const ' or '', self.nativename, m)
  368. def __str__(self):
  369. return "native %s(%s)\n" % (self.name, self.nativename)
  370. class Interface(object):
  371. kind = 'interface'
  372. def __init__(self, name, attlist, base, members, location, doccomments):
  373. self.name = name
  374. self.attributes = InterfaceAttributes(attlist, location)
  375. self.base = base
  376. self.members = members
  377. self.location = location
  378. self.namemap = NameMap()
  379. self.doccomments = doccomments
  380. self.nativename = name
  381. for m in members:
  382. if not isinstance(m, CDATA):
  383. self.namemap.set(m)
  384. def __eq__(self, other):
  385. return self.name == other.name and self.location == other.location
  386. def resolve(self, parent):
  387. self.idl = parent
  388. # Hack alert: if an identifier is already present, libIDL assigns
  389. # doc comments incorrectly. This is quirks-mode extraordinaire!
  390. if parent.hasName(self.name):
  391. for member in self.members:
  392. if hasattr(member, 'doccomments'):
  393. member.doccomments[0:0] = self.doccomments
  394. break
  395. self.doccomments = parent.getName(self.name, None).doccomments
  396. if self.attributes.function:
  397. has_method = False
  398. for member in self.members:
  399. if member.kind is 'method':
  400. if has_method:
  401. raise IDLError("interface '%s' has multiple methods, but marked 'function'" % self.name, self.location)
  402. else:
  403. has_method = True
  404. parent.setName(self)
  405. if self.base is not None:
  406. realbase = parent.getName(self.base, self.location)
  407. if realbase.kind != 'interface':
  408. raise IDLError("interface '%s' inherits from non-interface type '%s'" % (self.name, self.base), self.location)
  409. if self.attributes.scriptable and not realbase.attributes.scriptable:
  410. raise IDLError("interface '%s' is scriptable but derives from non-scriptable '%s'" % (self.name, self.base), self.location, warning=True)
  411. if self.attributes.scriptable and realbase.attributes.builtinclass and not self.attributes.builtinclass:
  412. raise IDLError("interface '%s' is not builtinclass but derives from builtinclass '%s'" % (self.name, self.base), self.location)
  413. for member in self.members:
  414. member.resolve(self)
  415. # The number 250 is NOT arbitrary; this number is the maximum number of
  416. # stub entries defined in xpcom/reflect/xptcall/genstubs.pl
  417. # Do not increase this value without increasing the number in that
  418. # location, or you WILL cause otherwise unknown problems!
  419. if self.countEntries() > 250 and not self.attributes.builtinclass:
  420. raise IDLError("interface '%s' has too many entries" % self.name, self.location)
  421. def isScriptable(self):
  422. # NOTE: this is not whether *this* interface is scriptable... it's
  423. # whether, when used as a type, it's scriptable, which is true of all
  424. # interfaces.
  425. return True
  426. def nativeType(self, calltype, const=False):
  427. return "%s%s %s" % (const and 'const ' or '',
  428. self.name,
  429. calltype != 'in' and '* *' or '*')
  430. def __str__(self):
  431. l = ["interface %s\n" % self.name]
  432. if self.base is not None:
  433. l.append("\tbase %s\n" % self.base)
  434. l.append(str(self.attributes))
  435. if self.members is None:
  436. l.append("\tincomplete type\n")
  437. else:
  438. for m in self.members:
  439. l.append(str(m))
  440. return "".join(l)
  441. def getConst(self, name, location):
  442. # The constant may be in a base class
  443. iface = self
  444. while name not in iface.namemap and iface is not None:
  445. iface = self.idl.getName(self.base, self.location)
  446. if iface is None:
  447. raise IDLError("cannot find symbol '%s'" % name)
  448. c = iface.namemap.get(name, location)
  449. if c.kind != 'const':
  450. raise IDLError("symbol '%s' is not a constant", c.location)
  451. return c.getValue()
  452. def needsJSTypes(self):
  453. for m in self.members:
  454. if m.kind == "attribute" and m.type == "jsval":
  455. return True
  456. if m.kind == "method" and m.needsJSTypes():
  457. return True
  458. return False
  459. def countEntries(self):
  460. ''' Returns the number of entries in the vtable for this interface. '''
  461. total = sum(member.count() for member in self.members)
  462. if self.base is not None:
  463. realbase = self.idl.getName(self.base, self.location)
  464. total += realbase.countEntries()
  465. return total
  466. class InterfaceAttributes(object):
  467. uuid = None
  468. scriptable = False
  469. builtinclass = False
  470. function = False
  471. deprecated = False
  472. noscript = False
  473. main_process_scriptable_only = False
  474. def setuuid(self, value):
  475. self.uuid = value.lower()
  476. def setscriptable(self):
  477. self.scriptable = True
  478. def setfunction(self):
  479. self.function = True
  480. def setnoscript(self):
  481. self.noscript = True
  482. def setbuiltinclass(self):
  483. self.builtinclass = True
  484. def setdeprecated(self):
  485. self.deprecated = True
  486. def setmain_process_scriptable_only(self):
  487. self.main_process_scriptable_only = True
  488. actions = {
  489. 'uuid': (True, setuuid),
  490. 'scriptable': (False, setscriptable),
  491. 'builtinclass': (False, setbuiltinclass),
  492. 'function': (False, setfunction),
  493. 'noscript': (False, setnoscript),
  494. 'deprecated': (False, setdeprecated),
  495. 'object': (False, lambda self: True),
  496. 'main_process_scriptable_only': (False, setmain_process_scriptable_only),
  497. }
  498. def __init__(self, attlist, location):
  499. def badattribute(self):
  500. raise IDLError("Unexpected interface attribute '%s'" % name, location)
  501. for name, val, aloc in attlist:
  502. hasval, action = self.actions.get(name, (False, badattribute))
  503. if hasval:
  504. if val is None:
  505. raise IDLError("Expected value for attribute '%s'" % name,
  506. aloc)
  507. action(self, val)
  508. else:
  509. if val is not None:
  510. raise IDLError("Unexpected value for attribute '%s'" % name,
  511. aloc)
  512. action(self)
  513. if self.uuid is None:
  514. raise IDLError("interface has no uuid", location)
  515. def __str__(self):
  516. l = []
  517. if self.uuid:
  518. l.append("\tuuid: %s\n" % self.uuid)
  519. if self.scriptable:
  520. l.append("\tscriptable\n")
  521. if self.builtinclass:
  522. l.append("\tbuiltinclass\n")
  523. if self.function:
  524. l.append("\tfunction\n")
  525. if self.main_process_scriptable_only:
  526. l.append("\tmain_process_scriptable_only\n")
  527. return "".join(l)
  528. class ConstMember(object):
  529. kind = 'const'
  530. def __init__(self, type, name, value, location, doccomments):
  531. self.type = type
  532. self.name = name
  533. self.value = value
  534. self.location = location
  535. self.doccomments = doccomments
  536. def resolve(self, parent):
  537. self.realtype = parent.idl.getName(self.type, self.location)
  538. self.iface = parent
  539. basetype = self.realtype
  540. while isinstance(basetype, Typedef):
  541. basetype = basetype.realtype
  542. if not isinstance(basetype, Builtin) or not basetype.maybeConst:
  543. raise IDLError("const may only be a short or long type, not %s" % self.type, self.location)
  544. self.basetype = basetype
  545. def getValue(self):
  546. return self.value(self.iface)
  547. def __str__(self):
  548. return "\tconst %s %s = %s\n" % (self.type, self.name, self.getValue())
  549. def count(self):
  550. return 0
  551. class Attribute(object):
  552. kind = 'attribute'
  553. noscript = False
  554. readonly = False
  555. implicit_jscontext = False
  556. nostdcall = False
  557. must_use = False
  558. binaryname = None
  559. null = None
  560. undefined = None
  561. deprecated = False
  562. infallible = False
  563. def __init__(self, type, name, attlist, readonly, location, doccomments):
  564. self.type = type
  565. self.name = name
  566. self.attlist = attlist
  567. self.readonly = readonly
  568. self.location = location
  569. self.doccomments = doccomments
  570. for name, value, aloc in attlist:
  571. if name == 'binaryname':
  572. if value is None:
  573. raise IDLError("binaryname attribute requires a value",
  574. aloc)
  575. self.binaryname = value
  576. continue
  577. if name == 'Null':
  578. if value is None:
  579. raise IDLError("'Null' attribute requires a value", aloc)
  580. if readonly:
  581. raise IDLError("'Null' attribute only makes sense for setters",
  582. aloc)
  583. if value not in ('Empty', 'Null', 'Stringify'):
  584. raise IDLError("'Null' attribute value must be 'Empty', 'Null' or 'Stringify'",
  585. aloc)
  586. self.null = value
  587. elif name == 'Undefined':
  588. if value is None:
  589. raise IDLError("'Undefined' attribute requires a value", aloc)
  590. if readonly:
  591. raise IDLError("'Undefined' attribute only makes sense for setters",
  592. aloc)
  593. if value not in ('Empty', 'Null'):
  594. raise IDLError("'Undefined' attribute value must be 'Empty' or 'Null'",
  595. aloc)
  596. self.undefined = value
  597. else:
  598. if value is not None:
  599. raise IDLError("Unexpected attribute value", aloc)
  600. if name == 'noscript':
  601. self.noscript = True
  602. elif name == 'implicit_jscontext':
  603. self.implicit_jscontext = True
  604. elif name == 'deprecated':
  605. self.deprecated = True
  606. elif name == 'nostdcall':
  607. self.nostdcall = True
  608. elif name == 'must_use':
  609. self.must_use = True
  610. elif name == 'infallible':
  611. self.infallible = True
  612. else:
  613. raise IDLError("Unexpected attribute '%s'" % name, aloc)
  614. def resolve(self, iface):
  615. self.iface = iface
  616. self.realtype = iface.idl.getName(self.type, self.location)
  617. if (self.null is not None and
  618. getBuiltinOrNativeTypeName(self.realtype) != '[domstring]'):
  619. raise IDLError("'Null' attribute can only be used on DOMString",
  620. self.location)
  621. if (self.undefined is not None and
  622. getBuiltinOrNativeTypeName(self.realtype) != '[domstring]'):
  623. raise IDLError("'Undefined' attribute can only be used on DOMString",
  624. self.location)
  625. if self.infallible and not self.realtype.kind == 'builtin':
  626. raise IDLError('[infallible] only works on builtin types '
  627. '(numbers, booleans, and raw char types)',
  628. self.location)
  629. if self.infallible and not iface.attributes.builtinclass:
  630. raise IDLError('[infallible] attributes are only allowed on '
  631. '[builtinclass] interfaces',
  632. self.location)
  633. def toIDL(self):
  634. attribs = attlistToIDL(self.attlist)
  635. readonly = self.readonly and 'readonly ' or ''
  636. return "%s%sattribute %s %s;" % (attribs, readonly, self.type, self.name)
  637. def isScriptable(self):
  638. if not self.iface.attributes.scriptable:
  639. return False
  640. return not self.noscript
  641. def __str__(self):
  642. return "\t%sattribute %s %s\n" % (self.readonly and 'readonly ' or '',
  643. self.type, self.name)
  644. def count(self):
  645. return self.readonly and 1 or 2
  646. class Method(object):
  647. kind = 'method'
  648. noscript = False
  649. notxpcom = False
  650. binaryname = None
  651. implicit_jscontext = False
  652. nostdcall = False
  653. must_use = False
  654. optional_argc = False
  655. deprecated = False
  656. def __init__(self, type, name, attlist, paramlist, location, doccomments, raises):
  657. self.type = type
  658. self.name = name
  659. self.attlist = attlist
  660. self.params = paramlist
  661. self.location = location
  662. self.doccomments = doccomments
  663. self.raises = raises
  664. for name, value, aloc in attlist:
  665. if name == 'binaryname':
  666. if value is None:
  667. raise IDLError("binaryname attribute requires a value",
  668. aloc)
  669. self.binaryname = value
  670. continue
  671. if value is not None:
  672. raise IDLError("Unexpected attribute value", aloc)
  673. if name == 'noscript':
  674. self.noscript = True
  675. elif name == 'notxpcom':
  676. self.notxpcom = True
  677. elif name == 'implicit_jscontext':
  678. self.implicit_jscontext = True
  679. elif name == 'optional_argc':
  680. self.optional_argc = True
  681. elif name == 'deprecated':
  682. self.deprecated = True
  683. elif name == 'nostdcall':
  684. self.nostdcall = True
  685. elif name == 'must_use':
  686. self.must_use = True
  687. else:
  688. raise IDLError("Unexpected attribute '%s'" % name, aloc)
  689. self.namemap = NameMap()
  690. for p in paramlist:
  691. self.namemap.set(p)
  692. def resolve(self, iface):
  693. self.iface = iface
  694. self.realtype = self.iface.idl.getName(self.type, self.location)
  695. for p in self.params:
  696. p.resolve(self)
  697. for p in self.params:
  698. if p.retval and p != self.params[-1]:
  699. raise IDLError("'retval' parameter '%s' is not the last parameter" % p.name, self.location)
  700. if p.size_is:
  701. found_size_param = False
  702. for size_param in self.params:
  703. if p.size_is == size_param.name:
  704. found_size_param = True
  705. if getBuiltinOrNativeTypeName(size_param.realtype) != 'unsigned long':
  706. raise IDLError("is_size parameter must have type 'unsigned long'", self.location)
  707. if not found_size_param:
  708. raise IDLError("could not find is_size parameter '%s'" % p.size_is, self.location)
  709. def isScriptable(self):
  710. if not self.iface.attributes.scriptable:
  711. return False
  712. return not (self.noscript or self.notxpcom)
  713. def __str__(self):
  714. return "\t%s %s(%s)\n" % (self.type, self.name, ", ".join([p.name for p in self.params]))
  715. def toIDL(self):
  716. if len(self.raises):
  717. raises = ' raises (%s)' % ','.join(self.raises)
  718. else:
  719. raises = ''
  720. return "%s%s %s (%s)%s;" % (attlistToIDL(self.attlist),
  721. self.type,
  722. self.name,
  723. ", ".join([p.toIDL()
  724. for p in self.params]),
  725. raises)
  726. def needsJSTypes(self):
  727. if self.implicit_jscontext:
  728. return True
  729. if self.type == "jsval":
  730. return True
  731. for p in self.params:
  732. t = p.realtype
  733. if isinstance(t, Native) and t.specialtype == "jsval":
  734. return True
  735. return False
  736. def count(self):
  737. return 1
  738. class Param(object):
  739. size_is = None
  740. iid_is = None
  741. const = False
  742. array = False
  743. retval = False
  744. shared = False
  745. optional = False
  746. null = None
  747. undefined = None
  748. def __init__(self, paramtype, type, name, attlist, location, realtype=None):
  749. self.paramtype = paramtype
  750. self.type = type
  751. self.name = name
  752. self.attlist = attlist
  753. self.location = location
  754. self.realtype = realtype
  755. for name, value, aloc in attlist:
  756. # Put the value-taking attributes first!
  757. if name == 'size_is':
  758. if value is None:
  759. raise IDLError("'size_is' must specify a parameter", aloc)
  760. self.size_is = value
  761. elif name == 'iid_is':
  762. if value is None:
  763. raise IDLError("'iid_is' must specify a parameter", aloc)
  764. self.iid_is = value
  765. elif name == 'Null':
  766. if value is None:
  767. raise IDLError("'Null' must specify a parameter", aloc)
  768. if value not in ('Empty', 'Null', 'Stringify'):
  769. raise IDLError("'Null' parameter value must be 'Empty', 'Null', or 'Stringify'",
  770. aloc)
  771. self.null = value
  772. elif name == 'Undefined':
  773. if value is None:
  774. raise IDLError("'Undefined' must specify a parameter", aloc)
  775. if value not in ('Empty', 'Null'):
  776. raise IDLError("'Undefined' parameter value must be 'Empty' or 'Null'",
  777. aloc)
  778. self.undefined = value
  779. else:
  780. if value is not None:
  781. raise IDLError("Unexpected value for attribute '%s'" % name,
  782. aloc)
  783. if name == 'const':
  784. self.const = True
  785. elif name == 'array':
  786. self.array = True
  787. elif name == 'retval':
  788. self.retval = True
  789. elif name == 'shared':
  790. self.shared = True
  791. elif name == 'optional':
  792. self.optional = True
  793. else:
  794. raise IDLError("Unexpected attribute '%s'" % name, aloc)
  795. def resolve(self, method):
  796. self.realtype = method.iface.idl.getName(self.type, self.location)
  797. if self.array:
  798. self.realtype = Array(self.realtype)
  799. if (self.null is not None and
  800. getBuiltinOrNativeTypeName(self.realtype) != '[domstring]'):
  801. raise IDLError("'Null' attribute can only be used on DOMString",
  802. self.location)
  803. if (self.undefined is not None and
  804. getBuiltinOrNativeTypeName(self.realtype) != '[domstring]'):
  805. raise IDLError("'Undefined' attribute can only be used on DOMString",
  806. self.location)
  807. def nativeType(self):
  808. kwargs = {}
  809. if self.shared:
  810. kwargs['shared'] = True
  811. if self.const:
  812. kwargs['const'] = True
  813. try:
  814. return self.realtype.nativeType(self.paramtype, **kwargs)
  815. except IDLError, e:
  816. raise IDLError(e.message, self.location)
  817. except TypeError, e:
  818. raise IDLError("Unexpected parameter attribute", self.location)
  819. def toIDL(self):
  820. return "%s%s %s %s" % (paramAttlistToIDL(self.attlist),
  821. self.paramtype,
  822. self.type,
  823. self.name)
  824. class Array(object):
  825. def __init__(self, basetype):
  826. self.type = basetype
  827. def isScriptable(self):
  828. return self.type.isScriptable()
  829. def nativeType(self, calltype, const=False):
  830. return "%s%s*" % (const and 'const ' or '',
  831. self.type.nativeType(calltype))
  832. class IDLParser(object):
  833. keywords = {
  834. 'const': 'CONST',
  835. 'interface': 'INTERFACE',
  836. 'in': 'IN',
  837. 'inout': 'INOUT',
  838. 'out': 'OUT',
  839. 'attribute': 'ATTRIBUTE',
  840. 'raises': 'RAISES',
  841. 'readonly': 'READONLY',
  842. 'native': 'NATIVE',
  843. 'typedef': 'TYPEDEF',
  844. }
  845. tokens = [
  846. 'IDENTIFIER',
  847. 'CDATA',
  848. 'INCLUDE',
  849. 'IID',
  850. 'NUMBER',
  851. 'HEXNUM',
  852. 'LSHIFT',
  853. 'RSHIFT',
  854. 'NATIVEID',
  855. ]
  856. tokens.extend(keywords.values())
  857. states = (
  858. ('nativeid', 'exclusive'),
  859. )
  860. hexchar = r'[a-fA-F0-9]'
  861. t_NUMBER = r'-?\d+'
  862. t_HEXNUM = r'0x%s+' % hexchar
  863. t_LSHIFT = r'<<'
  864. t_RSHIFT = r'>>'
  865. literals = '"(){}[],;:=|+-*'
  866. t_ignore = ' \t'
  867. def t_multilinecomment(self, t):
  868. r'/\*(?s).*?\*/'
  869. t.lexer.lineno += t.value.count('\n')
  870. if t.value.startswith("/**"):
  871. self._doccomments.append(t.value)
  872. def t_singlelinecomment(self, t):
  873. r'(?m)//.*?$'
  874. def t_IID(self, t):
  875. return t
  876. t_IID.__doc__ = r'%(c)s{8}-%(c)s{4}-%(c)s{4}-%(c)s{4}-%(c)s{12}' % {'c': hexchar}
  877. def t_IDENTIFIER(self, t):
  878. r'(unsigned\ long\ long|unsigned\ short|unsigned\ long|long\ long)(?!_?[A-Za-z][A-Za-z_0-9])|_?[A-Za-z][A-Za-z_0-9]*'
  879. t.type = self.keywords.get(t.value, 'IDENTIFIER')
  880. return t
  881. def t_LCDATA(self, t):
  882. r'(?s)%\{[ ]*C\+\+[ ]*\n(?P<cdata>.*?\n?)%\}[ ]*(C\+\+)?'
  883. t.type = 'CDATA'
  884. t.value = t.lexer.lexmatch.group('cdata')
  885. t.lexer.lineno += t.value.count('\n')
  886. return t
  887. def t_INCLUDE(self, t):
  888. r'\#include[ \t]+"[^"\n]+"'
  889. inc, value, end = t.value.split('"')
  890. t.value = value
  891. return t
  892. def t_directive(self, t):
  893. r'\#(?P<directive>[a-zA-Z]+)[^\n]+'
  894. raise IDLError("Unrecognized directive %s" % t.lexer.lexmatch.group('directive'),
  895. Location(lexer=self.lexer, lineno=self.lexer.lineno,
  896. lexpos=self.lexer.lexpos))
  897. def t_newline(self, t):
  898. r'\n+'
  899. t.lexer.lineno += len(t.value)
  900. def t_nativeid_NATIVEID(self, t):
  901. r'[^()\n]+(?=\))'
  902. t.lexer.begin('INITIAL')
  903. return t
  904. t_nativeid_ignore = ''
  905. def t_ANY_error(self, t):
  906. raise IDLError("unrecognized input",
  907. Location(lexer=self.lexer,
  908. lineno=self.lexer.lineno,
  909. lexpos=self.lexer.lexpos))
  910. precedence = (
  911. ('left', '|'),
  912. ('left', 'LSHIFT', 'RSHIFT'),
  913. ('left', '+', '-'),
  914. ('left', '*'),
  915. ('left', 'UMINUS'),
  916. )
  917. def p_idlfile(self, p):
  918. """idlfile : productions"""
  919. p[0] = IDL(p[1])
  920. def p_productions_start(self, p):
  921. """productions : """
  922. p[0] = []
  923. def p_productions_cdata(self, p):
  924. """productions : CDATA productions"""
  925. p[0] = list(p[2])
  926. p[0].insert(0, CDATA(p[1], self.getLocation(p, 1)))
  927. def p_productions_include(self, p):
  928. """productions : INCLUDE productions"""
  929. p[0] = list(p[2])
  930. p[0].insert(0, Include(p[1], self.getLocation(p, 1)))
  931. def p_productions_interface(self, p):
  932. """productions : interface productions
  933. | typedef productions
  934. | native productions"""
  935. p[0] = list(p[2])
  936. p[0].insert(0, p[1])
  937. def p_typedef(self, p):
  938. """typedef : TYPEDEF IDENTIFIER IDENTIFIER ';'"""
  939. p[0] = Typedef(type=p[2],
  940. name=p[3],
  941. location=self.getLocation(p, 1),
  942. doccomments=p.slice[1].doccomments)
  943. def p_native(self, p):
  944. """native : attributes NATIVE IDENTIFIER afternativeid '(' NATIVEID ')' ';'"""
  945. p[0] = Native(name=p[3],
  946. nativename=p[6],
  947. attlist=p[1]['attlist'],
  948. location=self.getLocation(p, 2))
  949. def p_afternativeid(self, p):
  950. """afternativeid : """
  951. # this is a place marker: we switch the lexer into literal identifier
  952. # mode here, to slurp up everything until the closeparen
  953. self.lexer.begin('nativeid')
  954. def p_anyident(self, p):
  955. """anyident : IDENTIFIER
  956. | CONST"""
  957. p[0] = {'value': p[1],
  958. 'location': self.getLocation(p, 1)}
  959. def p_attributes(self, p):
  960. """attributes : '[' attlist ']'
  961. | """
  962. if len(p) == 1:
  963. p[0] = {'attlist': []}
  964. else:
  965. p[0] = {'attlist': p[2],
  966. 'doccomments': p.slice[1].doccomments}
  967. def p_attlist_start(self, p):
  968. """attlist : attribute"""
  969. p[0] = [p[1]]
  970. def p_attlist_continue(self, p):
  971. """attlist : attribute ',' attlist"""
  972. p[0] = list(p[3])
  973. p[0].insert(0, p[1])
  974. def p_attribute(self, p):
  975. """attribute : anyident attributeval"""
  976. p[0] = (p[1]['value'], p[2], p[1]['location'])
  977. def p_attributeval(self, p):
  978. """attributeval : '(' IDENTIFIER ')'
  979. | '(' IID ')'
  980. | """
  981. if len(p) > 1:
  982. p[0] = p[2]
  983. def p_interface(self, p):
  984. """interface : attributes INTERFACE IDENTIFIER ifacebase ifacebody ';'"""
  985. atts, INTERFACE, name, base, body, SEMI = p[1:]
  986. attlist = atts['attlist']
  987. doccomments = []
  988. if 'doccomments' in atts:
  989. doccomments.extend(atts['doccomments'])
  990. doccomments.extend(p.slice[2].doccomments)
  991. l = lambda: self.getLocation(p, 2)
  992. if body is None:
  993. # forward-declared interface... must not have attributes!
  994. if len(attlist) != 0:
  995. raise IDLError("Forward-declared interface must not have attributes",
  996. list[0][3])
  997. if base is not None:
  998. raise IDLError("Forward-declared interface must not have a base",
  999. l())
  1000. p[0] = Forward(name=name, location=l(), doccomments=doccomments)
  1001. else:
  1002. p[0] = Interface(name=name,
  1003. attlist=attlist,
  1004. base=base,
  1005. members=body,
  1006. location=l(),
  1007. doccomments=doccomments)
  1008. def p_ifacebody(self, p):
  1009. """ifacebody : '{' members '}'
  1010. | """
  1011. if len(p) > 1:
  1012. p[0] = p[2]
  1013. def p_ifacebase(self, p):
  1014. """ifacebase : ':' IDENTIFIER
  1015. | """
  1016. if len(p) == 3:
  1017. p[0] = p[2]
  1018. def p_members_start(self, p):
  1019. """members : """
  1020. p[0] = []
  1021. def p_members_continue(self, p):
  1022. """members : member members"""
  1023. p[0] = list(p[2])
  1024. p[0].insert(0, p[1])
  1025. def p_member_cdata(self, p):
  1026. """member : CDATA"""
  1027. p[0] = CDATA(p[1], self.getLocation(p, 1))
  1028. def p_member_const(self, p):
  1029. """member : CONST IDENTIFIER IDENTIFIER '=' number ';' """
  1030. p[0] = ConstMember(type=p[2], name=p[3],
  1031. value=p[5], location=self.getLocation(p, 1),
  1032. doccomments=p.slice[1].doccomments)
  1033. # All "number" products return a function(interface)
  1034. def p_number_decimal(self, p):
  1035. """number : NUMBER"""
  1036. n = int(p[1])
  1037. p[0] = lambda i: n
  1038. def p_number_hex(self, p):
  1039. """number : HEXNUM"""
  1040. n = int(p[1], 16)
  1041. p[0] = lambda i: n
  1042. def p_number_identifier(self, p):
  1043. """number : IDENTIFIER"""
  1044. id = p[1]
  1045. loc = self.getLocation(p, 1)
  1046. p[0] = lambda i: i.getConst(id, loc)
  1047. def p_number_paren(self, p):
  1048. """number : '(' number ')'"""
  1049. p[0] = p[2]
  1050. def p_number_neg(self, p):
  1051. """number : '-' number %prec UMINUS"""
  1052. n = p[2]
  1053. p[0] = lambda i: - n(i)
  1054. def p_number_add(self, p):
  1055. """number : number '+' number
  1056. | number '-' number
  1057. | number '*' number"""
  1058. n1 = p[1]
  1059. n2 = p[3]
  1060. if p[2] == '+':
  1061. p[0] = lambda i: n1(i) + n2(i)
  1062. elif p[2] == '-':
  1063. p[0] = lambda i: n1(i) - n2(i)
  1064. else:
  1065. p[0] = lambda i: n1(i) * n2(i)
  1066. def p_number_shift(self, p):
  1067. """number : number LSHIFT number
  1068. | number RSHIFT number"""
  1069. n1 = p[1]
  1070. n2 = p[3]
  1071. if p[2] == '<<':
  1072. p[0] = lambda i: n1(i) << n2(i)
  1073. else:
  1074. p[0] = lambda i: n1(i) >> n2(i)
  1075. def p_number_bitor(self, p):
  1076. """number : number '|' number"""
  1077. n1 = p[1]
  1078. n2 = p[3]
  1079. p[0] = lambda i: n1(i) | n2(i)
  1080. def p_member_att(self, p):
  1081. """member : attributes optreadonly ATTRIBUTE IDENTIFIER IDENTIFIER ';'"""
  1082. if 'doccomments' in p[1]:
  1083. doccomments = p[1]['doccomments']
  1084. elif p[2] is not None:
  1085. doccomments = p[2]
  1086. else:
  1087. doccomments = p.slice[3].doccomments
  1088. p[0] = Attribute(type=p[4],
  1089. name=p[5],
  1090. attlist=p[1]['attlist'],
  1091. readonly=p[2] is not None,
  1092. location=self.getLocation(p, 3),
  1093. doccomments=doccomments)
  1094. def p_member_method(self, p):
  1095. """member : attributes IDENTIFIER IDENTIFIER '(' paramlist ')' raises ';'"""
  1096. if 'doccomments' in p[1]:
  1097. doccomments = p[1]['doccomments']
  1098. else:
  1099. doccomments = p.slice[2].doccomments
  1100. p[0] = Method(type=p[2],
  1101. name=p[3],
  1102. attlist=p[1]['attlist'],
  1103. paramlist=p[5],
  1104. location=self.getLocation(p, 3),
  1105. doccomments=doccomments,
  1106. raises=p[7])
  1107. def p_paramlist(self, p):
  1108. """paramlist : param moreparams
  1109. | """
  1110. if len(p) == 1:
  1111. p[0] = []
  1112. else:
  1113. p[0] = list(p[2])
  1114. p[0].insert(0, p[1])
  1115. def p_moreparams_start(self, p):
  1116. """moreparams :"""
  1117. p[0] = []
  1118. def p_moreparams_continue(self, p):
  1119. """moreparams : ',' param moreparams"""
  1120. p[0] = list(p[3])
  1121. p[0].insert(0, p[2])
  1122. def p_param(self, p):
  1123. """param : attributes paramtype IDENTIFIER IDENTIFIER"""
  1124. p[0] = Param(paramtype=p[2],
  1125. type=p[3],
  1126. name=p[4],
  1127. attlist=p[1]['attlist'],
  1128. location=self.getLocation(p, 3))
  1129. def p_paramtype(self, p):
  1130. """paramtype : IN
  1131. | INOUT
  1132. | OUT"""
  1133. p[0] = p[1]
  1134. def p_optreadonly(self, p):
  1135. """optreadonly : READONLY
  1136. | """
  1137. if len(p) > 1:
  1138. p[0] = p.slice[1].doccomments
  1139. else:
  1140. p[0] = None
  1141. def p_raises(self, p):
  1142. """raises : RAISES '(' idlist ')'
  1143. | """
  1144. if len(p) == 1:
  1145. p[0] = []
  1146. else:
  1147. p[0] = p[3]
  1148. def p_idlist(self, p):
  1149. """idlist : IDENTIFIER"""
  1150. p[0] = [p[1]]
  1151. def p_idlist_continue(self, p):
  1152. """idlist : IDENTIFIER ',' idlist"""
  1153. p[0] = list(p[3])
  1154. p[0].insert(0, p[1])
  1155. def p_error(self, t):
  1156. if not t:
  1157. raise IDLError("Syntax Error at end of file. Possibly due to missing semicolon(;), braces(}) or both", None)
  1158. else:
  1159. location = Location(self.lexer, t.lineno, t.lexpos)
  1160. raise IDLError("invalid syntax", location)
  1161. def __init__(self, outputdir=''):
  1162. self._doccomments = []
  1163. self.lexer = lex.lex(object=self,
  1164. outputdir=outputdir,
  1165. lextab='xpidllex',
  1166. optimize=1)
  1167. self.parser = yacc.yacc(module=self,
  1168. outputdir=outputdir,
  1169. debug=0,
  1170. tabmodule='xpidlyacc',
  1171. optimize=1)
  1172. def clearComments(self):
  1173. self._doccomments = []
  1174. def token(self):
  1175. t = self.lexer.token()
  1176. if t is not None and t.type != 'CDATA':
  1177. t.doccomments = self._doccomments
  1178. self._doccomments = []
  1179. return t
  1180. def parse(self, data, filename=None):
  1181. if filename is not None:
  1182. self.lexer.filename = filename
  1183. self.lexer.lineno = 1
  1184. self.lexer.input(data)
  1185. idl = self.parser.parse(lexer=self)
  1186. if filename is not None:
  1187. idl.deps.append(filename)
  1188. return idl
  1189. def getLocation(self, p, i):
  1190. return Location(self.lexer, p.lineno(i), p.lexpos(i))
  1191. if __name__ == '__main__':
  1192. p = IDLParser()
  1193. for f in sys.argv[1:]:
  1194. print "Parsing %s" % f
  1195. p.parse(open(f).read(), filename=f)