lex.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. /*
  2. Copyright 2016 Google Inc. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Lexical scanning for BUILD file parser.
  14. package build
  15. import (
  16. "bytes"
  17. "fmt"
  18. "path/filepath"
  19. "sort"
  20. "strings"
  21. "unicode/utf8"
  22. )
  23. // FileType represents a type of a file (default (for .bzl files), BUILD, or WORKSPACE).
  24. // Certain formatting or refactoring rules can be applied to several file types, so they support
  25. // bitwise operations: `type1 | type2` can represent a scope (e.g. BUILD and WORKSPACE files) and
  26. // `scope & fileType` can be used to check whether a file type belongs to a scope.
  27. type FileType int
  28. const (
  29. // TypeDefault represents general Starlark files
  30. TypeDefault FileType = 1 << iota
  31. // TypeBuild represents BUILD files
  32. TypeBuild
  33. // TypeWorkspace represents WORKSPACE files
  34. TypeWorkspace
  35. // TypeBzl represents .bzl files
  36. TypeBzl
  37. )
  38. func (t FileType) String() string {
  39. switch t {
  40. case TypeDefault:
  41. return "default"
  42. case TypeBuild:
  43. return "BUILD"
  44. case TypeWorkspace:
  45. return "WORKSPACE"
  46. case TypeBzl:
  47. return ".bzl"
  48. }
  49. return "unknown"
  50. }
  51. // ParseBuild parses a file, marks it as a BUILD file and returns the corresponding parse tree.
  52. //
  53. // The filename is used only for generating error messages.
  54. func ParseBuild(filename string, data []byte) (*File, error) {
  55. in := newInput(filename, data)
  56. f, err := in.parse()
  57. if f != nil {
  58. f.Type = TypeBuild
  59. }
  60. return f, err
  61. }
  62. // ParseWorkspace parses a file, marks it as a WORKSPACE file and returns the corresponding parse tree.
  63. //
  64. // The filename is used only for generating error messages.
  65. func ParseWorkspace(filename string, data []byte) (*File, error) {
  66. in := newInput(filename, data)
  67. f, err := in.parse()
  68. if f != nil {
  69. f.Type = TypeWorkspace
  70. }
  71. return f, err
  72. }
  73. // ParseBzl parses a file, marks it as a .bzl file and returns the corresponding parse tree.
  74. //
  75. // The filename is used only for generating error messages.
  76. func ParseBzl(filename string, data []byte) (*File, error) {
  77. in := newInput(filename, data)
  78. f, err := in.parse()
  79. if f != nil {
  80. f.Type = TypeBzl
  81. }
  82. return f, err
  83. }
  84. // ParseDefault parses a file, marks it as a generic Starlark file and returns the corresponding parse tree.
  85. //
  86. // The filename is used only for generating error messages.
  87. func ParseDefault(filename string, data []byte) (*File, error) {
  88. in := newInput(filename, data)
  89. f, err := in.parse()
  90. if f != nil {
  91. f.Type = TypeDefault
  92. }
  93. return f, err
  94. }
  95. func getFileType(filename string) FileType {
  96. if filename == "" { // stdin
  97. return TypeDefault
  98. }
  99. basename := strings.ToLower(filepath.Base(filename))
  100. if strings.HasSuffix(basename, ".oss") {
  101. basename = basename[:len(basename)-4]
  102. }
  103. ext := filepath.Ext(basename)
  104. switch ext {
  105. case ".bzl":
  106. return TypeBzl
  107. case ".sky":
  108. return TypeDefault
  109. }
  110. base := basename[:len(basename)-len(ext)]
  111. switch {
  112. case ext == ".build" || base == "build" || strings.HasPrefix(base, "build."):
  113. return TypeBuild
  114. case ext == ".workspace" || base == "workspace" || strings.HasPrefix(base, "workspace."):
  115. return TypeWorkspace
  116. }
  117. return TypeDefault
  118. }
  119. // Parse parses the input data and returns the corresponding parse tree.
  120. //
  121. // Uses the filename to detect the formatting type (build, workspace, or default) and calls
  122. // ParseBuild, ParseWorkspace, or ParseDefault correspondingly.
  123. func Parse(filename string, data []byte) (*File, error) {
  124. switch getFileType(filename) {
  125. case TypeBuild:
  126. return ParseBuild(filename, data)
  127. case TypeWorkspace:
  128. return ParseWorkspace(filename, data)
  129. case TypeBzl:
  130. return ParseBzl(filename, data)
  131. }
  132. return ParseDefault(filename, data)
  133. }
  134. // ParseError contains information about the error encountered during parsing.
  135. type ParseError struct {
  136. Message string
  137. Filename string
  138. Pos Position
  139. }
  140. // Error returns a string representation of the parse error.
  141. func (e ParseError) Error() string {
  142. filename := e.Filename
  143. if filename == "" {
  144. filename = "<stdin>"
  145. }
  146. return fmt.Sprintf("%s:%d:%d: %v", filename, e.Pos.Line, e.Pos.LineRune, e.Message)
  147. }
  148. // An input represents a single input file being parsed.
  149. type input struct {
  150. // Lexing state.
  151. filename string // name of input file, for errors
  152. complete []byte // entire input
  153. remaining []byte // remaining input
  154. token []byte // token being scanned
  155. lastToken string // most recently returned token, for error messages
  156. pos Position // current input position
  157. lineComments []Comment // accumulated line comments
  158. suffixComments []Comment // accumulated suffix comments
  159. depth int // nesting of [ ] { } ( )
  160. cleanLine bool // true if the current line only contains whitespace before the current position
  161. indent int // current line indentation in spaces
  162. indents []int // stack of indentation levels in spaces
  163. // Parser state.
  164. file *File // returned top-level syntax tree
  165. parseError error // error encountered during parsing
  166. // Comment assignment state.
  167. pre []Expr // all expressions, in preorder traversal
  168. post []Expr // all expressions, in postorder traversal
  169. }
  170. func newInput(filename string, data []byte) *input {
  171. // The syntax requires that each simple statement ends with '\n', however it's optional at EOF.
  172. // If `data` doesn't end with '\n' we add it here to keep parser simple.
  173. // It shouldn't affect neither the parsed tree nor its formatting.
  174. data = append(data, '\n')
  175. return &input{
  176. filename: filename,
  177. complete: data,
  178. remaining: data,
  179. pos: Position{Line: 1, LineRune: 1, Byte: 0},
  180. cleanLine: true,
  181. indents: []int{0},
  182. }
  183. }
  184. func (in *input) currentIndent() int {
  185. return in.indents[len(in.indents)-1]
  186. }
  187. // parse parses the input file.
  188. func (in *input) parse() (f *File, err error) {
  189. // The parser panics for both routine errors like syntax errors
  190. // and for programmer bugs like array index errors.
  191. // Turn both into error returns. Catching bug panics is
  192. // especially important when processing many files.
  193. defer func() {
  194. if e := recover(); e != nil {
  195. if e == in.parseError {
  196. err = in.parseError
  197. } else {
  198. err = ParseError{Message: fmt.Sprintf("internal error: %v", e), Filename: in.filename, Pos: in.pos}
  199. }
  200. }
  201. }()
  202. // Invoke the parser generated from parse.y.
  203. yyParse(in)
  204. if in.parseError != nil {
  205. return nil, in.parseError
  206. }
  207. in.file.Path = in.filename
  208. // Assign comments to nearby syntax.
  209. in.assignComments()
  210. return in.file, nil
  211. }
  212. // Error is called to report an error.
  213. // When called by the generated code s is always "syntax error".
  214. // Error does not return: it panics.
  215. func (in *input) Error(s string) {
  216. if s == "syntax error" && in.lastToken != "" {
  217. s += " near " + in.lastToken
  218. }
  219. in.parseError = ParseError{Message: s, Filename: in.filename, Pos: in.pos}
  220. panic(in.parseError)
  221. }
  222. // eof reports whether the input has reached end of file.
  223. func (in *input) eof() bool {
  224. return len(in.remaining) == 0
  225. }
  226. // peekRune returns the next rune in the input without consuming it.
  227. func (in *input) peekRune() int {
  228. if len(in.remaining) == 0 {
  229. return 0
  230. }
  231. r, _ := utf8.DecodeRune(in.remaining)
  232. return int(r)
  233. }
  234. // readRune consumes and returns the next rune in the input.
  235. func (in *input) readRune() int {
  236. if len(in.remaining) == 0 {
  237. in.Error("internal lexer error: readRune at EOF")
  238. }
  239. r, size := utf8.DecodeRune(in.remaining)
  240. in.remaining = in.remaining[size:]
  241. if r == '\n' {
  242. in.pos.Line++
  243. in.pos.LineRune = 1
  244. } else {
  245. in.pos.LineRune++
  246. }
  247. in.pos.Byte += size
  248. return int(r)
  249. }
  250. // startToken marks the beginning of the next input token.
  251. // It must be followed by a call to endToken, once the token has
  252. // been consumed using readRune.
  253. func (in *input) startToken(val *yySymType) {
  254. in.token = in.remaining
  255. val.tok = ""
  256. val.pos = in.pos
  257. }
  258. // yySymType (used in the next few functions) is defined by the
  259. // generated parser. It is a struct containing all the fields listed
  260. // in parse.y's %union [sic] section.
  261. // endToken marks the end of an input token.
  262. // It records the actual token string in val.tok if the caller
  263. // has not done that already.
  264. func (in *input) endToken(val *yySymType) {
  265. if val.tok == "" {
  266. tok := string(in.token[:len(in.token)-len(in.remaining)])
  267. val.tok = tok
  268. in.lastToken = val.tok
  269. }
  270. }
  271. // Lex is called from the generated parser to obtain the next input token.
  272. // It returns the token value (either a rune like '+' or a symbolic token _FOR)
  273. // and sets val to the data associated with the token.
  274. //
  275. // For all our input tokens, the associated data is
  276. // val.Pos (the position where the token begins)
  277. // and val.Token (the input string corresponding to the token).
  278. func (in *input) Lex(val *yySymType) int {
  279. // Skip past spaces, stopping at non-space or EOF.
  280. countNL := 0 // number of newlines we've skipped past
  281. for !in.eof() {
  282. // Skip over spaces. Count newlines so we can give the parser
  283. // information about where top-level blank lines are,
  284. // for top-level comment assignment.
  285. c := in.peekRune()
  286. if c == ' ' || c == '\t' || c == '\r' || c == '\n' {
  287. if c == '\n' {
  288. in.indent = 0
  289. in.cleanLine = true
  290. if in.depth == 0 {
  291. // Not in a statememt. Tell parser about top-level blank line.
  292. in.startToken(val)
  293. in.readRune()
  294. in.endToken(val)
  295. return '\n'
  296. }
  297. countNL++
  298. } else if c == ' ' && in.cleanLine {
  299. in.indent++
  300. }
  301. in.readRune()
  302. continue
  303. }
  304. // Comment runs to end of line.
  305. if c == '#' {
  306. // If a line contains just a comment its indentation level doesn't matter.
  307. // Reset it to zero.
  308. in.indent = 0
  309. isLineComment := in.cleanLine
  310. in.cleanLine = true
  311. // Is this comment the only thing on its line?
  312. // Find the last \n before this # and see if it's all
  313. // spaces from there to here.
  314. // If it's a suffix comment but the last non-space symbol before
  315. // it is one of (, [, or {, or it's a suffix comment to "):"
  316. // (e.g. trailing closing bracket or a function definition),
  317. // treat it as a line comment that should be
  318. // put inside the corresponding block.
  319. i := bytes.LastIndex(in.complete[:in.pos.Byte], []byte("\n"))
  320. prefix := bytes.TrimSpace(in.complete[i+1 : in.pos.Byte])
  321. prefix = bytes.Replace(prefix, []byte{' '}, []byte{}, -1)
  322. isSuffix := true
  323. if len(prefix) == 0 ||
  324. (len(prefix) == 2 && prefix[0] == ')' && prefix[1] == ':') ||
  325. prefix[len(prefix)-1] == '[' ||
  326. prefix[len(prefix)-1] == '(' ||
  327. prefix[len(prefix)-1] == '{' {
  328. isSuffix = false
  329. }
  330. // Consume comment without the \n it ends with.
  331. in.startToken(val)
  332. for len(in.remaining) > 0 && in.peekRune() != '\n' {
  333. in.readRune()
  334. }
  335. in.endToken(val)
  336. val.tok = strings.TrimRight(val.tok, "\n")
  337. in.lastToken = "comment"
  338. // If we are at top level (not in a rule), hand the comment to
  339. // the parser as a _COMMENT token. The grammar is written
  340. // to handle top-level comments itself.
  341. if in.depth == 0 && isLineComment {
  342. // Not in a statement. Tell parser about top-level comment.
  343. return _COMMENT
  344. }
  345. // Otherwise, save comment for later attachment to syntax tree.
  346. if countNL > 1 {
  347. in.lineComments = append(in.lineComments, Comment{val.pos, ""})
  348. }
  349. if isSuffix {
  350. in.suffixComments = append(in.suffixComments, Comment{val.pos, val.tok})
  351. } else {
  352. in.lineComments = append(in.lineComments, Comment{val.pos, val.tok})
  353. }
  354. countNL = 0
  355. continue
  356. }
  357. if c == '\\' && len(in.remaining) >= 2 && in.remaining[1] == '\n' {
  358. // We can ignore a trailing \ at end of line together with the \n.
  359. in.readRune()
  360. in.readRune()
  361. continue
  362. }
  363. // Found non-space non-comment.
  364. break
  365. }
  366. // Check for changes in indentation
  367. // Skip if we're inside a statement, or if there were non-space
  368. // characters before in the current line.
  369. if in.depth == 0 && in.cleanLine {
  370. if in.indent > in.currentIndent() {
  371. // A new indentation block starts
  372. in.indents = append(in.indents, in.indent)
  373. in.lastToken = "indent"
  374. in.cleanLine = false
  375. return _INDENT
  376. } else if in.indent < in.currentIndent() {
  377. // An indentation block ends
  378. in.indents = in.indents[:len(in.indents)-1]
  379. // It's a syntax error if the current line indentation level in now greater than
  380. // currentIndent(), should be either equal (a parent block continues) or still less
  381. // (need to unindent more).
  382. if in.indent > in.currentIndent() {
  383. in.pos = val.pos
  384. in.Error("unexpected indentation")
  385. }
  386. in.lastToken = "unindent"
  387. return _UNINDENT
  388. }
  389. }
  390. in.cleanLine = false
  391. // If the file ends with an indented block, return the corresponding amounts of unindents.
  392. if in.eof() && in.currentIndent() > 0 {
  393. in.indents = in.indents[:len(in.indents)-1]
  394. in.lastToken = "unindent"
  395. return _UNINDENT
  396. }
  397. // Found the beginning of the next token.
  398. in.startToken(val)
  399. defer in.endToken(val)
  400. // End of file.
  401. if in.eof() {
  402. in.lastToken = "EOF"
  403. return _EOF
  404. }
  405. // Punctuation tokens.
  406. switch c := in.peekRune(); c {
  407. case '[', '(', '{':
  408. in.depth++
  409. in.readRune()
  410. return c
  411. case ']', ')', '}':
  412. in.depth--
  413. in.readRune()
  414. return c
  415. case '.', ':', ';', ',': // single-char tokens
  416. in.readRune()
  417. return c
  418. case '<', '>', '=', '!', '+', '-', '*', '/', '%', '|', '&', '~', '^': // possibly followed by =
  419. in.readRune()
  420. if c == '~' {
  421. // unary bitwise not, shouldn't be followed by anything
  422. return c
  423. }
  424. if c == '*' && in.peekRune() == '*' {
  425. // double asterisk
  426. in.readRune()
  427. return _STAR_STAR
  428. }
  429. if c == in.peekRune() {
  430. switch c {
  431. case '/':
  432. // integer division
  433. in.readRune()
  434. c = _INT_DIV
  435. case '<':
  436. // left shift
  437. in.readRune()
  438. c = _BIT_LSH
  439. case '>':
  440. // right shift
  441. in.readRune()
  442. c = _BIT_RSH
  443. }
  444. }
  445. if in.peekRune() == '=' {
  446. in.readRune()
  447. switch c {
  448. case '<':
  449. return _LE
  450. case '>':
  451. return _GE
  452. case '=':
  453. return _EQ
  454. case '!':
  455. return _NE
  456. default:
  457. return _AUGM
  458. }
  459. }
  460. return c
  461. case 'r': // possible beginning of raw quoted string
  462. if len(in.remaining) < 2 || in.remaining[1] != '"' && in.remaining[1] != '\'' {
  463. break
  464. }
  465. in.readRune()
  466. c = in.peekRune()
  467. fallthrough
  468. case '"', '\'': // quoted string
  469. quote := c
  470. if len(in.remaining) >= 3 && in.remaining[0] == byte(quote) && in.remaining[1] == byte(quote) && in.remaining[2] == byte(quote) {
  471. // Triple-quoted string.
  472. in.readRune()
  473. in.readRune()
  474. in.readRune()
  475. var c1, c2, c3 int
  476. for {
  477. if in.eof() {
  478. in.pos = val.pos
  479. in.Error("unexpected EOF in string")
  480. }
  481. c1, c2, c3 = c2, c3, in.readRune()
  482. if c1 == quote && c2 == quote && c3 == quote {
  483. break
  484. }
  485. if c3 == '\\' {
  486. if in.eof() {
  487. in.pos = val.pos
  488. in.Error("unexpected EOF in string")
  489. }
  490. in.readRune()
  491. }
  492. }
  493. } else {
  494. in.readRune()
  495. for {
  496. if in.eof() {
  497. in.pos = val.pos
  498. in.Error("unexpected EOF in string")
  499. }
  500. if in.peekRune() == '\n' {
  501. in.Error("unexpected newline in string")
  502. }
  503. c := in.readRune()
  504. if c == quote {
  505. break
  506. }
  507. if c == '\\' {
  508. if in.eof() {
  509. in.pos = val.pos
  510. in.Error("unexpected EOF in string")
  511. }
  512. in.readRune()
  513. }
  514. }
  515. }
  516. in.endToken(val)
  517. s, triple, err := Unquote(val.tok)
  518. if err != nil {
  519. in.Error(fmt.Sprint(err))
  520. }
  521. val.str = s
  522. val.triple = triple
  523. return _STRING
  524. }
  525. // Checked all punctuation. Must be identifier token.
  526. if c := in.peekRune(); !isIdent(c) {
  527. in.Error(fmt.Sprintf("unexpected input character %#q", c))
  528. }
  529. // Scan over alphanumeric identifier.
  530. for {
  531. c := in.peekRune()
  532. if !isIdent(c) {
  533. break
  534. }
  535. in.readRune()
  536. }
  537. // Call endToken to set val.tok to identifier we just scanned,
  538. // so we can look to see if val.tok is a keyword.
  539. in.endToken(val)
  540. if k := keywordToken[val.tok]; k != 0 {
  541. return k
  542. }
  543. switch val.tok {
  544. case "pass":
  545. return _PASS
  546. case "break":
  547. return _BREAK
  548. case "continue":
  549. return _CONTINUE
  550. }
  551. if len(val.tok) > 0 && val.tok[0] >= '0' && val.tok[0] <= '9' {
  552. return _NUMBER
  553. }
  554. return _IDENT
  555. }
  556. // isIdent reports whether c is an identifier rune.
  557. // We treat all non-ASCII runes as identifier runes.
  558. func isIdent(c int) bool {
  559. return '0' <= c && c <= '9' ||
  560. 'A' <= c && c <= 'Z' ||
  561. 'a' <= c && c <= 'z' ||
  562. c == '_' ||
  563. c >= 0x80
  564. }
  565. // keywordToken records the special tokens for
  566. // strings that should not be treated as ordinary identifiers.
  567. var keywordToken = map[string]int{
  568. "and": _AND,
  569. "for": _FOR,
  570. "if": _IF,
  571. "else": _ELSE,
  572. "elif": _ELIF,
  573. "in": _IN,
  574. "is": _IS,
  575. "lambda": _LAMBDA,
  576. "load": _LOAD,
  577. "not": _NOT,
  578. "or": _OR,
  579. "def": _DEF,
  580. "return": _RETURN,
  581. }
  582. // Comment assignment.
  583. // We build two lists of all subexpressions, preorder and postorder.
  584. // The preorder list is ordered by start location, with outer expressions first.
  585. // The postorder list is ordered by end location, with outer expressions last.
  586. // We use the preorder list to assign each whole-line comment to the syntax
  587. // immediately following it, and we use the postorder list to assign each
  588. // end-of-line comment to the syntax immediately preceding it.
  589. // order walks the expression adding it and its subexpressions to the
  590. // preorder and postorder lists.
  591. func (in *input) order(v Expr) {
  592. if v != nil {
  593. in.pre = append(in.pre, v)
  594. }
  595. switch v := v.(type) {
  596. default:
  597. panic(fmt.Errorf("order: unexpected type %T", v))
  598. case nil:
  599. // nothing
  600. case *End:
  601. // nothing
  602. case *File:
  603. for _, stmt := range v.Stmt {
  604. in.order(stmt)
  605. }
  606. case *CommentBlock:
  607. // nothing
  608. case *CallExpr:
  609. in.order(v.X)
  610. for _, x := range v.List {
  611. in.order(x)
  612. }
  613. in.order(&v.End)
  614. case *LoadStmt:
  615. in.order(v.Module)
  616. for i := range v.From {
  617. in.order(v.To[i])
  618. in.order(v.From[i])
  619. }
  620. in.order(&v.Rparen)
  621. case *LiteralExpr:
  622. // nothing
  623. case *StringExpr:
  624. // nothing
  625. case *Ident:
  626. // nothing
  627. case *BranchStmt:
  628. // nothing
  629. case *DotExpr:
  630. in.order(v.X)
  631. case *ListExpr:
  632. for _, x := range v.List {
  633. in.order(x)
  634. }
  635. in.order(&v.End)
  636. case *Comprehension:
  637. in.order(v.Body)
  638. for _, c := range v.Clauses {
  639. in.order(c)
  640. }
  641. in.order(&v.End)
  642. case *SetExpr:
  643. for _, x := range v.List {
  644. in.order(x)
  645. }
  646. in.order(&v.End)
  647. case *ForClause:
  648. in.order(v.Vars)
  649. in.order(v.X)
  650. case *IfClause:
  651. in.order(v.Cond)
  652. case *KeyValueExpr:
  653. in.order(v.Key)
  654. in.order(v.Value)
  655. case *DictExpr:
  656. for _, x := range v.List {
  657. in.order(x)
  658. }
  659. in.order(&v.End)
  660. case *TupleExpr:
  661. for _, x := range v.List {
  662. in.order(x)
  663. }
  664. if !v.NoBrackets {
  665. in.order(&v.End)
  666. }
  667. case *UnaryExpr:
  668. in.order(v.X)
  669. case *BinaryExpr:
  670. in.order(v.X)
  671. in.order(v.Y)
  672. case *AssignExpr:
  673. in.order(v.LHS)
  674. in.order(v.RHS)
  675. case *ConditionalExpr:
  676. in.order(v.Then)
  677. in.order(v.Test)
  678. in.order(v.Else)
  679. case *ParenExpr:
  680. in.order(v.X)
  681. in.order(&v.End)
  682. case *SliceExpr:
  683. in.order(v.X)
  684. in.order(v.From)
  685. in.order(v.To)
  686. in.order(v.Step)
  687. case *IndexExpr:
  688. in.order(v.X)
  689. in.order(v.Y)
  690. case *LambdaExpr:
  691. for _, param := range v.Params {
  692. in.order(param)
  693. }
  694. for _, expr := range v.Body {
  695. in.order(expr)
  696. }
  697. case *ReturnStmt:
  698. if v.Result != nil {
  699. in.order(v.Result)
  700. }
  701. case *DefStmt:
  702. for _, x := range v.Params {
  703. in.order(x)
  704. }
  705. for _, x := range v.Body {
  706. in.order(x)
  707. }
  708. case *ForStmt:
  709. in.order(v.Vars)
  710. in.order(v.X)
  711. for _, x := range v.Body {
  712. in.order(x)
  713. }
  714. case *IfStmt:
  715. in.order(v.Cond)
  716. for _, s := range v.True {
  717. in.order(s)
  718. }
  719. if len(v.False) > 0 {
  720. in.order(&v.ElsePos)
  721. }
  722. for _, s := range v.False {
  723. in.order(s)
  724. }
  725. }
  726. if v != nil {
  727. in.post = append(in.post, v)
  728. }
  729. }
  730. // assignComments attaches comments to nearby syntax.
  731. func (in *input) assignComments() {
  732. // Generate preorder and postorder lists.
  733. in.order(in.file)
  734. in.assignSuffixComments()
  735. in.assignLineComments()
  736. }
  737. func (in *input) assignSuffixComments() {
  738. // Assign suffix comments to syntax immediately before.
  739. suffix := in.suffixComments
  740. for i := len(in.post) - 1; i >= 0; i-- {
  741. x := in.post[i]
  742. // Do not assign suffix comments to file or to block statements
  743. switch x.(type) {
  744. case *File, *DefStmt, *IfStmt, *ForStmt, *CommentBlock:
  745. continue
  746. }
  747. _, end := x.Span()
  748. xcom := x.Comment()
  749. for len(suffix) > 0 && end.Byte <= suffix[len(suffix)-1].Start.Byte {
  750. xcom.Suffix = append(xcom.Suffix, suffix[len(suffix)-1])
  751. suffix = suffix[:len(suffix)-1]
  752. }
  753. }
  754. // We assigned suffix comments in reverse.
  755. // If multiple suffix comments were appended to the same
  756. // expression node, they are now in reverse. Fix that.
  757. for _, x := range in.post {
  758. reverseComments(x.Comment().Suffix)
  759. }
  760. // Remaining suffix comments go at beginning of file.
  761. in.file.Before = append(in.file.Before, suffix...)
  762. }
  763. func (in *input) assignLineComments() {
  764. // Assign line comments to syntax immediately following.
  765. line := in.lineComments
  766. for _, x := range in.pre {
  767. start, _ := x.Span()
  768. xcom := x.Comment()
  769. for len(line) > 0 && start.Byte >= line[0].Start.Byte {
  770. xcom.Before = append(xcom.Before, line[0])
  771. line = line[1:]
  772. }
  773. // Line comments can be sorted in a wrong order because they get assigned from different
  774. // parts of the lexer and the parser. Restore the original order.
  775. sort.SliceStable(xcom.Before, func(i, j int) bool {
  776. return xcom.Before[i].Start.Byte < xcom.Before[j].Start.Byte
  777. })
  778. }
  779. // Remaining line comments go at end of file.
  780. in.file.After = append(in.file.After, line...)
  781. }
  782. // reverseComments reverses the []Comment list.
  783. func reverseComments(list []Comment) {
  784. for i, j := 0, len(list)-1; i < j; i, j = i+1, j-1 {
  785. list[i], list[j] = list[j], list[i]
  786. }
  787. }