blob: 28bd7011be1d458e091553151df81dfa5c397e2f [file] [log] [blame]
Guido van Rossum9ab75cb1998-03-31 14:31:39 +00001#! /home/guido/python/src/sparc/python
2#! /usr/bin/env python
3
4"""The Tab Nanny despises ambiguous indentation. She knows no mercy.
5
6CAUTION: this version requires Guido's "NL" patch to lib/tokenize.py,
7posted 30-Mar-98. This version will not run at all with an unpatched
8tokenize (it will raise AttributeError while loading), while previous
9versions will run incorrectly with the patched tokenize.
10"""
11
12# Released to the public domain, by Tim Peters, 30 March 1998.
13
14__version__ = "2"
15
16import os
17import sys
18import getopt
19import tokenize
20
21try:
22 tokenize.NL
23except AttributeError:
24 raise AttributeError, "Sorry, I need a version of tokenize.py " \
25 "that supports the NL pseudo-token."
26
27verbose = 0
28
29def main():
30 global verbose
31 try:
32 opts, args = getopt.getopt(sys.argv[1:], "v")
33 except getopt.error, msg:
34 print msg
35 for o, a in opts:
36 if o == '-v':
37 verbose = verbose + 1
38 for arg in args:
39 check(arg)
40
41class NannyNag:
42 def __init__(self, lineno, msg, line):
43 self.lineno, self.msg, self.line = lineno, msg, line
44 def get_lineno(self):
45 return self.lineno
46 def get_msg(self):
47 return self.msg
48 def get_line(self):
49 return self.line
50
51def check(file):
52 if os.path.isdir(file) and not os.path.islink(file):
53 if verbose:
54 print "%s: listing directory" % `file`
55 names = os.listdir(file)
56 for name in names:
57 fullname = os.path.join(file, name)
58 if (os.path.isdir(fullname) and
59 not os.path.islink(fullname) or
60 os.path.normcase(name[-3:]) == ".py"):
61 check(fullname)
62 return
63
64 try:
65 f = open(file)
66 except IOError, msg:
67 print "%s: I/O Error: %s" % (`file`, str(msg))
68 return
69
70 if verbose > 1:
71 print "checking", `file`, "..."
72
73 reset_globals()
74 try:
75 tokenize.tokenize(f.readline, tokeneater)
76
77 except tokenize.TokenError, msg:
78 print "%s: Token Error: %s" % (`fname`, str(msg))
79 return
80
81 except NannyNag, nag:
82 badline = nag.get_lineno()
83 line = nag.get_line()
84 if verbose:
85 print "%s: *** Line %d: trouble in tab city! ***" % (
86 `file`, badline)
87 print "offending line:", `line`
88 print nag.get_msg()
89 else:
90 print file, badline, `line`
91 return
92
93 if verbose:
94 print "%s: Clean bill of health." % `file`
95
96class Whitespace:
97 # the characters used for space and tab
98 S, T = ' \t'
99
100 # members:
101 # raw
102 # the original string
103 # n
104 # the number of leading whitespace characters in raw
105 # nt
106 # the number of tabs in raw[:n]
107 # norm
108 # the normal form as a pair (count, trailing), where:
109 # count
110 # a tuple such that raw[:n] contains count[i]
111 # instances of S * i + T
112 # trailing
113 # the number of trailing spaces in raw[:n]
114 # It's A Theorem that m.indent_level(t) ==
115 # n.indent_level(t) for all t >= 1 iff m.norm == n.norm.
116 # is_simple
117 # true iff raw[:n] is of the form (T*)(S*)
118
119 def __init__(self, ws):
120 self.raw = ws
121 S, T = Whitespace.S, Whitespace.T
122 count = []
123 b = n = nt = 0
124 for ch in self.raw:
125 if ch == S:
126 n = n + 1
127 b = b + 1
128 elif ch == T:
129 n = n + 1
130 nt = nt + 1
131 if b >= len(count):
132 count = count + [0] * (b - len(count) + 1)
133 count[b] = count[b] + 1
134 b = 0
135 else:
136 break
137 self.n = n
138 self.nt = nt
139 self.norm = tuple(count), b
140 self.is_simple = len(count) <= 1
141
142 # return length of longest contiguous run of spaces (whether or not
143 # preceding a tab)
144 def longest_run_of_spaces(self):
145 count, trailing = self.norm
146 return max(len(count)-1, trailing)
147
148 def indent_level(self, tabsize):
149 # count, il = self.norm
150 # for i in range(len(count)):
151 # if count[i]:
152 # il = il + (i/tabsize + 1)*tabsize * count[i]
153 # return il
154
155 # quicker:
156 # il = trailing + sum (i/ts + 1)*ts*count[i] =
157 # trailing + ts * sum (i/ts + 1)*count[i] =
158 # trailing + ts * sum i/ts*count[i] + count[i] =
159 # trailing + ts * [(sum i/ts*count[i]) + (sum count[i])] =
160 # trailing + ts * [(sum i/ts*count[i]) + num_tabs]
161 # and note that i/ts*count[i] is 0 when i < ts
162
163 count, trailing = self.norm
164 il = 0
165 for i in range(tabsize, len(count)):
166 il = il + i/tabsize * count[i]
167 return trailing + tabsize * (il + self.nt)
168
169 # return true iff self.indent_level(t) == other.indent_level(t)
170 # for all t >= 1
171 def equal(self, other):
172 return self.norm == other.norm
173
174 # return a list of tuples (ts, i1, i2) such that
175 # i1 == self.indent_level(ts) != other.indent_level(ts) == i2.
176 # Intended to be used after not self.equal(other) is known, in which
177 # case it will return at least one witnessing tab size.
178 def not_equal_witness(self, other):
179 n = max(self.longest_run_of_spaces(),
180 other.longest_run_of_spaces()) + 1
181 a = []
182 for ts in range(1, n+1):
183 if self.indent_level(ts) != other.indent_level(ts):
184 a.append( (ts,
185 self.indent_level(ts),
186 other.indent_level(ts)) )
187 return a
188
189 # Return true iff self.indent_level(t) < other.indent_level(t)
190 # for all t >= 1.
191 # The algorithm is due to Vincent Broman.
192 # Easy to prove it's correct.
193 # XXXpost that.
194 # Trivial to prove n is sharp (consider T vs ST).
195 # Unknown whether there's a faster general way. I suspected so at
196 # first, but no longer.
197 # For the special (but common!) case where M and N are both of the
198 # form (T*)(S*), M.less(N) iff M.len() < N.len() and
199 # M.num_tabs() <= N.num_tabs(). Proof is easy but kinda long-winded.
200 # XXXwrite that up.
201 # Note that M is of the form (T*)(S*) iff len(M.norm[0]) <= 1.
202 def less(self, other):
203 if self.n >= other.n:
204 return 0
205 if self.is_simple and other.is_simple:
206 return self.nt <= other.nt
207 n = max(self.longest_run_of_spaces(),
208 other.longest_run_of_spaces()) + 1
209 # the self.n >= other.n test already did it for ts=1
210 for ts in range(2, n+1):
211 if self.indent_level(ts) >= other.indent_level(ts):
212 return 0
213 return 1
214
215 # return a list of tuples (ts, i1, i2) such that
216 # i1 == self.indent_level(ts) >= other.indent_level(ts) == i2.
217 # Intended to be used after not self.less(other) is known, in which
218 # case it will return at least one witnessing tab size.
219 def not_less_witness(self, other):
220 n = max(self.longest_run_of_spaces(),
221 other.longest_run_of_spaces()) + 1
222 a = []
223 for ts in range(1, n+1):
224 if self.indent_level(ts) >= other.indent_level(ts):
225 a.append( (ts,
226 self.indent_level(ts),
227 other.indent_level(ts)) )
228 return a
229
230def format_witnesses(w):
231 import string
232 firsts = map(lambda tup: str(tup[0]), w)
233 prefix = "at tab size"
234 if len(w) > 1:
235 prefix = prefix + "s"
236 return prefix + " " + string.join(firsts, ', ')
237
238indents = []
239check_equal = 0
240
241def reset_globals():
242 global indents, check_equal
243 check_equal = 0
244 indents = [Whitespace("")]
245
246def tokeneater(type, token, start, end, line,
247 INDENT=tokenize.INDENT,
248 DEDENT=tokenize.DEDENT,
249 NEWLINE=tokenize.NEWLINE,
250 COMMENT=tokenize.COMMENT,
251 NL=tokenize.NL):
252 global indents, check_equal
253
254 # test in decreasing order of frequency, although the check_equal
255 # test *must* be last; INDENT and DEDENT appear equally often
256
257 if type in (COMMENT, NL):
258 # the indentation of these guys is meaningless
259 pass
260
261 elif type == NEWLINE:
262 # a program statement, or ENDMARKER, will eventually follow,
263 # after some (possibly empty) run of tokens of the form
264 # (NL | COMMENT)* (INDENT | DEDENT+)?
265 # If an INDENT appears, setting check_equal is wrong, and will
266 # be undone when we see the INDENT.
267 check_equal = 1
268
269 elif type == INDENT:
270 check_equal = 0
271 thisguy = Whitespace(token)
272 if not indents[-1].less(thisguy):
273 witness = indents[-1].not_less_witness(thisguy)
274 msg = "indent not greater e.g. " + format_witnesses(witness)
275 raise NannyNag(start[0], msg, line)
276 indents.append(thisguy)
277
278 elif type == DEDENT:
279 # there's nothing we need to check here! what's important is
280 # that when the run of DEDENTs ends, the indentation of the
281 # program statement (or ENDMARKER) that triggered the run is
282 # equal to what's left at the top of the indents stack
283 assert check_equal # else no earlier NEWLINE, or an earlier INDENT
284 del indents[-1]
285
286 elif check_equal:
287 # this is the first "real token" following a NEWLINE, so it
288 # must be the first token of the next program statment, or an
289 # ENDMARKER; the "line" argument exposes the leading whitespace
290 # for this statement; in the case of ENDMARKER, line is an empty
291 # string, so will properly match the empty string with which the
292 # "indents" stack was seeded
293 check_equal = 0
294 thisguy = Whitespace(line)
295 if not indents[-1].equal(thisguy):
296 witness = indents[-1].not_equal_witness(thisguy)
297 msg = "indent not equal e.g. " + format_witnesses(witness)
298 raise NannyNag(start[0], msg, line)
299
300if __name__ == '__main__':
301 main()
302