xpt.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. # ***** BEGIN LICENSE BLOCK *****
  2. # Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3. #
  4. # The contents of this file are subject to the Mozilla Public License Version
  5. # 1.1 (the "License"); you may not use this file except in compliance with
  6. # the License. You may obtain a copy of the License at
  7. # http://www.mozilla.org/MPL/
  8. #
  9. # Software distributed under the License is distributed on an "AS IS" basis,
  10. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11. # for the specific language governing rights and limitations under the
  12. # License.
  13. #
  14. # The Original Code is the Python XPCOM language bindings.
  15. #
  16. # The Initial Developer of the Original Code is
  17. # ActiveState Tool Corp.
  18. # Portions created by the Initial Developer are Copyright (C) 2000, 2001
  19. # the Initial Developer. All Rights Reserved.
  20. #
  21. # Contributor(s):
  22. # David Ascher <DavidA@ActiveState.com> (original author)
  23. # Mark Hammond <mhammond@skippinet.com.au>
  24. #
  25. # Alternatively, the contents of this file may be used under the terms of
  26. # either the GNU General Public License Version 2 or later (the "GPL"), or
  27. # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  28. # in which case the provisions of the GPL or the LGPL are applicable instead
  29. # of those above. If you wish to allow use of your version of this file only
  30. # under the terms of either the GPL or the LGPL, and not to allow others to
  31. # use your version of this file under the terms of the MPL, indicate your
  32. # decision by deleting the provisions above and replace them with the notice
  33. # and other provisions required by the GPL or the LGPL. If you do not delete
  34. # the provisions above, a recipient may use your version of this file under
  35. # the terms of any one of the MPL, the GPL or the LGPL.
  36. #
  37. # ***** END LICENSE BLOCK *****
  38. """
  39. Program: xpt.py
  40. Task: describe interfaces etc using XPCOM reflection.
  41. Subtasks:
  42. output (nearly) exactly the same stuff as xpt_dump, for verification
  43. output Python source code that can be used as a template for an interface
  44. Status: Works pretty well if you ask me :-)
  45. Author:
  46. David Ascher did an original version that parsed XPT files
  47. directly. Mark Hammond changed it to use the reflection interfaces,
  48. but kept most of the printing logic.
  49. Revision:
  50. 0.1: March 6, 2000
  51. 0.2: April 2000 - Mark removed lots of Davids lovely parsing code in favour
  52. of the new xpcom interfaces that provide this info.
  53. May 2000 - Moved into Perforce - track the log there!
  54. Early 2001 - Moved into the Mozilla CVS tree - track the log there!
  55. Todo:
  56. Fill out this todo list.
  57. """
  58. import string, sys
  59. import xpcom
  60. import xpcom._xpcom
  61. from xpcom_consts import *
  62. class Interface:
  63. def __init__(self, iid):
  64. iim = xpcom._xpcom.XPTI_GetInterfaceInfoManager()
  65. if isinstance(iid, basestring):
  66. item = iim.GetInfoForName(iid)
  67. else:
  68. item = iim.GetInfoForIID(iid)
  69. self.interface_info = item
  70. self.namespace = "" # where does this come from?
  71. self.methods = Methods(item)
  72. self.constants = Constants(item)
  73. # delegate attributes to the real interface
  74. def __getattr__(self, attr):
  75. return getattr(self.interface_info, attr)
  76. def GetParent(self):
  77. try:
  78. raw_parent = self.interface_info.GetParent()
  79. if raw_parent is None:
  80. return None
  81. return Interface(raw_parent.GetIID())
  82. except xpcom.Exception:
  83. # Parent interface is probably not scriptable - assume nsISupports.
  84. if xpcom.verbose:
  85. # The user may be confused as to why this is happening!
  86. print "The parent interface of IID '%s' can not be located - assuming nsISupports"
  87. return Interface(xpcom._xpcom.IID_nsISupports)
  88. def Describe_Python(self):
  89. method_reprs = []
  90. methods = filter(lambda m: not m.IsNotXPCOM(), self.methods)
  91. for m in methods:
  92. method_reprs.append(m.Describe_Python())
  93. method_joiner = "\n"
  94. methods_repr = method_joiner.join(method_reprs)
  95. return \
  96. """from xpcom import ServerException, nsError
  97. class %s:
  98. _com_interfaces_ = xpcom.components.interfaces.%s
  99. # If this object needs to be registered, the following 2 are also needed.
  100. # _reg_clsid_ = "{a new clsid generated for this object}"
  101. # _reg_contractid_ = "@providername.org/object-name;1"\n%s""" % (self.GetName(), self.GetIID().name, methods_repr)
  102. def Describe(self):
  103. # Make the IID look like xtp_dump - "(" instead of "{"
  104. iid_use = "(" + str(self.GetIID())[1:-1] + ")"
  105. s = ' - '+self.namespace+'::'+ self.GetName() + ' ' + iid_use + ':\n'
  106. parent = self.GetParent()
  107. if parent is not None:
  108. s = s + ' Parent: ' + parent.namespace + '::' + parent.GetName() + '\n'
  109. s = s + ' Flags:\n'
  110. if self.IsScriptable(): word = 'TRUE'
  111. else: word = 'FALSE'
  112. s = s + ' Scriptable: ' + word + '\n'
  113. s = s + ' Methods:\n'
  114. methods = filter(lambda m: not m.IsNotXPCOM(), self.methods)
  115. if len(methods):
  116. for m in methods:
  117. s = s + ' ' + m.Describe() + '\n'
  118. else:
  119. s = s + ' No Methods\n'
  120. s = s + ' Constants:\n'
  121. if self.constants:
  122. for c in self.constants:
  123. s = s + ' ' + c.Describe() + '\n'
  124. else:
  125. s = s + ' No Constants\n'
  126. return s
  127. # A class that allows caching and iterating of methods.
  128. class Methods:
  129. def __init__(self, interface_info):
  130. self.interface_info = interface_info
  131. try:
  132. self.items = [None] * interface_info.GetMethodCount()
  133. except xpcom.Exception:
  134. if xpcom.verbose:
  135. print "** GetMethodCount failed?? - assuming no methods"
  136. self.items = []
  137. def __len__(self):
  138. return len(self.items)
  139. def __getitem__(self, index):
  140. ret = self.items[index]
  141. if ret is None:
  142. mi = self.interface_info.GetMethodInfo(index)
  143. ret = self.items[index] = Method(mi, index, self.interface_info)
  144. return ret
  145. class Method:
  146. def __init__(self, method_info, method_index, interface_info = None):
  147. self.interface_info = interface_info
  148. self.method_index = method_index
  149. self.flags, self.name, param_descs, self.result_desc = method_info
  150. # Build the params.
  151. self.params = []
  152. pi=0
  153. for pd in param_descs:
  154. self.params.append( Parameter(pd, pi, method_index, interface_info) )
  155. pi = pi + 1
  156. # Run over the params setting the "sizeof" params to hidden.
  157. for p in self.params:
  158. td = p.type_desc
  159. tag = XPT_TDP_TAG(td[0])
  160. if tag==T_ARRAY and p.IsIn():
  161. self.params[td[1]].hidden_indicator = 2
  162. elif tag in [T_PSTRING_SIZE_IS, T_PWSTRING_SIZE_IS] and p.IsIn():
  163. self.params[td[1]].hidden_indicator = 1
  164. def IsGetter(self):
  165. return (self.flags & XPT_MD_GETTER)
  166. def IsSetter(self):
  167. return (self.flags & XPT_MD_SETTER)
  168. def IsNotXPCOM(self):
  169. return (self.flags & XPT_MD_NOTXPCOM)
  170. def IsConstructor(self):
  171. return (self.flags & XPT_MD_CTOR)
  172. def IsHidden(self):
  173. return (self.flags & XPT_MD_HIDDEN)
  174. def Describe_Python(self):
  175. if self.method_index < 3: # Ignore QI etc
  176. return ""
  177. base_name = self.name
  178. if self.IsGetter():
  179. name = "get_%s" % (base_name,)
  180. elif self.IsSetter():
  181. name = "set_%s" % (base_name,)
  182. else:
  183. name = base_name
  184. param_decls = ["self"]
  185. in_comments = []
  186. out_descs = []
  187. result_comment = "Result: void - None"
  188. for p in self.params:
  189. in_desc, in_desc_comments, out_desc, this_result_comment = p.Describe_Python()
  190. if in_desc is not None:
  191. param_decls.append(in_desc)
  192. if in_desc_comments is not None:
  193. in_comments.append(in_desc_comments)
  194. if out_desc is not None:
  195. out_descs.append(out_desc)
  196. if this_result_comment is not None:
  197. result_comment = this_result_comment
  198. joiner = "\n # "
  199. in_comment = out_desc = ""
  200. if in_comments: in_comment = joiner + joiner.join(in_comments)
  201. if out_descs: out_desc = joiner + joiner.join(out_descs)
  202. return """ def %s( %s ):
  203. # %s%s%s
  204. raise ServerException(nsError.NS_ERROR_NOT_IMPLEMENTED)""" % (name, ", ".join(param_decls), result_comment, in_comment, out_desc)
  205. def Describe(self):
  206. s = ''
  207. if self.IsGetter():
  208. G = 'G'
  209. else:
  210. G = ' '
  211. if self.IsSetter():
  212. S = 'S'
  213. else: S = ' '
  214. if self.IsHidden():
  215. H = 'H'
  216. else:
  217. H = ' '
  218. if self.IsNotXPCOM():
  219. N = 'N'
  220. else:
  221. N = ' '
  222. if self.IsConstructor():
  223. C = 'C'
  224. else:
  225. C = ' '
  226. def desc(a): return a.Describe()
  227. method_desc = string.join(map(desc, self.params), ', ')
  228. result_type = TypeDescriber(self.result_desc[0], None)
  229. return_desc = result_type.Describe()
  230. i = string.find(return_desc, 'retval ')
  231. if i != -1:
  232. return_desc = return_desc[:i] + return_desc[i+len('retval '):]
  233. return G+S+H+N+C+' '+return_desc+' '+self.name + '('+ method_desc + ');'
  234. class Parameter:
  235. def __init__(self, param_desc, param_index, method_index, interface_info = None):
  236. self.param_flags, self.type_desc = param_desc
  237. self.hidden_indicator = 0 # Is this a special "size" type param that will be hidden from Python?
  238. self.param_index = param_index
  239. self.method_index= method_index
  240. self.interface_info = interface_info
  241. def __repr__(self):
  242. return "<param %(param_index)d (method %(method_index)d) - flags = 0x%(param_flags)x, type = %(type_desc)s>" % self.__dict__
  243. def IsIn(self):
  244. return XPT_PD_IS_IN(self.param_flags)
  245. def IsOut(self):
  246. return XPT_PD_IS_OUT(self.param_flags)
  247. def IsInOut(self):
  248. return self.IsIn() and self.IsOut()
  249. def IsRetval(self):
  250. return XPT_PD_IS_RETVAL(self.param_flags)
  251. def IsShared(self):
  252. return XPT_PD_IS_SHARED(self.param_flags)
  253. def IsDipper(self):
  254. return XPT_PD_IS_DIPPER(self.param_flags)
  255. def IsOptional(self):
  256. return XPT_PD_IS_OPTIONAL(self.param_flags)
  257. def Describe_Python(self):
  258. name = "param%d" % (self.param_index,)
  259. if self.hidden_indicator:
  260. # Could remove the comment - Im trying to tell the user where that param has
  261. # gone from the signature!
  262. return None, "%s is a hidden parameter" % (name,), None, None
  263. t = TypeDescriber(self.type_desc[0], self)
  264. decl = in_comment = out_comment = result_comment = None
  265. type_desc = t.Describe()
  266. if self.IsIn() and not self.IsDipper():
  267. decl = name
  268. extra=""
  269. if self.IsOut():
  270. extra = "Out"
  271. in_comment = "In%s: %s: %s" % (extra, name, type_desc)
  272. elif self.IsOut() or self.IsDipper():
  273. if self.IsRetval():
  274. result_comment = "Result: %s" % (type_desc,)
  275. else:
  276. out_comment = "Out: %s" % (type_desc,)
  277. return decl, in_comment, out_comment, result_comment
  278. def Describe(self):
  279. parts = []
  280. if self.IsOptional():
  281. parts.append('optional')
  282. if self.IsInOut():
  283. parts.append('inout')
  284. elif self.IsIn():
  285. parts.append('in')
  286. elif self.IsOut():
  287. parts.append('out')
  288. if self.IsDipper(): parts.append("dipper")
  289. if self.IsRetval(): parts.append('retval')
  290. if self.IsShared(): parts.append('shared')
  291. t = TypeDescriber(self.type_desc[0], self)
  292. type_str = t.Describe()
  293. parts.append(type_str)
  294. return string.join(parts)
  295. # A class that allows caching and iterating of constants.
  296. class Constants:
  297. def __init__(self, interface_info):
  298. self.interface_info = interface_info
  299. try:
  300. self.items = [None] * interface_info.GetConstantCount()
  301. except xpcom.Exception:
  302. if xpcom.verbose:
  303. print "** GetConstantCount failed?? - assuming no constants"
  304. self.items = []
  305. def __len__(self):
  306. return len(self.items)
  307. def __getitem__(self, index):
  308. ret = self.items[index]
  309. if ret is None:
  310. ci = self.interface_info.GetConstant(index)
  311. ret = self.items[index] = Constant(ci)
  312. return ret
  313. class Constant:
  314. def __init__(self, ci):
  315. self.name, self.type, self.value = ci
  316. def Describe(self):
  317. return TypeDescriber(self.type, None).Describe() + ' ' +self.name+' = '+str(self.value)+';'
  318. __str__ = Describe
  319. def MakeReprForInvoke(param):
  320. tag = param.type_desc[0] & XPT_TDP_TAGMASK
  321. if tag == T_INTERFACE:
  322. i_info = param.interface_info
  323. try:
  324. iid = i_info.GetIIDForParam(param.method_index, param.param_index)
  325. except xpcom.Exception:
  326. # IID not available (probably not scriptable) - just use nsISupports.
  327. iid = xpcom._xpcom.IID_nsISupports
  328. return param.type_desc[0], 0, 0, str(iid)
  329. elif tag == T_ARRAY:
  330. i_info = param.interface_info
  331. array_desc = i_info.GetTypeForParam(param.method_index, param.param_index, 1)
  332. if XPT_TDP_TAG(array_desc[0]) in (T_INTERFACE, T_INTERFACE_IS):
  333. iid = str(i_info.GetIIDForParam(param.method_index, param.param_index))
  334. else:
  335. iid = None
  336. return param.type_desc[:-1] + (iid, array_desc[0])
  337. return param.type_desc
  338. class TypeDescriber:
  339. def __init__(self, type_flags, param):
  340. self.type_flags = type_flags
  341. self.tag = XPT_TDP_TAG(self.type_flags)
  342. self.param = param
  343. def IsPointer(self):
  344. return XPT_TDP_IS_POINTER(self.type_flags)
  345. def IsUniquePointer(self):
  346. return XPT_TDP_IS_UNIQUE_POINTER(self.type_flags)
  347. def IsReference(self):
  348. return XPT_TDP_IS_REFERENCE(self.type_flags)
  349. def repr_for_invoke(self):
  350. return (self.type_flags,)
  351. def GetName(self):
  352. is_ptr = self.IsPointer()
  353. data = type_info_map.get(self.tag)
  354. if data is None:
  355. data = ("unknown",)
  356. if self.IsReference():
  357. if len(data) > 2:
  358. return data[2]
  359. return data[0] + " &"
  360. if self.IsPointer():
  361. if len(data)>1:
  362. return data[1]
  363. return data[0] + " *"
  364. return data[0]
  365. def Describe(self):
  366. if self.tag == T_ARRAY:
  367. # NOTE - Adding a type specifier to the array is different from xpt_dump.exe
  368. if self.param is None or self.param.interface_info is None:
  369. type_desc = "" # Don't have explicit info about the array type :-(
  370. else:
  371. i_info = self.param.interface_info
  372. type_code = i_info.GetTypeForParam(self.param.method_index, self.param.param_index, 1)
  373. type_desc = TypeDescriber( type_code[0], None).Describe()
  374. return self.GetName() + "[" + type_desc + "]"
  375. elif self.tag == T_INTERFACE:
  376. if self.param is None or self.param.interface_info is None:
  377. return "nsISomething" # Don't have explicit info about the IID :-(
  378. i_info = self.param.interface_info
  379. m_index = self.param.method_index
  380. p_index = self.param.param_index
  381. try:
  382. iid = i_info.GetIIDForParam(m_index, p_index)
  383. return iid.name
  384. except xpcom.Exception:
  385. return "nsISomething"
  386. return self.GetName()
  387. # These are just for output purposes, so should be
  388. # the same as xpt_dump uses
  389. type_info_map = {
  390. T_I8 : ("int8",),
  391. T_I16 : ("int16",),
  392. T_I32 : ("int32",),
  393. T_I64 : ("int64",),
  394. T_U8 : ("uint8",),
  395. T_U16 : ("uint16",),
  396. T_U32 : ("uint32",),
  397. T_U64 : ("uint64",),
  398. T_FLOAT : ("float",),
  399. T_DOUBLE : ("double",),
  400. T_BOOL : ("boolean",),
  401. T_CHAR : ("char",),
  402. T_WCHAR : ("wchar_t", "wstring"),
  403. T_VOID : ("void",),
  404. T_IID : ("reserved", "nsIID *", "nsIID &"),
  405. T_DOMSTRING : ("DOMString",),
  406. T_CHAR_STR : ("reserved", "string"),
  407. T_WCHAR_STR : ("reserved", "wstring"),
  408. T_INTERFACE : ("reserved", "Interface"),
  409. T_INTERFACE_IS : ("reserved", "InterfaceIs *"),
  410. T_ARRAY : ("reserved", "Array"),
  411. T_PSTRING_SIZE_IS : ("string", "string_s"),
  412. T_PWSTRING_SIZE_IS : ("unicode", "wstring_s"),
  413. T_UTF8STRING : ("utf8string", "utf8string"),
  414. T_CSTRING : ("string", "cstring"),
  415. T_ASTRING : ("unicode", "astring"),
  416. }
  417. def dump_interface(iid, mode):
  418. interface = Interface(iid)
  419. describer_name = "Describe"
  420. if mode == "xptinfo": mode = None
  421. if mode is not None:
  422. describer_name = describer_name + "_" + mode.capitalize()
  423. describer = getattr(interface, describer_name)
  424. print describer()
  425. if __name__=='__main__':
  426. if len(sys.argv) == 1:
  427. print "Usage: xpt.py [-xptinfo] interface_name, ..."
  428. print " -info: Dump in a style similar to the xptdump tool"
  429. print "Dumping nsISupports and nsIInterfaceInfo"
  430. sys.argv.append('nsIInterfaceInfo')
  431. sys.argv.append('-xptinfo')
  432. sys.argv.append('nsISupports')
  433. sys.argv.append('nsIInterfaceInfo')
  434. mode = "Python"
  435. for i in sys.argv[1:]:
  436. if i[0] == "-":
  437. mode = i[1:]
  438. else:
  439. dump_interface(i, mode)