blob: ea3cc27796f9a32061c67c2e37655459334de1ba [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
97_tran = ['x'] * 256
98for ch in "({[":
99 _tran[ord(ch)] = '('
100for ch in ")}]":
101 _tran[ord(ch)] = ')'
102for ch in "\"'\\\n#":
103 _tran[ord(ch)] = ch
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000104_tran = ''.join(_tran)
David Scherer7aced172000-08-15 01:13:23 +0000105del ch
106
107class Parser:
108
109 def __init__(self, indentwidth, tabwidth):
110 self.indentwidth = indentwidth
111 self.tabwidth = tabwidth
112
Walter Dörwald5de48bd2007-06-11 21:38:39 +0000113 def set_str(self, s):
114 assert len(s) == 0 or s[-1] == '\n'
115 if isinstance(s, str):
Kurt B. Kaiser3269cc82001-07-13 20:33:46 +0000116 # The parse functions have no idea what to do with Unicode, so
117 # replace all Unicode characters with "x". This is "safe"
118 # so long as the only characters germane to parsing the structure
119 # of Python are 7-bit ASCII. It's *necessary* because Unicode
120 # strings don't have a .translate() method that supports
121 # deletechars.
Walter Dörwald5de48bd2007-06-11 21:38:39 +0000122 uniphooey = s
Kurt B. Kaiser3269cc82001-07-13 20:33:46 +0000123 str = []
Walter Dörwald5de48bd2007-06-11 21:38:39 +0000124 push = s.append
Kurt B. Kaiser3269cc82001-07-13 20:33:46 +0000125 for raw in map(ord, uniphooey):
126 push(raw < 127 and chr(raw) or "x")
Walter Dörwald5de48bd2007-06-11 21:38:39 +0000127 s = "".join(s)
128 self.str = s
David Scherer7aced172000-08-15 01:13:23 +0000129 self.study_level = 0
130
131 # Return index of a good place to begin parsing, as close to the
132 # end of the string as possible. This will be the start of some
133 # popular stmt like "if" or "def". Return None if none found:
134 # the caller should pass more prior context then, if possible, or
135 # if not (the entire program text up until the point of interest
136 # has already been tried) pass 0 to set_lo.
137 #
138 # This will be reliable iff given a reliable is_char_in_string
139 # function, meaning that when it says "no", it's absolutely
140 # guaranteed that the char is not in a string.
David Scherer7aced172000-08-15 01:13:23 +0000141
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000142 def find_good_parse_start(self, is_char_in_string=None,
David Scherer7aced172000-08-15 01:13:23 +0000143 _synchre=_synchre):
144 str, pos = self.str, None
David Scherer7aced172000-08-15 01:13:23 +0000145
David Scherer7aced172000-08-15 01:13:23 +0000146 if not is_char_in_string:
147 # no clue -- make the caller pass everything
148 return None
149
150 # Peek back from the end for a good place to start,
151 # but don't try too often; pos will be left None, or
152 # bumped to a legitimate synch point.
153 limit = len(str)
154 for tries in range(5):
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000155 i = str.rfind(":\n", 0, limit)
David Scherer7aced172000-08-15 01:13:23 +0000156 if i < 0:
157 break
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000158 i = str.rfind('\n', 0, i) + 1 # start of colon line
David Scherer7aced172000-08-15 01:13:23 +0000159 m = _synchre(str, i, limit)
160 if m and not is_char_in_string(m.start()):
161 pos = m.start()
162 break
163 limit = i
164 if pos is None:
165 # Nothing looks like a block-opener, or stuff does
166 # but is_char_in_string keeps returning true; most likely
167 # we're in or near a giant string, the colorizer hasn't
168 # caught up enough to be helpful, or there simply *aren't*
169 # any interesting stmts. In any of these cases we're
170 # going to have to parse the whole thing to be sure, so
171 # give it one last try from the start, but stop wasting
172 # time here regardless of the outcome.
173 m = _synchre(str)
174 if m and not is_char_in_string(m.start()):
175 pos = m.start()
176 return pos
177
178 # Peeking back worked; look forward until _synchre no longer
179 # matches.
180 i = pos + 1
181 while 1:
182 m = _synchre(str, i)
183 if m:
184 s, i = m.span()
185 if not is_char_in_string(s):
186 pos = s
187 else:
188 break
189 return pos
190
191 # Throw away the start of the string. Intended to be called with
192 # find_good_parse_start's result.
193
194 def set_lo(self, lo):
195 assert lo == 0 or self.str[lo-1] == '\n'
196 if lo > 0:
197 self.str = self.str[lo:]
198
199 # As quickly as humanly possible <wink>, find the line numbers (0-
200 # based) of the non-continuation lines.
201 # Creates self.{goodlines, continuation}.
202
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000203 def _study1(self):
David Scherer7aced172000-08-15 01:13:23 +0000204 if self.study_level >= 1:
205 return
206 self.study_level = 1
207
208 # Map all uninteresting characters to "x", all open brackets
209 # to "(", all close brackets to ")", then collapse runs of
210 # uninteresting characters. This can cut the number of chars
211 # by a factor of 10-40, and so greatly speed the following loop.
212 str = self.str
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000213 str = str.translate(_tran)
214 str = str.replace('xxxxxxxx', 'x')
215 str = str.replace('xxxx', 'x')
216 str = str.replace('xx', 'x')
217 str = str.replace('xx', 'x')
218 str = str.replace('\nx', '\n')
David Scherer7aced172000-08-15 01:13:23 +0000219 # note that replacing x\n with \n would be incorrect, because
220 # x may be preceded by a backslash
221
222 # March over the squashed version of the program, accumulating
223 # the line numbers of non-continued stmts, and determining
224 # whether & why the last stmt is a continuation.
225 continuation = C_NONE
226 level = lno = 0 # level is nesting level; lno is line number
227 self.goodlines = goodlines = [0]
228 push_good = goodlines.append
229 i, n = 0, len(str)
230 while i < n:
231 ch = str[i]
232 i = i+1
233
234 # cases are checked in decreasing order of frequency
235 if ch == 'x':
236 continue
237
238 if ch == '\n':
239 lno = lno + 1
240 if level == 0:
241 push_good(lno)
242 # else we're in an unclosed bracket structure
243 continue
244
245 if ch == '(':
246 level = level + 1
247 continue
248
249 if ch == ')':
250 if level:
251 level = level - 1
252 # else the program is invalid, but we can't complain
253 continue
254
255 if ch == '"' or ch == "'":
256 # consume the string
257 quote = ch
258 if str[i-1:i+2] == quote * 3:
259 quote = quote * 3
Kurt B. Kaiserb61602c2005-11-15 07:20:06 +0000260 firstlno = lno
David Scherer7aced172000-08-15 01:13:23 +0000261 w = len(quote) - 1
262 i = i+w
263 while i < n:
264 ch = str[i]
265 i = i+1
266
267 if ch == 'x':
268 continue
269
270 if str[i-1:i+w] == quote:
271 i = i+w
272 break
273
274 if ch == '\n':
275 lno = lno + 1
276 if w == 0:
277 # unterminated single-quoted string
278 if level == 0:
279 push_good(lno)
280 break
281 continue
282
283 if ch == '\\':
284 assert i < n
285 if str[i] == '\n':
286 lno = lno + 1
287 i = i+1
288 continue
289
290 # else comment char or paren inside string
291
292 else:
293 # didn't break out of the loop, so we're still
294 # inside a string
Kurt B. Kaiserb61602c2005-11-15 07:20:06 +0000295 if (lno - 1) == firstlno:
296 # before the previous \n in str, we were in the first
297 # line of the string
298 continuation = C_STRING_FIRST_LINE
299 else:
300 continuation = C_STRING_NEXT_LINES
David Scherer7aced172000-08-15 01:13:23 +0000301 continue # with outer loop
302
303 if ch == '#':
304 # consume the comment
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000305 i = str.find('\n', i)
David Scherer7aced172000-08-15 01:13:23 +0000306 assert i >= 0
307 continue
308
309 assert ch == '\\'
310 assert i < n
311 if str[i] == '\n':
312 lno = lno + 1
313 if i+1 == n:
314 continuation = C_BACKSLASH
315 i = i+1
316
317 # The last stmt may be continued for all 3 reasons.
318 # String continuation takes precedence over bracket
319 # continuation, which beats backslash continuation.
Kurt B. Kaiserb61602c2005-11-15 07:20:06 +0000320 if (continuation != C_STRING_FIRST_LINE
321 and continuation != C_STRING_NEXT_LINES and level > 0):
David Scherer7aced172000-08-15 01:13:23 +0000322 continuation = C_BRACKET
323 self.continuation = continuation
324
325 # Push the final line number as a sentinel value, regardless of
326 # whether it's continued.
327 assert (continuation == C_NONE) == (goodlines[-1] == lno)
328 if goodlines[-1] != lno:
329 push_good(lno)
330
331 def get_continuation_type(self):
332 self._study1()
333 return self.continuation
334
335 # study1 was sufficient to determine the continuation status,
336 # but doing more requires looking at every character. study2
337 # does this for the last interesting statement in the block.
338 # Creates:
339 # self.stmt_start, stmt_end
340 # slice indices of last interesting stmt
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000341 # self.stmt_bracketing
342 # the bracketing structure of the last interesting stmt;
343 # for example, for the statement "say(boo) or die", stmt_bracketing
344 # will be [(0, 0), (3, 1), (8, 0)]. Strings and comments are
345 # treated as brackets, for the matter.
David Scherer7aced172000-08-15 01:13:23 +0000346 # self.lastch
347 # last non-whitespace character before optional trailing
348 # comment
349 # self.lastopenbracketpos
350 # if continuation is C_BRACKET, index of last open bracket
351
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000352 def _study2(self):
David Scherer7aced172000-08-15 01:13:23 +0000353 if self.study_level >= 2:
354 return
355 self._study1()
356 self.study_level = 2
357
358 # Set p and q to slice indices of last interesting stmt.
359 str, goodlines = self.str, self.goodlines
360 i = len(goodlines) - 1
361 p = len(str) # index of newest line
362 while i:
363 assert p
364 # p is the index of the stmt at line number goodlines[i].
365 # Move p back to the stmt at line number goodlines[i-1].
366 q = p
367 for nothing in range(goodlines[i-1], goodlines[i]):
368 # tricky: sets p to 0 if no preceding newline
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000369 p = str.rfind('\n', 0, p-1) + 1
David Scherer7aced172000-08-15 01:13:23 +0000370 # The stmt str[p:q] isn't a continuation, but may be blank
371 # or a non-indenting comment line.
372 if _junkre(str, p):
373 i = i-1
374 else:
375 break
376 if i == 0:
377 # nothing but junk!
378 assert p == 0
379 q = p
380 self.stmt_start, self.stmt_end = p, q
381
382 # Analyze this stmt, to find the last open bracket (if any)
383 # and last interesting character (if any).
384 lastch = ""
385 stack = [] # stack of open bracket indices
386 push_stack = stack.append
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000387 bracketing = [(p, 0)]
David Scherer7aced172000-08-15 01:13:23 +0000388 while p < q:
389 # suck up all except ()[]{}'"#\\
390 m = _chew_ordinaryre(str, p, q)
391 if m:
392 # we skipped at least one boring char
Kurt B. Kaiser3269cc82001-07-13 20:33:46 +0000393 newp = m.end()
David Scherer7aced172000-08-15 01:13:23 +0000394 # back up over totally boring whitespace
Kurt B. Kaiser3269cc82001-07-13 20:33:46 +0000395 i = newp - 1 # index of last boring char
396 while i >= p and str[i] in " \t\n":
David Scherer7aced172000-08-15 01:13:23 +0000397 i = i-1
Kurt B. Kaiser3269cc82001-07-13 20:33:46 +0000398 if i >= p:
David Scherer7aced172000-08-15 01:13:23 +0000399 lastch = str[i]
Kurt B. Kaiser3269cc82001-07-13 20:33:46 +0000400 p = newp
David Scherer7aced172000-08-15 01:13:23 +0000401 if p >= q:
402 break
403
404 ch = str[p]
405
406 if ch in "([{":
407 push_stack(p)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000408 bracketing.append((p, len(stack)))
David Scherer7aced172000-08-15 01:13:23 +0000409 lastch = ch
410 p = p+1
411 continue
412
413 if ch in ")]}":
414 if stack:
415 del stack[-1]
416 lastch = ch
417 p = p+1
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000418 bracketing.append((p, len(stack)))
David Scherer7aced172000-08-15 01:13:23 +0000419 continue
420
421 if ch == '"' or ch == "'":
422 # consume string
423 # Note that study1 did this with a Python loop, but
424 # we use a regexp here; the reason is speed in both
425 # cases; the string may be huge, but study1 pre-squashed
426 # strings to a couple of characters per line. study1
427 # also needed to keep track of newlines, and we don't
428 # have to.
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000429 bracketing.append((p, len(stack)+1))
David Scherer7aced172000-08-15 01:13:23 +0000430 lastch = ch
431 p = _match_stringre(str, p, q).end()
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000432 bracketing.append((p, len(stack)))
David Scherer7aced172000-08-15 01:13:23 +0000433 continue
434
435 if ch == '#':
436 # consume comment and trailing newline
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000437 bracketing.append((p, len(stack)+1))
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000438 p = str.find('\n', p, q) + 1
David Scherer7aced172000-08-15 01:13:23 +0000439 assert p > 0
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000440 bracketing.append((p, len(stack)))
David Scherer7aced172000-08-15 01:13:23 +0000441 continue
442
443 assert ch == '\\'
444 p = p+1 # beyond backslash
445 assert p < q
446 if str[p] != '\n':
447 # the program is invalid, but can't complain
448 lastch = ch + str[p]
449 p = p+1 # beyond escaped char
450
451 # end while p < q:
452
453 self.lastch = lastch
454 if stack:
455 self.lastopenbracketpos = stack[-1]
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000456 self.stmt_bracketing = tuple(bracketing)
David Scherer7aced172000-08-15 01:13:23 +0000457
458 # Assuming continuation is C_BRACKET, return the number
459 # of spaces the next line should be indented.
460
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000461 def compute_bracket_indent(self):
David Scherer7aced172000-08-15 01:13:23 +0000462 self._study2()
463 assert self.continuation == C_BRACKET
464 j = self.lastopenbracketpos
465 str = self.str
466 n = len(str)
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000467 origi = i = str.rfind('\n', 0, j) + 1
David Scherer7aced172000-08-15 01:13:23 +0000468 j = j+1 # one beyond open bracket
469 # find first list item; set i to start of its line
470 while j < n:
471 m = _itemre(str, j)
472 if m:
473 j = m.end() - 1 # index of first interesting char
474 extra = 0
475 break
476 else:
477 # this line is junk; advance to next line
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000478 i = j = str.find('\n', j) + 1
David Scherer7aced172000-08-15 01:13:23 +0000479 else:
480 # nothing interesting follows the bracket;
481 # reproduce the bracket line's indentation + a level
482 j = i = origi
483 while str[j] in " \t":
484 j = j+1
485 extra = self.indentwidth
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000486 return len(str[i:j].expandtabs(self.tabwidth)) + extra
David Scherer7aced172000-08-15 01:13:23 +0000487
488 # Return number of physical lines in last stmt (whether or not
489 # it's an interesting stmt! this is intended to be called when
490 # continuation is C_BACKSLASH).
491
492 def get_num_lines_in_stmt(self):
493 self._study1()
494 goodlines = self.goodlines
495 return goodlines[-1] - goodlines[-2]
496
497 # Assuming continuation is C_BACKSLASH, return the number of spaces
498 # the next line should be indented. Also assuming the new line is
499 # the first one following the initial line of the stmt.
500
501 def compute_backslash_indent(self):
502 self._study2()
503 assert self.continuation == C_BACKSLASH
504 str = self.str
505 i = self.stmt_start
506 while str[i] in " \t":
507 i = i+1
508 startpos = i
509
510 # See whether the initial line starts an assignment stmt; i.e.,
511 # look for an = operator
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000512 endpos = str.find('\n', startpos) + 1
David Scherer7aced172000-08-15 01:13:23 +0000513 found = level = 0
514 while i < endpos:
515 ch = str[i]
516 if ch in "([{":
517 level = level + 1
518 i = i+1
519 elif ch in ")]}":
520 if level:
521 level = level - 1
522 i = i+1
523 elif ch == '"' or ch == "'":
524 i = _match_stringre(str, i, endpos).end()
525 elif ch == '#':
526 break
527 elif level == 0 and ch == '=' and \
528 (i == 0 or str[i-1] not in "=<>!") and \
529 str[i+1] != '=':
530 found = 1
531 break
532 else:
533 i = i+1
534
535 if found:
536 # found a legit =, but it may be the last interesting
537 # thing on the line
538 i = i+1 # move beyond the =
539 found = re.match(r"\s*\\", str[i:endpos]) is None
540
541 if not found:
542 # oh well ... settle for moving beyond the first chunk
543 # of non-whitespace chars
544 i = startpos
545 while str[i] not in " \t\n":
546 i = i+1
547
Kurt B. Kaiser254eb532002-09-17 03:55:13 +0000548 return len(str[self.stmt_start:i].expandtabs(\
David Scherer7aced172000-08-15 01:13:23 +0000549 self.tabwidth)) + 1
550
551 # Return the leading whitespace on the initial line of the last
552 # interesting stmt.
553
554 def get_base_indent_string(self):
555 self._study2()
556 i, n = self.stmt_start, self.stmt_end
557 j = i
558 str = self.str
559 while j < n and str[j] in " \t":
560 j = j + 1
561 return str[i:j]
562
563 # Did the last interesting stmt open a block?
564
565 def is_block_opener(self):
566 self._study2()
567 return self.lastch == ':'
568
569 # Did the last interesting stmt close a block?
570
571 def is_block_closer(self):
572 self._study2()
573 return _closere(self.str, self.stmt_start) is not None
574
575 # index of last open bracket ({[, or None if none
576 lastopenbracketpos = None
577
578 def get_last_open_bracket_pos(self):
579 self._study2()
580 return self.lastopenbracketpos
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000581
582 # the structure of the bracketing of the last interesting statement,
583 # in the format defined in _study2, or None if the text didn't contain
584 # anything
585 stmt_bracketing = None
586
587 def get_last_stmt_bracketing(self):
588 self._study2()
589 return self.stmt_bracketing