Debian Codegraph @

pypy/interpreter/pyparser/pytokenizer.py

raw symbols SCIP
1 from pypy.interpreter.pyparser import automata
2 from pypy.interpreter.pyparser.parser import Token
3 from pypy.interpreter.pyparser.pygram import tokens
4 from pypy.interpreter.pyparser.pytoken import python_opmap
5 from pypy.interpreter.pyparser.error import TokenError, TokenIndentationError, TabError
6 from pypy.interpreter.pyparser.pytokenize import tabsize, alttabsize, whiteSpaceDFA, \
7 triple_quoted, endDFAs, single_quoted, pseudoDFA
8 from pypy.interpreter.astcompiler import consts
9 from rpython.rlib import rutf8
10
11 NAMECHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
12 NUMCHARS = '0123456789'
13 ALNUMCHARS = NAMECHARS + NUMCHARS
14 EXTENDED_ALNUMCHARS = ALNUMCHARS + '-.'
15 WHITESPACES = ' \t\n\r\v\f'
16 TYPE_COMMENT_PREFIX = 'type'
17 TYPE_IGNORE = 'ignore'
18
19 TRIPLE_QUOTE_UNTERMINATED_ERROR = "unterminated triple-quoted string literal"
20 SINGLE_QUOTE_UNTERMINATED_ERROR = "unterminated string literal"
21 EOF_MULTI_LINE_STATEMENT_ERROR = "unexpected end of file (EOF) in multi-line statement"
22
23 def match_encoding_declaration(comment):
24 """returns the declared encoding or None
25
26 This function is a replacement for :
27 >>> py_encoding = re.compile(r"coding[:=]\s*([-\w.]+)")
28 >>> py_encoding.search(comment)
29 """
30 index = comment.find('coding')
31 if index < 0:
32 return None
33 next_char = comment[index + 6]
34 if next_char not in ':=':
35 return None
36 end_of_decl = comment[index + 7:]
37 index = 0
38 for char in end_of_decl:
39 if char not in WHITESPACES:
40 break
41 index += 1
42 else:
43 return None
44 encoding = ''
45 for char in end_of_decl[index:]:
46 if char in EXTENDED_ALNUMCHARS:
47 encoding += char
48 else:
49 break
50 if encoding != '':
51 return encoding
52 return None
53
54
55 def handle_type_comment(token, flags, lnum, start, line):
56 sub_tokens = token.split(":", 1)
57 if not (
58 flags & consts.PyCF_TYPE_COMMENTS
59 and len(sub_tokens) == 2
60 and sub_tokens[0][1:].strip() == TYPE_COMMENT_PREFIX
61 ):
62 return None
63
64 # A TYPE_IGNORE is "type: ignore" followed by the end of the token
65 # or anything ASCII and non-alphanumeric. */
66
67 # Leading whitespace is ignored
68 type_decl = sub_tokens[1].lstrip()
69 following_char = type_decl[len(TYPE_IGNORE):]
70 if type_decl.startswith(TYPE_IGNORE) and (
71 following_char == '' or
72 ord(following_char[0]) < 0x80 and not following_char[0].isalnum()
73 ):
74 tok_type = tokens.TYPE_IGNORE
75 type_decl = type_decl[len(TYPE_IGNORE):]
76 else:
77 tok_type = tokens.TYPE_COMMENT
78 return Token(tok_type, type_decl, lnum, start, line)
79
80
81 def verify_utf8(token):
82 try:
83 rutf8.check_utf8(token, False)
84 except rutf8.CheckError:
85 return False
86 return True
87
88 def bad_utf8(location_msg, line, lnum, pos, token_list, flags, filename='<unknown>'):
89 # Find the first non-ASCII byte to report its value (CPython format)
90 bad_byte = 0x80
91 for ch in line:
92 o = ord(ch)
93 if o >= 0x80:
94 bad_byte = o
95 break
96 hex_byte = hex(bad_byte)[2:] # strip '0x'
97 if len(hex_byte) < 2:
98 hex_byte = "0" + hex_byte
99 msg = "Non-UTF-8 code starting with '\\x" + hex_byte + "' in file " + filename
100 if not (flags & consts.PyCF_FOUND_ENCODING):
101 msg += ' on line %d, but no encoding declared; see ' % lnum
102 msg += 'https://python.org/dev/peps/pep-0263/ for details'
103 return TokenError(msg, line, lnum, pos, token_list)
104
105
106 def verify_identifier(token, line, lnum, start, token_list, flags, filename='<unknown>'):
107 # -2=ok; positive=not an identifier; -1=bad utf-8
108 from pypy.module.unicodedata.interp_ucd import unicodedb
109 try:
110 rutf8.check_utf8(token, False)
111 except rutf8.CheckError:
112 raise bad_utf8("identifier", line, lnum, start + 1,
113 token_list, flags, filename)
114 if not token:
115 return
116 first = token[0]
117 it = rutf8.Utf8StringIterator(token)
118 code = it.next()
119 if not (unicodedb.isxidstart(code) or first == '_'):
120 raise_invalid_unicode_char(code, line, lnum, start, token_list)
121 pos = it.get_pos()
122 for ch in it:
123 if not unicodedb.isxidcontinue(ch):
124 raise_invalid_unicode_char(ch, line, lnum, start + pos, token_list)
125 pos = it.get_pos()
126
127 def raise_invalid_unicode_char(code, line, lnum, start, token_list):
128 from pypy.module.unicodedata.interp_ucd import unicodedb
129 # valid utf-8, but it gives a unicode char that cannot
130 # be used in identifiers
131 assert code >= 0
132 h = hex(code)[2:].upper()
133 if len(h) < 4:
134 h = "0" * (4 - len(h)) + h
135 if not unicodedb.isprintable(code):
136 msg = "invalid non-printable character U+%s" % h
137 else:
138 msg = "invalid character '%s' (U+%s)" % (
139 rutf8.unichr_as_utf8(code), h)
140 raise TokenError(msg, line, lnum, start + 1, token_list)
141
142 def raise_unterminated_string(is_triple_quoted, line, lineno, column, tokens,
143 end_lineno, end_offset=0):
144 # same arguments as TokenError, ie 1-based offsets
145 if is_triple_quoted:
146 msg = TRIPLE_QUOTE_UNTERMINATED_ERROR + " (detected at line %s)" % (end_lineno, )
147 else:
148 msg = SINGLE_QUOTE_UNTERMINATED_ERROR + " (detected at line %s)" % (end_lineno, )
149 raise TokenError(msg, line, lineno, column, tokens, end_lineno, end_offset)
150
151 def potential_identifier_char(ch):
152 return (ch in NAMECHARS or # ordinary name
153 ord(ch) >= 0x80) # unicode
154
155 def raise_unknown_character(line, start, lnum, token_list, flags, filename='<unknown>'):
156 from pypy.module.unicodedata.interp_ucd import unicodedb
157 code = ord(line[start])
158 if code < 128:
159 try:
160 rutf8.check_utf8(line, False, start=start)
161 except rutf8.CheckError:
162 raise bad_utf8("line", line, lnum, start + 1,
163 token_list, flags, filename)
164 code = rutf8.codepoint_at_pos(line, start)
165 raise_invalid_unicode_char(code, line, lnum, start, token_list)
166
167 DUMMY_DFA = automata.DFA([], [])
168
169 def generate_tokens(lines, flags, filename='<unknown>'):
170 """
171 This is a rewrite of pypy.module.parser.pytokenize.generate_tokens since
172 the original function is not RPYTHON (uses yield)
173 It was also slightly modified to generate Token instances instead
174 of the original 5-tuples -- it's now a 4-tuple of
175
176 * the Token instance
177 * the whole line as a string
178 * the line number (the real one, counting continuation lines)
179 * the position on the line of the end of the token.
180
181 Original docstring ::
182
183 The generate_tokens() generator requires one argment, readline, which
184 must be a callable object which provides the same interface as the
185 readline() method of built-in file objects. Each call to the function
186 should return one line of input as a string.
187
188 The generator produces 5-tuples with these members: the token type; the
189 token string; a 2-tuple (srow, scol) of ints specifying the row and
190 column where the token begins in the source; a 2-tuple (erow, ecol) of
191 ints specifying the row and column where the token ends in the source;
192 and the line on which the token was found. The line passed is the
193 logical line; continuation lines are included.
194 """
195
196 token_list = []
197 lnum = 0
198 continued = False
199 numchars = NUMCHARS
200 contstrs, needcont = [], False
201 indents = [0]
202 altindents = [0]
203 last_comment = ''
204 # contains the tokens of the opening parens
205 parenstack = []
206 async_hacks = flags & consts.PyCF_ASYNC_HACKS
207 async_def = False
208 async_def_nl = False
209 async_def_indent = 0
210
211 # make the annotator happy
212 endDFA = DUMMY_DFA
213 # make the annotator happy
214 line = ''
215 pos = 0
216 lines.append("")
217 strstart = (0, 0, "", False) # linenumber, offset, starting_line, is_triple_quoted
218 cont_line_col = 0
219 for lines_index, line in enumerate(lines):
220 lnum = lnum + 1
221 line = universal_newline(line)
222 pos, max = 0, len(line)
223 switch_indents = 0
224
225 if contstrs:
226 if not line:
227 raise_unterminated_string(strstart[3], strstart[2], strstart[0],
228 strstart[1] + 1, token_list,
229 lnum - 1, len(line))
230 endmatch = endDFA.recognize(line)
231 if endmatch >= 0:
232 pos = end = endmatch
233 contstrs.append(line[:end])
234 tok = Token(tokens.STRING, "".join(contstrs), strstart[0],
235 strstart[1], line, lnum, end, level=len(parenstack))
236 token_list.append(tok)
237 last_comment = ''
238 contstrs, needcont = [], False
239 elif (needcont and not line.endswith('\\\n') and
240 not line.endswith('\\\r\n')):
241 contstrs.append(line)
242 raise_unterminated_string(strstart[3], strstart[2], strstart[0],
243 strstart[1] + 1, token_list,
244 lnum, len(line))
245 continue
246 else:
247 contstrs.append(line)
248 continue
249
250 elif not parenstack and not continued: # new statement
251 if not line: break
252 column = cont_line_col
253 altcolumn = cont_line_col
254 while pos < max: # measure leading whitespace
255 if line[pos] == ' ':
256 column = column + 1
257 altcolumn = altcolumn + 1
258 elif line[pos] == '\t':
259 column = (column/tabsize + 1)*tabsize
260 altcolumn = (altcolumn/alttabsize + 1)*alttabsize
261 elif line[pos] == '\f':
262 column = 0
263 else:
264 break
265 pos = pos + 1
266 if pos == max: break
267
268 if line[pos] in '#\r\n':
269 # skip blank lines
270 if line[pos] == '#':
271 # skip full-line comment, but still check that it is valid utf-8
272 if not verify_utf8(line):
273 raise bad_utf8("comment",
274 line, lnum, pos, token_list, flags, filename)
275 type_comment_tok = handle_type_comment(line.lstrip(),
276 flags, lnum, pos, line)
277 if type_comment_tok is None:
278 continue
279 else:
280 switch_indents += 1
281 else:
282 continue
283 if line[pos] == '\\' and line[pos + 1] in '\r\n':
284 # first non-whitespace char and last char in line is \
285 if lines[lines_index + 1] not in ("\r\n", "\n", "\x0C\n"):
286 # continuation marker after spaces increase the
287 # indentation level if column > 0
288 if column == 0:
289 pass
290 elif pos != cont_line_col:
291 indents.append(pos)
292 altindents.append(pos)
293 token_list.append(Token(tokens.INDENT, line[:pos], lnum, 0, line[:pos] + lines[lines_index + 1], lnum, pos, level=len(parenstack)))
294 cont_line_col = pos
295 continued = True
296 continue
297 if lines[lines_index + 1] != "":
298 # skip lines that are only a line continuation char
299 # followed by an empty line (not last line)
300 continue
301 else:
302 cont_line_col = 0
303 if column == indents[-1]:
304 if altcolumn != altindents[-1]:
305 raise TabError(lnum, pos, line)
306 elif column > indents[-1]: # count indents or dedents
307 if altcolumn <= altindents[-1]:
308 raise TabError(lnum, pos, line)
309 indents.append(column)
310 altindents.append(altcolumn)
311 token_list.append(Token(tokens.INDENT, line[:pos], lnum, 0, line, lnum, pos, level=len(parenstack)))
312 last_comment = ''
313 else:
314 while column < indents[-1]:
315 indents.pop()
316 altindents.pop()
317 token_list.append(Token(tokens.DEDENT, '', lnum, pos, line, level=len(parenstack)))
318 last_comment = ''
319 if column != indents[-1]:
320 err = "unindent does not match any outer indentation level"
321 raise TokenIndentationError(err, line, lnum, column+1, token_list)
322 if altcolumn != altindents[-1]:
323 raise TabError(lnum, pos, line)
324 if async_def_nl and async_def_indent >= indents[-1]:
325 async_def = False
326 async_def_nl = False
327 async_def_indent = 0
328
329 else: # continued statement
330 if not line:
331 if parenstack:
332 openparen = parenstack[0]
333 parenkind = openparen.value[0]
334 lnum1 = openparen.lineno
335 start1 = openparen.column
336 line1 = openparen.line
337 raise TokenError("'%s' was never closed" % (parenkind, ), line1,
338 lnum1, start1 + 1, token_list, lnum)
339 prevline = lines[lines_index - 1]
340 raise TokenError(EOF_MULTI_LINE_STATEMENT_ERROR , prevline,
341 lnum - 1, len(prevline) - 1, token_list) # XXX why is the offset 0 here?
342 continued = False
343
344 while pos < max:
345 pseudomatch = pseudoDFA.recognize(line, pos)
346 start = whiteSpaceDFA.recognize(line, pos)
347 if pseudomatch >= 0: # scan for tokens
348 # JDR: Modified
349 if start < 0:
350 start = pos
351 end = pseudomatch
352
353 if start == end:
354 if line[start] == "\\":
355 raise TokenError("unexpected character after line continuation character", line,
356 lnum, start + 2, token_list)
357
358 raise_unknown_character(line, start, lnum, token_list, flags, filename)
359
360 pos = end
361 token, initial = line[start:end], line[start]
362 if (initial in numchars or \
363 (initial == '.' and token != '.' and token != '...')):
364 # ordinary number
365 token_list.append(Token(tokens.NUMBER, token, lnum, start, line, lnum, end, level=len(parenstack)))
366 _maybe_raise_number_error(token, line, lnum, start, end, token_list)
367 last_comment = ''
368 elif initial in '\r\n':
369 if not parenstack:
370 if async_def:
371 async_def_nl = True
372 tok = Token(tokens.NEWLINE, last_comment, lnum, start, line, level=len(parenstack))
373 token_list.append(tok)
374
375 # Shift the indent token to the next line
376 # when it is followed by a type_comment.
377 if (
378 switch_indents == 2
379 and len(token_list) >= 3
380 and token_list[-3].token_type == tokens.INDENT
381 ):
382 indent = token_list.pop(-3)
383 token_list.append(indent)
384 switch_indents = 0
385 last_comment = ''
386 elif initial == '#':
387 # skip comment, but still check that it is valid utf-8
388 if not verify_utf8(token):
389 raise bad_utf8("comment",
390 line, lnum, start, token_list, flags, filename)
391 type_comment_tok = handle_type_comment(token, flags, lnum, start, line)
392 if type_comment_tok is not None:
393 switch_indents += 1
394 token_list.append(type_comment_tok)
395 else:
396 last_comment = token
397 elif token in triple_quoted:
398 endDFA = endDFAs[token]
399 endmatch = endDFA.recognize(line, pos)
400 if endmatch >= 0: # all on one line
401 pos = endmatch
402 token = line[start:pos]
403 tok = Token(tokens.STRING, token, lnum, start, line, lnum, pos, level=len(parenstack))
404 token_list.append(tok)
405 last_comment = ''
406 else:
407 strstart = (lnum, start, line, True)
408 contstrs = [line[start:]]
409 break
410 elif initial in single_quoted or \
411 token[:2] in single_quoted or \
412 token[:3] in single_quoted:
413 if token[-1] == '\n': # continued string
414 strstart = (lnum, start, line, False)
415 endDFA = (endDFAs[initial] or endDFAs[token[1]] or
416 endDFAs[token[2]])
417 contstrs, needcont = [line[start:]], True
418 break
419 else: # ordinary string
420 tok = Token(tokens.STRING, token, lnum, start, line, lnum, pos, level=len(parenstack))
421 token_list.append(tok)
422 last_comment = ''
423 elif potential_identifier_char(initial): # unicode identifier
424 verify_identifier(token, line, lnum, start, token_list, flags, filename)
425 # inside 'async def' function or no async_hacks
426 # so recognize them unconditionally.
427 if not async_hacks or async_def:
428 if token == 'async':
429 token_list.append(Token(tokens.ASYNC, token, lnum, start, line, lnum, end, level=len(parenstack)))
430 elif token == 'await':
431 token_list.append(Token(tokens.AWAIT, token, lnum, start, line, lnum, end, level=len(parenstack)))
432 else:
433 token_list.append(Token(tokens.NAME, token, lnum, start, line, lnum, end, level=len(parenstack)))
434 elif token == 'async': # async token, look ahead
435 #ahead token
436 if pos < max:
437 async_end = pseudoDFA.recognize(line, pos)
438 assert async_end >= 3
439 async_start = async_end - 3
440 assert async_start >= 0
441 ahead_token = line[async_start:async_end]
442 if ahead_token == 'def':
443 async_def = True
444 async_def_indent = indents[-1]
445 token_list.append(Token(tokens.ASYNC, token, lnum, start, line, lnum, end, level=len(parenstack)))
446 else:
447 token_list.append(Token(tokens.NAME, token, lnum, start, line, lnum, end, level=len(parenstack)))
448 else:
449 token_list.append(Token(tokens.NAME, token, lnum, start, line, lnum, end, level=len(parenstack)))
450 else:
451 token_list.append(Token(tokens.NAME, token, lnum, start, line, lnum, end, level=len(parenstack)))
452 last_comment = ''
453 elif initial == '\\': # continued stmt
454 continued = True
455 elif initial == '$':
456 token_list.append(Token(tokens.REVDBMETAVAR, token,
457 lnum, start, line, lnum, pos, level=len(parenstack)))
458 last_comment = ''
459 else:
460 if token in python_opmap:
461 punct = python_opmap[token]
462 else:
463 punct = tokens.OP
464
465 level_adjustment = 0
466 if initial in '([{':
467 level_adjustment = 1
468 elif initial in ')]}':
469 level_adjustment = -1
470
471 tok = Token(punct, token, lnum, start, line, lnum, end, level=len(parenstack) + level_adjustment)
472 if level_adjustment == 1:
473 parenstack.append(tok)
474 if level_adjustment == -1:
475 if not parenstack:
476 raise TokenError("unmatched '%s'" % initial, line,
477 lnum, start + 1, token_list)
478 openparen = parenstack.pop()
479 opening = openparen.value[0]
480 lnum1 = openparen.lineno
481 start1 = openparen.column
482 line1 = openparen.line
483
484 if not ((opening == "(" and initial == ")") or
485 (opening == "[" and initial == "]") or
486 (opening == "{" and initial == "}")):
487 msg = "closing parenthesis '%s' does not match opening parenthesis '%s'" % (
488 initial, opening)
489
490 if lnum1 != lnum:
491 msg += " on line " + str(lnum1)
492 raise TokenError(
493 msg, line, lnum, start + 1, token_list)
494 token_list.append(tok)
495 last_comment = ''
496 else:
497 if start < 0:
498 start = pos
499 if start<max and line[start] in single_quoted:
500 raise_unterminated_string(False, line, lnum, start+1,
501 token_list, lnum, len(line))
502 if line[pos] == "0":
503 raise TokenError("leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers",
504 line, lnum, pos+1, token_list)
505 if line[pos] in NUMCHARS:
506 _maybe_raise_invalid_float_exponent(line, lnum, pos, max, token_list)
507 tok = Token(tokens.ERRORTOKEN, line[pos], lnum, pos, line, level=len(parenstack))
508 token_list.append(tok)
509 last_comment = ''
510 pos = pos + 1
511 lnum -= 1
512 if not (flags & consts.PyCF_DONT_IMPLY_DEDENT):
513 if token_list and token_list[-1].token_type != tokens.NEWLINE:
514 tok = Token(tokens.NEWLINE, '', lnum, 0, '\n', level=len(parenstack))
515 token_list.append(tok)
516 for indent in indents[1:]: # pop remaining indent levels
517 token_list.append(Token(tokens.DEDENT, '', lnum, pos, line, level=len(parenstack)))
518 tok = Token(tokens.NEWLINE, '', lnum, 0, '\n', level=len(parenstack))
519 token_list.append(tok)
520
521 token_list.append(Token(tokens.ENDMARKER, '', lnum, pos, line, level=len(parenstack)))
522 return token_list
523
524 def _maybe_raise_invalid_float_exponent(line, lnum, pos, max, token_list):
525 """Detect invalid float exponents like 32e-+4 (DFA won't match them).
526 Raises 'invalid decimal literal' at the sign position, matching CPython."""
527 i = pos
528 while i < max and line[i] in NUMCHARS:
529 i += 1
530 if i >= max or line[i] not in 'eE':
531 return
532 i += 1 # skip e/E
533 if i < max and line[i] in '+-':
534 sign_pos = i
535 i += 1
536 else:
537 sign_pos = -1
538 if i < max and line[i] in NUMCHARS:
539 return # valid exponent
540 err_pos = sign_pos if sign_pos >= 0 else i - 1
541 raise TokenError("invalid decimal literal", line, lnum, err_pos + 1, token_list)
542
543 def _maybe_raise_number_error(token, line, lnum, start, end, token_list):
544 ch = _get_next_or_nul(line, end)
545 if end == start + 1 and token[0] == "0":
546 if ch == "b":
547 token = "0b"
548 end += 1
549 ch = _get_next_or_nul(line, end)
550 if not ch.isdigit():
551 raise TokenError("invalid binary literal",
552 line, lnum, end, token_list)
553 elif ch == "o":
554 token = "0o"
555 end += 1
556 ch = _get_next_or_nul(line, end)
557 if not ch.isdigit():
558 raise TokenError("invalid octal literal",
559 line, lnum, end, token_list)
560 elif ch == "x":
561 token = "0x"
562 end += 1
563 ch = _get_next_or_nul(line, end)
564 if not ch.isdigit():
565 raise TokenError("invalid hexadecimal literal",
566 line, lnum, end, token_list)
567 if token.startswith("0b"):
568 kind = "binary"
569 nextch = _skip_underscore(ch, line, end)
570 if nextch.isdigit():
571 raise TokenError("invalid digit '%s' in binary literal" % (nextch, ),
572 line, lnum, end + 1, token_list)
573 elif ch == "_":
574 raise TokenError("invalid binary literal",
575 line, lnum, end, token_list)
576
577 elif token.startswith("0o"):
578 kind = "octal"
579 nextch = _skip_underscore(ch, line, end)
580 if nextch.isdigit():
581 raise TokenError("invalid digit '%s' in octal literal" % (nextch, ),
582 line, lnum, end + 1, token_list)
583 elif ch == "_":
584 raise TokenError("invalid octal literal",
585 line, lnum, end, token_list)
586
587 elif token.startswith("0x"):
588 kind = "hexadecimal"
589 if ch == "_":
590 raise TokenError("invalid hexadecimal literal",
591 line, lnum, end + 1, token_list)
592
593 else:
594 kind = "decimal"
595 if ch == "_":
596 raise TokenError("invalid decimal literal",
597 line, lnum, end + 1, token_list)
598
599 # now that we've covered the actual error cases, let's see whether we need
600 # to insert a WARNING token
601
602 # we only need to do that in the cases of *valid* syntax, ie it's a
603 # number followed by one of the keywords that starts with [a-f]
604 warn = False
605 if ch == 'a':
606 warn = _lookahead(line, end + 1, "nd")
607 elif ch == 'e':
608 warn = _lookahead(line, end + 1, "lse")
609 elif ch == 'f':
610 warn = _lookahead(line, end + 1, "or")
611 elif ch == 'i':
612 ch = _get_next_or_nul(line, end + 1)
613 warn = ch == 'f' or ch == 'n' or ch == 's'
614 elif ch == 'n':
615 warn = _lookahead(line, end + 1, "ot")
616 elif ch == 'o':
617 ch = _get_next_or_nul(line, end + 1)
618 warn = ch == 'r'
619
620 if warn:
621 # need a warning token
622 token_list.append(Token(tokens.WARNING, "invalid %s literal" % kind,
623 lnum, start, line, -1, -1))
624 elif potential_identifier_char(ch):
625 # raise an error right here
626 if ord(ch) >= 0x80:
627 from pypy.module.unicodedata.interp_ucd import unicodedb
628 code = rutf8.codepoint_at_pos(line, end)
629 if not unicodedb.isxidcontinue(code):
630 raise_invalid_unicode_char(code, line, lnum, end, token_list)
631 raise TokenError("invalid %s literal" % kind,
632 line, lnum, start + 1, token_list, lnum, end + 2)
633
634
635 def _get_next_or_nul(line, end):
636 if end < len(line):
637 return line[end]
638 return chr(0)
639
640 def _lookahead(line, pos, s):
641 if not (pos + len(s) <= len(line)):
642 return False
643 for char in s:
644 if line[pos] != char:
645 return False
646 pos += 1
647 return True
648
649 def _skip_underscore(ch, line, end):
650 if ch == "_":
651 return _get_next_or_nul(line, end + 1)
652 return ch
653
654 def universal_newline(line):
655 # show annotator that indexes below are non-negative
656 line_len_m2 = len(line) - 2
657 if line_len_m2 >= 0 and line[-2] == '\r' and line[-1] == '\n':
658 return line[:line_len_m2] + '\n'
659 line_len_m1 = len(line) - 1
660 if line_len_m1 >= 0 and line[-1] == '\r':
661 return line[:line_len_m1] + '\n'
662 return line