pyparse.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. """Define partial Python code Parser used by editor and hyperparser.
  2. Instances of ParseMap are used with str.translate.
  3. The following bound search and match functions are defined:
  4. _synchre - start of popular statement;
  5. _junkre - whitespace or comment line;
  6. _match_stringre: string, possibly without closer;
  7. _itemre - line that may have bracket structure start;
  8. _closere - line that must be followed by dedent.
  9. _chew_ordinaryre - non-special characters.
  10. """
  11. import re
  12. # Reason last statement is continued (or C_NONE if it's not).
  13. (C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE,
  14. C_STRING_NEXT_LINES, C_BRACKET) = range(5)
  15. # Find what looks like the start of a popular statement.
  16. _synchre = re.compile(r"""
  17. ^
  18. [ \t]*
  19. (?: while
  20. | else
  21. | def
  22. | return
  23. | assert
  24. | break
  25. | class
  26. | continue
  27. | elif
  28. | try
  29. | except
  30. | raise
  31. | import
  32. | yield
  33. )
  34. \b
  35. """, re.VERBOSE | re.MULTILINE).search
  36. # Match blank line or non-indenting comment line.
  37. _junkre = re.compile(r"""
  38. [ \t]*
  39. (?: \# \S .* )?
  40. \n
  41. """, re.VERBOSE).match
  42. # Match any flavor of string; the terminating quote is optional
  43. # so that we're robust in the face of incomplete program text.
  44. _match_stringre = re.compile(r"""
  45. \""" [^"\\]* (?:
  46. (?: \\. | "(?!"") )
  47. [^"\\]*
  48. )*
  49. (?: \""" )?
  50. | " [^"\\\n]* (?: \\. [^"\\\n]* )* "?
  51. | ''' [^'\\]* (?:
  52. (?: \\. | '(?!'') )
  53. [^'\\]*
  54. )*
  55. (?: ''' )?
  56. | ' [^'\\\n]* (?: \\. [^'\\\n]* )* '?
  57. """, re.VERBOSE | re.DOTALL).match
  58. # Match a line that starts with something interesting;
  59. # used to find the first item of a bracket structure.
  60. _itemre = re.compile(r"""
  61. [ \t]*
  62. [^\s#\\] # if we match, m.end()-1 is the interesting char
  63. """, re.VERBOSE).match
  64. # Match start of statements that should be followed by a dedent.
  65. _closere = re.compile(r"""
  66. \s*
  67. (?: return
  68. | break
  69. | continue
  70. | raise
  71. | pass
  72. )
  73. \b
  74. """, re.VERBOSE).match
  75. # Chew up non-special chars as quickly as possible. If match is
  76. # successful, m.end() less 1 is the index of the last boring char
  77. # matched. If match is unsuccessful, the string starts with an
  78. # interesting char.
  79. _chew_ordinaryre = re.compile(r"""
  80. [^[\](){}#'"\\]+
  81. """, re.VERBOSE).match
  82. class ParseMap(dict):
  83. r"""Dict subclass that maps anything not in dict to 'x'.
  84. This is designed to be used with str.translate in study1.
  85. Anything not specifically mapped otherwise becomes 'x'.
  86. Example: replace everything except whitespace with 'x'.
  87. >>> keepwhite = ParseMap((ord(c), ord(c)) for c in ' \t\n\r')
  88. >>> "a + b\tc\nd".translate(keepwhite)
  89. 'x x x\tx\nx'
  90. """
  91. # Calling this triples access time; see bpo-32940
  92. def __missing__(self, key):
  93. return 120 # ord('x')
  94. # Map all ascii to 120 to avoid __missing__ call, then replace some.
  95. trans = ParseMap.fromkeys(range(128), 120)
  96. trans.update((ord(c), ord('(')) for c in "({[") # open brackets => '(';
  97. trans.update((ord(c), ord(')')) for c in ")}]") # close brackets => ')'.
  98. trans.update((ord(c), ord(c)) for c in "\"'\\\n#") # Keep these.
  99. class Parser:
  100. def __init__(self, indentwidth, tabwidth):
  101. self.indentwidth = indentwidth
  102. self.tabwidth = tabwidth
  103. def set_code(self, s):
  104. assert len(s) == 0 or s[-1] == '\n'
  105. self.code = s
  106. self.study_level = 0
  107. def find_good_parse_start(self, is_char_in_string):
  108. """
  109. Return index of a good place to begin parsing, as close to the
  110. end of the string as possible. This will be the start of some
  111. popular stmt like "if" or "def". Return None if none found:
  112. the caller should pass more prior context then, if possible, or
  113. if not (the entire program text up until the point of interest
  114. has already been tried) pass 0 to set_lo().
  115. This will be reliable iff given a reliable is_char_in_string()
  116. function, meaning that when it says "no", it's absolutely
  117. guaranteed that the char is not in a string.
  118. """
  119. code, pos = self.code, None
  120. # Peek back from the end for a good place to start,
  121. # but don't try too often; pos will be left None, or
  122. # bumped to a legitimate synch point.
  123. limit = len(code)
  124. for tries in range(5):
  125. i = code.rfind(":\n", 0, limit)
  126. if i < 0:
  127. break
  128. i = code.rfind('\n', 0, i) + 1 # start of colon line (-1+1=0)
  129. m = _synchre(code, i, limit)
  130. if m and not is_char_in_string(m.start()):
  131. pos = m.start()
  132. break
  133. limit = i
  134. if pos is None:
  135. # Nothing looks like a block-opener, or stuff does
  136. # but is_char_in_string keeps returning true; most likely
  137. # we're in or near a giant string, the colorizer hasn't
  138. # caught up enough to be helpful, or there simply *aren't*
  139. # any interesting stmts. In any of these cases we're
  140. # going to have to parse the whole thing to be sure, so
  141. # give it one last try from the start, but stop wasting
  142. # time here regardless of the outcome.
  143. m = _synchre(code)
  144. if m and not is_char_in_string(m.start()):
  145. pos = m.start()
  146. return pos
  147. # Peeking back worked; look forward until _synchre no longer
  148. # matches.
  149. i = pos + 1
  150. while m := _synchre(code, i):
  151. s, i = m.span()
  152. if not is_char_in_string(s):
  153. pos = s
  154. return pos
  155. def set_lo(self, lo):
  156. """ Throw away the start of the string.
  157. Intended to be called with the result of find_good_parse_start().
  158. """
  159. assert lo == 0 or self.code[lo-1] == '\n'
  160. if lo > 0:
  161. self.code = self.code[lo:]
  162. def _study1(self):
  163. """Find the line numbers of non-continuation lines.
  164. As quickly as humanly possible <wink>, find the line numbers (0-
  165. based) of the non-continuation lines.
  166. Creates self.{goodlines, continuation}.
  167. """
  168. if self.study_level >= 1:
  169. return
  170. self.study_level = 1
  171. # Map all uninteresting characters to "x", all open brackets
  172. # to "(", all close brackets to ")", then collapse runs of
  173. # uninteresting characters. This can cut the number of chars
  174. # by a factor of 10-40, and so greatly speed the following loop.
  175. code = self.code
  176. code = code.translate(trans)
  177. code = code.replace('xxxxxxxx', 'x')
  178. code = code.replace('xxxx', 'x')
  179. code = code.replace('xx', 'x')
  180. code = code.replace('xx', 'x')
  181. code = code.replace('\nx', '\n')
  182. # Replacing x\n with \n would be incorrect because
  183. # x may be preceded by a backslash.
  184. # March over the squashed version of the program, accumulating
  185. # the line numbers of non-continued stmts, and determining
  186. # whether & why the last stmt is a continuation.
  187. continuation = C_NONE
  188. level = lno = 0 # level is nesting level; lno is line number
  189. self.goodlines = goodlines = [0]
  190. push_good = goodlines.append
  191. i, n = 0, len(code)
  192. while i < n:
  193. ch = code[i]
  194. i = i+1
  195. # cases are checked in decreasing order of frequency
  196. if ch == 'x':
  197. continue
  198. if ch == '\n':
  199. lno = lno + 1
  200. if level == 0:
  201. push_good(lno)
  202. # else we're in an unclosed bracket structure
  203. continue
  204. if ch == '(':
  205. level = level + 1
  206. continue
  207. if ch == ')':
  208. if level:
  209. level = level - 1
  210. # else the program is invalid, but we can't complain
  211. continue
  212. if ch == '"' or ch == "'":
  213. # consume the string
  214. quote = ch
  215. if code[i-1:i+2] == quote * 3:
  216. quote = quote * 3
  217. firstlno = lno
  218. w = len(quote) - 1
  219. i = i+w
  220. while i < n:
  221. ch = code[i]
  222. i = i+1
  223. if ch == 'x':
  224. continue
  225. if code[i-1:i+w] == quote:
  226. i = i+w
  227. break
  228. if ch == '\n':
  229. lno = lno + 1
  230. if w == 0:
  231. # unterminated single-quoted string
  232. if level == 0:
  233. push_good(lno)
  234. break
  235. continue
  236. if ch == '\\':
  237. assert i < n
  238. if code[i] == '\n':
  239. lno = lno + 1
  240. i = i+1
  241. continue
  242. # else comment char or paren inside string
  243. else:
  244. # didn't break out of the loop, so we're still
  245. # inside a string
  246. if (lno - 1) == firstlno:
  247. # before the previous \n in code, we were in the first
  248. # line of the string
  249. continuation = C_STRING_FIRST_LINE
  250. else:
  251. continuation = C_STRING_NEXT_LINES
  252. continue # with outer loop
  253. if ch == '#':
  254. # consume the comment
  255. i = code.find('\n', i)
  256. assert i >= 0
  257. continue
  258. assert ch == '\\'
  259. assert i < n
  260. if code[i] == '\n':
  261. lno = lno + 1
  262. if i+1 == n:
  263. continuation = C_BACKSLASH
  264. i = i+1
  265. # The last stmt may be continued for all 3 reasons.
  266. # String continuation takes precedence over bracket
  267. # continuation, which beats backslash continuation.
  268. if (continuation != C_STRING_FIRST_LINE
  269. and continuation != C_STRING_NEXT_LINES and level > 0):
  270. continuation = C_BRACKET
  271. self.continuation = continuation
  272. # Push the final line number as a sentinel value, regardless of
  273. # whether it's continued.
  274. assert (continuation == C_NONE) == (goodlines[-1] == lno)
  275. if goodlines[-1] != lno:
  276. push_good(lno)
  277. def get_continuation_type(self):
  278. self._study1()
  279. return self.continuation
  280. def _study2(self):
  281. """
  282. study1 was sufficient to determine the continuation status,
  283. but doing more requires looking at every character. study2
  284. does this for the last interesting statement in the block.
  285. Creates:
  286. self.stmt_start, stmt_end
  287. slice indices of last interesting stmt
  288. self.stmt_bracketing
  289. the bracketing structure of the last interesting stmt; for
  290. example, for the statement "say(boo) or die",
  291. stmt_bracketing will be ((0, 0), (0, 1), (2, 0), (2, 1),
  292. (4, 0)). Strings and comments are treated as brackets, for
  293. the matter.
  294. self.lastch
  295. last interesting character before optional trailing comment
  296. self.lastopenbracketpos
  297. if continuation is C_BRACKET, index of last open bracket
  298. """
  299. if self.study_level >= 2:
  300. return
  301. self._study1()
  302. self.study_level = 2
  303. # Set p and q to slice indices of last interesting stmt.
  304. code, goodlines = self.code, self.goodlines
  305. i = len(goodlines) - 1 # Index of newest line.
  306. p = len(code) # End of goodlines[i]
  307. while i:
  308. assert p
  309. # Make p be the index of the stmt at line number goodlines[i].
  310. # Move p back to the stmt at line number goodlines[i-1].
  311. q = p
  312. for nothing in range(goodlines[i-1], goodlines[i]):
  313. # tricky: sets p to 0 if no preceding newline
  314. p = code.rfind('\n', 0, p-1) + 1
  315. # The stmt code[p:q] isn't a continuation, but may be blank
  316. # or a non-indenting comment line.
  317. if _junkre(code, p):
  318. i = i-1
  319. else:
  320. break
  321. if i == 0:
  322. # nothing but junk!
  323. assert p == 0
  324. q = p
  325. self.stmt_start, self.stmt_end = p, q
  326. # Analyze this stmt, to find the last open bracket (if any)
  327. # and last interesting character (if any).
  328. lastch = ""
  329. stack = [] # stack of open bracket indices
  330. push_stack = stack.append
  331. bracketing = [(p, 0)]
  332. while p < q:
  333. # suck up all except ()[]{}'"#\\
  334. m = _chew_ordinaryre(code, p, q)
  335. if m:
  336. # we skipped at least one boring char
  337. newp = m.end()
  338. # back up over totally boring whitespace
  339. i = newp - 1 # index of last boring char
  340. while i >= p and code[i] in " \t\n":
  341. i = i-1
  342. if i >= p:
  343. lastch = code[i]
  344. p = newp
  345. if p >= q:
  346. break
  347. ch = code[p]
  348. if ch in "([{":
  349. push_stack(p)
  350. bracketing.append((p, len(stack)))
  351. lastch = ch
  352. p = p+1
  353. continue
  354. if ch in ")]}":
  355. if stack:
  356. del stack[-1]
  357. lastch = ch
  358. p = p+1
  359. bracketing.append((p, len(stack)))
  360. continue
  361. if ch == '"' or ch == "'":
  362. # consume string
  363. # Note that study1 did this with a Python loop, but
  364. # we use a regexp here; the reason is speed in both
  365. # cases; the string may be huge, but study1 pre-squashed
  366. # strings to a couple of characters per line. study1
  367. # also needed to keep track of newlines, and we don't
  368. # have to.
  369. bracketing.append((p, len(stack)+1))
  370. lastch = ch
  371. p = _match_stringre(code, p, q).end()
  372. bracketing.append((p, len(stack)))
  373. continue
  374. if ch == '#':
  375. # consume comment and trailing newline
  376. bracketing.append((p, len(stack)+1))
  377. p = code.find('\n', p, q) + 1
  378. assert p > 0
  379. bracketing.append((p, len(stack)))
  380. continue
  381. assert ch == '\\'
  382. p = p+1 # beyond backslash
  383. assert p < q
  384. if code[p] != '\n':
  385. # the program is invalid, but can't complain
  386. lastch = ch + code[p]
  387. p = p+1 # beyond escaped char
  388. # end while p < q:
  389. self.lastch = lastch
  390. self.lastopenbracketpos = stack[-1] if stack else None
  391. self.stmt_bracketing = tuple(bracketing)
  392. def compute_bracket_indent(self):
  393. """Return number of spaces the next line should be indented.
  394. Line continuation must be C_BRACKET.
  395. """
  396. self._study2()
  397. assert self.continuation == C_BRACKET
  398. j = self.lastopenbracketpos
  399. code = self.code
  400. n = len(code)
  401. origi = i = code.rfind('\n', 0, j) + 1
  402. j = j+1 # one beyond open bracket
  403. # find first list item; set i to start of its line
  404. while j < n:
  405. m = _itemre(code, j)
  406. if m:
  407. j = m.end() - 1 # index of first interesting char
  408. extra = 0
  409. break
  410. else:
  411. # this line is junk; advance to next line
  412. i = j = code.find('\n', j) + 1
  413. else:
  414. # nothing interesting follows the bracket;
  415. # reproduce the bracket line's indentation + a level
  416. j = i = origi
  417. while code[j] in " \t":
  418. j = j+1
  419. extra = self.indentwidth
  420. return len(code[i:j].expandtabs(self.tabwidth)) + extra
  421. def get_num_lines_in_stmt(self):
  422. """Return number of physical lines in last stmt.
  423. The statement doesn't have to be an interesting statement. This is
  424. intended to be called when continuation is C_BACKSLASH.
  425. """
  426. self._study1()
  427. goodlines = self.goodlines
  428. return goodlines[-1] - goodlines[-2]
  429. def compute_backslash_indent(self):
  430. """Return number of spaces the next line should be indented.
  431. Line continuation must be C_BACKSLASH. Also assume that the new
  432. line is the first one following the initial line of the stmt.
  433. """
  434. self._study2()
  435. assert self.continuation == C_BACKSLASH
  436. code = self.code
  437. i = self.stmt_start
  438. while code[i] in " \t":
  439. i = i+1
  440. startpos = i
  441. # See whether the initial line starts an assignment stmt; i.e.,
  442. # look for an = operator
  443. endpos = code.find('\n', startpos) + 1
  444. found = level = 0
  445. while i < endpos:
  446. ch = code[i]
  447. if ch in "([{":
  448. level = level + 1
  449. i = i+1
  450. elif ch in ")]}":
  451. if level:
  452. level = level - 1
  453. i = i+1
  454. elif ch == '"' or ch == "'":
  455. i = _match_stringre(code, i, endpos).end()
  456. elif ch == '#':
  457. # This line is unreachable because the # makes a comment of
  458. # everything after it.
  459. break
  460. elif level == 0 and ch == '=' and \
  461. (i == 0 or code[i-1] not in "=<>!") and \
  462. code[i+1] != '=':
  463. found = 1
  464. break
  465. else:
  466. i = i+1
  467. if found:
  468. # found a legit =, but it may be the last interesting
  469. # thing on the line
  470. i = i+1 # move beyond the =
  471. found = re.match(r"\s*\\", code[i:endpos]) is None
  472. if not found:
  473. # oh well ... settle for moving beyond the first chunk
  474. # of non-whitespace chars
  475. i = startpos
  476. while code[i] not in " \t\n":
  477. i = i+1
  478. return len(code[self.stmt_start:i].expandtabs(\
  479. self.tabwidth)) + 1
  480. def get_base_indent_string(self):
  481. """Return the leading whitespace on the initial line of the last
  482. interesting stmt.
  483. """
  484. self._study2()
  485. i, n = self.stmt_start, self.stmt_end
  486. j = i
  487. code = self.code
  488. while j < n and code[j] in " \t":
  489. j = j + 1
  490. return code[i:j]
  491. def is_block_opener(self):
  492. "Return True if the last interesting statement opens a block."
  493. self._study2()
  494. return self.lastch == ':'
  495. def is_block_closer(self):
  496. "Return True if the last interesting statement closes a block."
  497. self._study2()
  498. return _closere(self.code, self.stmt_start) is not None
  499. def get_last_stmt_bracketing(self):
  500. """Return bracketing structure of the last interesting statement.
  501. The returned tuple is in the format defined in _study2().
  502. """
  503. self._study2()
  504. return self.stmt_bracketing
  505. if __name__ == '__main__':
  506. from unittest import main
  507. main('idlelib.idle_test.test_pyparse', verbosity=2)