1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
|
# -*- coding: utf-8 -*-
# Copyright JS Foundation and other contributors, https://js.foundation/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import absolute_import, unicode_literals
import re
from .objects import Object
from .compat import xrange, unicode, uchr, uord
from .character import Character, HEX_CONV, OCTAL_CONV
from .messages import Messages
from .token import Token
def hexValue(ch):
return HEX_CONV[ch]
def octalValue(ch):
return OCTAL_CONV[ch]
class RegExp(Object):
def __init__(self, pattern=None, flags=None):
self.pattern = pattern
self.flags = flags
class Position(Object):
def __init__(self, line=None, column=None, offset=None):
self.line = line
self.column = column
self.offset = offset
class SourceLocation(Object):
def __init__(self, start=None, end=None, source=None):
self.start = start
self.end = end
self.source = source
class Comment(Object):
def __init__(self, multiLine=None, slice=None, range=None, loc=None):
self.multiLine = multiLine
self.slice = slice
self.range = range
self.loc = loc
class RawToken(Object):
def __init__(self, type=None, value=None, pattern=None, flags=None, regex=None, octal=None, cooked=None, head=None, tail=None, lineNumber=None, lineStart=None, start=None, end=None):
self.type = type
self.value = value
self.pattern = pattern
self.flags = flags
self.regex = regex
self.octal = octal
self.cooked = cooked
self.head = head
self.tail = tail
self.lineNumber = lineNumber
self.lineStart = lineStart
self.start = start
self.end = end
class ScannerState(Object):
def __init__(self, index=None, lineNumber=None, lineStart=None):
self.index = index
self.lineNumber = lineNumber
self.lineStart = lineStart
class Octal(object):
def __init__(self, octal, code):
self.octal = octal
self.code = code
class Scanner(object):
def __init__(self, code, handler):
self.source = unicode(code) + '\x00'
self.errorHandler = handler
self.trackComment = False
self.isModule = False
self.length = len(code)
self.index = 0
self.lineNumber = 1 if self.length > 0 else 0
self.lineStart = 0
self.curlyStack = []
def saveState(self):
return ScannerState(
index=self.index,
lineNumber=self.lineNumber,
lineStart=self.lineStart
)
def restoreState(self, state):
self.index = state.index
self.lineNumber = state.lineNumber
self.lineStart = state.lineStart
def eof(self):
return self.index >= self.length
def throwUnexpectedToken(self, message=Messages.UnexpectedTokenIllegal):
return self.errorHandler.throwError(self.index, self.lineNumber,
self.index - self.lineStart + 1, message)
def tolerateUnexpectedToken(self, message=Messages.UnexpectedTokenIllegal):
self.errorHandler.tolerateError(self.index, self.lineNumber,
self.index - self.lineStart + 1, message)
# https://tc39.github.io/ecma262/#sec-comments
def skipSingleLineComment(self, offset):
comments = []
if self.trackComment:
start = self.index - offset
loc = SourceLocation(
start=Position(
line=self.lineNumber,
column=self.index - self.lineStart - offset
),
end=Position()
)
while not self.eof():
ch = self.source[self.index]
self.index += 1
if Character.isLineTerminator(ch):
if self.trackComment:
loc.end = Position(
line=self.lineNumber,
column=self.index - self.lineStart - 1
)
entry = Comment(
multiLine=False,
slice=[start + offset, self.index - 1],
range=[start, self.index - 1],
loc=loc
)
comments.append(entry)
if ch == '\r' and self.source[self.index] == '\n':
self.index += 1
self.lineNumber += 1
self.lineStart = self.index
return comments
if self.trackComment:
loc.end = Position(
line=self.lineNumber,
column=self.index - self.lineStart
)
entry = Comment(
multiLine=False,
slice=[start + offset, self.index],
range=[start, self.index],
loc=loc
)
comments.append(entry)
return comments
def skipMultiLineComment(self):
comments = []
if self.trackComment:
comments = []
start = self.index - 2
loc = SourceLocation(
start=Position(
line=self.lineNumber,
column=self.index - self.lineStart - 2
),
end=Position()
)
while not self.eof():
ch = self.source[self.index]
if Character.isLineTerminator(ch):
if ch == '\r' and self.source[self.index + 1] == '\n':
self.index += 1
self.lineNumber += 1
self.index += 1
self.lineStart = self.index
elif ch == '*':
# Block comment ends with '*/'.
if self.source[self.index + 1] == '/':
self.index += 2
if self.trackComment:
loc.end = Position(
line=self.lineNumber,
column=self.index - self.lineStart
)
entry = Comment(
multiLine=True,
slice=[start + 2, self.index - 2],
range=[start, self.index],
loc=loc
)
comments.append(entry)
return comments
self.index += 1
else:
self.index += 1
# Ran off the end of the file - the whole thing is a comment
if self.trackComment:
loc.end = Position(
line=self.lineNumber,
column=self.index - self.lineStart
)
entry = Comment(
multiLine=True,
slice=[start + 2, self.index],
range=[start, self.index],
loc=loc
)
comments.append(entry)
self.tolerateUnexpectedToken()
return comments
def scanComments(self):
comments = []
start = self.index == 0
while not self.eof():
ch = self.source[self.index]
if Character.isWhiteSpace(ch):
self.index += 1
elif Character.isLineTerminator(ch):
self.index += 1
if ch == '\r' and self.source[self.index] == '\n':
self.index += 1
self.lineNumber += 1
self.lineStart = self.index
start = True
elif ch == '/': # U+002F is '/'
ch = self.source[self.index + 1]
if ch == '/':
self.index += 2
comment = self.skipSingleLineComment(2)
if self.trackComment:
comments.extend(comment)
start = True
elif ch == '*': # U+002A is '*'
self.index += 2
comment = self.skipMultiLineComment()
if self.trackComment:
comments.extend(comment)
else:
break
elif start and ch == '-': # U+002D is '-'
# U+003E is '>'
if self.source[self.index + 1:self.index + 3] == '->':
# '-->' is a single-line comment
self.index += 3
comment = self.skipSingleLineComment(3)
if self.trackComment:
comments.extend(comment)
else:
break
elif ch == '<' and not self.isModule: # U+003C is '<'
if self.source[self.index + 1:self.index + 4] == '!--':
self.index += 4 # `<!--`
comment = self.skipSingleLineComment(4)
if self.trackComment:
comments.extend(comment)
else:
break
else:
break
return comments
# https://tc39.github.io/ecma262/#sec-future-reserved-words
def isFutureReservedWord(self, id):
return id in self.isFutureReservedWord.set
isFutureReservedWord.set = set((
'enum',
'export',
'import',
'super',
))
def isStrictModeReservedWord(self, id):
return id in self.isStrictModeReservedWord.set
isStrictModeReservedWord.set = set((
'implements',
'interface',
'package',
'private',
'protected',
'public',
'static',
'yield',
'let',
))
def isRestrictedWord(self, id):
return id in self.isRestrictedWord.set
isRestrictedWord.set = set((
'eval', 'arguments',
))
# https://tc39.github.io/ecma262/#sec-keywords
def isKeyword(self, id):
return id in self.isKeyword.set
isKeyword.set = set((
'if', 'in', 'do',
'var', 'for', 'new',
'try', 'let',
'this', 'else', 'case',
'void', 'with', 'enum',
'while', 'break', 'catch',
'throw', 'const', 'yield',
'class', 'super',
'return', 'typeof', 'delete',
'switch', 'export', 'import',
'default', 'finally', 'extends',
'function', 'continue', 'debugger',
'instanceof',
))
def codePointAt(self, i):
return uord(self.source[i:i + 2])
def scanHexEscape(self, prefix):
length = 4 if prefix == 'u' else 2
code = 0
for i in xrange(length):
if not self.eof() and Character.isHexDigit(self.source[self.index]):
ch = self.source[self.index]
self.index += 1
code = code * 16 + hexValue(ch)
else:
return None
return uchr(code)
def scanUnicodeCodePointEscape(self):
ch = self.source[self.index]
code = 0
# At least, one hex digit is required.
if ch == '}':
self.throwUnexpectedToken()
while not self.eof():
ch = self.source[self.index]
self.index += 1
if not Character.isHexDigit(ch):
break
code = code * 16 + hexValue(ch)
if code > 0x10FFFF or ch != '}':
self.throwUnexpectedToken()
return Character.fromCodePoint(code)
def getIdentifier(self):
start = self.index
self.index += 1
while not self.eof():
ch = self.source[self.index]
if ch == '\\':
# Blackslash (U+005C) marks Unicode escape sequence.
self.index = start
return self.getComplexIdentifier()
else:
cp = ord(ch)
if cp >= 0xD800 and cp < 0xDFFF:
# Need to handle surrogate pairs.
self.index = start
return self.getComplexIdentifier()
if Character.isIdentifierPart(ch):
self.index += 1
else:
break
return self.source[start:self.index]
def getComplexIdentifier(self):
cp = self.codePointAt(self.index)
id = Character.fromCodePoint(cp)
self.index += len(id)
# '\u' (U+005C, U+0075) denotes an escaped character.
if cp == 0x5C:
if self.source[self.index] != 'u':
self.throwUnexpectedToken()
self.index += 1
if self.source[self.index] == '{':
self.index += 1
ch = self.scanUnicodeCodePointEscape()
else:
ch = self.scanHexEscape('u')
if not ch or ch == '\\' or not Character.isIdentifierStart(ch[0]):
self.throwUnexpectedToken()
id = ch
while not self.eof():
cp = self.codePointAt(self.index)
ch = Character.fromCodePoint(cp)
if not Character.isIdentifierPart(ch):
break
id += ch
self.index += len(ch)
# '\u' (U+005C, U+0075) denotes an escaped character.
if cp == 0x5C:
id = id[:-1]
if self.source[self.index] != 'u':
self.throwUnexpectedToken()
self.index += 1
if self.source[self.index] == '{':
self.index += 1
ch = self.scanUnicodeCodePointEscape()
else:
ch = self.scanHexEscape('u')
if not ch or ch == '\\' or not Character.isIdentifierPart(ch[0]):
self.throwUnexpectedToken()
id += ch
return id
def octalToDecimal(self, ch):
# \0 is not octal escape sequence
octal = ch != '0'
code = octalValue(ch)
if not self.eof() and Character.isOctalDigit(self.source[self.index]):
octal = True
code = code * 8 + octalValue(self.source[self.index])
self.index += 1
# 3 digits are only allowed when string starts
# with 0, 1, 2, 3
if ch in '0123' and not self.eof() and Character.isOctalDigit(self.source[self.index]):
code = code * 8 + octalValue(self.source[self.index])
self.index += 1
return Octal(octal, code)
# https://tc39.github.io/ecma262/#sec-names-and-keywords
def scanIdentifier(self):
start = self.index
# Backslash (U+005C) starts an escaped character.
id = self.getComplexIdentifier() if self.source[start] == '\\' else self.getIdentifier()
# There is no keyword or literal with only one character.
# Thus, it must be an identifier.
if len(id) == 1:
type = Token.Identifier
elif self.isKeyword(id):
type = Token.Keyword
elif id == 'null':
type = Token.NullLiteral
elif id == 'true' or id == 'false':
type = Token.BooleanLiteral
else:
type = Token.Identifier
if type is not Token.Identifier and start + len(id) != self.index:
restore = self.index
self.index = start
self.tolerateUnexpectedToken(Messages.InvalidEscapedReservedWord)
self.index = restore
return RawToken(
type=type,
value=id,
lineNumber=self.lineNumber,
lineStart=self.lineStart,
start=start,
end=self.index
)
# https://tc39.github.io/ecma262/#sec-punctuators
def scanPunctuator(self):
start = self.index
# Check for most common single-character punctuators.
str = self.source[self.index]
if str in (
'(',
'{',
):
if str == '{':
self.curlyStack.append('{')
self.index += 1
elif str == '.':
self.index += 1
if self.source[self.index] == '.' and self.source[self.index + 1] == '.':
# Spread operator: ...
self.index += 2
str = '...'
elif str == '}':
self.index += 1
if self.curlyStack:
self.curlyStack.pop()
elif str in (
')',
';',
',',
'[',
']',
':',
'?',
'~',
):
self.index += 1
else:
# 4-character punctuator.
str = self.source[self.index:self.index + 4]
if str == '>>>=':
self.index += 4
else:
# 3-character punctuators.
str = str[:3]
if str in (
'===', '!==', '>>>',
'<<=', '>>=', '**='
):
self.index += 3
else:
# 2-character punctuators.
str = str[:2]
if str in (
'&&', '||', '==', '!=',
'+=', '-=', '*=', '/=',
'++', '--', '<<', '>>',
'&=', '|=', '^=', '%=',
'<=', '>=', '=>', '**',
):
self.index += 2
else:
# 1-character punctuators.
str = self.source[self.index]
if str in '<>=!+-*%&|^/':
self.index += 1
if self.index == start:
self.throwUnexpectedToken()
return RawToken(
type=Token.Punctuator,
value=str,
lineNumber=self.lineNumber,
lineStart=self.lineStart,
start=start,
end=self.index
)
# https://tc39.github.io/ecma262/#sec-literals-numeric-literals
def scanHexLiteral(self, start):
num = ''
while not self.eof():
if not Character.isHexDigit(self.source[self.index]):
break
num += self.source[self.index]
self.index += 1
if len(num) == 0:
self.throwUnexpectedToken()
if Character.isIdentifierStart(self.source[self.index]):
self.throwUnexpectedToken()
return RawToken(
type=Token.NumericLiteral,
value=int(num, 16),
lineNumber=self.lineNumber,
lineStart=self.lineStart,
start=start,
end=self.index
)
def scanBinaryLiteral(self, start):
num = ''
while not self.eof():
ch = self.source[self.index]
if ch != '0' and ch != '1':
break
num += self.source[self.index]
self.index += 1
if len(num) == 0:
# only 0b or 0B
self.throwUnexpectedToken()
if not self.eof():
ch = self.source[self.index]
if Character.isIdentifierStart(ch) or Character.isDecimalDigit(ch):
self.throwUnexpectedToken()
return RawToken(
type=Token.NumericLiteral,
value=int(num, 2),
lineNumber=self.lineNumber,
lineStart=self.lineStart,
start=start,
end=self.index
)
def scanOctalLiteral(self, prefix, start):
num = ''
octal = False
if Character.isOctalDigit(prefix[0]):
octal = True
num = '0' + self.source[self.index]
self.index += 1
while not self.eof():
if not Character.isOctalDigit(self.source[self.index]):
break
num += self.source[self.index]
self.index += 1
if not octal and len(num) == 0:
# only 0o or 0O
self.throwUnexpectedToken()
if Character.isIdentifierStart(self.source[self.index]) or Character.isDecimalDigit(self.source[self.index]):
self.throwUnexpectedToken()
return RawToken(
type=Token.NumericLiteral,
value=int(num, 8),
octal=octal,
lineNumber=self.lineNumber,
lineStart=self.lineStart,
start=start,
end=self.index
)
def isImplicitOctalLiteral(self):
# Implicit octal, unless there is a non-octal digit.
# (Annex B.1.1 on Numeric Literals)
for i in xrange(self.index + 1, self.length):
ch = self.source[i]
if ch in '89':
return False
if not Character.isOctalDigit(ch):
return True
return True
def scanNumericLiteral(self):
start = self.index
ch = self.source[start]
assert Character.isDecimalDigit(ch) or ch == '.', 'Numeric literal must start with a decimal digit or a decimal point'
num = ''
if ch != '.':
num = self.source[self.index]
self.index += 1
ch = self.source[self.index]
# Hex number starts with '0x'.
# Octal number starts with '0'.
# Octal number in ES6 starts with '0o'.
# Binary number in ES6 starts with '0b'.
if num == '0':
if ch in ('x', 'X'):
self.index += 1
return self.scanHexLiteral(start)
if ch in ('b', 'B'):
self.index += 1
return self.scanBinaryLiteral(start)
if ch in ('o', 'O'):
return self.scanOctalLiteral(ch, start)
if ch and Character.isOctalDigit(ch):
if self.isImplicitOctalLiteral():
return self.scanOctalLiteral(ch, start)
while Character.isDecimalDigit(self.source[self.index]):
num += self.source[self.index]
self.index += 1
ch = self.source[self.index]
if ch == '.':
num += self.source[self.index]
self.index += 1
while Character.isDecimalDigit(self.source[self.index]):
num += self.source[self.index]
self.index += 1
ch = self.source[self.index]
if ch in ('e', 'E'):
num += self.source[self.index]
self.index += 1
ch = self.source[self.index]
if ch in ('+', '-'):
num += self.source[self.index]
self.index += 1
if Character.isDecimalDigit(self.source[self.index]):
while Character.isDecimalDigit(self.source[self.index]):
num += self.source[self.index]
self.index += 1
else:
self.throwUnexpectedToken()
if Character.isIdentifierStart(self.source[self.index]):
self.throwUnexpectedToken()
value = float(num)
return RawToken(
type=Token.NumericLiteral,
value=int(value) if value.is_integer() else value,
lineNumber=self.lineNumber,
lineStart=self.lineStart,
start=start,
end=self.index
)
# https://tc39.github.io/ecma262/#sec-literals-string-literals
def scanStringLiteral(self):
start = self.index
quote = self.source[start]
assert quote in ('\'', '"'), 'String literal must starts with a quote'
self.index += 1
octal = False
str = ''
while not self.eof():
ch = self.source[self.index]
self.index += 1
if ch == quote:
quote = ''
break
elif ch == '\\':
ch = self.source[self.index]
self.index += 1
if not ch or not Character.isLineTerminator(ch):
if ch == 'u':
if self.source[self.index] == '{':
self.index += 1
str += self.scanUnicodeCodePointEscape()
else:
unescapedChar = self.scanHexEscape(ch)
if not unescapedChar:
self.throwUnexpectedToken()
str += unescapedChar
elif ch == 'x':
unescaped = self.scanHexEscape(ch)
if not unescaped:
self.throwUnexpectedToken(Messages.InvalidHexEscapeSequence)
str += unescaped
elif ch == 'n':
str += '\n'
elif ch == 'r':
str += '\r'
elif ch == 't':
str += '\t'
elif ch == 'b':
str += '\b'
elif ch == 'f':
str += '\f'
elif ch == 'v':
str += '\x0B'
elif ch in (
'8',
'9',
):
str += ch
self.tolerateUnexpectedToken()
else:
if ch and Character.isOctalDigit(ch):
octToDec = self.octalToDecimal(ch)
octal = octToDec.octal or octal
str += uchr(octToDec.code)
else:
str += ch
else:
self.lineNumber += 1
if ch == '\r' and self.source[self.index] == '\n':
self.index += 1
self.lineStart = self.index
elif Character.isLineTerminator(ch):
break
else:
str += ch
if quote != '':
self.index = start
self.throwUnexpectedToken()
return RawToken(
type=Token.StringLiteral,
value=str,
octal=octal,
lineNumber=self.lineNumber,
lineStart=self.lineStart,
start=start,
end=self.index
)
# https://tc39.github.io/ecma262/#sec-template-literal-lexical-components
def scanTemplate(self):
cooked = ''
terminated = False
start = self.index
head = self.source[start] == '`'
tail = False
rawOffset = 2
self.index += 1
while not self.eof():
ch = self.source[self.index]
self.index += 1
if ch == '`':
rawOffset = 1
tail = True
terminated = True
break
elif ch == '$':
if self.source[self.index] == '{':
self.curlyStack.append('${')
self.index += 1
terminated = True
break
cooked += ch
elif ch == '\\':
ch = self.source[self.index]
self.index += 1
if not Character.isLineTerminator(ch):
if ch == 'n':
cooked += '\n'
elif ch == 'r':
cooked += '\r'
elif ch == 't':
cooked += '\t'
elif ch == 'u':
if self.source[self.index] == '{':
self.index += 1
cooked += self.scanUnicodeCodePointEscape()
else:
restore = self.index
unescapedChar = self.scanHexEscape(ch)
if unescapedChar:
cooked += unescapedChar
else:
self.index = restore
cooked += ch
elif ch == 'x':
unescaped = self.scanHexEscape(ch)
if not unescaped:
self.throwUnexpectedToken(Messages.InvalidHexEscapeSequence)
cooked += unescaped
elif ch == 'b':
cooked += '\b'
elif ch == 'f':
cooked += '\f'
elif ch == 'v':
cooked += '\v'
else:
if ch == '0':
if Character.isDecimalDigit(self.source[self.index]):
# Illegal: \01 \02 and so on
self.throwUnexpectedToken(Messages.TemplateOctalLiteral)
cooked += '\0'
elif Character.isOctalDigit(ch):
# Illegal: \1 \2
self.throwUnexpectedToken(Messages.TemplateOctalLiteral)
else:
cooked += ch
else:
self.lineNumber += 1
if ch == '\r' and self.source[self.index] == '\n':
self.index += 1
self.lineStart = self.index
elif Character.isLineTerminator(ch):
self.lineNumber += 1
if ch == '\r' and self.source[self.index] == '\n':
self.index += 1
self.lineStart = self.index
cooked += '\n'
else:
cooked += ch
if not terminated:
self.throwUnexpectedToken()
if not head:
if self.curlyStack:
self.curlyStack.pop()
return RawToken(
type=Token.Template,
value=self.source[start + 1:self.index - rawOffset],
cooked=cooked,
head=head,
tail=tail,
lineNumber=self.lineNumber,
lineStart=self.lineStart,
start=start,
end=self.index
)
# https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals
def testRegExp(self, pattern, flags):
# The BMP character to use as a replacement for astral symbols when
# translating an ES6 "u"-flagged pattern to an ES5-compatible
# approximation.
# Note: replacing with '\uFFFF' enables false positives in unlikely
# scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid
# pattern that would not be detected by this substitution.
astralSubstitute = '\uFFFF'
# Replace every Unicode escape sequence with the equivalent
# BMP character or a constant ASCII code point in the case of
# astral symbols. (See the above note on `astralSubstitute`
# for more information.)
def astralSub(m):
codePoint = int(m.group(1) or m.group(2), 16)
if codePoint > 0x10FFFF:
self.tolerateUnexpectedToken(Messages.InvalidRegExp)
elif codePoint <= 0xFFFF:
return uchr(codePoint)
return astralSubstitute
pattern = re.sub(r'\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})', astralSub, pattern)
# Replace each paired surrogate with a single ASCII symbol to
# avoid throwing on regular expressions that are only valid in
# combination with the "u" flag.
pattern = re.sub(r'[\uD800-\uDBFF][\uDC00-\uDFFF]', astralSubstitute, pattern)
# Return a regular expression object for this pattern-flag pair, or
# `null` in case the current environment doesn't support the flags it
# uses.
pyflags = 0 | re.M if 'm' in flags else 0 | re.I if 'i' in flags else 0
try:
return re.compile(pattern, pyflags)
except Exception:
self.tolerateUnexpectedToken(Messages.InvalidRegExp)
def scanRegExpBody(self):
ch = self.source[self.index]
assert ch == '/', 'Regular expression literal must start with a slash'
str = self.source[self.index]
self.index += 1
classMarker = False
terminated = False
while not self.eof():
ch = self.source[self.index]
self.index += 1
str += ch
if ch == '\\':
ch = self.source[self.index]
self.index += 1
# https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals
if Character.isLineTerminator(ch):
self.throwUnexpectedToken(Messages.UnterminatedRegExp)
str += ch
elif Character.isLineTerminator(ch):
self.throwUnexpectedToken(Messages.UnterminatedRegExp)
elif classMarker:
if ch == ']':
classMarker = False
else:
if ch == '/':
terminated = True
break
elif ch == '[':
classMarker = True
if not terminated:
self.throwUnexpectedToken(Messages.UnterminatedRegExp)
# Exclude leading and trailing slash.
return str[1:-1]
def scanRegExpFlags(self):
str = ''
flags = ''
while not self.eof():
ch = self.source[self.index]
if not Character.isIdentifierPart(ch):
break
self.index += 1
if ch == '\\' and not self.eof():
ch = self.source[self.index]
if ch == 'u':
self.index += 1
restore = self.index
char = self.scanHexEscape('u')
if char:
flags += char
str += '\\u'
while restore < self.index:
str += self.source[restore]
restore += 1
else:
self.index = restore
flags += 'u'
str += '\\u'
self.tolerateUnexpectedToken()
else:
str += '\\'
self.tolerateUnexpectedToken()
else:
flags += ch
str += ch
return flags
def scanRegExp(self):
start = self.index
pattern = self.scanRegExpBody()
flags = self.scanRegExpFlags()
value = self.testRegExp(pattern, flags)
return RawToken(
type=Token.RegularExpression,
value='',
pattern=pattern,
flags=flags,
regex=value,
lineNumber=self.lineNumber,
lineStart=self.lineStart,
start=start,
end=self.index
)
def lex(self):
if self.eof():
return RawToken(
type=Token.EOF,
value='',
lineNumber=self.lineNumber,
lineStart=self.lineStart,
start=self.index,
end=self.index
)
ch = self.source[self.index]
if Character.isIdentifierStart(ch):
return self.scanIdentifier()
# Very common: ( and ) and ;
if ch in ('(', ')', ';'):
return self.scanPunctuator()
# String literal starts with single quote (U+0027) or double quote (U+0022).
if ch in ('\'', '"'):
return self.scanStringLiteral()
# Dot (.) U+002E can also start a floating-point number, hence the need
# to check the next character.
if ch == '.':
if Character.isDecimalDigit(self.source[self.index + 1]):
return self.scanNumericLiteral()
return self.scanPunctuator()
if Character.isDecimalDigit(ch):
return self.scanNumericLiteral()
# Template literals start with ` (U+0060) for template head
# or } (U+007D) for template middle or template tail.
if ch == '`' or (ch == '}' and self.curlyStack and self.curlyStack[-1] == '${'):
return self.scanTemplate()
# Possible identifier start in a surrogate pair.
cp = ord(ch)
if cp >= 0xD800 and cp < 0xDFFF:
cp = self.codePointAt(self.index)
ch = Character.fromCodePoint(cp)
if Character.isIdentifierStart(ch):
return self.scanIdentifier()
return self.scanPunctuator()
|