blob: 61a0003ce5ae3244bd6c4c3e6c8793fb870882db [file] [log] [blame]
David Scherer7aced172000-08-15 01:13:23 +00001import re
2import sys
3
4# Reason last stmt is continued (or C_NONE if it's not).
Kurt B. Kaiserb61602c2005-11-15 07:20:06 +00005(C_NONE, C_BACKSLASH, C_STRING_FIRST_LINE,
6 C_STRING_NEXT_LINES, C_BRACKET) = range(5)
David Scherer7aced172000-08-15 01:13:23 +00007
8if 0: # for throwaway debugging output
9 def dump(*stuff):
Kurt B. Kaiser254eb532002-09-17 03:55:13 +000010 sys.__stdout__.write(" ".join(map(str, stuff)) + "\n")
David Scherer7aced172000-08-15 01:13:23 +000011
12# Find what looks like the start of a popular stmt.
13
14_synchre = re.compile(r"""
15 ^
16 [ \t]*
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000017 (?: while
David Scherer7aced172000-08-15 01:13:23 +000018 | else
19 | def
20 | return
21 | assert
22 | break
23 | class
24 | continue
25 | elif
26 | try
27 | except
28 | raise
29 | import
Kurt B. Kaiser752e4d52001-07-14 04:59:24 +000030 | yield
David Scherer7aced172000-08-15 01:13:23 +000031 )
32 \b
33""", re.VERBOSE | re.MULTILINE).search
34
35# Match blank line or non-indenting comment line.
36
37_junkre = re.compile(r"""
38 [ \t]*
39 (?: \# \S .* )?
40 \n
41""", re.VERBOSE).match
42
43# Match any flavor of string; the terminating quote is optional
44# so that we're robust in the face of incomplete program text.
45
46_match_stringre = re.compile(r"""
47 \""" [^"\\]* (?:
48 (?: \\. | "(?!"") )
49 [^"\\]*
50 )*
51 (?: \""" )?
52
53| " [^"\\\n]* (?: \\. [^"\\\n]* )* "?
54
55| ''' [^'\\]* (?:
56 (?: \\. | '(?!'') )
57 [^'\\]*
58 )*
59 (?: ''' )?
60
61| ' [^'\\\n]* (?: \\. [^'\\\n]* )* '?
62""", re.VERBOSE | re.DOTALL).match
63
64# Match a line that starts with something interesting;
65# used to find the first item of a bracket structure.
66
67_itemre = re.compile(r"""
68 [ \t]*
69 [^\s#\\] # if we match, m.end()-1 is the interesting char
70""", re.VERBOSE).match
71
72# Match start of stmts that should be followed by a dedent.
73
74_closere = re.compile(r"""
75 \s*
76 (?: return
77 | break
78 | continue
79 | raise
80 | pass
81 )
82 \b
83""", re.VERBOSE).match
84
85# Chew up non-special chars as quickly as possible. If match is
86# successful, m.end() less 1 is the index of the last boring char
87# matched. If match is unsuccessful, the string starts with an
88# interesting char.
89
90_chew_ordinaryre = re.compile(r"""
91 [^[\](){}#'"\\]+
92""", re.VERBOSE).match
93
94# Build translation table to map uninteresting chars to "x", open
95# brackets to "(", and close brackets to ")".
96
Guido van Rossumb0efee22007-11-21 20:07:54 +000097_tran = {}
98for i in range(256):
99 _tran[i] = 'x'
David Scherer7aced172000-08-15 01:13:23 +0000100for ch in "({[":
101 _tran[ord(ch)] = '('
102for ch in ")}]":
103 _tran[ord(ch)] = ')'
104for ch in "\"'\\\n#":
105 _tran[ord(ch)] = ch
Guido van Rossumb0efee22007-11-21 20:07:54 +0000106del i, ch
David Scherer7aced172000-08-15 01:13:23 +0000107
108class Parser:
109
110 def __init__(self, indentwidth, tabwidth):
111 self.indentwidth = indentwidth
112 self.tabwidth = tabwidth
113
Walter Dörwald5de48bd2007-06-11 21:38:39 +0000114 def set_str(self, s):
115 assert len(s) == 0 or s[-1] == '\n'
116 if isinstance(s, str):
Kurt B. Kaiser3269cc82001-07-13 20:33:46 +0000117 # The parse functions have no idea what to do with Unicode, so
118 # replace all Unicode characters with "x". This is "safe"
119 # so long as the only characters germane to parsing the structure
120 # of Python are 7-bit ASCII. It's *necessary* because Unicode
121 # strings don't have a .translate() method that supports
122 # deletechars.
Walter Dörwald5de48bd2007-06-11 21:38:39 +0000123 uniphooey = s
Martin v. Löwis163b7172007-08-13 06:02:09 +0000124 s = []
Walter Dörwald5de48bd2007-06-11 21:38:39 +0000125 push = s.append
Kurt B. Kaiser3269cc82001-07-13 20:33:46 +0000126 for raw in map(ord, uniphooey):
127 push(raw < 127 and chr(raw) or "x")
Walter Dörwald5de48bd2007-06-11 21:38:39 +0000128 s = "".join(s)
129 self.str = s
David Scherer7aced172000-08-15 01:13:23 +0000130 self.study_level = 0
131
132 # Return index of a good place to begin parsing, as close to the
133 # end of the string as possible. This will be the start of some
134 # popular stmt like "if" or "def". Return None if none found:
135 # the caller should pass more prior context then, if possible, or
136 # if not (the entire program text up until the point of interest
137 # has already been tried) pass 0 to set_lo.
138 #
139 # This will be reliable iff given a reliable is_char_in_string
140 # function, meaning that when it says "no", it's absolutely
141 # guaranteed that the char is not in a string.
David Scherer7aced172000-08-15 01:13:23 +0000142
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000143 def find_good_parse_start(self, is_char_in_string=None,
David Scherer7aced172000-08-15 01:13:23 +0000144 _synchre=_synchre):
145 str, pos = self.str, None
David Scherer7aced172000-08-15 01:13:23 +0000146
David Scherer7aced172000-08-15 01:13:23 +0000147 if not is_char_in_string:
148 # no clue -- make the caller pass everything
149 return None
150
151 # Peek back from the end for a good place to start,
152 # but don't try too often; pos will be left None, or
153 # bumped to a legitimate synch point.
154 limit = len(str)
155 for tries in range(5):
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000156 i = str.rfind(":\n", 0, limit)
David Scherer7aced172000-08-15 01:13:23 +0000157 if i < 0:
158 break
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000159 i = str.rfind('\n', 0, i) + 1 # start of colon line
David Scherer7aced172000-08-15 01:13:23 +0000160 m = _synchre(str, i, limit)
161 if m and not is_char_in_string(m.start()):
162 pos = m.start()
163 break
164 limit = i
165 if pos is None:
166 # Nothing looks like a block-opener, or stuff does
167 # but is_char_in_string keeps returning true; most likely
168 # we're in or near a giant string, the colorizer hasn't
169 # caught up enough to be helpful, or there simply *aren't*
170 # any interesting stmts. In any of these cases we're
171 # going to have to parse the whole thing to be sure, so
172 # give it one last try from the start, but stop wasting
173 # time here regardless of the outcome.
174 m = _synchre(str)
175 if m and not is_char_in_string(m.start()):
176 pos = m.start()
177 return pos
178
179 # Peeking back worked; look forward until _synchre no longer
180 # matches.
181 i = pos + 1
182 while 1:
183 m = _synchre(str, i)
184 if m:
185 s, i = m.span()
186 if not is_char_in_string(s):
187 pos = s
188 else:
189 break
190 return pos
191
192 # Throw away the start of the string. Intended to be called with
193 # find_good_parse_start's result.
194
195 def set_lo(self, lo):
196 assert lo == 0 or self.str[lo-1] == '\n'
197 if lo > 0:
198 self.str = self.str[lo:]
199
200 # As quickly as humanly possible <wink>, find the line numbers (0-
201 # based) of the non-continuation lines.
202 # Creates self.{goodlines, continuation}.
203
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000204 def _study1(self):
David Scherer7aced172000-08-15 01:13:23 +0000205 if self.study_level >= 1:
206 return
207 self.study_level = 1
208
209 # Map all uninteresting characters to "x", all open brackets
210 # to "(", all close brackets to ")", then collapse runs of
211 # uninteresting characters. This can cut the number of chars
212 # by a factor of 10-40, and so greatly speed the following loop.
213 str = self.str
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000214 str = str.translate(_tran)
215 str = str.replace('xxxxxxxx', 'x')
216 str = str.replace('xxxx', 'x')
217 str = str.replace('xx', 'x')
218 str = str.replace('xx', 'x')
219 str = str.replace('\nx', '\n')
David Scherer7aced172000-08-15 01:13:23 +0000220 # note that replacing x\n with \n would be incorrect, because
221 # x may be preceded by a backslash
222
223 # March over the squashed version of the program, accumulating
224 # the line numbers of non-continued stmts, and determining
225 # whether & why the last stmt is a continuation.
226 continuation = C_NONE
227 level = lno = 0 # level is nesting level; lno is line number
228 self.goodlines = goodlines = [0]
229 push_good = goodlines.append
230 i, n = 0, len(str)
231 while i < n:
232 ch = str[i]
233 i = i+1
234
235 # cases are checked in decreasing order of frequency
236 if ch == 'x':
237 continue
238
239 if ch == '\n':
240 lno = lno + 1
241 if level == 0:
242 push_good(lno)
243 # else we're in an unclosed bracket structure
244 continue
245
246 if ch == '(':
247 level = level + 1
248 continue
249
250 if ch == ')':
251 if level:
252 level = level - 1
253 # else the program is invalid, but we can't complain
254 continue
255
256 if ch == '"' or ch == "'":
257 # consume the string
258 quote = ch
259 if str[i-1:i+2] == quote * 3:
260 quote = quote * 3
Kurt B. Kaiserb61602c2005-11-15 07:20:06 +0000261 firstlno = lno
David Scherer7aced172000-08-15 01:13:23 +0000262 w = len(quote) - 1
263 i = i+w
264 while i < n:
265 ch = str[i]
266 i = i+1
267
268 if ch == 'x':
269 continue
270
271 if str[i-1:i+w] == quote:
272 i = i+w
273 break
274
275 if ch == '\n':
276 lno = lno + 1
277 if w == 0:
278 # unterminated single-quoted string
279 if level == 0:
280 push_good(lno)
281 break
282 continue
283
284 if ch == '\\':
285 assert i < n
286 if str[i] == '\n':
287 lno = lno + 1
288 i = i+1
289 continue
290
291 # else comment char or paren inside string
292
293 else:
294 # didn't break out of the loop, so we're still
295 # inside a string
Kurt B. Kaiserb61602c2005-11-15 07:20:06 +0000296 if (lno - 1) == firstlno:
297 # before the previous \n in str, we were in the first
298 # line of the string
299 continuation = C_STRING_FIRST_LINE
300 else:
301 continuation = C_STRING_NEXT_LINES
David Scherer7aced172000-08-15 01:13:23 +0000302 continue # with outer loop
303
304 if ch == '#':
305 # consume the comment
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000306 i = str.find('\n', i)
David Scherer7aced172000-08-15 01:13:23 +0000307 assert i >= 0
308 continue
309
310 assert ch == '\\'
311 assert i < n
312 if str[i] == '\n':
313 lno = lno + 1
314 if i+1 == n:
315 continuation = C_BACKSLASH
316 i = i+1
317
318 # The last stmt may be continued for all 3 reasons.
319 # String continuation takes precedence over bracket
320 # continuation, which beats backslash continuation.
Kurt B. Kaiserb61602c2005-11-15 07:20:06 +0000321 if (continuation != C_STRING_FIRST_LINE
322 and continuation != C_STRING_NEXT_LINES and level > 0):
David Scherer7aced172000-08-15 01:13:23 +0000323 continuation = C_BRACKET
324 self.continuation = continuation
325
326 # Push the final line number as a sentinel value, regardless of
327 # whether it's continued.
328 assert (continuation == C_NONE) == (goodlines[-1] == lno)
329 if goodlines[-1] != lno:
330 push_good(lno)
331
332 def get_continuation_type(self):
333 self._study1()
334 return self.continuation
335
336 # study1 was sufficient to determine the continuation status,
337 # but doing more requires looking at every character. study2
338 # does this for the last interesting statement in the block.
339 # Creates:
340 # self.stmt_start, stmt_end
341 # slice indices of last interesting stmt
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000342 # self.stmt_bracketing
343 # the bracketing structure of the last interesting stmt;
344 # for example, for the statement "say(boo) or die", stmt_bracketing
345 # will be [(0, 0), (3, 1), (8, 0)]. Strings and comments are
346 # treated as brackets, for the matter.
David Scherer7aced172000-08-15 01:13:23 +0000347 # self.lastch
348 # last non-whitespace character before optional trailing
349 # comment
350 # self.lastopenbracketpos
351 # if continuation is C_BRACKET, index of last open bracket
352
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000353 def _study2(self):
David Scherer7aced172000-08-15 01:13:23 +0000354 if self.study_level >= 2:
355 return
356 self._study1()
357 self.study_level = 2
358
359 # Set p and q to slice indices of last interesting stmt.
360 str, goodlines = self.str, self.goodlines
361 i = len(goodlines) - 1
362 p = len(str) # index of newest line
363 while i:
364 assert p
365 # p is the index of the stmt at line number goodlines[i].
366 # Move p back to the stmt at line number goodlines[i-1].
367 q = p
368 for nothing in range(goodlines[i-1], goodlines[i]):
369 # tricky: sets p to 0 if no preceding newline
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000370 p = str.rfind('\n', 0, p-1) + 1
David Scherer7aced172000-08-15 01:13:23 +0000371 # The stmt str[p:q] isn't a continuation, but may be blank
372 # or a non-indenting comment line.
373 if _junkre(str, p):
374 i = i-1
375 else:
376 break
377 if i == 0:
378 # nothing but junk!
379 assert p == 0
380 q = p
381 self.stmt_start, self.stmt_end = p, q
382
383 # Analyze this stmt, to find the last open bracket (if any)
384 # and last interesting character (if any).
385 lastch = ""
386 stack = [] # stack of open bracket indices
387 push_stack = stack.append
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000388 bracketing = [(p, 0)]
David Scherer7aced172000-08-15 01:13:23 +0000389 while p < q:
390 # suck up all except ()[]{}'"#\\
391 m = _chew_ordinaryre(str, p, q)
392 if m:
393 # we skipped at least one boring char
Kurt B. Kaiser3269cc82001-07-13 20:33:46 +0000394 newp = m.end()
David Scherer7aced172000-08-15 01:13:23 +0000395 # back up over totally boring whitespace
Kurt B. Kaiser3269cc82001-07-13 20:33:46 +0000396 i = newp - 1 # index of last boring char
397 while i >= p and str[i] in " \t\n":
David Scherer7aced172000-08-15 01:13:23 +0000398 i = i-1
Kurt B. Kaiser3269cc82001-07-13 20:33:46 +0000399 if i >= p:
David Scherer7aced172000-08-15 01:13:23 +0000400 lastch = str[i]
Kurt B. Kaiser3269cc82001-07-13 20:33:46 +0000401 p = newp
David Scherer7aced172000-08-15 01:13:23 +0000402 if p >= q:
403 break
404
405 ch = str[p]
406
407 if ch in "([{":
408 push_stack(p)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000409 bracketing.append((p, len(stack)))
David Scherer7aced172000-08-15 01:13:23 +0000410 lastch = ch
411 p = p+1
412 continue
413
414 if ch in ")]}":
415 if stack:
416 del stack[-1]
417 lastch = ch
418 p = p+1
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000419 bracketing.append((p, len(stack)))
David Scherer7aced172000-08-15 01:13:23 +0000420 continue
421
422 if ch == '"' or ch == "'":
423 # consume string
424 # Note that study1 did this with a Python loop, but
425 # we use a regexp here; the reason is speed in both
426 # cases; the string may be huge, but study1 pre-squashed
427 # strings to a couple of characters per line. study1
428 # also needed to keep track of newlines, and we don't
429 # have to.
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000430 bracketing.append((p, len(stack)+1))
David Scherer7aced172000-08-15 01:13:23 +0000431 lastch = ch
432 p = _match_stringre(str, p, q).end()
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000433 bracketing.append((p, len(stack)))
David Scherer7aced172000-08-15 01:13:23 +0000434 continue
435
436 if ch == '#':
437 # consume comment and trailing newline
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000438 bracketing.append((p, len(stack)+1))
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000439 p = str.find('\n', p, q) + 1
David Scherer7aced172000-08-15 01:13:23 +0000440 assert p > 0
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000441 bracketing.append((p, len(stack)))
David Scherer7aced172000-08-15 01:13:23 +0000442 continue
443
444 assert ch == '\\'
445 p = p+1 # beyond backslash
446 assert p < q
447 if str[p] != '\n':
448 # the program is invalid, but can't complain
449 lastch = ch + str[p]
450 p = p+1 # beyond escaped char
451
452 # end while p < q:
453
454 self.lastch = lastch
455 if stack:
456 self.lastopenbracketpos = stack[-1]
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000457 self.stmt_bracketing = tuple(bracketing)
David Scherer7aced172000-08-15 01:13:23 +0000458
459 # Assuming continuation is C_BRACKET, return the number
460 # of spaces the next line should be indented.
461
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000462 def compute_bracket_indent(self):
David Scherer7aced172000-08-15 01:13:23 +0000463 self._study2()
464 assert self.continuation == C_BRACKET
465 j = self.lastopenbracketpos
466 str = self.str
467 n = len(str)
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000468 origi = i = str.rfind('\n', 0, j) + 1
David Scherer7aced172000-08-15 01:13:23 +0000469 j = j+1 # one beyond open bracket
470 # find first list item; set i to start of its line
471 while j < n:
472 m = _itemre(str, j)
473 if m:
474 j = m.end() - 1 # index of first interesting char
475 extra = 0
476 break
477 else:
478 # this line is junk; advance to next line
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000479 i = j = str.find('\n', j) + 1
David Scherer7aced172000-08-15 01:13:23 +0000480 else:
481 # nothing interesting follows the bracket;
482 # reproduce the bracket line's indentation + a level
483 j = i = origi
484 while str[j] in " \t":
485 j = j+1
486 extra = self.indentwidth
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000487 return len(str[i:j].expandtabs(self.tabwidth)) + extra
David Scherer7aced172000-08-15 01:13:23 +0000488
489 # Return number of physical lines in last stmt (whether or not
490 # it's an interesting stmt! this is intended to be called when
491 # continuation is C_BACKSLASH).
492
493 def get_num_lines_in_stmt(self):
494 self._study1()
495 goodlines = self.goodlines
496 return goodlines[-1] - goodlines[-2]
497
498 # Assuming continuation is C_BACKSLASH, return the number of spaces
499 # the next line should be indented. Also assuming the new line is
500 # the first one following the initial line of the stmt.
501
502 def compute_backslash_indent(self):
503 self._study2()
504 assert self.continuation == C_BACKSLASH
505 str = self.str
506 i = self.stmt_start
507 while str[i] in " \t":
508 i = i+1
509 startpos = i
510
511 # See whether the initial line starts an assignment stmt; i.e.,
512 # look for an = operator
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000513 endpos = str.find('\n', startpos) + 1
David Scherer7aced172000-08-15 01:13:23 +0000514 found = level = 0
515 while i < endpos:
516 ch = str[i]
517 if ch in "([{":
518 level = level + 1
519 i = i+1
520 elif ch in ")]}":
521 if level:
522 level = level - 1
523 i = i+1
524 elif ch == '"' or ch == "'":
525 i = _match_stringre(str, i, endpos).end()
526 elif ch == '#':
527 break
528 elif level == 0 and ch == '=' and \
529 (i == 0 or str[i-1] not in "=<>!") and \
530 str[i+1] != '=':
531 found = 1
532 break
533 else:
534 i = i+1
535
536 if found:
537 # found a legit =, but it may be the last interesting
538 # thing on the line
539 i = i+1 # move beyond the =
540 found = re.match(r"\s*\\", str[i:endpos]) is None
541
542 if not found:
543 # oh well ... settle for moving beyond the first chunk
544 # of non-whitespace chars
545 i = startpos
546 while str[i] not in " \t\n":
547 i = i+1
548
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000549 return len(str[self.stmt_start:i].expandtabs(\
David Scherer7aced172000-08-15 01:13:23 +0000550 self.tabwidth)) + 1
551
552 # Return the leading whitespace on the initial line of the last
553 # interesting stmt.
554
555 def get_base_indent_string(self):
556 self._study2()
557 i, n = self.stmt_start, self.stmt_end
558 j = i
559 str = self.str
560 while j < n and str[j] in " \t":
561 j = j + 1
562 return str[i:j]
563
564 # Did the last interesting stmt open a block?
565
566 def is_block_opener(self):
567 self._study2()
568 return self.lastch == ':'
569
570 # Did the last interesting stmt close a block?
571
572 def is_block_closer(self):
573 self._study2()
574 return _closere(self.str, self.stmt_start) is not None
575
576 # index of last open bracket ({[, or None if none
577 lastopenbracketpos = None
578
579 def get_last_open_bracket_pos(self):
580 self._study2()
581 return self.lastopenbracketpos
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000582
583 # the structure of the bracketing of the last interesting statement,
584 # in the format defined in _study2, or None if the text didn't contain
585 # anything
586 stmt_bracketing = None
587
588 def get_last_stmt_bracketing(self):
589 self._study2()
590 return self.stmt_bracketing