3 """The Tab Nanny despises ambiguous indentation. She knows no mercy."""
5 # Released to the public domain, by Tim Peters, 15 April 1998.
19 sys
.stderr
.write(sep
+ str(arg
))
21 sys
.stderr
.write("\n")
26 opts
, args
= getopt
.getopt(sys
.argv
[1:], "v")
27 except getopt
.error
, msg
:
34 errprint("Usage:", sys
.argv
[0], "[-v] file_or_directory ...")
40 def __init__(self
, lineno
, msg
, line
):
41 self
.lineno
, self
.msg
, self
.line
= lineno
, msg
, line
50 if os
.path
.isdir(file) and not os
.path
.islink(file):
52 print "%s: listing directory" % `
file`
53 names
= os
.listdir(file)
55 fullname
= os
.path
.join(file, name
)
56 if (os
.path
.isdir(fullname
) and
57 not os
.path
.islink(fullname
) or
58 os
.path
.normcase(name
[-3:]) == ".py"):
65 errprint("%s: I/O Error: %s" % (`
file`
, str(msg
)))
69 print "checking", `
file`
, "..."
73 tokenize
.tokenize(f
.readline
, tokeneater
)
75 except tokenize
.TokenError
, msg
:
76 errprint("%s: Token Error: %s" % (`
file`
, str(msg
)))
80 badline
= nag
.get_lineno()
83 print "%s: *** Line %d: trouble in tab city! ***" % (
85 print "offending line:", `line`
88 print file, badline
, `line`
92 print "%s: Clean bill of health." % `
file`
95 # the characters used for space and tab
100 # the original string
102 # the number of leading whitespace characters in raw
104 # the number of tabs in raw[:n]
106 # the normal form as a pair (count, trailing), where:
108 # a tuple such that raw[:n] contains count[i]
109 # instances of S * i + T
111 # the number of trailing spaces in raw[:n]
112 # It's A Theorem that m.indent_level(t) ==
113 # n.indent_level(t) for all t >= 1 iff m.norm == n.norm.
115 # true iff raw[:n] is of the form (T*)(S*)
117 def __init__(self
, ws
):
119 S
, T
= Whitespace
.S
, Whitespace
.T
130 count
= count
+ [0] * (b
- len(count
) + 1)
131 count
[b
] = count
[b
] + 1
137 self
.norm
= tuple(count
), b
138 self
.is_simple
= len(count
) <= 1
140 # return length of longest contiguous run of spaces (whether or not
142 def longest_run_of_spaces(self
):
143 count
, trailing
= self
.norm
144 return max(len(count
)-1, trailing
)
146 def indent_level(self
, tabsize
):
147 # count, il = self.norm
148 # for i in range(len(count)):
150 # il = il + (i/tabsize + 1)*tabsize * count[i]
154 # il = trailing + sum (i/ts + 1)*ts*count[i] =
155 # trailing + ts * sum (i/ts + 1)*count[i] =
156 # trailing + ts * sum i/ts*count[i] + count[i] =
157 # trailing + ts * [(sum i/ts*count[i]) + (sum count[i])] =
158 # trailing + ts * [(sum i/ts*count[i]) + num_tabs]
159 # and note that i/ts*count[i] is 0 when i < ts
161 count
, trailing
= self
.norm
163 for i
in range(tabsize
, len(count
)):
164 il
= il
+ i
/tabsize
* count
[i
]
165 return trailing
+ tabsize
* (il
+ self
.nt
)
167 # return true iff self.indent_level(t) == other.indent_level(t)
169 def equal(self
, other
):
170 return self
.norm
== other
.norm
172 # return a list of tuples (ts, i1, i2) such that
173 # i1 == self.indent_level(ts) != other.indent_level(ts) == i2.
174 # Intended to be used after not self.equal(other) is known, in which
175 # case it will return at least one witnessing tab size.
176 def not_equal_witness(self
, other
):
177 n
= max(self
.longest_run_of_spaces(),
178 other
.longest_run_of_spaces()) + 1
180 for ts
in range(1, n
+1):
181 if self
.indent_level(ts
) != other
.indent_level(ts
):
183 self
.indent_level(ts
),
184 other
.indent_level(ts
)) )
187 # Return true iff self.indent_level(t) < other.indent_level(t)
189 # The algorithm is due to Vincent Broman.
190 # Easy to prove it's correct.
192 # Trivial to prove n is sharp (consider T vs ST).
193 # Unknown whether there's a faster general way. I suspected so at
194 # first, but no longer.
195 # For the special (but common!) case where M and N are both of the
196 # form (T*)(S*), M.less(N) iff M.len() < N.len() and
197 # M.num_tabs() <= N.num_tabs(). Proof is easy but kinda long-winded.
199 # Note that M is of the form (T*)(S*) iff len(M.norm[0]) <= 1.
200 def less(self
, other
):
201 if self
.n
>= other
.n
:
203 if self
.is_simple
and other
.is_simple
:
204 return self
.nt
<= other
.nt
205 n
= max(self
.longest_run_of_spaces(),
206 other
.longest_run_of_spaces()) + 1
207 # the self.n >= other.n test already did it for ts=1
208 for ts
in range(2, n
+1):
209 if self
.indent_level(ts
) >= other
.indent_level(ts
):
213 # return a list of tuples (ts, i1, i2) such that
214 # i1 == self.indent_level(ts) >= other.indent_level(ts) == i2.
215 # Intended to be used after not self.less(other) is known, in which
216 # case it will return at least one witnessing tab size.
217 def not_less_witness(self
, other
):
218 n
= max(self
.longest_run_of_spaces(),
219 other
.longest_run_of_spaces()) + 1
221 for ts
in range(1, n
+1):
222 if self
.indent_level(ts
) >= other
.indent_level(ts
):
224 self
.indent_level(ts
),
225 other
.indent_level(ts
)) )
228 def format_witnesses(w
):
230 firsts
= map(lambda tup
: str(tup
[0]), w
)
231 prefix
= "at tab size"
233 prefix
= prefix
+ "s"
234 return prefix
+ " " + string
.join(firsts
, ', ')
236 # The collection of globals, the reset_globals() function, and the
237 # tokeneater() function, depend on which version of tokenize is
240 if hasattr(tokenize
, 'NL'):
241 # take advantage of Guido's patch!
247 global indents
, check_equal
249 indents
= [Whitespace("")]
251 def tokeneater(type, token
, start
, end
, line
,
252 INDENT
=tokenize
.INDENT
,
253 DEDENT
=tokenize
.DEDENT
,
254 NEWLINE
=tokenize
.NEWLINE
,
255 JUNK
=(tokenize
.COMMENT
, tokenize
.NL
) ):
256 global indents
, check_equal
259 # a program statement, or ENDMARKER, will eventually follow,
260 # after some (possibly empty) run of tokens of the form
261 # (NL | COMMENT)* (INDENT | DEDENT+)?
262 # If an INDENT appears, setting check_equal is wrong, and will
263 # be undone when we see the INDENT.
268 thisguy
= Whitespace(token
)
269 if not indents
[-1].less(thisguy
):
270 witness
= indents
[-1].not_less_witness(thisguy
)
271 msg
= "indent not greater e.g. " + format_witnesses(witness
)
272 raise NannyNag(start
[0], msg
, line
)
273 indents
.append(thisguy
)
276 # there's nothing we need to check here! what's important is
277 # that when the run of DEDENTs ends, the indentation of the
278 # program statement (or ENDMARKER) that triggered the run is
279 # equal to what's left at the top of the indents stack
281 # Ouch! This assert triggers if the last line of the source
282 # is indented *and* lacks a newline -- then DEDENTs pop out
284 # assert check_equal # else no earlier NEWLINE, or an earlier INDENT
289 elif check_equal
and type not in JUNK
:
290 # this is the first "real token" following a NEWLINE, so it
291 # must be the first token of the next program statement, or an
292 # ENDMARKER; the "line" argument exposes the leading whitespace
293 # for this statement; in the case of ENDMARKER, line is an empty
294 # string, so will properly match the empty string with which the
295 # "indents" stack was seeded
297 thisguy
= Whitespace(line
)
298 if not indents
[-1].equal(thisguy
):
299 witness
= indents
[-1].not_equal_witness(thisguy
)
300 msg
= "indent not equal e.g. " + format_witnesses(witness
)
301 raise NannyNag(start
[0], msg
, line
)
304 # unpatched version of tokenize
311 global nesting_level
, indents
, check_equal
312 nesting_level
= check_equal
= 0
313 indents
= [Whitespace("")]
315 def tokeneater(type, token
, start
, end
, line
,
316 INDENT
=tokenize
.INDENT
,
317 DEDENT
=tokenize
.DEDENT
,
318 NEWLINE
=tokenize
.NEWLINE
,
319 COMMENT
=tokenize
.COMMENT
,
321 global nesting_level
, indents
, check_equal
325 thisguy
= Whitespace(token
)
326 if not indents
[-1].less(thisguy
):
327 witness
= indents
[-1].not_less_witness(thisguy
)
328 msg
= "indent not greater e.g. " + format_witnesses(witness
)
329 raise NannyNag(start
[0], msg
, line
)
330 indents
.append(thisguy
)
335 elif type == NEWLINE
:
336 if nesting_level
== 0:
339 elif type == COMMENT
:
344 thisguy
= Whitespace(line
)
345 if not indents
[-1].equal(thisguy
):
346 witness
= indents
[-1].not_equal_witness(thisguy
)
347 msg
= "indent not equal e.g. " + format_witnesses(witness
)
348 raise NannyNag(start
[0], msg
, line
)
350 if type == OP
and token
in ('{', '[', '('):
351 nesting_level
= nesting_level
+ 1
353 elif type == OP
and token
in ('}', ']', ')'):
354 if nesting_level
== 0:
355 raise NannyNag(start
[0],
356 "unbalanced bracket '" + token
+ "'",
358 nesting_level
= nesting_level
- 1
360 if __name__
== '__main__':