blob: ddafe399dc683324323e2b974319efecd37e80b6 [file] [log] [blame]
Guido van Rossum8113cdc1999-06-01 19:49:21 +00001import string
2import re
3import sys
4
5# Reason last stmt is continued (or C_NONE if it's not).
6C_NONE, C_BACKSLASH, C_STRING, C_BRACKET = range(4)
7
8if 0: # for throwaway debugging output
9 def dump(*stuff):
Guido van Rossum8113cdc1999-06-01 19:49:21 +000010 sys.__stdout__.write(string.join(map(str, stuff), " ") + "\n")
11
Guido van Rossumbbaba851999-06-01 19:55:34 +000012# Find a def or class stmt.
13
Guido van Rossum8113cdc1999-06-01 19:49:21 +000014_defclassre = re.compile(r"""
15 ^
16 [ \t]*
17 (?:
18 def [ \t]+ [a-zA-Z_]\w* [ \t]* \(
19 | class [ \t]+ [a-zA-Z_]\w* [ \t]*
20 (?: \( .* \) )?
21 [ \t]* :
22 )
23""", re.VERBOSE | re.MULTILINE).search
24
Guido van Rossumbbaba851999-06-01 19:55:34 +000025# Match blank line or non-indenting comment line.
26
Guido van Rossum8113cdc1999-06-01 19:49:21 +000027_junkre = re.compile(r"""
28 [ \t]*
Guido van Rossumbbaba851999-06-01 19:55:34 +000029 (?: \# \S .* )?
Guido van Rossum8113cdc1999-06-01 19:49:21 +000030 \n
31""", re.VERBOSE).match
32
Guido van Rossumbbaba851999-06-01 19:55:34 +000033# Match any flavor of string; the terminating quote is optional
34# so that we're robust in the face of incomplete program text.
35
Guido van Rossum8113cdc1999-06-01 19:49:21 +000036_match_stringre = re.compile(r"""
37 \""" [^"\\]* (?:
38 (?: \\. | "(?!"") )
39 [^"\\]*
40 )*
41 (?: \""" )?
42
43| " [^"\\\n]* (?: \\. [^"\\\n]* )* "?
44
45| ''' [^'\\]* (?:
46 (?: \\. | '(?!'') )
47 [^'\\]*
48 )*
49 (?: ''' )?
50
51| ' [^'\\\n]* (?: \\. [^'\\\n]* )* '?
52""", re.VERBOSE | re.DOTALL).match
53
Guido van Rossumbbaba851999-06-01 19:55:34 +000054# Match a line that starts with something interesting;
55# used to find the first item of a bracket structure.
56
57_itemre = re.compile(r"""
Guido van Rossum8113cdc1999-06-01 19:49:21 +000058 [ \t]*
Guido van Rossumbbaba851999-06-01 19:55:34 +000059 [^\s#\\] # if we match, m.end()-1 is the interesting char
Guido van Rossum8113cdc1999-06-01 19:49:21 +000060""", re.VERBOSE).match
61
Guido van Rossumbbaba851999-06-01 19:55:34 +000062# Match start of stmts that should be followed by a dedent.
63
Guido van Rossum8113cdc1999-06-01 19:49:21 +000064_closere = re.compile(r"""
65 \s*
66 (?: return
67 | break
68 | continue
69 | raise
70 | pass
71 )
72 \b
73""", re.VERBOSE).match
74
Guido van Rossumbbaba851999-06-01 19:55:34 +000075# Chew up non-special chars as quickly as possible, but retaining
76# enough info to determine the last non-ws char seen; if match is
77# successful, and m.group(1) isn't None, m.end(1) less 1 is the
78# index of the last non-ws char matched.
79
80_chew_ordinaryre = re.compile(r"""
81 (?: \s+
82 | ( [^\s[\](){}#'"\\]+ )
83 )+
84""", re.VERBOSE).match
85
Guido van Rossum8113cdc1999-06-01 19:49:21 +000086# Build translation table to map uninteresting chars to "x", open
87# brackets to "(", and close brackets to ")".
88
89_tran = ['x'] * 256
90for ch in "({[":
91 _tran[ord(ch)] = '('
92for ch in ")}]":
93 _tran[ord(ch)] = ')'
94for ch in "\"'\\\n#":
95 _tran[ord(ch)] = ch
96_tran = string.join(_tran, '')
97del ch
98
99class Parser:
100
101 def __init__(self, indentwidth, tabwidth):
102 self.indentwidth = indentwidth
103 self.tabwidth = tabwidth
104
105 def set_str(self, str):
106 assert len(str) == 0 or str[-1] == '\n'
107 self.str = str
108 self.study_level = 0
109
110 # Return index of start of last (probable!) def or class stmt, or
111 # None if none found. It's only probable because we can't know
112 # whether we're in a string without reparsing from the start of
Guido van Rossumbbaba851999-06-01 19:55:34 +0000113 # the file -- and that's too slow in large files for routine use.
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000114 #
115 # Ack, hack: in the shell window this kills us, because there's
116 # no way to tell the differences between output, >>> etc and
117 # user input. Indeed, IDLE's first output line makes the rest
118 # look like it's in an unclosed paren!:
119 # Python 1.5.2 (#0, Apr 13 1999, ...
120
Guido van Rossumbbaba851999-06-01 19:55:34 +0000121 def find_last_def_or_class(self, use_ps1, _defclassre=_defclassre):
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000122 str, pos = self.str, None
Guido van Rossumbbaba851999-06-01 19:55:34 +0000123 if use_ps1:
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000124 # hack for shell window
125 ps1 = '\n' + sys.ps1
126 i = string.rfind(str, ps1)
127 if i >= 0:
128 pos = i + len(ps1)
129 self.str = str[:pos-1] + '\n' + str[pos:]
Guido van Rossumbbaba851999-06-01 19:55:34 +0000130 else:
131 i = 0
132 while 1:
133 m = _defclassre(str, i)
134 if m:
135 pos, i = m.span()
136 else:
137 break
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000138 return pos
139
140 # Throw away the start of the string. Intended to be called with
141 # find_last_def_or_class's result.
142
143 def set_lo(self, lo):
144 assert lo == 0 or self.str[lo-1] == '\n'
145 if lo > 0:
146 self.str = self.str[lo:]
147
148 # As quickly as humanly possible <wink>, find the line numbers (0-
149 # based) of the non-continuation lines.
Guido van Rossumbbaba851999-06-01 19:55:34 +0000150 # Creates self.{goodlines, continuation}.
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000151
152 def _study1(self, _replace=string.replace, _find=string.find):
153 if self.study_level >= 1:
154 return
155 self.study_level = 1
156
157 # Map all uninteresting characters to "x", all open brackets
158 # to "(", all close brackets to ")", then collapse runs of
159 # uninteresting characters. This can cut the number of chars
160 # by a factor of 10-40, and so greatly speed the following loop.
161 str = self.str
162 str = string.translate(str, _tran)
163 str = _replace(str, 'xxxxxxxx', 'x')
164 str = _replace(str, 'xxxx', 'x')
165 str = _replace(str, 'xx', 'x')
166 str = _replace(str, 'xx', 'x')
167 str = _replace(str, '\nx', '\n')
168 # note that replacing x\n with \n would be incorrect, because
169 # x may be preceded by a backslash
170
171 # March over the squashed version of the program, accumulating
172 # the line numbers of non-continued stmts, and determining
173 # whether & why the last stmt is a continuation.
174 continuation = C_NONE
175 level = lno = 0 # level is nesting level; lno is line number
Guido van Rossumbbaba851999-06-01 19:55:34 +0000176 self.goodlines = goodlines = [0]
177 push_good = goodlines.append
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000178 i, n = 0, len(str)
179 while i < n:
180 ch = str[i]
Guido van Rossumbbaba851999-06-01 19:55:34 +0000181 i = i+1
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000182
Guido van Rossumbbaba851999-06-01 19:55:34 +0000183 # cases are checked in decreasing order of frequency
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000184 if ch == 'x':
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000185 continue
186
187 if ch == '\n':
188 lno = lno + 1
189 if level == 0:
Guido van Rossumbbaba851999-06-01 19:55:34 +0000190 push_good(lno)
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000191 # else we're in an unclosed bracket structure
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000192 continue
193
194 if ch == '(':
195 level = level + 1
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000196 continue
197
198 if ch == ')':
199 if level:
200 level = level - 1
201 # else the program is invalid, but we can't complain
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000202 continue
203
204 if ch == '"' or ch == "'":
205 # consume the string
206 quote = ch
Guido van Rossumbbaba851999-06-01 19:55:34 +0000207 if str[i-1:i+2] == quote * 3:
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000208 quote = quote * 3
Guido van Rossumbbaba851999-06-01 19:55:34 +0000209 w = len(quote) - 1
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000210 i = i+w
211 while i < n:
212 ch = str[i]
Guido van Rossumbbaba851999-06-01 19:55:34 +0000213 i = i+1
214
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000215 if ch == 'x':
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000216 continue
217
Guido van Rossumbbaba851999-06-01 19:55:34 +0000218 if str[i-1:i+w] == quote:
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000219 i = i+w
220 break
221
222 if ch == '\n':
223 lno = lno + 1
Guido van Rossumbbaba851999-06-01 19:55:34 +0000224 if w == 0:
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000225 # unterminated single-quoted string
226 if level == 0:
Guido van Rossumbbaba851999-06-01 19:55:34 +0000227 push_good(lno)
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000228 break
229 continue
230
231 if ch == '\\':
Guido van Rossumbbaba851999-06-01 19:55:34 +0000232 assert i < n
233 if str[i] == '\n':
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000234 lno = lno + 1
Guido van Rossumbbaba851999-06-01 19:55:34 +0000235 i = i+1
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000236 continue
237
238 # else comment char or paren inside string
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000239
240 else:
Guido van Rossumbbaba851999-06-01 19:55:34 +0000241 # didn't break out of the loop, so we're still
242 # inside a string
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000243 continuation = C_STRING
Guido van Rossumbbaba851999-06-01 19:55:34 +0000244 continue # with outer loop
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000245
246 if ch == '#':
247 # consume the comment
248 i = _find(str, '\n', i)
249 assert i >= 0
250 continue
251
252 assert ch == '\\'
Guido van Rossumbbaba851999-06-01 19:55:34 +0000253 assert i < n
254 if str[i] == '\n':
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000255 lno = lno + 1
Guido van Rossumbbaba851999-06-01 19:55:34 +0000256 if i+1 == n:
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000257 continuation = C_BACKSLASH
Guido van Rossumbbaba851999-06-01 19:55:34 +0000258 i = i+1
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000259
260 # The last stmt may be continued for all 3 reasons.
261 # String continuation takes precedence over bracket
262 # continuation, which beats backslash continuation.
263 if continuation != C_STRING and level > 0:
264 continuation = C_BRACKET
265 self.continuation = continuation
266
Guido van Rossumbbaba851999-06-01 19:55:34 +0000267 # Push the final line number as a sentinel value, regardless of
268 # whether it's continued.
269 assert (continuation == C_NONE) == (goodlines[-1] == lno)
270 if goodlines[-1] != lno:
271 push_good(lno)
272
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000273 def get_continuation_type(self):
274 self._study1()
275 return self.continuation
276
277 # study1 was sufficient to determine the continuation status,
278 # but doing more requires looking at every character. study2
279 # does this for the last interesting statement in the block.
280 # Creates:
281 # self.stmt_start, stmt_end
282 # slice indices of last interesting stmt
283 # self.lastch
284 # last non-whitespace character before optional trailing
285 # comment
286 # self.lastopenbracketpos
287 # if continuation is C_BRACKET, index of last open bracket
288
289 def _study2(self, _rfind=string.rfind, _find=string.find,
290 _ws=string.whitespace):
291 if self.study_level >= 2:
292 return
293 self._study1()
294 self.study_level = 2
295
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000296 # Set p and q to slice indices of last interesting stmt.
Guido van Rossumbbaba851999-06-01 19:55:34 +0000297 str, goodlines = self.str, self.goodlines
298 i = len(goodlines) - 1
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000299 p = len(str) # index of newest line
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000300 while i:
301 assert p
Guido van Rossumbbaba851999-06-01 19:55:34 +0000302 # p is the index of the stmt at line number goodlines[i].
303 # Move p back to the stmt at line number goodlines[i-1].
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000304 q = p
Guido van Rossumbbaba851999-06-01 19:55:34 +0000305 for nothing in range(goodlines[i-1], goodlines[i]):
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000306 # tricky: sets p to 0 if no preceding newline
307 p = _rfind(str, '\n', 0, p-1) + 1
308 # The stmt str[p:q] isn't a continuation, but may be blank
309 # or a non-indenting comment line.
310 if _junkre(str, p):
311 i = i-1
312 else:
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000313 break
Guido van Rossumbbaba851999-06-01 19:55:34 +0000314 if i == 0:
315 # nothing but junk!
316 assert p == 0
317 q = p
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000318 self.stmt_start, self.stmt_end = p, q
319
320 # Analyze this stmt, to find the last open bracket (if any)
321 # and last interesting character (if any).
Guido van Rossumbbaba851999-06-01 19:55:34 +0000322 lastch = ""
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000323 stack = [] # stack of open bracket indices
324 push_stack = stack.append
325 while p < q:
Guido van Rossumbbaba851999-06-01 19:55:34 +0000326 # suck up all except ()[]{}'"#\\
327 m = _chew_ordinaryre(str, p, q)
328 if m:
329 i = m.end(1) - 1 # last non-ws (if any)
330 if i >= 0:
331 lastch = str[i]
332 p = m.end()
333 if p >= q:
334 break
335
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000336 ch = str[p]
Guido van Rossumbbaba851999-06-01 19:55:34 +0000337
338 if ch in "([{":
339 push_stack(p)
340 lastch = ch
341 p = p+1
342 continue
343
344 if ch in ")]}":
345 if stack:
346 del stack[-1]
347 lastch = ch
348 p = p+1
349 continue
350
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000351 if ch == '"' or ch == "'":
352 # consume string
353 # Note that study1 did this with a Python loop, but
354 # we use a regexp here; the reason is speed in both
355 # cases; the string may be huge, but study1 pre-squashed
356 # strings to a couple of characters per line. study1
357 # also needed to keep track of newlines, and we don't
358 # have to.
Guido van Rossumbbaba851999-06-01 19:55:34 +0000359 lastch = ch
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000360 p = _match_stringre(str, p, q).end()
361 continue
362
363 if ch == '#':
364 # consume comment and trailing newline
365 p = _find(str, '\n', p, q) + 1
366 assert p > 0
367 continue
368
Guido van Rossumbbaba851999-06-01 19:55:34 +0000369 assert ch == '\\'
370 p = p+1 # beyond backslash
371 assert p < q
372 if str[p] != '\n':
373 # the program is invalid, but can't complain
374 lastch = ch + str[p]
375 p = p+1 # beyond escaped char
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000376
377 # end while p < q:
378
Guido van Rossumbbaba851999-06-01 19:55:34 +0000379 self.lastch = lastch
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000380 if stack:
381 self.lastopenbracketpos = stack[-1]
382
383 # Assuming continuation is C_BRACKET, return the number
384 # of spaces the next line should be indented.
385
386 def compute_bracket_indent(self, _find=string.find):
387 self._study2()
388 assert self.continuation == C_BRACKET
389 j = self.lastopenbracketpos
390 str = self.str
391 n = len(str)
392 origi = i = string.rfind(str, '\n', 0, j) + 1
Guido van Rossumbbaba851999-06-01 19:55:34 +0000393 j = j+1 # one beyond open bracket
394 # find first list item; set i to start of its line
395 while j < n:
396 m = _itemre(str, j)
397 if m:
398 j = m.end() - 1 # index of first interesting char
399 extra = 0
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000400 break
Guido van Rossumbbaba851999-06-01 19:55:34 +0000401 else:
402 # this line is junk; advance to next line
403 i = j = _find(str, '\n', j) + 1
404 else:
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000405 # nothing interesting follows the bracket;
406 # reproduce the bracket line's indentation + a level
407 j = i = origi
Guido van Rossumbbaba851999-06-01 19:55:34 +0000408 while str[j] in " \t":
409 j = j+1
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000410 extra = self.indentwidth
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000411 return len(string.expandtabs(str[i:j],
412 self.tabwidth)) + extra
413
414 # Return number of physical lines in last stmt (whether or not
415 # it's an interesting stmt! this is intended to be called when
416 # continuation is C_BACKSLASH).
417
418 def get_num_lines_in_stmt(self):
419 self._study1()
Guido van Rossumbbaba851999-06-01 19:55:34 +0000420 goodlines = self.goodlines
421 return goodlines[-1] - goodlines[-2]
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000422
423 # Assuming continuation is C_BACKSLASH, return the number of spaces
424 # the next line should be indented. Also assuming the new line is
425 # the first one following the initial line of the stmt.
426
427 def compute_backslash_indent(self):
428 self._study2()
429 assert self.continuation == C_BACKSLASH
430 str = self.str
431 i = self.stmt_start
432 while str[i] in " \t":
433 i = i+1
434 startpos = i
Guido van Rossumbbaba851999-06-01 19:55:34 +0000435
436 # See whether the initial line starts an assignment stmt; i.e.,
437 # look for an = operator
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000438 endpos = string.find(str, '\n', startpos) + 1
439 found = level = 0
440 while i < endpos:
441 ch = str[i]
442 if ch in "([{":
443 level = level + 1
444 i = i+1
445 elif ch in ")]}":
446 if level:
447 level = level - 1
448 i = i+1
449 elif ch == '"' or ch == "'":
450 i = _match_stringre(str, i, endpos).end()
451 elif ch == '#':
452 break
453 elif level == 0 and ch == '=' and \
Guido van Rossumbbaba851999-06-01 19:55:34 +0000454 (i == 0 or str[i-1] not in "=<>!") and \
455 str[i+1] != '=':
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000456 found = 1
457 break
458 else:
459 i = i+1
460
461 if found:
462 # found a legit =, but it may be the last interesting
463 # thing on the line
464 i = i+1 # move beyond the =
465 found = re.match(r"\s*\\", str[i:endpos]) is None
466
467 if not found:
468 # oh well ... settle for moving beyond the first chunk
469 # of non-whitespace chars
470 i = startpos
471 while str[i] not in " \t\n":
472 i = i+1
473
474 return len(string.expandtabs(str[self.stmt_start :
475 i],
476 self.tabwidth)) + 1
477
478 # Return the leading whitespace on the initial line of the last
479 # interesting stmt.
480
481 def get_base_indent_string(self):
482 self._study2()
483 i, n = self.stmt_start, self.stmt_end
Guido van Rossum8113cdc1999-06-01 19:49:21 +0000484 j = i
485 str = self.str
486 while j < n and str[j] in " \t":
487 j = j + 1
488 return str[i:j]
489
490 # Did the last interesting stmt open a block?
491
492 def is_block_opener(self):
493 self._study2()
494 return self.lastch == ':'
495
496 # Did the last interesting stmt close a block?
497
498 def is_block_closer(self):
499 self._study2()
500 return _closere(self.str, self.stmt_start) is not None