| 1 |
// Copyright 2017 The Bazel Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package syntax |
| 6 |
|
| 7 |
// This file defines a recursive-descent parser for Starlark. |
| 8 |
// The LL(1) grammar of Starlark and the names of many productions follow Python 2.7. |
| 9 |
// |
| 10 |
// TODO(adonovan): use syntax.Error more systematically throughout the |
| 11 |
// package. Verify that error positions are correct using the |
| 12 |
// chunkedfile mechanism. |
| 13 |
|
| 14 |
import ( |
| 15 |
"log" |
| 16 |
"slices" |
| 17 |
) |
| 18 |
|
| 19 |
// Enable this flag to print the token stream and log.Fatal on the first error. |
| 20 |
const debug = false |
| 21 |
|
| 22 |
// A Mode value is a set of flags (or 0) that controls optional parser functionality. |
| 23 |
type Mode uint |
| 24 |
|
| 25 |
const ( |
| 26 |
RetainComments Mode = 1 << iota // retain comments in AST; see Node.Comments |
| 27 |
) |
| 28 |
|
| 29 |
// Parse calls the Parse method of LegacyFileOptions(). |
| 30 |
// |
| 31 |
// Deprecated: use [FileOptions.Parse] instead, |
| 32 |
// because this function relies on legacy global variables. |
| 33 |
func Parse(filename string, src any, mode Mode) (f *File, err error) { |
| 34 |
return LegacyFileOptions().Parse(filename, src, mode) |
| 35 |
} |
| 36 |
|
| 37 |
// Parse parses the input data and returns the corresponding parse tree. |
| 38 |
// |
| 39 |
// If src != nil, Parse parses the source from src and the filename |
| 40 |
// is only used when recording position information. |
| 41 |
// The type of the argument for the src parameter must be string, |
| 42 |
// []byte, io.Reader, or FilePortion. |
| 43 |
// If src == nil, Parse parses the file specified by filename. |
| 44 |
func (opts *FileOptions) Parse(filename string, src any, mode Mode) (f *File, err error) { |
| 45 |
in, err := newScanner(filename, src, mode&RetainComments != 0) |
| 46 |
if err != nil { |
| 47 |
return nil, err |
| 48 |
} |
| 49 |
p := parser{options: opts, in: in} |
| 50 |
defer p.in.recover(&err) |
| 51 |
|
| 52 |
p.nextToken() // read first lookahead token |
| 53 |
f = p.parseFile() |
| 54 |
if f != nil { |
| 55 |
f.Path = filename |
| 56 |
} |
| 57 |
p.assignComments(f) |
| 58 |
return f, nil |
| 59 |
} |
| 60 |
|
| 61 |
// ParseCompoundStmt calls the ParseCompoundStmt method of LegacyFileOptions(). |
| 62 |
// |
| 63 |
// Deprecated: use [FileOptions.ParseCompoundStmt] instead, |
| 64 |
// because this function relies on legacy global variables. |
| 65 |
func ParseCompoundStmt(filename string, readline func() ([]byte, error)) (f *File, err error) { |
| 66 |
return LegacyFileOptions().ParseCompoundStmt(filename, readline) |
| 67 |
} |
| 68 |
|
| 69 |
// ParseCompoundStmt parses a single compound statement: |
| 70 |
// a blank line, a def, for, while, or if statement, or a |
| 71 |
// semicolon-separated list of simple statements followed |
| 72 |
// by a newline. These are the units on which the REPL operates. |
| 73 |
// ParseCompoundStmt does not consume any following input. |
| 74 |
// The parser calls the readline function each |
| 75 |
// time it needs a new line of input. |
| 76 |
func (opts *FileOptions) ParseCompoundStmt(filename string, readline func() ([]byte, error)) (f *File, err error) { |
| 77 |
in, err := newScanner(filename, readline, false) |
| 78 |
if err != nil { |
| 79 |
return nil, err |
| 80 |
} |
| 81 |
|
| 82 |
p := parser{options: opts, in: in} |
| 83 |
defer p.in.recover(&err) |
| 84 |
|
| 85 |
p.nextToken() // read first lookahead token |
| 86 |
|
| 87 |
var stmts []Stmt |
| 88 |
switch p.tok { |
| 89 |
case DEF, IF, FOR, WHILE: |
| 90 |
stmts = p.parseStmt(stmts) |
| 91 |
case NEWLINE: |
| 92 |
// blank line |
| 93 |
default: |
| 94 |
stmts = p.parseSimpleStmt(stmts, false) |
| 95 |
// Require but don't consume newline, to avoid blocking again. |
| 96 |
if p.tok != NEWLINE { |
| 97 |
p.in.errorf(p.in.pos, "invalid syntax") |
| 98 |
} |
| 99 |
} |
| 100 |
|
| 101 |
return &File{Options: opts, Path: filename, Stmts: stmts}, nil |
| 102 |
} |
| 103 |
|
| 104 |
// ParseExpr calls the ParseExpr method of LegacyFileOptions(). |
| 105 |
// |
| 106 |
// Deprecated: use [FileOptions.ParseExpr] instead, |
| 107 |
// because this function relies on legacy global variables. |
| 108 |
func ParseExpr(filename string, src any, mode Mode) (expr Expr, err error) { |
| 109 |
return LegacyFileOptions().ParseExpr(filename, src, mode) |
| 110 |
} |
| 111 |
|
| 112 |
// ParseExpr parses a Starlark expression. |
| 113 |
// A comma-separated list of expressions is parsed as a tuple. |
| 114 |
// See Parse for explanation of parameters. |
| 115 |
func (opts *FileOptions) ParseExpr(filename string, src any, mode Mode) (expr Expr, err error) { |
| 116 |
in, err := newScanner(filename, src, mode&RetainComments != 0) |
| 117 |
if err != nil { |
| 118 |
return nil, err |
| 119 |
} |
| 120 |
p := parser{options: opts, in: in} |
| 121 |
defer p.in.recover(&err) |
| 122 |
|
| 123 |
p.nextToken() // read first lookahead token |
| 124 |
|
| 125 |
// Use parseExpr, not parseTest, to permit an unparenthesized tuple. |
| 126 |
expr = p.parseExpr(false) |
| 127 |
|
| 128 |
// A following newline (e.g. "f()\n") appears outside any brackets, |
| 129 |
// on a non-blank line, and thus results in a NEWLINE token. |
| 130 |
if p.tok == NEWLINE { |
| 131 |
p.nextToken() |
| 132 |
} |
| 133 |
|
| 134 |
if p.tok != EOF { |
| 135 |
p.in.errorf(p.in.pos, "got %#v after expression, want EOF", p.tok) |
| 136 |
} |
| 137 |
p.assignComments(expr) |
| 138 |
return expr, nil |
| 139 |
} |
| 140 |
|
| 141 |
type parser struct { |
| 142 |
options *FileOptions |
| 143 |
in *scanner |
| 144 |
tok Token |
| 145 |
tokval tokenValue |
| 146 |
depth int |
| 147 |
} |
| 148 |
|
| 149 |
// enter increments the depth and checks the recursion limit. |
| 150 |
// It should be paired with a deferred call to [parser.leave]. |
| 151 |
// |
| 152 |
// Every cycle in the parser's static call graph must include at |
| 153 |
// least one function that uses enter+leave to break cycles. |
| 154 |
// TestParserCallGraphCycles statically verifies this property. |
| 155 |
func (p *parser) enter() { |
| 156 |
p.depth++ |
| 157 |
if p.depth > 1000 { |
| 158 |
p.in.errorf(p.in.pos, "excessive nesting") |
| 159 |
} |
| 160 |
} |
| 161 |
|
| 162 |
func (p *parser) leave() { |
| 163 |
p.depth-- |
| 164 |
} |
| 165 |
|
| 166 |
// nextToken advances the scanner and returns the position of the |
| 167 |
// previous token. |
| 168 |
func (p *parser) nextToken() Position { |
| 169 |
oldpos := p.tokval.pos |
| 170 |
p.tok = p.in.nextToken(&p.tokval) |
| 171 |
// enable to see the token stream |
| 172 |
if debug { |
| 173 |
log.Printf("nextToken: %-20s%+v\n", p.tok, p.tokval.pos) |
| 174 |
} |
| 175 |
return oldpos |
| 176 |
} |
| 177 |
|
| 178 |
// file_input = (NEWLINE | stmt)* EOF |
| 179 |
func (p *parser) parseFile() *File { |
| 180 |
var stmts []Stmt |
| 181 |
for p.tok != EOF { |
| 182 |
if p.tok == NEWLINE { |
| 183 |
p.nextToken() |
| 184 |
continue |
| 185 |
} |
| 186 |
stmts = p.parseStmt(stmts) |
| 187 |
} |
| 188 |
return &File{Options: p.options, Stmts: stmts} |
| 189 |
} |
| 190 |
|
| 191 |
func (p *parser) parseStmt(stmts []Stmt) []Stmt { |
| 192 |
if p.tok == DEF { |
| 193 |
return append(stmts, p.parseDefStmt()) |
| 194 |
} else if p.tok == IF { |
| 195 |
return append(stmts, p.parseIfStmt()) |
| 196 |
} else if p.tok == FOR { |
| 197 |
return append(stmts, p.parseForStmt()) |
| 198 |
} else if p.tok == WHILE { |
| 199 |
return append(stmts, p.parseWhileStmt()) |
| 200 |
} |
| 201 |
return p.parseSimpleStmt(stmts, true) |
| 202 |
} |
| 203 |
|
| 204 |
func (p *parser) parseDefStmt() Stmt { |
| 205 |
defpos := p.nextToken() // consume DEF |
| 206 |
id := p.parseIdent() |
| 207 |
lparen := p.consume(LPAREN) |
| 208 |
params := p.parseParams() |
| 209 |
rparen := p.consume(RPAREN) |
| 210 |
p.consume(COLON) |
| 211 |
body := p.parseSuite() |
| 212 |
return &DefStmt{ |
| 213 |
Def: defpos, |
| 214 |
Name: id, |
| 215 |
Lparen: lparen, |
| 216 |
Params: params, |
| 217 |
Rparen: rparen, |
| 218 |
Body: body, |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
func (p *parser) parseIfStmt() Stmt { |
| 223 |
ifpos := p.nextToken() // consume IF |
| 224 |
cond := p.parseTest() |
| 225 |
p.consume(COLON) |
| 226 |
body := p.parseSuite() |
| 227 |
ifStmt := &IfStmt{ |
| 228 |
If: ifpos, |
| 229 |
Cond: cond, |
| 230 |
True: body, |
| 231 |
} |
| 232 |
tail := ifStmt |
| 233 |
for p.tok == ELIF { |
| 234 |
elifpos := p.nextToken() // consume ELIF |
| 235 |
cond := p.parseTest() |
| 236 |
p.consume(COLON) |
| 237 |
body := p.parseSuite() |
| 238 |
elif := &IfStmt{ |
| 239 |
If: elifpos, |
| 240 |
Cond: cond, |
| 241 |
True: body, |
| 242 |
} |
| 243 |
tail.ElsePos = elifpos |
| 244 |
tail.False = []Stmt{elif} |
| 245 |
tail = elif |
| 246 |
} |
| 247 |
if p.tok == ELSE { |
| 248 |
tail.ElsePos = p.nextToken() // consume ELSE |
| 249 |
p.consume(COLON) |
| 250 |
tail.False = p.parseSuite() |
| 251 |
} |
| 252 |
return ifStmt |
| 253 |
} |
| 254 |
|
| 255 |
func (p *parser) parseForStmt() Stmt { |
| 256 |
forpos := p.nextToken() // consume FOR |
| 257 |
vars := p.parseForLoopVariables() |
| 258 |
p.consume(IN) |
| 259 |
x := p.parseExpr(false) |
| 260 |
p.consume(COLON) |
| 261 |
body := p.parseSuite() |
| 262 |
return &ForStmt{ |
| 263 |
For: forpos, |
| 264 |
Vars: vars, |
| 265 |
X: x, |
| 266 |
Body: body, |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
func (p *parser) parseWhileStmt() Stmt { |
| 271 |
whilepos := p.nextToken() // consume WHILE |
| 272 |
cond := p.parseTest() |
| 273 |
p.consume(COLON) |
| 274 |
body := p.parseSuite() |
| 275 |
return &WhileStmt{ |
| 276 |
While: whilepos, |
| 277 |
Cond: cond, |
| 278 |
Body: body, |
| 279 |
} |
| 280 |
} |
| 281 |
|
| 282 |
// Equivalent to 'exprlist' production in Python grammar. |
| 283 |
// |
| 284 |
// loop_variables = primary_with_suffix (COMMA primary_with_suffix)* COMMA? |
| 285 |
func (p *parser) parseForLoopVariables() Expr { |
| 286 |
// Avoid parseExpr because it would consume the IN token |
| 287 |
// following x in "for x in y: ...". |
| 288 |
v := p.parsePrimaryWithSuffix() |
| 289 |
if p.tok != COMMA { |
| 290 |
return v |
| 291 |
} |
| 292 |
|
| 293 |
list := []Expr{v} |
| 294 |
for p.tok == COMMA { |
| 295 |
p.nextToken() |
| 296 |
if terminatesExprList(p.tok) { |
| 297 |
break |
| 298 |
} |
| 299 |
list = append(list, p.parsePrimaryWithSuffix()) |
| 300 |
} |
| 301 |
return &TupleExpr{List: list} |
| 302 |
} |
| 303 |
|
| 304 |
// simple_stmt = small_stmt (SEMI small_stmt)* SEMI? NEWLINE |
| 305 |
// In REPL mode, it does not consume the NEWLINE. |
| 306 |
func (p *parser) parseSimpleStmt(stmts []Stmt, consumeNL bool) []Stmt { |
| 307 |
for { |
| 308 |
stmts = append(stmts, p.parseSmallStmt()) |
| 309 |
if p.tok != SEMI { |
| 310 |
break |
| 311 |
} |
| 312 |
p.nextToken() // consume SEMI |
| 313 |
if p.tok == NEWLINE || p.tok == EOF { |
| 314 |
break |
| 315 |
} |
| 316 |
} |
| 317 |
// EOF without NEWLINE occurs in `if x: pass`, for example. |
| 318 |
if p.tok != EOF && consumeNL { |
| 319 |
p.consume(NEWLINE) |
| 320 |
} |
| 321 |
|
| 322 |
return stmts |
| 323 |
} |
| 324 |
|
| 325 |
// small_stmt = RETURN expr? |
| 326 |
// |
| 327 |
// | PASS | BREAK | CONTINUE |
| 328 |
// | LOAD ... |
| 329 |
// | expr ('=' | '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=') expr // assign |
| 330 |
// | expr |
| 331 |
func (p *parser) parseSmallStmt() Stmt { |
| 332 |
switch p.tok { |
| 333 |
case RETURN: |
| 334 |
pos := p.nextToken() // consume RETURN |
| 335 |
var result Expr |
| 336 |
if p.tok != EOF && p.tok != NEWLINE && p.tok != SEMI { |
| 337 |
result = p.parseExpr(false) |
| 338 |
} |
| 339 |
return &ReturnStmt{Return: pos, Result: result} |
| 340 |
|
| 341 |
case BREAK, CONTINUE, PASS: |
| 342 |
tok := p.tok |
| 343 |
pos := p.nextToken() // consume it |
| 344 |
return &BranchStmt{Token: tok, TokenPos: pos} |
| 345 |
|
| 346 |
case LOAD: |
| 347 |
return p.parseLoadStmt() |
| 348 |
} |
| 349 |
|
| 350 |
// Assignment |
| 351 |
x := p.parseExpr(false) |
| 352 |
switch p.tok { |
| 353 |
case EQ, PLUS_EQ, MINUS_EQ, STAR_EQ, SLASH_EQ, SLASHSLASH_EQ, PERCENT_EQ, AMP_EQ, PIPE_EQ, CIRCUMFLEX_EQ, LTLT_EQ, GTGT_EQ: |
| 354 |
op := p.tok |
| 355 |
pos := p.nextToken() // consume op |
| 356 |
rhs := p.parseExpr(false) |
| 357 |
return &AssignStmt{OpPos: pos, Op: op, LHS: x, RHS: rhs} |
| 358 |
} |
| 359 |
|
| 360 |
// Expression statement (e.g. function call, doc string). |
| 361 |
return &ExprStmt{X: x} |
| 362 |
} |
| 363 |
|
| 364 |
// stmt = LOAD '(' STRING {',' (IDENT '=')? STRING} [','] ')' |
| 365 |
func (p *parser) parseLoadStmt() *LoadStmt { |
| 366 |
loadPos := p.nextToken() // consume LOAD |
| 367 |
lparen := p.consume(LPAREN) |
| 368 |
|
| 369 |
if p.tok != STRING { |
| 370 |
p.in.errorf(p.in.pos, "first operand of load statement must be a string literal") |
| 371 |
} |
| 372 |
module := p.parsePrimary().(*Literal) |
| 373 |
|
| 374 |
var from, to []*Ident |
| 375 |
for p.tok != RPAREN && p.tok != EOF { |
| 376 |
p.consume(COMMA) |
| 377 |
if p.tok == RPAREN { |
| 378 |
break // allow trailing comma |
| 379 |
} |
| 380 |
switch p.tok { |
| 381 |
case STRING: |
| 382 |
// load("module", "id") |
| 383 |
// To name is same as original. |
| 384 |
lit := p.parsePrimary().(*Literal) |
| 385 |
id := &Ident{ |
| 386 |
NamePos: lit.TokenPos.add(`"`), |
| 387 |
Name: lit.Value.(string), |
| 388 |
} |
| 389 |
to = append(to, id) |
| 390 |
from = append(from, id) |
| 391 |
|
| 392 |
case IDENT: |
| 393 |
// load("module", to="from") |
| 394 |
id := p.parseIdent() |
| 395 |
to = append(to, id) |
| 396 |
if p.tok != EQ { |
| 397 |
p.in.errorf(p.in.pos, `load operand must be "%[1]s" or %[1]s="originalname" (want '=' after %[1]s)`, id.Name) |
| 398 |
} |
| 399 |
p.consume(EQ) |
| 400 |
if p.tok != STRING { |
| 401 |
p.in.errorf(p.in.pos, `original name of loaded symbol must be quoted: %s="originalname"`, id.Name) |
| 402 |
} |
| 403 |
lit := p.parsePrimary().(*Literal) |
| 404 |
from = append(from, &Ident{ |
| 405 |
NamePos: lit.TokenPos.add(`"`), |
| 406 |
Name: lit.Value.(string), |
| 407 |
}) |
| 408 |
|
| 409 |
default: |
| 410 |
p.in.errorf(p.in.pos, `load operand must be "name" or localname="name" (got %#v)`, p.tok) |
| 411 |
} |
| 412 |
} |
| 413 |
rparen := p.consume(RPAREN) |
| 414 |
|
| 415 |
if len(to) == 0 { |
| 416 |
p.in.errorf(lparen, "load statement must import at least 1 symbol") |
| 417 |
} |
| 418 |
return &LoadStmt{ |
| 419 |
Load: loadPos, |
| 420 |
Module: module, |
| 421 |
To: to, |
| 422 |
From: from, |
| 423 |
Rparen: rparen, |
| 424 |
} |
| 425 |
} |
| 426 |
|
| 427 |
// suite is typically what follows a COLON (e.g. after DEF or FOR). |
| 428 |
// suite = simple_stmt | NEWLINE INDENT stmt+ OUTDENT |
| 429 |
func (p *parser) parseSuite() []Stmt { |
| 430 |
p.enter() |
| 431 |
defer p.leave() |
| 432 |
|
| 433 |
if p.tok == NEWLINE { |
| 434 |
p.nextToken() // consume NEWLINE |
| 435 |
p.consume(INDENT) |
| 436 |
var stmts []Stmt |
| 437 |
for p.tok != OUTDENT && p.tok != EOF { |
| 438 |
stmts = p.parseStmt(stmts) |
| 439 |
} |
| 440 |
p.consume(OUTDENT) |
| 441 |
return stmts |
| 442 |
} |
| 443 |
|
| 444 |
return p.parseSimpleStmt(nil, true) |
| 445 |
} |
| 446 |
|
| 447 |
func (p *parser) parseIdent() *Ident { |
| 448 |
if p.tok != IDENT { |
| 449 |
p.in.error(p.in.pos, "not an identifier") |
| 450 |
} |
| 451 |
id := &Ident{ |
| 452 |
NamePos: p.tokval.pos, |
| 453 |
Name: p.tokval.raw, |
| 454 |
} |
| 455 |
p.nextToken() |
| 456 |
return id |
| 457 |
} |
| 458 |
|
| 459 |
func (p *parser) consume(t Token) Position { |
| 460 |
if p.tok != t { |
| 461 |
p.in.errorf(p.in.pos, "got %#v, want %#v", p.tok, t) |
| 462 |
} |
| 463 |
return p.nextToken() |
| 464 |
} |
| 465 |
|
| 466 |
// params = (param COMMA)* param COMMA? |
| 467 |
// |
| 468 |
// | |
| 469 |
// |
| 470 |
// param = IDENT |
| 471 |
// |
| 472 |
// | IDENT EQ test |
| 473 |
// | STAR |
| 474 |
// | STAR IDENT |
| 475 |
// | STARSTAR IDENT |
| 476 |
// |
| 477 |
// parseParams parses a parameter list. The resulting expressions are of the form: |
| 478 |
// |
| 479 |
// *Ident x |
| 480 |
// *Binary{Op: EQ, X: *Ident, Y: Expr} x=y |
| 481 |
// *Unary{Op: STAR} * |
| 482 |
// *Unary{Op: STAR, X: *Ident} *args |
| 483 |
// *Unary{Op: STARSTAR, X: *Ident} **kwargs |
| 484 |
func (p *parser) parseParams() []Expr { |
| 485 |
var params []Expr |
| 486 |
for p.tok != RPAREN && p.tok != COLON && p.tok != EOF { |
| 487 |
if len(params) > 0 { |
| 488 |
p.consume(COMMA) |
| 489 |
} |
| 490 |
if p.tok == RPAREN { |
| 491 |
break |
| 492 |
} |
| 493 |
|
| 494 |
// * or *args or **kwargs |
| 495 |
if p.tok == STAR || p.tok == STARSTAR { |
| 496 |
op := p.tok |
| 497 |
pos := p.nextToken() |
| 498 |
var x Expr |
| 499 |
if op == STARSTAR || p.tok == IDENT { |
| 500 |
x = p.parseIdent() |
| 501 |
} |
| 502 |
params = append(params, &UnaryExpr{ |
| 503 |
OpPos: pos, |
| 504 |
Op: op, |
| 505 |
X: x, |
| 506 |
}) |
| 507 |
continue |
| 508 |
} |
| 509 |
|
| 510 |
// IDENT |
| 511 |
// IDENT = test |
| 512 |
id := p.parseIdent() |
| 513 |
if p.tok == EQ { // default value |
| 514 |
eq := p.nextToken() |
| 515 |
dflt := p.parseTest() |
| 516 |
params = append(params, &BinaryExpr{ |
| 517 |
X: id, |
| 518 |
OpPos: eq, |
| 519 |
Op: EQ, |
| 520 |
Y: dflt, |
| 521 |
}) |
| 522 |
continue |
| 523 |
} |
| 524 |
|
| 525 |
params = append(params, id) |
| 526 |
} |
| 527 |
return params |
| 528 |
} |
| 529 |
|
| 530 |
// parseExpr parses an expression, possible consisting of a |
| 531 |
// comma-separated list of 'test' expressions. |
| 532 |
// |
| 533 |
// In many cases we must use parseTest to avoid ambiguity such as |
| 534 |
// f(x, y) vs. f((x, y)). |
| 535 |
func (p *parser) parseExpr(inParens bool) Expr { |
| 536 |
x := p.parseTest() |
| 537 |
if p.tok != COMMA { |
| 538 |
return x |
| 539 |
} |
| 540 |
|
| 541 |
// tuple |
| 542 |
exprs := p.parseExprs([]Expr{x}, inParens) |
| 543 |
return &TupleExpr{List: exprs} |
| 544 |
} |
| 545 |
|
| 546 |
// parseExprs parses a comma-separated list of expressions, starting with the comma. |
| 547 |
// It is used to parse tuples and list elements. |
| 548 |
// expr_list = (',' expr)* ','? |
| 549 |
func (p *parser) parseExprs(exprs []Expr, allowTrailingComma bool) []Expr { |
| 550 |
for p.tok == COMMA { |
| 551 |
pos := p.nextToken() |
| 552 |
if terminatesExprList(p.tok) { |
| 553 |
if !allowTrailingComma { |
| 554 |
p.in.error(pos, "unparenthesized tuple with trailing comma") |
| 555 |
} |
| 556 |
break |
| 557 |
} |
| 558 |
exprs = append(exprs, p.parseTest()) |
| 559 |
} |
| 560 |
return exprs |
| 561 |
} |
| 562 |
|
| 563 |
// parseTest parses a 'test', a single-component expression. |
| 564 |
func (p *parser) parseTest() Expr { |
| 565 |
p.enter() |
| 566 |
defer p.leave() |
| 567 |
|
| 568 |
if p.tok == LAMBDA { |
| 569 |
return p.parseLambda(true) |
| 570 |
} |
| 571 |
|
| 572 |
x := p.parseTestPrec(0) |
| 573 |
|
| 574 |
// conditional expression (t IF cond ELSE f) |
| 575 |
if p.tok == IF { |
| 576 |
ifpos := p.nextToken() |
| 577 |
cond := p.parseTestPrec(0) |
| 578 |
if p.tok != ELSE { |
| 579 |
p.in.error(ifpos, "conditional expression without else clause") |
| 580 |
} |
| 581 |
elsepos := p.nextToken() |
| 582 |
else_ := p.parseTest() |
| 583 |
return &CondExpr{If: ifpos, Cond: cond, True: x, ElsePos: elsepos, False: else_} |
| 584 |
} |
| 585 |
|
| 586 |
return x |
| 587 |
} |
| 588 |
|
| 589 |
// parseTestNoCond parses a single-component expression without |
| 590 |
// consuming a trailing 'if expr else expr'. |
| 591 |
func (p *parser) parseTestNoCond() Expr { |
| 592 |
if p.tok == LAMBDA { |
| 593 |
return p.parseLambda(false) |
| 594 |
} |
| 595 |
return p.parseTestPrec(0) |
| 596 |
} |
| 597 |
|
| 598 |
// parseLambda parses a lambda expression. |
| 599 |
// The allowCond flag allows the body to be an 'a if b else c' conditional. |
| 600 |
func (p *parser) parseLambda(allowCond bool) Expr { |
| 601 |
p.enter() |
| 602 |
defer p.leave() |
| 603 |
|
| 604 |
lambda := p.nextToken() |
| 605 |
var params []Expr |
| 606 |
if p.tok != COLON { |
| 607 |
params = p.parseParams() |
| 608 |
} |
| 609 |
p.consume(COLON) |
| 610 |
|
| 611 |
var body Expr |
| 612 |
if allowCond { |
| 613 |
body = p.parseTest() |
| 614 |
} else { |
| 615 |
body = p.parseTestNoCond() |
| 616 |
} |
| 617 |
|
| 618 |
return &LambdaExpr{ |
| 619 |
Lambda: lambda, |
| 620 |
Params: params, |
| 621 |
Body: body, |
| 622 |
} |
| 623 |
} |
| 624 |
|
| 625 |
func (p *parser) parseTestPrec(prec int) Expr { |
| 626 |
p.enter() |
| 627 |
defer p.leave() |
| 628 |
|
| 629 |
if prec >= len(preclevels) { |
| 630 |
return p.parsePrimaryWithSuffix() |
| 631 |
} |
| 632 |
|
| 633 |
// expr = NOT expr |
| 634 |
if p.tok == NOT && prec == int(precedence[NOT]) { |
| 635 |
pos := p.nextToken() |
| 636 |
x := p.parseTestPrec(prec) |
| 637 |
return &UnaryExpr{ |
| 638 |
OpPos: pos, |
| 639 |
Op: NOT, |
| 640 |
X: x, |
| 641 |
} |
| 642 |
} |
| 643 |
|
| 644 |
return p.parseBinopExpr(prec) |
| 645 |
} |
| 646 |
|
| 647 |
// expr = test (OP test)* |
| 648 |
// Uses precedence climbing; see http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm#climbing. |
| 649 |
func (p *parser) parseBinopExpr(prec int) Expr { |
| 650 |
x := p.parseTestPrec(prec + 1) |
| 651 |
for first := true; ; first = false { |
| 652 |
if p.tok == NOT { |
| 653 |
p.nextToken() // consume NOT |
| 654 |
// In this context, NOT must be followed by IN. |
| 655 |
// Replace NOT IN by a single NOT_IN token. |
| 656 |
if p.tok != IN { |
| 657 |
p.in.errorf(p.in.pos, "got %#v, want in", p.tok) |
| 658 |
} |
| 659 |
p.tok = NOT_IN |
| 660 |
} |
| 661 |
|
| 662 |
// Binary operator of specified precedence? |
| 663 |
opprec := int(precedence[p.tok]) |
| 664 |
if opprec < prec { |
| 665 |
return x |
| 666 |
} |
| 667 |
|
| 668 |
// Comparisons are non-associative. |
| 669 |
if !first && opprec == int(precedence[EQL]) { |
| 670 |
p.in.errorf(p.in.pos, "%s does not associate with %s (use parens)", |
| 671 |
x.(*BinaryExpr).Op, p.tok) |
| 672 |
} |
| 673 |
|
| 674 |
op := p.tok |
| 675 |
pos := p.nextToken() |
| 676 |
y := p.parseTestPrec(opprec + 1) |
| 677 |
x = &BinaryExpr{OpPos: pos, Op: op, X: x, Y: y} |
| 678 |
} |
| 679 |
} |
| 680 |
|
| 681 |
// precedence maps each operator to its precedence (0-7), or -1 for other tokens. |
| 682 |
var precedence [maxToken]int8 |
| 683 |
|
| 684 |
// preclevels groups operators of equal precedence. |
| 685 |
// Comparisons are nonassociative; other binary operators associate to the left. |
| 686 |
// Unary MINUS, unary PLUS, and TILDE have higher precedence so are handled in parsePrimary. |
| 687 |
// See https://github.com/google/starlark-go/blob/master/doc/spec.md#binary-operators |
| 688 |
var preclevels = [...][]Token{ |
| 689 |
{OR}, // or |
| 690 |
{AND}, // and |
| 691 |
{NOT}, // not (unary) |
| 692 |
{EQL, NEQ, LT, GT, LE, GE, IN, NOT_IN}, // == != < > <= >= in not in |
| 693 |
{PIPE}, // | |
| 694 |
{CIRCUMFLEX}, // ^ |
| 695 |
{AMP}, // & |
| 696 |
{LTLT, GTGT}, // << >> |
| 697 |
{MINUS, PLUS}, // - |
| 698 |
{STAR, PERCENT, SLASH, SLASHSLASH}, // * % / // |
| 699 |
} |
| 700 |
|
| 701 |
func init() { |
| 702 |
// populate precedence table |
| 703 |
for i := range precedence { |
| 704 |
precedence[i] = -1 |
| 705 |
} |
| 706 |
for level, tokens := range preclevels { |
| 707 |
for _, tok := range tokens { |
| 708 |
precedence[tok] = int8(level) |
| 709 |
} |
| 710 |
} |
| 711 |
} |
| 712 |
|
| 713 |
// primary_with_suffix = primary |
| 714 |
// |
| 715 |
// | primary '.' IDENT |
| 716 |
// | primary slice_suffix |
| 717 |
// | primary call_suffix |
| 718 |
func (p *parser) parsePrimaryWithSuffix() Expr { |
| 719 |
x := p.parsePrimary() |
| 720 |
for { |
| 721 |
switch p.tok { |
| 722 |
case DOT: |
| 723 |
dot := p.nextToken() |
| 724 |
id := p.parseIdent() |
| 725 |
x = &DotExpr{Dot: dot, X: x, Name: id} |
| 726 |
case LBRACK: |
| 727 |
x = p.parseSliceSuffix(x) |
| 728 |
case LPAREN: |
| 729 |
x = p.parseCallSuffix(x) |
| 730 |
default: |
| 731 |
return x |
| 732 |
} |
| 733 |
} |
| 734 |
} |
| 735 |
|
| 736 |
// slice_suffix = '[' expr? ':' expr? ':' expr? ']' |
| 737 |
func (p *parser) parseSliceSuffix(x Expr) Expr { |
| 738 |
lbrack := p.nextToken() |
| 739 |
var lo, hi, step Expr |
| 740 |
if p.tok != COLON { |
| 741 |
y := p.parseExpr(false) |
| 742 |
|
| 743 |
// index x[y] |
| 744 |
if p.tok == RBRACK { |
| 745 |
rbrack := p.nextToken() |
| 746 |
return &IndexExpr{X: x, Lbrack: lbrack, Y: y, Rbrack: rbrack} |
| 747 |
} |
| 748 |
|
| 749 |
lo = y |
| 750 |
} |
| 751 |
|
| 752 |
// slice or substring x[lo:hi:step] |
| 753 |
if p.tok == COLON { |
| 754 |
p.nextToken() |
| 755 |
if p.tok != COLON && p.tok != RBRACK { |
| 756 |
hi = p.parseTest() |
| 757 |
} |
| 758 |
} |
| 759 |
if p.tok == COLON { |
| 760 |
p.nextToken() |
| 761 |
if p.tok != RBRACK { |
| 762 |
step = p.parseTest() |
| 763 |
} |
| 764 |
} |
| 765 |
rbrack := p.consume(RBRACK) |
| 766 |
return &SliceExpr{X: x, Lbrack: lbrack, Lo: lo, Hi: hi, Step: step, Rbrack: rbrack} |
| 767 |
} |
| 768 |
|
| 769 |
// call_suffix = '(' arg_list? ')' |
| 770 |
func (p *parser) parseCallSuffix(fn Expr) Expr { |
| 771 |
lparen := p.consume(LPAREN) |
| 772 |
var rparen Position |
| 773 |
var args []Expr |
| 774 |
if p.tok == RPAREN { |
| 775 |
rparen = p.nextToken() |
| 776 |
} else { |
| 777 |
args = p.parseArgs() |
| 778 |
rparen = p.consume(RPAREN) |
| 779 |
} |
| 780 |
return &CallExpr{Fn: fn, Lparen: lparen, Args: args, Rparen: rparen} |
| 781 |
} |
| 782 |
|
| 783 |
// parseArgs parses a list of actual parameter values (arguments). |
| 784 |
// It mirrors the structure of parseParams. |
| 785 |
// arg_list = ((arg COMMA)* arg COMMA?)? |
| 786 |
func (p *parser) parseArgs() []Expr { |
| 787 |
var args []Expr |
| 788 |
for p.tok != RPAREN && p.tok != EOF { |
| 789 |
if len(args) > 0 { |
| 790 |
p.consume(COMMA) |
| 791 |
} |
| 792 |
if p.tok == RPAREN { |
| 793 |
break |
| 794 |
} |
| 795 |
|
| 796 |
// *args or **kwargs |
| 797 |
if p.tok == STAR || p.tok == STARSTAR { |
| 798 |
op := p.tok |
| 799 |
pos := p.nextToken() |
| 800 |
x := p.parseTest() |
| 801 |
args = append(args, &UnaryExpr{ |
| 802 |
OpPos: pos, |
| 803 |
Op: op, |
| 804 |
X: x, |
| 805 |
}) |
| 806 |
continue |
| 807 |
} |
| 808 |
|
| 809 |
// We use a different strategy from Bazel here to stay within LL(1). |
| 810 |
// Instead of looking ahead two tokens (IDENT, EQ) we parse |
| 811 |
// 'test = test' then check that the first was an IDENT. |
| 812 |
x := p.parseTest() |
| 813 |
|
| 814 |
if p.tok == EQ { |
| 815 |
// name = value |
| 816 |
if _, ok := x.(*Ident); !ok { |
| 817 |
p.in.errorf(p.in.pos, "keyword argument must have form name=expr") |
| 818 |
} |
| 819 |
eq := p.nextToken() |
| 820 |
y := p.parseTest() |
| 821 |
x = &BinaryExpr{ |
| 822 |
X: x, |
| 823 |
OpPos: eq, |
| 824 |
Op: EQ, |
| 825 |
Y: y, |
| 826 |
} |
| 827 |
} |
| 828 |
|
| 829 |
args = append(args, x) |
| 830 |
} |
| 831 |
return args |
| 832 |
} |
| 833 |
|
| 834 |
// primary = IDENT |
| 835 |
// |
| 836 |
// | INT | FLOAT | STRING | BYTES |
| 837 |
// | '[' ... // list literal or comprehension |
| 838 |
// | '{' ... // dict literal or comprehension |
| 839 |
// | '(' ... // tuple or parenthesized expression |
| 840 |
// | ('-'|'+'|'~') primary_with_suffix |
| 841 |
func (p *parser) parsePrimary() Expr { |
| 842 |
p.enter() |
| 843 |
defer p.leave() |
| 844 |
|
| 845 |
switch p.tok { |
| 846 |
case IDENT: |
| 847 |
return p.parseIdent() |
| 848 |
|
| 849 |
case INT, FLOAT, STRING, BYTES: |
| 850 |
var val any |
| 851 |
tok := p.tok |
| 852 |
switch tok { |
| 853 |
case INT: |
| 854 |
if p.tokval.bigInt != nil { |
| 855 |
val = p.tokval.bigInt |
| 856 |
} else { |
| 857 |
val = p.tokval.int |
| 858 |
} |
| 859 |
case FLOAT: |
| 860 |
val = p.tokval.float |
| 861 |
case STRING, BYTES: |
| 862 |
val = p.tokval.string |
| 863 |
} |
| 864 |
raw := p.tokval.raw |
| 865 |
pos := p.nextToken() |
| 866 |
return &Literal{Token: tok, TokenPos: pos, Raw: raw, Value: val} |
| 867 |
|
| 868 |
case LBRACK: |
| 869 |
return p.parseList() |
| 870 |
|
| 871 |
case LBRACE: |
| 872 |
return p.parseDict() |
| 873 |
|
| 874 |
case LPAREN: |
| 875 |
lparen := p.nextToken() |
| 876 |
if p.tok == RPAREN { |
| 877 |
// empty tuple |
| 878 |
rparen := p.nextToken() |
| 879 |
return &TupleExpr{Lparen: lparen, Rparen: rparen} |
| 880 |
} |
| 881 |
e := p.parseExpr(true) // allow trailing comma |
| 882 |
rparen := p.consume(RPAREN) |
| 883 |
return &ParenExpr{ |
| 884 |
Lparen: lparen, |
| 885 |
X: e, |
| 886 |
Rparen: rparen, |
| 887 |
} |
| 888 |
|
| 889 |
case MINUS, PLUS, TILDE: // unary |
| 890 |
tok := p.tok |
| 891 |
pos := p.nextToken() |
| 892 |
x := p.parsePrimaryWithSuffix() |
| 893 |
return &UnaryExpr{ |
| 894 |
OpPos: pos, |
| 895 |
Op: tok, |
| 896 |
X: x, |
| 897 |
} |
| 898 |
} |
| 899 |
|
| 900 |
// Report start pos of final token as it may be a NEWLINE (#532). |
| 901 |
p.in.errorf(p.tokval.pos, "got %#v, want primary expression", p.tok) |
| 902 |
panic("unreachable") |
| 903 |
} |
| 904 |
|
| 905 |
// list = '[' ']' |
| 906 |
// |
| 907 |
// | '[' expr ']' |
| 908 |
// | '[' expr expr_list ']' |
| 909 |
// | '[' expr (FOR loop_variables IN expr)+ ']' |
| 910 |
func (p *parser) parseList() Expr { |
| 911 |
lbrack := p.nextToken() |
| 912 |
if p.tok == RBRACK { |
| 913 |
// empty List |
| 914 |
rbrack := p.nextToken() |
| 915 |
return &ListExpr{Lbrack: lbrack, Rbrack: rbrack} |
| 916 |
} |
| 917 |
|
| 918 |
x := p.parseTest() |
| 919 |
|
| 920 |
if p.tok == FOR { |
| 921 |
// list comprehension |
| 922 |
return p.parseComprehensionSuffix(lbrack, x, RBRACK) |
| 923 |
} |
| 924 |
|
| 925 |
exprs := []Expr{x} |
| 926 |
if p.tok == COMMA { |
| 927 |
// multi-item list literal |
| 928 |
exprs = p.parseExprs(exprs, true) // allow trailing comma |
| 929 |
} |
| 930 |
|
| 931 |
rbrack := p.consume(RBRACK) |
| 932 |
return &ListExpr{Lbrack: lbrack, List: exprs, Rbrack: rbrack} |
| 933 |
} |
| 934 |
|
| 935 |
// dict = '{' '}' |
| 936 |
// |
| 937 |
// | '{' dict_entry_list '}' |
| 938 |
// | '{' dict_entry FOR loop_variables IN expr '}' |
| 939 |
func (p *parser) parseDict() Expr { |
| 940 |
lbrace := p.nextToken() |
| 941 |
if p.tok == RBRACE { |
| 942 |
// empty dict |
| 943 |
rbrace := p.nextToken() |
| 944 |
return &DictExpr{Lbrace: lbrace, Rbrace: rbrace} |
| 945 |
} |
| 946 |
|
| 947 |
x := p.parseDictEntry() |
| 948 |
|
| 949 |
if p.tok == FOR { |
| 950 |
// dict comprehension |
| 951 |
return p.parseComprehensionSuffix(lbrace, x, RBRACE) |
| 952 |
} |
| 953 |
|
| 954 |
entries := []Expr{x} |
| 955 |
for p.tok == COMMA { |
| 956 |
p.nextToken() |
| 957 |
if p.tok == RBRACE { |
| 958 |
break |
| 959 |
} |
| 960 |
entries = append(entries, p.parseDictEntry()) |
| 961 |
} |
| 962 |
|
| 963 |
rbrace := p.consume(RBRACE) |
| 964 |
return &DictExpr{Lbrace: lbrace, List: entries, Rbrace: rbrace} |
| 965 |
} |
| 966 |
|
| 967 |
// dict_entry = test ':' test |
| 968 |
func (p *parser) parseDictEntry() *DictEntry { |
| 969 |
k := p.parseTest() |
| 970 |
colon := p.consume(COLON) |
| 971 |
v := p.parseTest() |
| 972 |
return &DictEntry{Key: k, Colon: colon, Value: v} |
| 973 |
} |
| 974 |
|
| 975 |
// comp_suffix = FOR loopvars IN expr comp_suffix |
| 976 |
// |
| 977 |
// | IF expr comp_suffix |
| 978 |
// | ']' or ')' (end) |
| 979 |
// |
| 980 |
// There can be multiple FOR/IF clauses; the first is always a FOR. |
| 981 |
func (p *parser) parseComprehensionSuffix(lbrace Position, body Expr, endBrace Token) Expr { |
| 982 |
var clauses []Node |
| 983 |
for p.tok != endBrace { |
| 984 |
if p.tok == FOR { |
| 985 |
pos := p.nextToken() |
| 986 |
vars := p.parseForLoopVariables() |
| 987 |
in := p.consume(IN) |
| 988 |
// Following Python 3, the operand of IN cannot be: |
| 989 |
// - a conditional expression ('x if y else z'), |
| 990 |
// due to conflicts in Python grammar |
| 991 |
// ('if' is used by the comprehension); |
| 992 |
// - a lambda expression |
| 993 |
// - an unparenthesized tuple. |
| 994 |
x := p.parseTestPrec(0) |
| 995 |
clauses = append(clauses, &ForClause{For: pos, Vars: vars, In: in, X: x}) |
| 996 |
} else if p.tok == IF { |
| 997 |
pos := p.nextToken() |
| 998 |
cond := p.parseTestNoCond() |
| 999 |
clauses = append(clauses, &IfClause{If: pos, Cond: cond}) |
| 1000 |
} else { |
| 1001 |
p.in.errorf(p.in.pos, "got %#v, want '%s', for, or if", p.tok, endBrace) |
| 1002 |
} |
| 1003 |
} |
| 1004 |
rbrace := p.nextToken() |
| 1005 |
|
| 1006 |
return &Comprehension{ |
| 1007 |
Curly: endBrace == RBRACE, |
| 1008 |
Lbrack: lbrace, |
| 1009 |
Body: body, |
| 1010 |
Clauses: clauses, |
| 1011 |
Rbrack: rbrace, |
| 1012 |
} |
| 1013 |
} |
| 1014 |
|
| 1015 |
func terminatesExprList(tok Token) bool { |
| 1016 |
switch tok { |
| 1017 |
case EOF, NEWLINE, EQ, RBRACE, RBRACK, RPAREN, SEMI: |
| 1018 |
return true |
| 1019 |
} |
| 1020 |
return false |
| 1021 |
} |
| 1022 |
|
| 1023 |
// Comment assignment. |
| 1024 |
// We build two lists of all subnodes, preorder and postorder. |
| 1025 |
// The preorder list is ordered by start location, with outer nodes first. |
| 1026 |
// The postorder list is ordered by end location, with outer nodes last. |
| 1027 |
// We use the preorder list to assign each whole-line comment to the syntax |
| 1028 |
// immediately following it, and we use the postorder list to assign each |
| 1029 |
// end-of-line comment to the syntax immediately preceding it. |
| 1030 |
|
| 1031 |
// flattenAST returns the list of AST nodes, both in prefix order and in postfix |
| 1032 |
// order. |
| 1033 |
func flattenAST(root Node) (pre, post []Node) { |
| 1034 |
stack := []Node{} |
| 1035 |
Walk(root, func(n Node) bool { |
| 1036 |
if n != nil { |
| 1037 |
pre = append(pre, n) |
| 1038 |
stack = append(stack, n) |
| 1039 |
} else { |
| 1040 |
post = append(post, stack[len(stack)-1]) |
| 1041 |
stack = stack[:len(stack)-1] |
| 1042 |
} |
| 1043 |
return true |
| 1044 |
}) |
| 1045 |
return pre, post |
| 1046 |
} |
| 1047 |
|
| 1048 |
// assignComments attaches comments to nearby syntax. |
| 1049 |
func (p *parser) assignComments(n Node) { |
| 1050 |
// Leave early if there are no comments |
| 1051 |
if len(p.in.lineComments)+len(p.in.suffixComments) == 0 { |
| 1052 |
return |
| 1053 |
} |
| 1054 |
|
| 1055 |
pre, post := flattenAST(n) |
| 1056 |
|
| 1057 |
// Assign line comments to syntax immediately following. |
| 1058 |
line := p.in.lineComments |
| 1059 |
for _, x := range pre { |
| 1060 |
start, _ := x.Span() |
| 1061 |
|
| 1062 |
switch x.(type) { |
| 1063 |
case *File: |
| 1064 |
continue |
| 1065 |
} |
| 1066 |
|
| 1067 |
for len(line) > 0 && !start.isBefore(line[0].Start) { |
| 1068 |
x.AllocComments() |
| 1069 |
x.Comments().Before = append(x.Comments().Before, line[0]) |
| 1070 |
line = line[1:] |
| 1071 |
} |
| 1072 |
} |
| 1073 |
|
| 1074 |
// Remaining line comments go at end of file. |
| 1075 |
if len(line) > 0 { |
| 1076 |
n.AllocComments() |
| 1077 |
n.Comments().After = append(n.Comments().After, line...) |
| 1078 |
} |
| 1079 |
|
| 1080 |
// Assign suffix comments to syntax immediately before. |
| 1081 |
suffix := p.in.suffixComments |
| 1082 |
for _, x := range slices.Backward(post) { |
| 1083 |
// Do not assign suffix comments to file |
| 1084 |
switch x.(type) { |
| 1085 |
case *File: |
| 1086 |
continue |
| 1087 |
} |
| 1088 |
|
| 1089 |
_, end := x.Span() |
| 1090 |
if len(suffix) > 0 && end.isBefore(suffix[len(suffix)-1].Start) { |
| 1091 |
x.AllocComments() |
| 1092 |
x.Comments().Suffix = append(x.Comments().Suffix, suffix[len(suffix)-1]) |
| 1093 |
suffix = suffix[:len(suffix)-1] |
| 1094 |
} |
| 1095 |
} |
| 1096 |
} |