/Lib/idlelib/HyperParser.py

http://unladen-swallow.googlecode.com/ · Python · 241 lines · 145 code · 27 blank · 69 comment · 54 complexity · 3b940280741b91c8bec47d750da6d6c0 MD5 · raw file

  1. """
  2. HyperParser
  3. ===========
  4. This module defines the HyperParser class, which provides advanced parsing
  5. abilities for the ParenMatch and other extensions.
  6. The HyperParser uses PyParser. PyParser is intended mostly to give information
  7. on the proper indentation of code. HyperParser gives some information on the
  8. structure of code, used by extensions to help the user.
  9. """
  10. import string
  11. import keyword
  12. import PyParse
  13. class HyperParser:
  14. def __init__(self, editwin, index):
  15. """Initialize the HyperParser to analyze the surroundings of the given
  16. index.
  17. """
  18. self.editwin = editwin
  19. self.text = text = editwin.text
  20. parser = PyParse.Parser(editwin.indentwidth, editwin.tabwidth)
  21. def index2line(index):
  22. return int(float(index))
  23. lno = index2line(text.index(index))
  24. if not editwin.context_use_ps1:
  25. for context in editwin.num_context_lines:
  26. startat = max(lno - context, 1)
  27. startatindex = `startat` + ".0"
  28. stopatindex = "%d.end" % lno
  29. # We add the newline because PyParse requires a newline at end.
  30. # We add a space so that index won't be at end of line, so that
  31. # its status will be the same as the char before it, if should.
  32. parser.set_str(text.get(startatindex, stopatindex)+' \n')
  33. bod = parser.find_good_parse_start(
  34. editwin._build_char_in_string_func(startatindex))
  35. if bod is not None or startat == 1:
  36. break
  37. parser.set_lo(bod or 0)
  38. else:
  39. r = text.tag_prevrange("console", index)
  40. if r:
  41. startatindex = r[1]
  42. else:
  43. startatindex = "1.0"
  44. stopatindex = "%d.end" % lno
  45. # We add the newline because PyParse requires a newline at end.
  46. # We add a space so that index won't be at end of line, so that
  47. # its status will be the same as the char before it, if should.
  48. parser.set_str(text.get(startatindex, stopatindex)+' \n')
  49. parser.set_lo(0)
  50. # We want what the parser has, except for the last newline and space.
  51. self.rawtext = parser.str[:-2]
  52. # As far as I can see, parser.str preserves the statement we are in,
  53. # so that stopatindex can be used to synchronize the string with the
  54. # text box indices.
  55. self.stopatindex = stopatindex
  56. self.bracketing = parser.get_last_stmt_bracketing()
  57. # find which pairs of bracketing are openers. These always correspond
  58. # to a character of rawtext.
  59. self.isopener = [i>0 and self.bracketing[i][1] > self.bracketing[i-1][1]
  60. for i in range(len(self.bracketing))]
  61. self.set_index(index)
  62. def set_index(self, index):
  63. """Set the index to which the functions relate. Note that it must be
  64. in the same statement.
  65. """
  66. indexinrawtext = \
  67. len(self.rawtext) - len(self.text.get(index, self.stopatindex))
  68. if indexinrawtext < 0:
  69. raise ValueError("The index given is before the analyzed statement")
  70. self.indexinrawtext = indexinrawtext
  71. # find the rightmost bracket to which index belongs
  72. self.indexbracket = 0
  73. while self.indexbracket < len(self.bracketing)-1 and \
  74. self.bracketing[self.indexbracket+1][0] < self.indexinrawtext:
  75. self.indexbracket += 1
  76. if self.indexbracket < len(self.bracketing)-1 and \
  77. self.bracketing[self.indexbracket+1][0] == self.indexinrawtext and \
  78. not self.isopener[self.indexbracket+1]:
  79. self.indexbracket += 1
  80. def is_in_string(self):
  81. """Is the index given to the HyperParser is in a string?"""
  82. # The bracket to which we belong should be an opener.
  83. # If it's an opener, it has to have a character.
  84. return self.isopener[self.indexbracket] and \
  85. self.rawtext[self.bracketing[self.indexbracket][0]] in ('"', "'")
  86. def is_in_code(self):
  87. """Is the index given to the HyperParser is in a normal code?"""
  88. return not self.isopener[self.indexbracket] or \
  89. self.rawtext[self.bracketing[self.indexbracket][0]] not in \
  90. ('#', '"', "'")
  91. def get_surrounding_brackets(self, openers='([{', mustclose=False):
  92. """If the index given to the HyperParser is surrounded by a bracket
  93. defined in openers (or at least has one before it), return the
  94. indices of the opening bracket and the closing bracket (or the
  95. end of line, whichever comes first).
  96. If it is not surrounded by brackets, or the end of line comes before
  97. the closing bracket and mustclose is True, returns None.
  98. """
  99. bracketinglevel = self.bracketing[self.indexbracket][1]
  100. before = self.indexbracket
  101. while not self.isopener[before] or \
  102. self.rawtext[self.bracketing[before][0]] not in openers or \
  103. self.bracketing[before][1] > bracketinglevel:
  104. before -= 1
  105. if before < 0:
  106. return None
  107. bracketinglevel = min(bracketinglevel, self.bracketing[before][1])
  108. after = self.indexbracket + 1
  109. while after < len(self.bracketing) and \
  110. self.bracketing[after][1] >= bracketinglevel:
  111. after += 1
  112. beforeindex = self.text.index("%s-%dc" %
  113. (self.stopatindex, len(self.rawtext)-self.bracketing[before][0]))
  114. if after >= len(self.bracketing) or \
  115. self.bracketing[after][0] > len(self.rawtext):
  116. if mustclose:
  117. return None
  118. afterindex = self.stopatindex
  119. else:
  120. # We are after a real char, so it is a ')' and we give the index
  121. # before it.
  122. afterindex = self.text.index("%s-%dc" %
  123. (self.stopatindex,
  124. len(self.rawtext)-(self.bracketing[after][0]-1)))
  125. return beforeindex, afterindex
  126. # This string includes all chars that may be in a white space
  127. _whitespace_chars = " \t\n\\"
  128. # This string includes all chars that may be in an identifier
  129. _id_chars = string.ascii_letters + string.digits + "_"
  130. # This string includes all chars that may be the first char of an identifier
  131. _id_first_chars = string.ascii_letters + "_"
  132. # Given a string and pos, return the number of chars in the identifier
  133. # which ends at pos, or 0 if there is no such one. Saved words are not
  134. # identifiers.
  135. def _eat_identifier(self, str, limit, pos):
  136. i = pos
  137. while i > limit and str[i-1] in self._id_chars:
  138. i -= 1
  139. if i < pos and (str[i] not in self._id_first_chars or \
  140. keyword.iskeyword(str[i:pos])):
  141. i = pos
  142. return pos - i
  143. def get_expression(self):
  144. """Return a string with the Python expression which ends at the given
  145. index, which is empty if there is no real one.
  146. """
  147. if not self.is_in_code():
  148. raise ValueError("get_expression should only be called if index "\
  149. "is inside a code.")
  150. rawtext = self.rawtext
  151. bracketing = self.bracketing
  152. brck_index = self.indexbracket
  153. brck_limit = bracketing[brck_index][0]
  154. pos = self.indexinrawtext
  155. last_identifier_pos = pos
  156. postdot_phase = True
  157. while 1:
  158. # Eat whitespaces, comments, and if postdot_phase is False - one dot
  159. while 1:
  160. if pos>brck_limit and rawtext[pos-1] in self._whitespace_chars:
  161. # Eat a whitespace
  162. pos -= 1
  163. elif not postdot_phase and \
  164. pos > brck_limit and rawtext[pos-1] == '.':
  165. # Eat a dot
  166. pos -= 1
  167. postdot_phase = True
  168. # The next line will fail if we are *inside* a comment, but we
  169. # shouldn't be.
  170. elif pos == brck_limit and brck_index > 0 and \
  171. rawtext[bracketing[brck_index-1][0]] == '#':
  172. # Eat a comment
  173. brck_index -= 2
  174. brck_limit = bracketing[brck_index][0]
  175. pos = bracketing[brck_index+1][0]
  176. else:
  177. # If we didn't eat anything, quit.
  178. break
  179. if not postdot_phase:
  180. # We didn't find a dot, so the expression end at the last
  181. # identifier pos.
  182. break
  183. ret = self._eat_identifier(rawtext, brck_limit, pos)
  184. if ret:
  185. # There is an identifier to eat
  186. pos = pos - ret
  187. last_identifier_pos = pos
  188. # Now, in order to continue the search, we must find a dot.
  189. postdot_phase = False
  190. # (the loop continues now)
  191. elif pos == brck_limit:
  192. # We are at a bracketing limit. If it is a closing bracket,
  193. # eat the bracket, otherwise, stop the search.
  194. level = bracketing[brck_index][1]
  195. while brck_index > 0 and bracketing[brck_index-1][1] > level:
  196. brck_index -= 1
  197. if bracketing[brck_index][0] == brck_limit:
  198. # We were not at the end of a closing bracket
  199. break
  200. pos = bracketing[brck_index][0]
  201. brck_index -= 1
  202. brck_limit = bracketing[brck_index][0]
  203. last_identifier_pos = pos
  204. if rawtext[pos] in "([":
  205. # [] and () may be used after an identifier, so we
  206. # continue. postdot_phase is True, so we don't allow a dot.
  207. pass
  208. else:
  209. # We can't continue after other types of brackets
  210. break
  211. else:
  212. # We've found an operator or something.
  213. break
  214. return rawtext[last_identifier_pos:self.indexinrawtext]