PageRenderTime 121ms CodeModel.GetById 51ms RepoModel.GetById 1ms app.codeStats 0ms

/Packages/SublimeCodeIntel/libs/codeintel2/gencix_utils.py

https://bitbucket.org/luobailiang/sublime-config
Python | 364 lines | 316 code | 4 blank | 44 comment | 1 complexity | 91f3a532d5c6548c17c3a47be1f2cc3a MD5 | raw file
  1. #!/usr/bin/env python
  2. # ***** BEGIN LICENSE BLOCK *****
  3. # Version: MPL 1.1/GPL 2.0/LGPL 2.1
  4. #
  5. # The contents of this file are subject to the Mozilla Public License
  6. # Version 1.1 (the "License"); you may not use this file except in
  7. # compliance with the License. You may obtain a copy of the License at
  8. # http://www.mozilla.org/MPL/
  9. #
  10. # Software distributed under the License is distributed on an "AS IS"
  11. # basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
  12. # License for the specific language governing rights and limitations
  13. # under the License.
  14. #
  15. # The Original Code is Komodo code.
  16. #
  17. # The Initial Developer of the Original Code is ActiveState Software Inc.
  18. # Portions created by ActiveState Software Inc are Copyright (C) 2000-2007
  19. # ActiveState Software Inc. All Rights Reserved.
  20. #
  21. # Contributor(s):
  22. # ActiveState Software Inc
  23. #
  24. # Alternatively, the contents of this file may be used under the terms of
  25. # either the GNU General Public License Version 2 or later (the "GPL"), or
  26. # the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  27. # in which case the provisions of the GPL or the LGPL are applicable instead
  28. # of those above. If you wish to allow use of your version of this file only
  29. # under the terms of either the GPL or the LGPL, and not to allow others to
  30. # use your version of this file under the terms of the MPL, indicate your
  31. # decision by deleting the provisions above and replace them with the notice
  32. # and other provisions required by the GPL or the LGPL. If you do not delete
  33. # the provisions above, a recipient may use your version of this file under
  34. # the terms of any one of the MPL, the GPL or the LGPL.
  35. #
  36. # ***** END LICENSE BLOCK *****
  37. """Shared CIX tools for Code Intelligence
  38. CIX helpers for codeintel creation. Code Intelligence XML format. See:
  39. http://specs.tl.activestate.com/kd/kd-0100.html#xml-based-import-export-syntax-cix
  40. """
  41. import os
  42. import sys
  43. import re
  44. import shutil
  45. from cStringIO import StringIO
  46. import warnings
  47. from ciElementTree import Element, ElementTree, SubElement
  48. from codeintel2.util import parseDocSummary
  49. # Dictionary of known js types and what they map to
  50. known_javascript_types = {
  51. "object": "Object",
  52. "obj": "Object",
  53. "function": "Function",
  54. "array": "Array",
  55. "string": "String",
  56. "text": "String",
  57. "int": "Number",
  58. "integer": "Number",
  59. "number": "Number",
  60. "numeric": "Number",
  61. "decimal": "Number",
  62. "short": "Number",
  63. "unsigned short": "Number",
  64. "long": "Number",
  65. "unsigned long":"Number",
  66. "float": "Number",
  67. "bool": "Boolean",
  68. "boolean": "Boolean",
  69. "true": "Boolean",
  70. "false": "Boolean",
  71. "date": "Date",
  72. "regexp": "RegExp",
  73. # Dom elements
  74. "element": "Element",
  75. "node": "Node",
  76. "domnode": "DOMNode",
  77. "domstring": "DOMString",
  78. "widget": "Widget",
  79. "domwidget": "DOMWidget",
  80. "htmlelement": "HTMLElement",
  81. "xmldocument": "XMLDocument",
  82. "htmldocument": "HTMLDocument",
  83. # Special
  84. "xmlhttprequest": "XMLHttpRequest",
  85. "void": "",
  86. # Mozilla special
  87. "UTF8String": "String",
  88. "AString": "String",
  89. }
  90. def standardizeJSType(vartype):
  91. """Return a standardized name for the given type if it is a known type.
  92. Example1: given vartype of "int", returns "Number"
  93. Example2: given vartype of "YAHOO.tool", returns "YAHOO.tool"
  94. """
  95. if vartype:
  96. typename = known_javascript_types.get(vartype.lower(), None)
  97. if typename is None:
  98. #print "Unknown type: %s" % (vartype)
  99. return vartype
  100. return typename
  101. spacere = re.compile(r'\s+')
  102. def condenseSpaces(s):
  103. """Remove any line enedings and condense multiple spaces"""
  104. s = s.replace("\n", " ")
  105. s = spacere.sub(' ', s)
  106. return s.strip()
  107. def remove_directory(dirpath):
  108. """ Recursively remove the directory path given """
  109. if os.path.exists(dirpath):
  110. shutil.rmtree(dirpath, ignore_errors=True)
  111. def getText(elem):
  112. """Return the internal text for the given ElementTree node"""
  113. l = []
  114. for element in elem.getiterator():
  115. if element.text:
  116. l.append(element.text)
  117. if element.tail:
  118. l.append(element.tail)
  119. return " ".join(l)
  120. def getAllTextFromSubElements(elem, subelementname):
  121. descnodes = elem.findall(subelementname)
  122. if len(descnodes) == 1:
  123. return getText(descnodes[0])
  124. return None
  125. _invalid_char_re = re.compile(u'[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD]')
  126. def strip_invalid_xml_chars(s):
  127. """Return the string with any invalid XML characters removed.
  128. The valid characters are listed here:
  129. http://www.w3.org/TR/REC-xml/#charsets
  130. #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
  131. """
  132. return _invalid_char_re.sub("", s)
  133. def setCixDoc(cixelement, doctext, parse=False):
  134. if parse:
  135. doclines = parseDocSummary(doctext.splitlines(0))
  136. doctext = "\n".join(doclines)
  137. elif sys.platform.startswith("win"):
  138. doctext = doctext.replace("\r\n", "\n")
  139. #TODO: By default clip doc content down to a smaller set -- just
  140. # enough for a good calltip. By then also want an option to
  141. # *not* clip, for use in documentation generation.
  142. #if len(doctext) > 1000:
  143. # warnings.warn("doctext for cixelement: %r has length: %d" % (
  144. # cixelement.get("name"), len(doctext)))
  145. cixelement.attrib["doc"] = strip_invalid_xml_chars(doctext)
  146. def setCixDocFromNodeChildren(cixelement, node, childnodename):
  147. doctext = getAllTextFromSubElements(node, childnodename)
  148. if doctext:
  149. setCixDoc(cixelement, condenseSpaces(doctext), parse=True)
  150. def addCixArgument(cixelement, argname, argtype=None, doc=None):
  151. cixarg = SubElement(cixelement, "variable", ilk="argument", name=argname)
  152. if argtype:
  153. addCixType(cixarg, argtype)
  154. if doc:
  155. setCixDoc(cixarg, doc)
  156. return cixarg
  157. def addCixReturns(cixelement, returntype=None):
  158. if returntype and returntype != "void":
  159. cixelement.attrib["returns"] = returntype
  160. def addCixType(cixobject, vartype):
  161. if vartype:
  162. cixobject.attrib["citdl"] = vartype
  163. def addCixAttribute(cixobject, attribute):
  164. attrs = cixobject.get("attributes")
  165. if attrs:
  166. sp = attrs.split()
  167. if attribute not in sp:
  168. attrs = "%s %s" % (attrs, attribute)
  169. else:
  170. attrs = attribute
  171. cixobject.attrib["attributes"] = attrs
  172. def addClassRef(cixclass, name):
  173. refs = cixclass.get("classrefs", None)
  174. if refs:
  175. if name not in refs.split(" "):
  176. cixclass.attrib["classrefs"] = "%s %s" % (refs, name)
  177. else:
  178. cixclass.attrib["classrefs"] = "%s" % (name)
  179. def addInterfaceRef(cixinterface, name):
  180. refs = cixinterface.get("interfacerefs", None)
  181. if refs:
  182. if name not in refs.split(" "):
  183. cixinterface.attrib["interfacerefs"] = "%s %s" % (refs, name)
  184. else:
  185. cixinterface.attrib["interfacerefs"] = "%s" % (name)
  186. def setCixSignature(cixelement, signature):
  187. cixelement.attrib["signature"] = signature
  188. def createCixVariable(cixobject, name, vartype=None, attributes=None):
  189. if attributes:
  190. v = SubElement(cixobject, "variable", name=name,
  191. attributes=attributes)
  192. else:
  193. v = SubElement(cixobject, "variable", name=name)
  194. if vartype:
  195. addCixType(v, vartype)
  196. return v
  197. def createCixFunction(cixmodule, name, attributes=None):
  198. if attributes:
  199. return SubElement(cixmodule, "scope", ilk="function", name=name,
  200. attributes=attributes)
  201. else:
  202. return SubElement(cixmodule, "scope", ilk="function", name=name)
  203. def createCixInterface(cixmodule, name):
  204. return SubElement(cixmodule, "scope", ilk="interface", name=name)
  205. def createCixClass(cixmodule, name):
  206. return SubElement(cixmodule, "scope", ilk="class", name=name)
  207. def createCixNamespace(cixmodule, name):
  208. return SubElement(cixmodule, "scope", ilk="namespace", name=name)
  209. def createCixModule(cixfile, name, lang, src=None):
  210. if src is None:
  211. return SubElement(cixfile, "scope", ilk="blob", name=name, lang=lang)
  212. else:
  213. return SubElement(cixfile, "scope", ilk="blob", name=name, lang=lang, src=src)
  214. def createOrFindCixModule(cixfile, name, lang, src=None):
  215. for module in cixfile.findall("./scope"):
  216. if module.get("ilk") == "blob" and module.get("name") == name and \
  217. module.get("lang") == lang:
  218. return module
  219. return createCixModule(cixfile, name, lang, src)
  220. def createCixFile(cix, path, lang="JavaScript", mtime="1102379523"):
  221. return SubElement(cix, "file",
  222. lang=lang,
  223. #mtime=mtime,
  224. path=path)
  225. def createCixRoot(version="2.0", name=None, description=None):
  226. cixroot = Element("codeintel", version=version)
  227. if name is not None:
  228. cixroot.attrib["name"] = name
  229. if description is not None:
  230. cixroot.attrib["description"] = description
  231. return cixroot
  232. # Add .text and .tail values to make the CIX output pretty. (Only have
  233. # to avoid "doc" tags: they are the only ones with text content.)
  234. def prettify(elem, level=0, indent=' ', youngestsibling=0):
  235. if elem and elem.tag != "doc":
  236. elem.text = '\n' + (indent*(level+1))
  237. for i in range(len(elem)):
  238. prettify(elem[i], level+1, indent, i==len(elem)-1)
  239. elem.tail = '\n' + (indent*(level-youngestsibling))
  240. def get_cix_string(cix, prettyFormat=True):
  241. # Get the CIX.
  242. if prettyFormat:
  243. prettify(cix)
  244. cixstream = StringIO()
  245. cixtree = ElementTree(cix)
  246. cixstream.write('<?xml version="1.0" encoding="UTF-8"?>\n')
  247. cixtree.write(cixstream)
  248. cixcontent = cixstream.getvalue()
  249. cixstream.close()
  250. return cixcontent
  251. def outline_ci_elem(elem, _lvl=0, brief=False, doSort=False, includeLineNos=False):
  252. """Return an outline of the given codeintel tree element."""
  253. indent = ' '
  254. result = []
  255. def _dump(s):
  256. if includeLineNos:
  257. startline = elem.get("line")
  258. lineend = elem.get("lineend")
  259. line_str = ""
  260. if startline or lineend:
  261. line_str = " (%r-%r)" % (startline, lineend)
  262. result.append(indent*_lvl + s + line_str + '\n')
  263. else:
  264. result.append(indent*_lvl + s + '\n')
  265. if elem.tag == "codeintel":
  266. _lvl -= 1 # don't count this one
  267. elif brief:
  268. name = elem.get("name")
  269. if name:
  270. _dump(name)
  271. elif elem.tag == "file":
  272. lang = elem.get("lang")
  273. _dump("file %(path)s [%(lang)s]" % elem.attrib)
  274. elif elem.tag == "variable":
  275. if elem.get("ilk") == "argument":
  276. s = "arg "+elem.get("name") # skip?
  277. else:
  278. s = "var "+elem.get("name")
  279. if elem.get("citdl"):
  280. s += " [%s]" % elem.get("citdl")
  281. _dump(s)
  282. elif elem.tag == "scope" and elem.get("ilk") == "function" \
  283. and elem.get("signature"):
  284. _dump("function %s" % elem.get("signature").split('\n')[0])
  285. elif elem.tag == "scope" and elem.get("ilk") == "blob":
  286. lang = elem.get("lang")
  287. _dump("blob %(name)s [%(lang)s]" % elem.attrib)
  288. elif elem.tag == "scope" and elem.get("ilk") == "class" \
  289. and elem.get("classrefs"):
  290. _dump("%s %s(%s)" % (elem.get("ilk"), elem.get("name"),
  291. ', '.join(elem.get("classrefs").split())))
  292. elif elem.tag == "scope":
  293. _dump("%s %s" % (elem.get("ilk"), elem.get("name")))
  294. elif elem.tag == "import":
  295. module = elem.get("module")
  296. symbol = elem.get("symbol")
  297. alias = elem.get("alias")
  298. value = "import '%s" % (module, )
  299. if symbol:
  300. value += ".%s" % (symbol, )
  301. value += "'"
  302. if alias:
  303. value +" as %r" % (alias, )
  304. _dump(value)
  305. else:
  306. raise ValueError("unknown tag: %r (%r)" % (elem.tag, elem))
  307. if doSort and hasattr(elem, "names") and elem.names:
  308. for name in sorted(elem.names.keys()):
  309. child = elem.names[name]
  310. result.append(outline_ci_elem(child, _lvl=_lvl+1,
  311. brief=brief, doSort=doSort,
  312. includeLineNos=includeLineNos))
  313. else:
  314. for child in elem:
  315. result.append(outline_ci_elem(child, _lvl=_lvl+1,
  316. brief=brief, doSort=doSort,
  317. includeLineNos=includeLineNos))
  318. return "".join(result)
  319. def remove_cix_line_numbers_from_tree(tree):
  320. for node in tree.getiterator():
  321. node.attrib.pop("line", None)
  322. node.attrib.pop("lineend", None)