| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright 2014-2017 The Meson development team |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
from dataclasses import dataclass, field |
| 6 |
import re |
| 7 |
import codecs |
| 8 |
import os |
| 9 |
import typing as T |
| 10 |
|
| 11 |
from .mesonlib import MesonException |
| 12 |
from . import mlog |
| 13 |
|
| 14 |
if T.TYPE_CHECKING: |
| 15 |
from typing_extensions import Literal |
| 16 |
|
| 17 |
from .ast import AstVisitor |
| 18 |
|
| 19 |
BaseNodeT = T.TypeVar('BaseNodeT', bound='BaseNode') |
| 20 |
|
| 21 |
# This is the regex for the supported escape sequences of a regular string |
| 22 |
# literal, like 'abc\x00' |
| 23 |
ESCAPE_SEQUENCE_SINGLE_RE = re.compile(r''' |
| 24 |
( \\U[A-Fa-f0-9]{8} # 8-digit hex escapes |
| 25 |
| \\u[A-Fa-f0-9]{4} # 4-digit hex escapes |
| 26 |
| \\x[A-Fa-f0-9]{2} # 2-digit hex escapes |
| 27 |
| \\[0-7]{1,3} # Octal escapes |
| 28 |
| \\N\{[^}]+\} # Unicode characters by name |
| 29 |
| \\[\\'abfnrtv] # Single-character escapes |
| 30 |
)''', re.UNICODE | re.VERBOSE) |
| 31 |
|
| 32 |
def decode_match(match: T.Match[str]) -> str: |
| 33 |
return codecs.decode(match.group(0).encode(), 'unicode_escape') |
| 34 |
|
| 35 |
class ParseException(MesonException): |
| 36 |
|
| 37 |
ast: T.Optional[CodeBlockNode] = None |
| 38 |
|
| 39 |
def __init__(self, text: str, line: str, lineno: int, colno: int) -> None: |
| 40 |
# Format as error message, followed by the line with the error, followed by a caret to show the error column. |
| 41 |
super().__init__(mlog.code_line(text, line, colno)) |
| 42 |
self.lineno = lineno |
| 43 |
self.colno = colno |
| 44 |
|
| 45 |
class BlockParseException(ParseException): |
| 46 |
def __init__( |
| 47 |
self, |
| 48 |
text: str, |
| 49 |
line: str, |
| 50 |
lineno: int, |
| 51 |
colno: int, |
| 52 |
start_line: str, |
| 53 |
start_lineno: int, |
| 54 |
start_colno: int, |
| 55 |
) -> None: |
| 56 |
# This can be formatted in two ways - one if the block start and end are on the same line, and a different way if they are on different lines. |
| 57 |
|
| 58 |
if lineno == start_lineno: |
| 59 |
# If block start and end are on the same line, it is formatted as: |
| 60 |
# Error message |
| 61 |
# Followed by the line with the error |
| 62 |
# Followed by a caret to show the block start |
| 63 |
# Followed by underscores |
| 64 |
# Followed by a caret to show the block end. |
| 65 |
MesonException.__init__(self, "{}\n{}\n{}".format(text, line, '{}^{}^'.format(' ' * start_colno, '_' * (colno - start_colno - 1)))) |
| 66 |
else: |
| 67 |
# If block start and end are on different lines, it is formatted as: |
| 68 |
# Error message |
| 69 |
# Followed by the line with the error |
| 70 |
# Followed by a caret to show the error column. |
| 71 |
# Followed by a message saying where the block started. |
| 72 |
# Followed by the line of the block start. |
| 73 |
# Followed by a caret for the block start. |
| 74 |
MesonException.__init__(self, "%s\n%s\n%s\nFor a block that started at %d,%d\n%s\n%s" % (text, line, '%s^' % (' ' * colno), start_lineno, start_colno, start_line, "%s^" % (' ' * start_colno))) |
| 75 |
self.lineno = lineno |
| 76 |
self.colno = colno |
| 77 |
|
| 78 |
TV_TokenTypes = T.TypeVar('TV_TokenTypes', int, str, bool) |
| 79 |
|
| 80 |
@dataclass(eq=False) |
| 81 |
class Token(T.Generic[TV_TokenTypes]): |
| 82 |
tid: str |
| 83 |
filename: str |
| 84 |
line_start: int |
| 85 |
lineno: int |
| 86 |
colno: int |
| 87 |
bytespan: T.Tuple[int, int] |
| 88 |
value: TV_TokenTypes |
| 89 |
|
| 90 |
def __eq__(self, other: object) -> bool: |
| 91 |
if isinstance(other, str): |
| 92 |
return self.tid == other |
| 93 |
elif isinstance(other, Token): |
| 94 |
return self.tid == other.tid |
| 95 |
return NotImplemented |
| 96 |
|
| 97 |
|
| 98 |
IDENT_RE_STR = r'[_a-zA-Z][_0-9a-zA-Z]*' |
| 99 |
IDENT_RE = re.compile(IDENT_RE_STR) |
| 100 |
IDENT_RE_MACHINEFILE = re.compile(IDENT_RE_STR + '|~') |
| 101 |
|
| 102 |
class Lexer: |
| 103 |
def __init__(self, code: str, *, machinefile: bool = False): |
| 104 |
if code.startswith(codecs.BOM_UTF8.decode('utf-8')): |
| 105 |
line, *_ = code.split('\n', maxsplit=1) |
| 106 |
raise ParseException('Builder file must be encoded in UTF-8 (with no BOM)', line, lineno=0, colno=0) |
| 107 |
|
| 108 |
self.code = code |
| 109 |
self.keywords = {'true', 'false', 'if', 'else', 'elif', |
| 110 |
'endif', 'and', 'or', 'not', 'foreach', 'endforeach', |
| 111 |
'in', 'continue', 'break'} |
| 112 |
self.future_keywords = {'return'} |
| 113 |
self.in_unit_test = 'MESON_RUNNING_IN_PROJECT_TESTS' in os.environ |
| 114 |
if self.in_unit_test: |
| 115 |
self.keywords.update({'testcase', 'endtestcase'}) |
| 116 |
self.token_specification = [ |
| 117 |
# Need to be sorted longest to shortest. |
| 118 |
('whitespace', re.compile(r'[ \t]+')), |
| 119 |
('multiline_fstring', re.compile(r"f'''(.|\n)*?'''", re.M)), |
| 120 |
('fstring', re.compile(r"f'([^'\\]|(\\.))*'")), |
| 121 |
('id', IDENT_RE_MACHINEFILE if machinefile else IDENT_RE), |
| 122 |
('number', re.compile(r'0[bB][01]+|0[oO][0-7]+|0[xX][0-9a-fA-F]+|0|[1-9]\d*')), |
| 123 |
('eol_cont', re.compile(r'\\[ \t]*(#.*)?\n')), |
| 124 |
('multiline_string', re.compile(r"'''(.|\n)*?'''", re.M)), |
| 125 |
('comment', re.compile(r'#.*')), |
| 126 |
('string', re.compile(r"'([^'\\]|(\\.))*'")), |
| 127 |
('plusassign', re.compile(r'\+=')), |
| 128 |
('equal', re.compile(r'==')), |
| 129 |
('nequal', re.compile(r'!=')), |
| 130 |
('le', re.compile(r'<=')), |
| 131 |
('ge', re.compile(r'>=')), |
| 132 |
] |
| 133 |
|
| 134 |
self.single_char_tokens = { |
| 135 |
'\n': 'eol', |
| 136 |
'(': 'lparen', |
| 137 |
')': 'rparen', |
| 138 |
'[': 'lbracket', |
| 139 |
']': 'rbracket', |
| 140 |
'{': 'lcurl', |
| 141 |
'}': 'rcurl', |
| 142 |
'"': 'dblquote', |
| 143 |
',': 'comma', |
| 144 |
'.': 'dot', |
| 145 |
'+': 'plus', |
| 146 |
'-': 'dash', |
| 147 |
'*': 'star', |
| 148 |
'%': 'percent', |
| 149 |
'/': 'fslash', |
| 150 |
':': 'colon', |
| 151 |
'=': 'assign', |
| 152 |
'<': 'lt', |
| 153 |
'>': 'gt', |
| 154 |
'?': 'questionmark', |
| 155 |
} |
| 156 |
|
| 157 |
def getline(self, line_start: int) -> str: |
| 158 |
return self.code[line_start:self.code.find('\n', line_start)] |
| 159 |
|
| 160 |
def lex(self, filename: str) -> T.Generator[Token, None, None]: |
| 161 |
line_start = 0 |
| 162 |
lineno = 1 |
| 163 |
loc = 0 |
| 164 |
par_count = 0 |
| 165 |
bracket_count = 0 |
| 166 |
curl_count = 0 |
| 167 |
try: |
| 168 |
while loc < len(self.code): |
| 169 |
value: str |
| 170 |
span_start = loc |
| 171 |
col = loc - line_start |
| 172 |
curline = lineno |
| 173 |
curline_start = line_start |
| 174 |
for (tid, reg) in self.token_specification: |
| 175 |
mo = reg.match(self.code, loc) |
| 176 |
if mo: |
| 177 |
value = mo.group() |
| 178 |
loc = mo.end() |
| 179 |
break |
| 180 |
else: |
| 181 |
# lex single characters and raise an exception for invalid tokens |
| 182 |
value = self.code[loc] |
| 183 |
tid = self.single_char_tokens[value] |
| 184 |
loc += 1 |
| 185 |
|
| 186 |
if tid == 'lparen': |
| 187 |
par_count += 1 |
| 188 |
elif tid == 'rparen': |
| 189 |
par_count -= 1 |
| 190 |
elif tid == 'lbracket': |
| 191 |
bracket_count += 1 |
| 192 |
elif tid == 'rbracket': |
| 193 |
bracket_count -= 1 |
| 194 |
elif tid == 'lcurl': |
| 195 |
curl_count += 1 |
| 196 |
elif tid == 'rcurl': |
| 197 |
curl_count -= 1 |
| 198 |
elif tid == 'dblquote': |
| 199 |
raise ParseException('Double quotes are not supported. Use single quotes.', self.getline(line_start), lineno, col) |
| 200 |
elif tid == 'eol': |
| 201 |
lineno += 1 |
| 202 |
line_start = loc |
| 203 |
if par_count > 0 or bracket_count > 0 or curl_count > 0: |
| 204 |
tid = 'whitespace' |
| 205 |
|
| 206 |
if tid == 'id': |
| 207 |
if value in self.keywords: |
| 208 |
tid = value |
| 209 |
else: |
| 210 |
if value in self.future_keywords: |
| 211 |
mlog.warning(f"Identifier '{value}' will become a reserved keyword in a future release. Please rename it.", |
| 212 |
location=BaseNode(lineno, col, filename)) |
| 213 |
elif tid in {'string', 'fstring'}: |
| 214 |
if value.find("\n") != -1: |
| 215 |
msg = ("Newline character in a string detected, use ''' (three single quotes) " |
| 216 |
"for multiline strings instead.\n" |
| 217 |
"This will become a hard error in a future Meson release.") |
| 218 |
mlog.warning(mlog.code_line(msg, self.getline(line_start), col), location=BaseNode(lineno, col, filename)) |
| 219 |
value = value[2 if tid == 'fstring' else 1:-1] |
| 220 |
elif tid in {'multiline_string', 'multiline_fstring'}: |
| 221 |
value = value[4 if tid == 'multiline_fstring' else 3:-3] |
| 222 |
lines = value.split('\n') |
| 223 |
if len(lines) > 1: |
| 224 |
lineno += len(lines) - 1 |
| 225 |
line_start = loc - len(lines[-1]) - 3 |
| 226 |
elif tid == 'eol_cont': |
| 227 |
lineno += 1 |
| 228 |
line_start = loc |
| 229 |
tid = 'whitespace' |
| 230 |
bytespan = (span_start, loc) |
| 231 |
yield Token(tid, filename, curline_start, curline, col, bytespan, value) |
| 232 |
|
| 233 |
except KeyError: |
| 234 |
raise ParseException(f'lexer: unrecognized token {self.code[loc]!r}', self.getline(line_start), lineno, loc - line_start) |
| 235 |
|
| 236 |
@dataclass |
| 237 |
class BaseNode: |
| 238 |
lineno: int |
| 239 |
colno: int |
| 240 |
filename: str = field(hash=False) |
| 241 |
end_lineno: int = field(hash=False) |
| 242 |
end_colno: int = field(hash=False) |
| 243 |
whitespaces: T.Optional[WhitespaceNode] = field(hash=False) |
| 244 |
|
| 245 |
def __init__(self, lineno: int, colno: int, filename: str, |
| 246 |
end_lineno: T.Optional[int] = None, end_colno: T.Optional[int] = None) -> None: |
| 247 |
self.lineno = lineno |
| 248 |
self.colno = colno |
| 249 |
self.filename = filename |
| 250 |
self.end_lineno = end_lineno if end_lineno is not None else lineno |
| 251 |
self.end_colno = end_colno if end_colno is not None else colno |
| 252 |
self.whitespaces = None |
| 253 |
|
| 254 |
# Attributes for the visitors |
| 255 |
self.level = 0 |
| 256 |
self.ast_id = '' |
| 257 |
self.condition_level = 0 |
| 258 |
|
| 259 |
def accept(self, visitor: 'AstVisitor') -> None: |
| 260 |
fname = 'visit_{}'.format(type(self).__name__) |
| 261 |
if hasattr(visitor, fname): |
| 262 |
func = getattr(visitor, fname) |
| 263 |
if callable(func): |
| 264 |
func(self) |
| 265 |
|
| 266 |
def append_whitespaces(self, token: Token) -> None: |
| 267 |
if self.whitespaces is None: |
| 268 |
self.whitespaces = WhitespaceNode(token) |
| 269 |
else: |
| 270 |
self.whitespaces.append(token) |
| 271 |
|
| 272 |
|
| 273 |
@dataclass(unsafe_hash=True) |
| 274 |
class WhitespaceNode(BaseNode): |
| 275 |
|
| 276 |
value: str |
| 277 |
|
| 278 |
def __init__(self, token: Token[str]): |
| 279 |
super().__init__(token.lineno, token.colno, token.filename) |
| 280 |
self.value = '' |
| 281 |
self.append(token) |
| 282 |
self.block_indent = False |
| 283 |
self.is_continuation = False |
| 284 |
|
| 285 |
def append(self, token: Token[str]) -> None: |
| 286 |
self.value += token.value |
| 287 |
|
| 288 |
@dataclass(unsafe_hash=True) |
| 289 |
class ElementaryNode(T.Generic[TV_TokenTypes], BaseNode): |
| 290 |
|
| 291 |
value: TV_TokenTypes |
| 292 |
bytespan: T.Tuple[int, int] = field(hash=False) |
| 293 |
|
| 294 |
def __init__(self, token: Token[TV_TokenTypes]): |
| 295 |
super().__init__(token.lineno, token.colno, token.filename) |
| 296 |
self.value = token.value |
| 297 |
self.bytespan = token.bytespan |
| 298 |
|
| 299 |
class BooleanNode(ElementaryNode[bool]): |
| 300 |
pass |
| 301 |
|
| 302 |
class IdNode(ElementaryNode[str]): |
| 303 |
pass |
| 304 |
|
| 305 |
@dataclass(unsafe_hash=True) |
| 306 |
class NumberNode(ElementaryNode[int]): |
| 307 |
|
| 308 |
raw_value: str = field(hash=False) |
| 309 |
|
| 310 |
def __init__(self, token: Token[str]): |
| 311 |
BaseNode.__init__(self, token.lineno, token.colno, token.filename) |
| 312 |
self.raw_value = token.value |
| 313 |
self.value = int(token.value, base=0) |
| 314 |
self.bytespan = token.bytespan |
| 315 |
|
| 316 |
@dataclass(unsafe_hash=True) |
| 317 |
class StringNode(ElementaryNode[str]): |
| 318 |
|
| 319 |
raw_value: str = field(hash=False) |
| 320 |
is_multiline: bool |
| 321 |
is_fstring: bool |
| 322 |
|
| 323 |
def __init__(self, token: Token[str], escape: bool = True): |
| 324 |
super().__init__(token) |
| 325 |
|
| 326 |
self.is_multiline = 'multiline' in token.tid |
| 327 |
self.is_fstring = 'fstring' in token.tid |
| 328 |
self.raw_value = token.value |
| 329 |
|
| 330 |
if escape and not self.is_multiline: |
| 331 |
self.value = self.escape() |
| 332 |
|
| 333 |
def escape(self) -> str: |
| 334 |
return ESCAPE_SEQUENCE_SINGLE_RE.sub(decode_match, self.raw_value) |
| 335 |
|
| 336 |
class ContinueNode(ElementaryNode): |
| 337 |
pass |
| 338 |
|
| 339 |
class BreakNode(ElementaryNode): |
| 340 |
pass |
| 341 |
|
| 342 |
class SymbolNode(ElementaryNode[str]): |
| 343 |
pass |
| 344 |
|
| 345 |
@dataclass(unsafe_hash=True) |
| 346 |
class ArgumentNode(BaseNode): |
| 347 |
|
| 348 |
arguments: T.List[BaseNode] = field(hash=False) |
| 349 |
commas: T.List[SymbolNode] = field(hash=False) |
| 350 |
colons: T.List[SymbolNode] = field(hash=False) |
| 351 |
kwargs: T.Dict[BaseNode, BaseNode] = field(hash=False) |
| 352 |
|
| 353 |
def __init__(self, token: Token[TV_TokenTypes]): |
| 354 |
super().__init__(token.lineno, token.colno, token.filename) |
| 355 |
self.arguments = [] |
| 356 |
self.commas = [] |
| 357 |
self.colons = [] |
| 358 |
self.kwargs = {} |
| 359 |
self.order_error = False |
| 360 |
|
| 361 |
# Attributes for the visitors |
| 362 |
self.is_multiline = False |
| 363 |
|
| 364 |
def prepend(self, statement: BaseNode) -> None: |
| 365 |
if self.num_kwargs() > 0: |
| 366 |
self.order_error = True |
| 367 |
if not isinstance(statement, EmptyNode): |
| 368 |
self.arguments = [statement] + self.arguments |
| 369 |
|
| 370 |
def append(self, statement: BaseNode) -> None: |
| 371 |
if self.num_kwargs() > 0: |
| 372 |
self.order_error = True |
| 373 |
if not isinstance(statement, EmptyNode): |
| 374 |
self.arguments += [statement] |
| 375 |
|
| 376 |
def set_kwarg(self, name: IdNode, value: BaseNode) -> None: |
| 377 |
if any((isinstance(x, IdNode) and name.value == x.value) for x in self.kwargs): |
| 378 |
mlog.warning(f'Keyword argument "{name.value}" defined multiple times.', location=self) |
| 379 |
mlog.warning('This will be an error in Meson 2.0.') |
| 380 |
self.kwargs[name] = value |
| 381 |
|
| 382 |
def get_kwarg_or_default(self, name: str, default: BaseNode) -> BaseNode: |
| 383 |
for k, v in self.kwargs.items(): |
| 384 |
assert isinstance(k, IdNode) |
| 385 |
if k.value == name: |
| 386 |
return v |
| 387 |
return default |
| 388 |
|
| 389 |
def set_kwarg_no_check(self, name: BaseNode, value: BaseNode) -> None: |
| 390 |
self.kwargs[name] = value |
| 391 |
|
| 392 |
def num_args(self) -> int: |
| 393 |
return len(self.arguments) |
| 394 |
|
| 395 |
def num_kwargs(self) -> int: |
| 396 |
return len(self.kwargs) |
| 397 |
|
| 398 |
def incorrect_order(self) -> bool: |
| 399 |
return self.order_error |
| 400 |
|
| 401 |
def __len__(self) -> int: |
| 402 |
return self.num_args() + self.num_kwargs() |
| 403 |
|
| 404 |
@dataclass(unsafe_hash=True) |
| 405 |
class ArrayNode(BaseNode): |
| 406 |
|
| 407 |
lbracket: SymbolNode |
| 408 |
args: ArgumentNode |
| 409 |
rbracket: SymbolNode |
| 410 |
|
| 411 |
def __init__(self, lbracket: SymbolNode, args: ArgumentNode, rbracket: SymbolNode): |
| 412 |
super().__init__(lbracket.lineno, lbracket.colno, args.filename, end_lineno=rbracket.lineno, end_colno=rbracket.colno+1) |
| 413 |
self.lbracket = lbracket |
| 414 |
self.args = args |
| 415 |
self.rbracket = rbracket |
| 416 |
|
| 417 |
@dataclass(unsafe_hash=True) |
| 418 |
class DictNode(BaseNode): |
| 419 |
|
| 420 |
lcurl: SymbolNode |
| 421 |
args: ArgumentNode |
| 422 |
rcurl: SymbolNode |
| 423 |
|
| 424 |
def __init__(self, lcurl: SymbolNode, args: ArgumentNode, rcurl: SymbolNode): |
| 425 |
super().__init__(lcurl.lineno, lcurl.colno, args.filename, end_lineno=rcurl.lineno, end_colno=rcurl.colno+1) |
| 426 |
self.lcurl = lcurl |
| 427 |
self.args = args |
| 428 |
self.rcurl = rcurl |
| 429 |
|
| 430 |
class EmptyNode(BaseNode): |
| 431 |
pass |
| 432 |
|
| 433 |
@dataclass(unsafe_hash=True) |
| 434 |
class BinaryOperatorNode(BaseNode): |
| 435 |
|
| 436 |
left: BaseNode |
| 437 |
operator: SymbolNode |
| 438 |
right: BaseNode |
| 439 |
|
| 440 |
def __init__(self, left: BaseNode, operator: SymbolNode, right: BaseNode): |
| 441 |
super().__init__(left.lineno, left.colno, left.filename) |
| 442 |
self.left = left |
| 443 |
self.operator = operator |
| 444 |
self.right = right |
| 445 |
|
| 446 |
class OrNode(BinaryOperatorNode): |
| 447 |
pass |
| 448 |
|
| 449 |
class AndNode(BinaryOperatorNode): |
| 450 |
pass |
| 451 |
|
| 452 |
@dataclass(unsafe_hash=True) |
| 453 |
class ComparisonNode(BinaryOperatorNode): |
| 454 |
|
| 455 |
ctype: COMPARISONS |
| 456 |
|
| 457 |
def __init__(self, ctype: COMPARISONS, left: BaseNode, operator: SymbolNode, right: BaseNode): |
| 458 |
super().__init__(left, operator, right) |
| 459 |
self.ctype = ctype |
| 460 |
|
| 461 |
@dataclass(unsafe_hash=True) |
| 462 |
class ArithmeticNode(BinaryOperatorNode): |
| 463 |
|
| 464 |
operation: ARITH_OPERATORS |
| 465 |
|
| 466 |
def __init__(self, operation: ARITH_OPERATORS, left: BaseNode, operator: SymbolNode, right: BaseNode): |
| 467 |
super().__init__(left, operator, right) |
| 468 |
self.operation = operation |
| 469 |
|
| 470 |
@dataclass(unsafe_hash=True) |
| 471 |
class UnaryOperatorNode(BaseNode): |
| 472 |
|
| 473 |
operator: SymbolNode |
| 474 |
value: BaseNode |
| 475 |
|
| 476 |
def __init__(self, token: Token[TV_TokenTypes], operator: SymbolNode, value: BaseNode): |
| 477 |
super().__init__(token.lineno, token.colno, token.filename) |
| 478 |
self.operator = operator |
| 479 |
self.value = value |
| 480 |
|
| 481 |
class NotNode(UnaryOperatorNode): |
| 482 |
pass |
| 483 |
|
| 484 |
class UMinusNode(UnaryOperatorNode): |
| 485 |
pass |
| 486 |
|
| 487 |
@dataclass(unsafe_hash=True) |
| 488 |
class CodeBlockNode(BaseNode): |
| 489 |
|
| 490 |
pre_whitespaces: T.Optional[WhitespaceNode] = field(hash=False) |
| 491 |
lines: T.List[BaseNode] = field(hash=False) |
| 492 |
|
| 493 |
def __init__(self, token: Token[TV_TokenTypes]): |
| 494 |
super().__init__(token.lineno, token.colno, token.filename) |
| 495 |
self.pre_whitespaces = None |
| 496 |
self.lines = [] |
| 497 |
|
| 498 |
def append_whitespaces(self, token: Token) -> None: |
| 499 |
if self.lines: |
| 500 |
self.lines[-1].append_whitespaces(token) |
| 501 |
elif self.pre_whitespaces is None: |
| 502 |
self.pre_whitespaces = WhitespaceNode(token) |
| 503 |
else: |
| 504 |
self.pre_whitespaces.append(token) |
| 505 |
|
| 506 |
@dataclass(unsafe_hash=True) |
| 507 |
class IndexNode(BaseNode): |
| 508 |
|
| 509 |
iobject: BaseNode |
| 510 |
lbracket: SymbolNode |
| 511 |
index: BaseNode |
| 512 |
rbracket: SymbolNode |
| 513 |
|
| 514 |
def __init__(self, iobject: BaseNode, lbracket: SymbolNode, index: BaseNode, rbracket: SymbolNode): |
| 515 |
super().__init__(iobject.lineno, iobject.colno, iobject.filename) |
| 516 |
self.iobject = iobject |
| 517 |
self.lbracket = lbracket |
| 518 |
self.index = index |
| 519 |
self.rbracket = rbracket |
| 520 |
|
| 521 |
@dataclass(unsafe_hash=True) |
| 522 |
class MethodNode(BaseNode): |
| 523 |
|
| 524 |
source_object: BaseNode |
| 525 |
dot: SymbolNode |
| 526 |
name: IdNode |
| 527 |
lpar: SymbolNode |
| 528 |
args: ArgumentNode |
| 529 |
rpar: SymbolNode |
| 530 |
|
| 531 |
def __init__(self, source_object: BaseNode, dot: SymbolNode, name: IdNode, lpar: SymbolNode, args: ArgumentNode, rpar: SymbolNode): |
| 532 |
super().__init__(name.lineno, name.colno, name.filename, end_lineno=rpar.lineno, end_colno=rpar.colno+1) |
| 533 |
self.source_object = source_object |
| 534 |
self.dot = dot |
| 535 |
self.name = name |
| 536 |
self.lpar = lpar |
| 537 |
self.args = args |
| 538 |
self.rpar = rpar |
| 539 |
|
| 540 |
@dataclass(unsafe_hash=True) |
| 541 |
class FunctionNode(BaseNode): |
| 542 |
|
| 543 |
func_name: IdNode |
| 544 |
lpar: SymbolNode |
| 545 |
args: ArgumentNode |
| 546 |
rpar: SymbolNode |
| 547 |
|
| 548 |
def __init__(self, func_name: IdNode, lpar: SymbolNode, args: ArgumentNode, rpar: SymbolNode): |
| 549 |
super().__init__(func_name.lineno, func_name.colno, func_name.filename, end_lineno=rpar.end_lineno, end_colno=rpar.end_colno+1) |
| 550 |
self.func_name = func_name |
| 551 |
self.lpar = lpar |
| 552 |
self.args = args |
| 553 |
self.rpar = rpar |
| 554 |
|
| 555 |
@dataclass(unsafe_hash=True) |
| 556 |
class AssignmentNode(BaseNode): |
| 557 |
|
| 558 |
var_name: IdNode |
| 559 |
operator: SymbolNode |
| 560 |
value: BaseNode |
| 561 |
|
| 562 |
def __init__(self, var_name: IdNode, operator: SymbolNode, value: BaseNode): |
| 563 |
super().__init__(var_name.lineno, var_name.colno, var_name.filename) |
| 564 |
self.var_name = var_name |
| 565 |
self.operator = operator |
| 566 |
self.value = value |
| 567 |
|
| 568 |
class PlusAssignmentNode(AssignmentNode): |
| 569 |
pass |
| 570 |
|
| 571 |
@dataclass(unsafe_hash=True) |
| 572 |
class ForeachClauseNode(BaseNode): |
| 573 |
|
| 574 |
foreach_: SymbolNode = field(hash=False) |
| 575 |
varnames: T.List[IdNode] = field(hash=False) |
| 576 |
commas: T.List[SymbolNode] = field(hash=False) |
| 577 |
colon: SymbolNode = field(hash=False) |
| 578 |
items: BaseNode |
| 579 |
block: CodeBlockNode |
| 580 |
endforeach: SymbolNode = field(hash=False) |
| 581 |
|
| 582 |
def __init__(self, foreach_: SymbolNode, varnames: T.List[IdNode], commas: T.List[SymbolNode], colon: SymbolNode, items: BaseNode, block: CodeBlockNode, endforeach: SymbolNode): |
| 583 |
super().__init__(foreach_.lineno, foreach_.colno, foreach_.filename) |
| 584 |
self.foreach_ = foreach_ |
| 585 |
self.varnames = varnames |
| 586 |
self.commas = commas |
| 587 |
self.colon = colon |
| 588 |
self.items = items |
| 589 |
self.block = block |
| 590 |
self.endforeach = endforeach |
| 591 |
|
| 592 |
|
| 593 |
@dataclass(unsafe_hash=True) |
| 594 |
class IfNode(BaseNode): |
| 595 |
|
| 596 |
if_: SymbolNode |
| 597 |
condition: BaseNode |
| 598 |
block: CodeBlockNode |
| 599 |
|
| 600 |
def __init__(self, linenode: BaseNode, if_node: SymbolNode, condition: BaseNode, block: CodeBlockNode): |
| 601 |
super().__init__(linenode.lineno, linenode.colno, linenode.filename) |
| 602 |
self.if_ = if_node |
| 603 |
self.condition = condition |
| 604 |
self.block = block |
| 605 |
|
| 606 |
@dataclass(unsafe_hash=True) |
| 607 |
class ElseNode(BaseNode): |
| 608 |
|
| 609 |
else_: SymbolNode |
| 610 |
block: CodeBlockNode |
| 611 |
|
| 612 |
def __init__(self, else_: SymbolNode, block: CodeBlockNode): |
| 613 |
super().__init__(block.lineno, block.colno, block.filename) |
| 614 |
self.else_ = else_ |
| 615 |
self.block = block |
| 616 |
|
| 617 |
@dataclass(unsafe_hash=True) |
| 618 |
class IfClauseNode(BaseNode): |
| 619 |
|
| 620 |
ifs: T.List[IfNode] = field(hash=False) |
| 621 |
elseblock: T.Union[EmptyNode, ElseNode] |
| 622 |
endif: SymbolNode |
| 623 |
|
| 624 |
def __init__(self, linenode: BaseNode): |
| 625 |
super().__init__(linenode.lineno, linenode.colno, linenode.filename) |
| 626 |
self.ifs = [] |
| 627 |
self.elseblock = EmptyNode(linenode.lineno, linenode.colno, linenode.filename) |
| 628 |
|
| 629 |
@dataclass(unsafe_hash=True) |
| 630 |
class TestCaseClauseNode(BaseNode): |
| 631 |
|
| 632 |
testcase: SymbolNode |
| 633 |
condition: BaseNode |
| 634 |
block: CodeBlockNode |
| 635 |
endtestcase: SymbolNode |
| 636 |
|
| 637 |
def __init__(self, testcase: SymbolNode, condition: BaseNode, block: CodeBlockNode, endtestcase: SymbolNode): |
| 638 |
super().__init__(condition.lineno, condition.colno, condition.filename) |
| 639 |
self.testcase = testcase |
| 640 |
self.condition = condition |
| 641 |
self.block = block |
| 642 |
self.endtestcase = endtestcase |
| 643 |
|
| 644 |
@dataclass(unsafe_hash=True) |
| 645 |
class TernaryNode(BaseNode): |
| 646 |
|
| 647 |
condition: BaseNode |
| 648 |
questionmark: SymbolNode |
| 649 |
trueblock: BaseNode |
| 650 |
colon: SymbolNode |
| 651 |
falseblock: BaseNode |
| 652 |
|
| 653 |
def __init__(self, condition: BaseNode, questionmark: SymbolNode, trueblock: BaseNode, colon: SymbolNode, falseblock: BaseNode): |
| 654 |
super().__init__(condition.lineno, condition.colno, condition.filename) |
| 655 |
self.condition = condition |
| 656 |
self.questionmark = questionmark |
| 657 |
self.trueblock = trueblock |
| 658 |
self.colon = colon |
| 659 |
self.falseblock = falseblock |
| 660 |
|
| 661 |
|
| 662 |
@dataclass(unsafe_hash=True) |
| 663 |
class ParenthesizedNode(BaseNode): |
| 664 |
|
| 665 |
lpar: SymbolNode = field(hash=False) |
| 666 |
inner: BaseNode |
| 667 |
rpar: SymbolNode = field(hash=False) |
| 668 |
is_multiline: bool |
| 669 |
|
| 670 |
def __init__(self, lpar: SymbolNode, inner: BaseNode, rpar: SymbolNode): |
| 671 |
super().__init__(lpar.lineno, lpar.colno, inner.filename, end_lineno=rpar.lineno, end_colno=rpar.colno+1) |
| 672 |
self.lpar = lpar |
| 673 |
self.inner = inner |
| 674 |
self.rpar = rpar |
| 675 |
self.is_multiline = False |
| 676 |
|
| 677 |
if T.TYPE_CHECKING: |
| 678 |
COMPARISONS = Literal['==', '!=', '<', '<=', '>=', '>', 'in', 'not in'] |
| 679 |
ARITH_OPERATORS = Literal['+', '-', '*', '/', '%'] |
| 680 |
|
| 681 |
ALL_STRINGS = frozenset({'string', 'fstring', 'multiline_string', 'multiline_fstring'}) |
| 682 |
|
| 683 |
COMPARISON_MAP: T.Mapping[str, COMPARISONS] = { |
| 684 |
'equal': '==', |
| 685 |
'nequal': '!=', |
| 686 |
'lt': '<', |
| 687 |
'le': '<=', |
| 688 |
'gt': '>', |
| 689 |
'ge': '>=', |
| 690 |
'in': 'in', |
| 691 |
'not in': 'not in', |
| 692 |
} |
| 693 |
|
| 694 |
ADDSUB_MAP: T.Mapping[str, ARITH_OPERATORS] = { |
| 695 |
'plus': '+', |
| 696 |
'dash': '-', |
| 697 |
} |
| 698 |
|
| 699 |
MULDIV_MAP: T.Mapping[str, ARITH_OPERATORS] = { |
| 700 |
'percent': '%', |
| 701 |
'star': '*', |
| 702 |
'fslash': '/', |
| 703 |
} |
| 704 |
|
| 705 |
# Recursive descent parser for Meson's definition language. |
| 706 |
# Very basic apart from the fact that we have many precedence |
| 707 |
# levels so there are not enough words to describe them all. |
| 708 |
# Enter numbering: |
| 709 |
# |
| 710 |
# 1 assignment |
| 711 |
# 2 or |
| 712 |
# 3 and |
| 713 |
# 4 comparison |
| 714 |
# 5 addition and subtraction |
| 715 |
# 6 multiplication, division and modulus |
| 716 |
# 7 negation |
| 717 |
# 8 funcall, method call |
| 718 |
# 9 parentheses |
| 719 |
# 10 plain token |
| 720 |
|
| 721 |
class Parser: |
| 722 |
def __init__(self, code: str, filename: str, *, machinefile: bool = False): |
| 723 |
self.lexer = Lexer(code, machinefile=machinefile) |
| 724 |
self.stream = self.lexer.lex(filename) |
| 725 |
self.current: Token = Token('eof', '', 0, 0, 0, (0, 0), None) |
| 726 |
self.previous = self.current |
| 727 |
self.current_ws: T.List[Token] = [] |
| 728 |
|
| 729 |
self.getsym() |
| 730 |
self.in_ternary = False |
| 731 |
|
| 732 |
def create_node(self, node_type: T.Type[BaseNodeT], *args: T.Any, **kwargs: T.Any) -> BaseNodeT: |
| 733 |
node = node_type(*args, **kwargs) |
| 734 |
for ws_token in self.current_ws: |
| 735 |
node.append_whitespaces(ws_token) |
| 736 |
self.current_ws = [] |
| 737 |
return node |
| 738 |
|
| 739 |
def getsym(self) -> None: |
| 740 |
self.previous = self.current |
| 741 |
try: |
| 742 |
self.current = next(self.stream) |
| 743 |
|
| 744 |
while self.current.tid in {'eol', 'comment', 'whitespace'}: |
| 745 |
self.current_ws.append(self.current) |
| 746 |
if self.current.tid == 'eol': |
| 747 |
break |
| 748 |
self.current = next(self.stream) |
| 749 |
|
| 750 |
except StopIteration: |
| 751 |
self.current = Token('eof', '', self.current.line_start, self.current.lineno, self.current.colno + self.current.bytespan[1] - self.current.bytespan[0], (0, 0), None) |
| 752 |
|
| 753 |
def getline(self) -> str: |
| 754 |
return self.lexer.getline(self.current.line_start) |
| 755 |
|
| 756 |
def accept(self, s: str) -> bool: |
| 757 |
if self.current.tid == s: |
| 758 |
self.getsym() |
| 759 |
return True |
| 760 |
return False |
| 761 |
|
| 762 |
def accept_any(self, tids: T.Union[T.AbstractSet[str], T.Mapping[str, object]]) -> str: |
| 763 |
tid = self.current.tid |
| 764 |
if tid in tids: |
| 765 |
self.getsym() |
| 766 |
return tid |
| 767 |
return '' |
| 768 |
|
| 769 |
def expect(self, s: str) -> bool: |
| 770 |
if self.accept(s): |
| 771 |
return True |
| 772 |
raise ParseException(f'Expecting {s} got {self.current.tid}.', self.getline(), self.current.lineno, self.current.colno) |
| 773 |
|
| 774 |
def block_expect(self, s: str, block_start: Token) -> bool: |
| 775 |
if self.accept(s): |
| 776 |
return True |
| 777 |
raise BlockParseException(f'Expecting {s} got {self.current.tid}.', self.getline(), self.current.lineno, self.current.colno, self.lexer.getline(block_start.line_start), block_start.lineno, block_start.colno) |
| 778 |
|
| 779 |
def parse(self) -> CodeBlockNode: |
| 780 |
block = self.codeblock() |
| 781 |
try: |
| 782 |
self.expect('eof') |
| 783 |
except ParseException as e: |
| 784 |
e.ast = block |
| 785 |
raise |
| 786 |
return block |
| 787 |
|
| 788 |
def statement(self) -> BaseNode: |
| 789 |
return self.e1() |
| 790 |
|
| 791 |
def e1(self) -> BaseNode: |
| 792 |
left = self.e2() |
| 793 |
if self.accept('plusassign'): |
| 794 |
operator = self.create_node(SymbolNode, self.previous) |
| 795 |
value = self.e1() |
| 796 |
if not isinstance(left, IdNode): |
| 797 |
raise ParseException('Plusassignment target must be an id.', self.getline(), left.lineno, left.colno) |
| 798 |
assert isinstance(left.value, str) |
| 799 |
return self.create_node(PlusAssignmentNode, left, operator, value) |
| 800 |
elif self.accept('assign'): |
| 801 |
operator = self.create_node(SymbolNode, self.previous) |
| 802 |
value = self.e1() |
| 803 |
if not isinstance(left, IdNode): |
| 804 |
raise ParseException('Assignment target must be an id.', |
| 805 |
self.getline(), left.lineno, left.colno) |
| 806 |
assert isinstance(left.value, str) |
| 807 |
return self.create_node(AssignmentNode, left, operator, value) |
| 808 |
elif self.accept('questionmark'): |
| 809 |
if self.in_ternary: |
| 810 |
raise ParseException('Nested ternary operators are not allowed.', |
| 811 |
self.getline(), left.lineno, left.colno) |
| 812 |
|
| 813 |
qm_node = self.create_node(SymbolNode, self.previous) |
| 814 |
self.in_ternary = True |
| 815 |
trueblock = self.e1() |
| 816 |
self.expect('colon') |
| 817 |
colon_node = self.create_node(SymbolNode, self.previous) |
| 818 |
falseblock = self.e1() |
| 819 |
self.in_ternary = False |
| 820 |
return self.create_node(TernaryNode, left, qm_node, trueblock, colon_node, falseblock) |
| 821 |
return left |
| 822 |
|
| 823 |
def e2(self) -> BaseNode: |
| 824 |
left = self.e3() |
| 825 |
while self.accept('or'): |
| 826 |
operator = self.create_node(SymbolNode, self.previous) |
| 827 |
if isinstance(left, EmptyNode): |
| 828 |
raise ParseException('Invalid or clause.', |
| 829 |
self.getline(), left.lineno, left.colno) |
| 830 |
left = self.create_node(OrNode, left, operator, self.e3()) |
| 831 |
return left |
| 832 |
|
| 833 |
def e3(self) -> BaseNode: |
| 834 |
left = self.e4() |
| 835 |
while self.accept('and'): |
| 836 |
operator = self.create_node(SymbolNode, self.previous) |
| 837 |
if isinstance(left, EmptyNode): |
| 838 |
raise ParseException('Invalid and clause.', |
| 839 |
self.getline(), left.lineno, left.colno) |
| 840 |
left = self.create_node(AndNode, left, operator, self.e4()) |
| 841 |
return left |
| 842 |
|
| 843 |
def e4(self) -> BaseNode: |
| 844 |
left = self.e5() |
| 845 |
op = self.accept_any(COMPARISON_MAP) |
| 846 |
if op: |
| 847 |
operator = self.create_node(SymbolNode, self.previous) |
| 848 |
return self.create_node(ComparisonNode, COMPARISON_MAP[op], left, operator, self.e5()) |
| 849 |
if self.accept('not'): |
| 850 |
ws = self.current_ws.copy() |
| 851 |
not_token = self.previous |
| 852 |
if self.accept('in'): |
| 853 |
in_token = self.previous |
| 854 |
self.current_ws = self.current_ws[len(ws):] # remove whitespaces between not and in |
| 855 |
temp_node = EmptyNode(in_token.lineno, in_token.colno, in_token.filename) |
| 856 |
for w in ws: |
| 857 |
temp_node.append_whitespaces(w) |
| 858 |
|
| 859 |
not_token.bytespan = (not_token.bytespan[0], in_token.bytespan[1]) |
| 860 |
not_token.value += temp_node.whitespaces.value + in_token.value |
| 861 |
operator = self.create_node(SymbolNode, not_token) |
| 862 |
return self.create_node(ComparisonNode, 'not in', left, operator, self.e5()) |
| 863 |
return left |
| 864 |
|
| 865 |
def e5(self) -> BaseNode: |
| 866 |
left = self.e6() |
| 867 |
while True: |
| 868 |
op = self.accept_any(ADDSUB_MAP) |
| 869 |
if op: |
| 870 |
operator = self.create_node(SymbolNode, self.previous) |
| 871 |
left = self.create_node(ArithmeticNode, ADDSUB_MAP[op], left, operator, self.e6()) |
| 872 |
else: |
| 873 |
break |
| 874 |
return left |
| 875 |
|
| 876 |
def e6(self) -> BaseNode: |
| 877 |
left = self.e7() |
| 878 |
while True: |
| 879 |
op = self.accept_any(MULDIV_MAP) |
| 880 |
if op: |
| 881 |
operator = self.create_node(SymbolNode, self.previous) |
| 882 |
left = self.create_node(ArithmeticNode, MULDIV_MAP[op], left, operator, self.e7()) |
| 883 |
else: |
| 884 |
break |
| 885 |
return left |
| 886 |
|
| 887 |
def e7(self) -> BaseNode: |
| 888 |
if self.accept('not'): |
| 889 |
operator = self.create_node(SymbolNode, self.previous) |
| 890 |
return self.create_node(NotNode, self.current, operator, self.e8()) |
| 891 |
if self.accept('dash'): |
| 892 |
operator = self.create_node(SymbolNode, self.previous) |
| 893 |
return self.create_node(UMinusNode, self.current, operator, self.e8()) |
| 894 |
return self.e8() |
| 895 |
|
| 896 |
def e8(self) -> BaseNode: |
| 897 |
left = self.e9() |
| 898 |
block_start = self.current |
| 899 |
if self.accept('lparen'): |
| 900 |
lpar = self.create_node(SymbolNode, block_start) |
| 901 |
args = self.args() |
| 902 |
self.block_expect('rparen', block_start) |
| 903 |
rpar = self.create_node(SymbolNode, self.previous) |
| 904 |
if not isinstance(left, IdNode): |
| 905 |
raise ParseException('Function call must be applied to plain id', |
| 906 |
self.getline(), left.lineno, left.colno) |
| 907 |
assert isinstance(left.value, str) |
| 908 |
left = self.create_node(FunctionNode, left, lpar, args, rpar) |
| 909 |
go_again = True |
| 910 |
while go_again: |
| 911 |
go_again = False |
| 912 |
if self.accept('dot'): |
| 913 |
go_again = True |
| 914 |
left = self.method_call(left) |
| 915 |
if self.accept('lbracket'): |
| 916 |
go_again = True |
| 917 |
left = self.index_call(left) |
| 918 |
return left |
| 919 |
|
| 920 |
def e9(self) -> BaseNode: |
| 921 |
block_start = self.current |
| 922 |
if self.accept('lparen'): |
| 923 |
lpar = self.create_node(SymbolNode, block_start) |
| 924 |
e = self.statement() |
| 925 |
self.block_expect('rparen', block_start) |
| 926 |
rpar = self.create_node(SymbolNode, self.previous) |
| 927 |
return ParenthesizedNode(lpar, e, rpar) |
| 928 |
elif self.accept('lbracket'): |
| 929 |
lbracket = self.create_node(SymbolNode, block_start) |
| 930 |
args = self.args() |
| 931 |
self.block_expect('rbracket', block_start) |
| 932 |
rbracket = self.create_node(SymbolNode, self.previous) |
| 933 |
return self.create_node(ArrayNode, lbracket, args, rbracket) |
| 934 |
elif self.accept('lcurl'): |
| 935 |
lcurl = self.create_node(SymbolNode, block_start) |
| 936 |
key_values = self.key_values() |
| 937 |
self.block_expect('rcurl', block_start) |
| 938 |
rcurl = self.create_node(SymbolNode, self.previous) |
| 939 |
return self.create_node(DictNode, lcurl, key_values, rcurl) |
| 940 |
else: |
| 941 |
return self.e10() |
| 942 |
|
| 943 |
def e10(self) -> BaseNode: |
| 944 |
t = self.current |
| 945 |
if self.accept('true'): |
| 946 |
t.value = True |
| 947 |
return self.create_node(BooleanNode, t) |
| 948 |
if self.accept('false'): |
| 949 |
t.value = False |
| 950 |
return self.create_node(BooleanNode, t) |
| 951 |
if self.accept('id'): |
| 952 |
return self.create_node(IdNode, t) |
| 953 |
if self.accept('number'): |
| 954 |
return self.create_node(NumberNode, t) |
| 955 |
if self.accept_any(ALL_STRINGS): |
| 956 |
return self.create_node(StringNode, t) |
| 957 |
return EmptyNode(self.current.lineno, self.current.colno, self.current.filename) |
| 958 |
|
| 959 |
def key_values(self) -> ArgumentNode: |
| 960 |
s = self.statement() |
| 961 |
a = self.create_node(ArgumentNode, self.current) |
| 962 |
|
| 963 |
while not isinstance(s, EmptyNode): |
| 964 |
if self.accept('colon'): |
| 965 |
a.colons.append(self.create_node(SymbolNode, self.previous)) |
| 966 |
a.set_kwarg_no_check(s, self.statement()) |
| 967 |
if not self.accept('comma'): |
| 968 |
return a |
| 969 |
a.commas.append(self.create_node(SymbolNode, self.previous)) |
| 970 |
else: |
| 971 |
raise ParseException('Only key:value pairs are valid in dict construction.', |
| 972 |
self.getline(), s.lineno, s.colno) |
| 973 |
s = self.statement() |
| 974 |
return a |
| 975 |
|
| 976 |
def args(self) -> ArgumentNode: |
| 977 |
s = self.statement() |
| 978 |
a = self.create_node(ArgumentNode, self.current) |
| 979 |
|
| 980 |
while not isinstance(s, EmptyNode): |
| 981 |
if self.accept('comma'): |
| 982 |
a.commas.append(self.create_node(SymbolNode, self.previous)) |
| 983 |
a.append(s) |
| 984 |
elif self.accept('colon'): |
| 985 |
a.colons.append(self.create_node(SymbolNode, self.previous)) |
| 986 |
if not isinstance(s, IdNode): |
| 987 |
raise ParseException('Dictionary key must be a plain identifier.', |
| 988 |
self.getline(), s.lineno, s.colno) |
| 989 |
a.set_kwarg(s, self.statement()) |
| 990 |
if not self.accept('comma'): |
| 991 |
return a |
| 992 |
a.commas.append(self.create_node(SymbolNode, self.previous)) |
| 993 |
else: |
| 994 |
a.append(s) |
| 995 |
return a |
| 996 |
s = self.statement() |
| 997 |
return a |
| 998 |
|
| 999 |
def method_call(self, source_object: BaseNode) -> MethodNode: |
| 1000 |
dot = self.create_node(SymbolNode, self.previous) |
| 1001 |
methodname = self.e10() |
| 1002 |
if not isinstance(methodname, IdNode): |
| 1003 |
if isinstance(source_object, NumberNode) and isinstance(methodname, NumberNode): |
| 1004 |
raise ParseException('meson does not support float numbers', |
| 1005 |
self.getline(), source_object.lineno, source_object.colno) |
| 1006 |
raise ParseException('Method name must be plain id', |
| 1007 |
self.getline(), self.current.lineno, self.current.colno) |
| 1008 |
assert isinstance(methodname.value, str) |
| 1009 |
self.expect('lparen') |
| 1010 |
lpar = self.create_node(SymbolNode, self.previous) |
| 1011 |
args = self.args() |
| 1012 |
rpar = self.create_node(SymbolNode, self.current) |
| 1013 |
self.expect('rparen') |
| 1014 |
method = self.create_node(MethodNode, source_object, dot, methodname, lpar, args, rpar) |
| 1015 |
if self.accept('dot'): |
| 1016 |
return self.method_call(method) |
| 1017 |
return method |
| 1018 |
|
| 1019 |
def index_call(self, source_object: BaseNode) -> IndexNode: |
| 1020 |
lbracket = self.create_node(SymbolNode, self.previous) |
| 1021 |
index_statement = self.statement() |
| 1022 |
self.expect('rbracket') |
| 1023 |
rbracket = self.create_node(SymbolNode, self.previous) |
| 1024 |
return self.create_node(IndexNode, source_object, lbracket, index_statement, rbracket) |
| 1025 |
|
| 1026 |
def foreachblock(self) -> ForeachClauseNode: |
| 1027 |
foreach_ = self.create_node(SymbolNode, self.previous) |
| 1028 |
self.expect('id') |
| 1029 |
assert isinstance(self.previous.value, str) |
| 1030 |
varnames = [self.create_node(IdNode, self.previous)] |
| 1031 |
commas = [] |
| 1032 |
|
| 1033 |
if self.accept('comma'): |
| 1034 |
commas.append(self.create_node(SymbolNode, self.previous)) |
| 1035 |
self.expect('id') |
| 1036 |
assert isinstance(self.previous.value, str) |
| 1037 |
varnames.append(self.create_node(IdNode, self.previous)) |
| 1038 |
|
| 1039 |
self.expect('colon') |
| 1040 |
colon = self.create_node(SymbolNode, self.previous) |
| 1041 |
items = self.statement() |
| 1042 |
block = self.codeblock() |
| 1043 |
endforeach = self.create_node(SymbolNode, self.current) |
| 1044 |
return self.create_node(ForeachClauseNode, foreach_, varnames, commas, colon, items, block, endforeach) |
| 1045 |
|
| 1046 |
def ifblock(self) -> IfClauseNode: |
| 1047 |
if_node = self.create_node(SymbolNode, self.previous) |
| 1048 |
condition = self.statement() |
| 1049 |
clause = self.create_node(IfClauseNode, condition) |
| 1050 |
self.expect('eol') |
| 1051 |
block = self.codeblock() |
| 1052 |
clause.ifs.append(self.create_node(IfNode, clause, if_node, condition, block)) |
| 1053 |
self.elseifblock(clause) |
| 1054 |
clause.elseblock = self.elseblock() |
| 1055 |
clause.endif = self.create_node(SymbolNode, self.current) |
| 1056 |
return clause |
| 1057 |
|
| 1058 |
def elseifblock(self, clause: IfClauseNode) -> None: |
| 1059 |
while self.accept('elif'): |
| 1060 |
elif_ = self.create_node(SymbolNode, self.previous) |
| 1061 |
s = self.statement() |
| 1062 |
self.expect('eol') |
| 1063 |
b = self.codeblock() |
| 1064 |
clause.ifs.append(self.create_node(IfNode, s, elif_, s, b)) |
| 1065 |
|
| 1066 |
def elseblock(self) -> T.Union[ElseNode, EmptyNode]: |
| 1067 |
if self.accept('else'): |
| 1068 |
else_ = self.create_node(SymbolNode, self.previous) |
| 1069 |
self.expect('eol') |
| 1070 |
block = self.codeblock() |
| 1071 |
return ElseNode(else_, block) |
| 1072 |
return EmptyNode(self.current.lineno, self.current.colno, self.current.filename) |
| 1073 |
|
| 1074 |
def testcaseblock(self) -> TestCaseClauseNode: |
| 1075 |
testcase = self.create_node(SymbolNode, self.previous) |
| 1076 |
condition = self.statement() |
| 1077 |
self.expect('eol') |
| 1078 |
block = self.codeblock() |
| 1079 |
endtestcase = SymbolNode(self.current) |
| 1080 |
return self.create_node(TestCaseClauseNode, testcase, condition, block, endtestcase) |
| 1081 |
|
| 1082 |
def line(self) -> BaseNode: |
| 1083 |
block_start = self.current |
| 1084 |
if self.current == 'eol': |
| 1085 |
return EmptyNode(self.current.lineno, self.current.colno, self.current.filename) |
| 1086 |
if self.accept('if'): |
| 1087 |
ifblock = self.ifblock() |
| 1088 |
self.block_expect('endif', block_start) |
| 1089 |
return ifblock |
| 1090 |
if self.accept('foreach'): |
| 1091 |
forblock = self.foreachblock() |
| 1092 |
self.block_expect('endforeach', block_start) |
| 1093 |
return forblock |
| 1094 |
if self.accept('continue'): |
| 1095 |
return self.create_node(ContinueNode, self.current) |
| 1096 |
if self.accept('break'): |
| 1097 |
return self.create_node(BreakNode, self.current) |
| 1098 |
if self.lexer.in_unit_test and self.accept('testcase'): |
| 1099 |
block = self.testcaseblock() |
| 1100 |
self.block_expect('endtestcase', block_start) |
| 1101 |
return block |
| 1102 |
return self.statement() |
| 1103 |
|
| 1104 |
def codeblock(self) -> CodeBlockNode: |
| 1105 |
block = self.create_node(CodeBlockNode, self.current) |
| 1106 |
cond = True |
| 1107 |
|
| 1108 |
try: |
| 1109 |
while cond: |
| 1110 |
for ws_token in self.current_ws: |
| 1111 |
block.append_whitespaces(ws_token) |
| 1112 |
self.current_ws = [] |
| 1113 |
|
| 1114 |
curline = self.line() |
| 1115 |
|
| 1116 |
if not isinstance(curline, EmptyNode): |
| 1117 |
block.lines.append(curline) |
| 1118 |
|
| 1119 |
cond = self.accept('eol') |
| 1120 |
|
| 1121 |
except ParseException as e: |
| 1122 |
e.ast = block |
| 1123 |
raise |
| 1124 |
|
| 1125 |
# Remaining whitespaces will not be caught since there are no more nodes |
| 1126 |
for ws_token in self.current_ws: |
| 1127 |
block.append_whitespaces(ws_token) |
| 1128 |
self.current_ws = [] |
| 1129 |
|
| 1130 |
return block |