Debian Codegraph @

scripts/debug_lexer.py

raw
1 #!/usr/bin/python
2 """
3 Lexing error finder
4 ~~~~~~~~~~~~~~~~~~~
5
6 For the source files given on the command line, display
7 the text where Error tokens are being generated, along
8 with some context.
9
10 :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
11 :license: BSD, see LICENSE for details.
12 """
13
14 import os
15 import sys
16 import struct
17
18 # always prefer Pygments from source if exists
19 srcpath = os.path.join(os.path.dirname(__file__), '..')
20 if os.path.isdir(os.path.join(srcpath, 'pygments')):
21 sys.path.insert(0, srcpath)
22
23 # ruff: noqa: E402
24 from pygments.lexer import ExtendedRegexLexer, LexerContext
25 from pygments.lexers import get_lexer_by_name, find_lexer_class, \
26 find_lexer_class_for_filename, guess_lexer
27 from pygments.token import Error, Text, _TokenType
28 from pygments.cmdline import _parse_options
29
30
31 class DebuggingRegexLexer(ExtendedRegexLexer):
32 """Make the state stack, position and current match instance attributes."""
33
34 def get_tokens_unprocessed(self, text, stack=('root',)):
35 """
36 Split ``text`` into (tokentype, text) pairs.
37
38 ``stack`` is the initial stack (default: ``['root']``)
39 """
40 tokendefs = self._tokens
41 self.ctx = ctx = LexerContext(text, 0)
42 ctx.stack = list(stack)
43 statetokens = tokendefs[ctx.stack[-1]]
44 while 1:
45 for rexmatch, action, new_state in statetokens:
46 self.m = m = rexmatch(text, ctx.pos, ctx.end)
47 if m:
48 if action is not None:
49 if type(action) is _TokenType:
50 yield ctx.pos, action, m.group()
51 ctx.pos = m.end()
52 else:
53 if not isinstance(self, ExtendedRegexLexer):
54 yield from action(self, m)
55 ctx.pos = m.end()
56 else:
57 yield from action(self, m, ctx)
58 if not new_state:
59 # altered the state stack?
60 statetokens = tokendefs[ctx.stack[-1]]
61 if new_state is not None:
62 # state transition
63 if isinstance(new_state, tuple):
64 for state in new_state:
65 if state == '#pop':
66 ctx.stack.pop()
67 elif state == '#push':
68 ctx.stack.append(ctx.stack[-1])
69 else:
70 ctx.stack.append(state)
71 elif isinstance(new_state, int):
72 # pop
73 del ctx.stack[new_state:]
74 elif new_state == '#push':
75 ctx.stack.append(ctx.stack[-1])
76 else:
77 assert False, f'wrong state def: {new_state!r}'
78 statetokens = tokendefs[ctx.stack[-1]]
79 break
80 else:
81 try:
82 if ctx.pos >= ctx.end:
83 break
84 if text[ctx.pos] == '\n':
85 # at EOL, reset state to 'root'
86 ctx.stack = ['root']
87 statetokens = tokendefs['root']
88 yield ctx.pos, Text, '\n'
89 ctx.pos += 1
90 continue
91 yield ctx.pos, Error, text[ctx.pos]
92 ctx.pos += 1
93 except IndexError:
94 break
95
96
97 def decode_atheris(bstr):
98 """Decode a byte string into a Unicode string using the algorithm
99 of Google's Atheris fuzzer library, which aims to produce a wide
100 range of possible Unicode inputs.
101
102 Corresponds to ConsumeUnicodeImpl() with filter_surrogates=false in
103 https://github.com/google/atheris/blob/master/fuzzed_data_provider.cc
104 """
105 if len(bstr) < 2:
106 return ''
107 # The first byte only selects if the rest is decoded as ascii, "utf-16" or "utf-32"
108 spec, bstr = bstr[0], bstr[1:]
109 if spec & 1: # pure ASCII
110 return ''.join(chr(ch & 0x7f) for ch in bstr)
111 elif spec & 2: # UTF-16
112 bstr = bstr if len(bstr) % 2 == 0 else bstr[:-1]
113 return bstr.decode('utf16')
114
115 # else UTF-32
116 def valid_codepoint(ch):
117 ch &= 0x1fffff
118 if ch & 0x100000:
119 ch &= ~0x0f0000
120 return chr(ch)
121
122 chars = struct.unpack('%dI%dx' % divmod(len(bstr), 4), bstr)
123 return ''.join(map(valid_codepoint, chars))
124
125
126 def main(fn, lexer=None, options={}):
127 if fn == '-':
128 text = sys.stdin.read()
129 else:
130 with open(fn, 'rb') as fp:
131 text = fp.read()
132 if decode_strategy == 'latin1':
133 try:
134 text = text.decode('utf8')
135 except UnicodeError:
136 print('Warning: non-UTF8 input, using latin1')
137 text = text.decode('latin1')
138 elif decode_strategy == 'utf8-ignore':
139 try:
140 text = text.decode('utf8')
141 except UnicodeError:
142 print('Warning: ignoring non-UTF8 bytes in input')
143 text = text.decode('utf8', 'ignore')
144 elif decode_strategy == 'atheris':
145 text = decode_atheris(text)
146
147 text = text.strip('\n') + '\n'
148
149 if lexer is not None:
150 lxcls = get_lexer_by_name(lexer).__class__
151 elif guess:
152 lxcls = guess_lexer(text).__class__
153 print(f'Using lexer: {lxcls.name} ({lxcls.__module__}.{lxcls.__name__})')
154 else:
155 lxcls = find_lexer_class_for_filename(os.path.basename(fn))
156 if lxcls is None:
157 name, rest = fn.split('_', 1)
158 lxcls = find_lexer_class(name)
159 if lxcls is None:
160 raise AssertionError(f'no lexer found for file {fn!r}')
161 print(f'Using lexer: {lxcls.name} ({lxcls.__module__}.{lxcls.__name__})')
162 debug_lexer = False
163 # if profile:
164 # # does not work for e.g. ExtendedRegexLexers
165 # if lxcls.__bases__ == (RegexLexer,):
166 # # yes we can! (change the metaclass)
167 # lxcls.__class__ = ProfilingRegexLexerMeta
168 # lxcls.__bases__ = (ProfilingRegexLexer,)
169 # lxcls._prof_sort_index = profsort
170 # else:
171 # if lxcls.__bases__ == (RegexLexer,):
172 # lxcls.__bases__ = (DebuggingRegexLexer,)
173 # debug_lexer = True
174 # elif lxcls.__bases__ == (DebuggingRegexLexer,):
175 # # already debugged before
176 # debug_lexer = True
177 # else:
178 # # HACK: ExtendedRegexLexer subclasses will only partially work here.
179 # lxcls.__bases__ = (DebuggingRegexLexer,)
180 # debug_lexer = True
181
182 lx = lxcls(**options)
183 lno = 1
184 tokens = []
185 states = []
186
187 def show_token(tok, state):
188 reprs = list(map(repr, tok))
189 print(' ' + reprs[1] + ' ' + ' ' * (29-len(reprs[1])) + reprs[0], end=' ')
190 if debug_lexer:
191 print(' ' + ' ' * (29-len(reprs[0])) + ' : '.join(state)
192 if state else '', end=' ')
193 print()
194
195 for type, val in lx.get_tokens(text):
196 lno += val.count('\n')
197 if type == Error and not ignerror:
198 print('Error parsing', fn, 'on line', lno)
199 if not showall:
200 print('Previous tokens' + (debug_lexer and ' and states' or '') + ':')
201 for i in range(max(len(tokens) - num, 0), len(tokens)):
202 if debug_lexer:
203 show_token(tokens[i], states[i])
204 else:
205 show_token(tokens[i], None)
206 print('Error token:')
207 vlen = len(repr(val))
208 print(' ' + repr(val), end=' ')
209 if debug_lexer and hasattr(lx, 'ctx'):
210 print(' ' * (60-vlen) + ' : '.join(lx.ctx.stack), end=' ')
211 print()
212 print()
213 return 1
214 tokens.append((type, val))
215 if debug_lexer:
216 if hasattr(lx, 'ctx'):
217 states.append(lx.ctx.stack[:])
218 else:
219 states.append(None)
220 if showall:
221 show_token((type, val), states[-1] if debug_lexer else None)
222 return 0
223
224
225 def print_help():
226 print('''\
227 Pygments development helper to quickly debug lexers.
228
229 scripts/debug_lexer.py [options] file ...
230
231 Give one or more filenames to lex them and display possible error tokens
232 and/or profiling info. Files are assumed to be encoded in UTF-8.
233
234 Selecting lexer and options:
235
236 -l NAME use lexer named NAME (default is to guess from
237 the given filenames)
238 -g guess lexer from content
239 -u if input is non-utf8, use "ignore" handler instead
240 of using latin1 encoding
241 -U use Atheris fuzzer's method of converting
242 byte input to Unicode
243 -O OPTIONSTR use lexer options parsed from OPTIONSTR
244
245 Debugging lexing errors:
246
247 -n N show the last N tokens on error
248 -a always show all lexed tokens (default is only
249 to show them when an error occurs)
250 -e do not stop on error tokens
251
252 Profiling:
253
254 -p use the ProfilingRegexLexer to profile regexes
255 instead of the debugging lexer
256 -s N sort profiling output by column N (default is
257 column 4, the time per call)
258 ''')
259
260
261 num = 10
262 showall = False
263 ignerror = False
264 lexer = None
265 options = {}
266 profile = False
267 profsort = 4
268 guess = False
269 decode_strategy = 'latin1'
270
271 if __name__ == '__main__':
272 import getopt
273 opts, args = getopt.getopt(sys.argv[1:], 'n:l:aepO:s:hguU')
274 for opt, val in opts:
275 if opt == '-n':
276 num = int(val)
277 elif opt == '-a':
278 showall = True
279 elif opt == '-e':
280 ignerror = True
281 elif opt == '-l':
282 lexer = val
283 elif opt == '-p':
284 profile = True
285 elif opt == '-s':
286 profsort = int(val)
287 elif opt == '-O':
288 options = _parse_options([val])
289 elif opt == '-g':
290 guess = True
291 elif opt == '-u':
292 decode_strategy = 'utf8-ignore'
293 elif opt == '-U':
294 decode_strategy = 'atheris'
295 elif opt == '-h':
296 print_help()
297 sys.exit(0)
298 ret = 0
299 if not args:
300 print_help()
301 for f in args:
302 ret += main(f, lexer, options)
303 sys.exit(bool(ret))