scanner.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  1. // Copyright 2022 The Gc 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. package gc // import "modernc.org/gc/v3"
  5. import (
  6. "bytes"
  7. "fmt"
  8. "go/token"
  9. "path/filepath"
  10. "strings"
  11. "unicode"
  12. "unicode/utf8"
  13. "modernc.org/mathutil"
  14. mtoken "modernc.org/token"
  15. )
  16. var (
  17. _ Node = (*Token)(nil)
  18. _ Node = (*nonode)(nil)
  19. keywords = map[string]token.Token{
  20. "break": BREAK,
  21. "case": CASE,
  22. "chan": CHAN,
  23. "const": CONST,
  24. "continue": CONTINUE,
  25. "default": DEFAULT,
  26. "defer": DEFER,
  27. "else": ELSE,
  28. "fallthrough": FALLTHROUGH,
  29. "for": FOR,
  30. "func": FUNC,
  31. "go": GO,
  32. "goto": GOTO,
  33. "if": IF,
  34. "import": IMPORT,
  35. "interface": INTERFACE,
  36. "map": MAP,
  37. "package": PACKAGE,
  38. "range": RANGE,
  39. "return": RETURN,
  40. "select": SELECT,
  41. "struct": STRUCT,
  42. "switch": SWITCH,
  43. "type": TYPE,
  44. "var": VAR,
  45. }
  46. lineCommentTag = []byte("line ")
  47. znode = &nonode{}
  48. )
  49. type nonode struct{}
  50. func (*nonode) Position() (r token.Position) { return r }
  51. func (*nonode) Source(full bool) string { return "" }
  52. // Token represents a lexeme, its position and its semantic value.
  53. type Token struct { // 16 bytes on 64 bit arch
  54. source *source
  55. ch int32
  56. index int32
  57. }
  58. // Ch returns which token t represents
  59. func (t Token) Ch() token.Token { return token.Token(t.ch) }
  60. // Source implements Node.
  61. func (t Token) Source(full bool) string {
  62. // trc("%10s %v: #%v sep %v, src %v, buf %v", tokSource(t.Ch()), t.Position(), t.index, t.source.toks[t.index].sep, t.source.toks[t.index].src, len(t.source.buf))
  63. sep := t.Sep()
  64. if !full && sep != "" {
  65. sep = " "
  66. }
  67. src := t.Src()
  68. if !full && strings.ContainsRune(src, '\n') {
  69. src = " "
  70. }
  71. // trc("%q %q -> %q %q", t.Sep(), t.Src(), sep, src)
  72. return sep + src
  73. }
  74. // Positions implements Node.
  75. func (t Token) Position() (r token.Position) {
  76. if t.source == nil {
  77. return r
  78. }
  79. s := t.source
  80. off := mathutil.MinInt32(int32(len(s.buf)), s.toks[t.index].src)
  81. return token.Position(s.file.PositionFor(mtoken.Pos(s.base+off), true))
  82. }
  83. // Prev returns the token preceding t or a zero value if no such token exists.
  84. func (t Token) Prev() (r Token) {
  85. if index := t.index - 1; index >= 0 {
  86. s := t.source
  87. return Token{source: s, ch: s.toks[index].ch, index: index}
  88. }
  89. return r
  90. }
  91. // Next returns the token following t or a zero value if no such token exists.
  92. func (t Token) Next() (r Token) {
  93. if index := t.index + 1; index < int32(len(t.source.toks)) {
  94. s := t.source
  95. return Token{source: s, ch: s.toks[index].ch, index: index}
  96. }
  97. return r
  98. }
  99. // Sep returns any separators, combined, preceding t.
  100. func (t Token) Sep() string {
  101. s := t.source
  102. if p, ok := s.sepPatches[t.index]; ok {
  103. return p
  104. }
  105. return string(s.buf[s.toks[t.index].sep:s.toks[t.index].src])
  106. }
  107. // SetSep sets t's separator.
  108. func (t Token) SetSep(s string) {
  109. src := t.source
  110. if src.sepPatches == nil {
  111. src.sepPatches = map[int32]string{}
  112. }
  113. src.sepPatches[t.index] = s
  114. }
  115. // Src returns t's source form.
  116. func (t Token) Src() string {
  117. s := t.source
  118. if p, ok := s.srcPatches[t.index]; ok {
  119. return p
  120. }
  121. if t.ch != int32(EOF) {
  122. next := t.source.off
  123. if t.index < int32(len(s.toks))-1 {
  124. next = s.toks[t.index+1].sep
  125. }
  126. return string(s.buf[s.toks[t.index].src:next])
  127. }
  128. return ""
  129. }
  130. // SetSrc sets t's source form.
  131. func (t Token) SetSrc(s string) {
  132. src := t.source
  133. if src.srcPatches == nil {
  134. src.srcPatches = map[int32]string{}
  135. }
  136. src.srcPatches[t.index] = s
  137. }
  138. // IsValid reports t is a valid token. Zero value reports false.
  139. func (t Token) IsValid() bool { return t.source != nil }
  140. type tok struct { // 12 bytes
  141. ch int32
  142. sep int32
  143. src int32
  144. }
  145. func (t *tok) token() token.Token { return token.Token(t.ch) }
  146. func (t *tok) position(s *source) (r token.Position) {
  147. off := mathutil.MinInt32(int32(len(s.buf)), t.src)
  148. return token.Position(s.file.PositionFor(mtoken.Pos(s.base+off), true))
  149. }
  150. // source represents a single Go source file, editor text buffer etc.
  151. type source struct {
  152. buf []byte
  153. file *mtoken.File
  154. name string
  155. sepPatches map[int32]string
  156. srcPatches map[int32]string
  157. toks []tok
  158. base int32
  159. off int32
  160. }
  161. // 'buf' becomes owned by the result and must not be modified afterwards.
  162. func newSource(name string, buf []byte) *source {
  163. file := mtoken.NewFile(name, len(buf))
  164. return &source{
  165. buf: buf,
  166. file: file,
  167. name: name,
  168. base: int32(file.Base()),
  169. }
  170. }
  171. type ErrWithPosition struct {
  172. pos token.Position
  173. err error
  174. }
  175. func (e ErrWithPosition) String() string {
  176. switch {
  177. case e.pos.IsValid():
  178. return fmt.Sprintf("%v: %v", e.pos, e.err)
  179. default:
  180. return fmt.Sprintf("%v", e.err)
  181. }
  182. }
  183. type errList []ErrWithPosition
  184. func (e errList) Err() (r error) {
  185. if len(e) == 0 {
  186. return nil
  187. }
  188. return e
  189. }
  190. func (e errList) Error() string {
  191. w := 0
  192. prev := ErrWithPosition{pos: token.Position{Offset: -1}}
  193. for _, v := range e {
  194. if v.pos.Line == 0 || v.pos.Offset != prev.pos.Offset || v.err.Error() != prev.err.Error() {
  195. e[w] = v
  196. w++
  197. prev = v
  198. }
  199. }
  200. var a []string
  201. for _, v := range e {
  202. a = append(a, fmt.Sprint(v))
  203. }
  204. return strings.Join(a, "\n")
  205. }
  206. func (e *errList) err(pos token.Position, msg string, args ...interface{}) {
  207. if trcErrors {
  208. trc("FAIL "+msg, args...)
  209. }
  210. switch {
  211. case len(args) == 0:
  212. *e = append(*e, ErrWithPosition{pos, fmt.Errorf("%s", msg)})
  213. default:
  214. *e = append(*e, ErrWithPosition{pos, fmt.Errorf(msg, args...)})
  215. }
  216. }
  217. type scanner struct {
  218. *source
  219. dir string
  220. errs errList
  221. tok tok
  222. last int32
  223. errBudget int
  224. c byte // Lookahead byte.
  225. eof bool
  226. isClosed bool
  227. }
  228. func newScanner(name string, buf []byte) *scanner {
  229. dir, _ := filepath.Split(name)
  230. r := &scanner{source: newSource(name, buf), errBudget: 10, dir: dir}
  231. switch {
  232. case len(buf) == 0:
  233. r.eof = true
  234. default:
  235. r.c = buf[0]
  236. if r.c == '\n' {
  237. r.file.AddLine(int(r.base + r.off))
  238. }
  239. }
  240. return r
  241. }
  242. func isDigit(c byte) bool { return c >= '0' && c <= '9' }
  243. func isHexDigit(c byte) bool { return isDigit(c) || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F' }
  244. func isIDNext(c byte) bool { return isIDFirst(c) || isDigit(c) }
  245. func isOctalDigit(c byte) bool { return c >= '0' && c <= '7' }
  246. func isIDFirst(c byte) bool {
  247. return c >= 'a' && c <= 'z' ||
  248. c >= 'A' && c <= 'Z' ||
  249. c == '_'
  250. }
  251. func (s *scanner) position() token.Position {
  252. return token.Position(s.source.file.PositionFor(mtoken.Pos(s.base+s.off), true))
  253. }
  254. func (s *scanner) pos(off int32) token.Position {
  255. return token.Position(s.file.PositionFor(mtoken.Pos(s.base+off), true))
  256. }
  257. func (s *scanner) token() Token {
  258. return Token{source: s.source, ch: s.tok.ch, index: int32(len(s.toks) - 1)}
  259. }
  260. func (s *scanner) err(off int32, msg string, args ...interface{}) {
  261. if s.errBudget <= 0 {
  262. s.close()
  263. return
  264. }
  265. s.errBudget--
  266. if n := int32(len(s.buf)); off >= n {
  267. off = n
  268. }
  269. s.errs.err(s.pos(off), msg, args...)
  270. }
  271. func (s *scanner) close() {
  272. if s.isClosed {
  273. return
  274. }
  275. s.tok.ch = int32(ILLEGAL)
  276. s.eof = true
  277. s.isClosed = true
  278. }
  279. func (s *scanner) next() {
  280. if s.eof {
  281. return
  282. }
  283. s.off++
  284. if int(s.off) == len(s.buf) {
  285. s.c = 0
  286. s.eof = true
  287. return
  288. }
  289. s.c = s.buf[s.off]
  290. if s.c == '\n' {
  291. s.file.AddLine(int(s.base + s.off))
  292. }
  293. }
  294. func (s *scanner) nextN(n int) {
  295. if int(s.off) == len(s.buf)-n {
  296. s.c = 0
  297. s.eof = true
  298. return
  299. }
  300. s.off += int32(n)
  301. s.c = s.buf[s.off]
  302. if s.c == '\n' {
  303. s.file.AddLine(int(s.base + s.off))
  304. }
  305. }
  306. func (s *scanner) scan() (r bool) {
  307. if s.isClosed {
  308. return false
  309. }
  310. s.last = s.tok.ch
  311. s.tok.sep = s.off
  312. s.tok.ch = -1
  313. for {
  314. if r = s.scan0(); !r || s.tok.ch >= 0 {
  315. s.toks = append(s.toks, s.tok)
  316. // trc("", dump(s.token()))
  317. return r
  318. }
  319. }
  320. }
  321. func (s *scanner) scan0() (r bool) {
  322. s.tok.src = mathutil.MinInt32(s.off, int32(len(s.buf)))
  323. switch s.c {
  324. case ' ', '\t', '\r', '\n':
  325. // White space, formed from spaces (U+0020), horizontal tabs (U+0009), carriage
  326. // returns (U+000D), and newlines (U+000A), is ignored except as it separates
  327. // tokens that would otherwise combine into a single token.
  328. if s.c == '\n' && s.injectSemi() {
  329. return true
  330. }
  331. s.next()
  332. return true
  333. case '/':
  334. off := s.off
  335. s.next()
  336. switch s.c {
  337. case '=':
  338. s.next()
  339. s.tok.ch = int32(QUO_ASSIGN)
  340. case '/':
  341. // Line comments start with the character sequence // and stop at the end of
  342. // the line.
  343. s.next()
  344. s.lineComment(off)
  345. return true
  346. case '*':
  347. // General comments start with the character sequence /* and stop with the
  348. // first subsequent character sequence */.
  349. s.next()
  350. s.generalComment(off)
  351. return true
  352. default:
  353. s.tok.ch = int32(QUO)
  354. }
  355. case '(':
  356. s.tok.ch = int32(LPAREN)
  357. s.next()
  358. case ')':
  359. s.tok.ch = int32(RPAREN)
  360. s.next()
  361. case '[':
  362. s.tok.ch = int32(LBRACK)
  363. s.next()
  364. case ']':
  365. s.tok.ch = int32(RBRACK)
  366. s.next()
  367. case '{':
  368. s.tok.ch = int32(LBRACE)
  369. s.next()
  370. case '}':
  371. s.tok.ch = int32(RBRACE)
  372. s.next()
  373. case ',':
  374. s.tok.ch = int32(COMMA)
  375. s.next()
  376. case ';':
  377. s.tok.ch = int32(SEMICOLON)
  378. s.next()
  379. case '~':
  380. s.tok.ch = int32(TILDE)
  381. s.next()
  382. case '"':
  383. off := s.off
  384. s.next()
  385. s.stringLiteral(off)
  386. case '\'':
  387. off := s.off
  388. s.next()
  389. s.runeLiteral(off)
  390. case '`':
  391. s.next()
  392. for {
  393. switch {
  394. case s.c == '`':
  395. s.next()
  396. s.tok.ch = int32(STRING)
  397. return true
  398. case s.eof:
  399. s.err(s.off, "raw string literal not terminated")
  400. s.tok.ch = int32(STRING)
  401. return true
  402. case s.c == 0:
  403. panic(todo("%v: %#U", s.position(), s.c))
  404. default:
  405. s.next()
  406. }
  407. }
  408. case '.':
  409. s.next()
  410. off := s.off
  411. if isDigit(s.c) {
  412. s.dot(false, true)
  413. return true
  414. }
  415. if s.c != '.' {
  416. s.tok.ch = int32(PERIOD)
  417. return true
  418. }
  419. s.next()
  420. if s.c != '.' {
  421. s.off = off
  422. s.c = '.'
  423. s.tok.ch = int32(PERIOD)
  424. return true
  425. }
  426. s.next()
  427. s.tok.ch = int32(ELLIPSIS)
  428. return true
  429. case '%':
  430. s.next()
  431. switch s.c {
  432. case '=':
  433. s.next()
  434. s.tok.ch = int32(REM_ASSIGN)
  435. default:
  436. s.tok.ch = int32(REM)
  437. }
  438. case '*':
  439. s.next()
  440. switch s.c {
  441. case '=':
  442. s.next()
  443. s.tok.ch = int32(MUL_ASSIGN)
  444. default:
  445. s.tok.ch = int32(MUL)
  446. }
  447. case '^':
  448. s.next()
  449. switch s.c {
  450. case '=':
  451. s.next()
  452. s.tok.ch = int32(XOR_ASSIGN)
  453. default:
  454. s.tok.ch = int32(XOR)
  455. }
  456. case '+':
  457. s.next()
  458. switch s.c {
  459. case '+':
  460. s.next()
  461. s.tok.ch = int32(INC)
  462. case '=':
  463. s.next()
  464. s.tok.ch = int32(ADD_ASSIGN)
  465. default:
  466. s.tok.ch = int32(ADD)
  467. }
  468. case '-':
  469. s.next()
  470. switch s.c {
  471. case '-':
  472. s.next()
  473. s.tok.ch = int32(DEC)
  474. case '=':
  475. s.next()
  476. s.tok.ch = int32(SUB_ASSIGN)
  477. default:
  478. s.tok.ch = int32(SUB)
  479. }
  480. case ':':
  481. s.next()
  482. switch {
  483. case s.c == '=':
  484. s.next()
  485. s.tok.ch = int32(DEFINE)
  486. default:
  487. s.tok.ch = int32(COLON)
  488. }
  489. case '=':
  490. s.next()
  491. switch {
  492. case s.c == '=':
  493. s.next()
  494. s.tok.ch = int32(EQL)
  495. default:
  496. s.tok.ch = int32(ASSIGN)
  497. }
  498. case '!':
  499. s.next()
  500. switch {
  501. case s.c == '=':
  502. s.next()
  503. s.tok.ch = int32(NEQ)
  504. default:
  505. s.tok.ch = int32(NOT)
  506. }
  507. case '>':
  508. s.next()
  509. switch s.c {
  510. case '=':
  511. s.next()
  512. s.tok.ch = int32(GEQ)
  513. case '>':
  514. s.next()
  515. switch s.c {
  516. case '=':
  517. s.next()
  518. s.tok.ch = int32(SHR_ASSIGN)
  519. default:
  520. s.tok.ch = int32(SHR)
  521. }
  522. default:
  523. s.tok.ch = int32(GTR)
  524. }
  525. case '<':
  526. s.next()
  527. switch s.c {
  528. case '=':
  529. s.next()
  530. s.tok.ch = int32(LEQ)
  531. case '<':
  532. s.next()
  533. switch s.c {
  534. case '=':
  535. s.next()
  536. s.tok.ch = int32(SHL_ASSIGN)
  537. default:
  538. s.tok.ch = int32(SHL)
  539. }
  540. case '-':
  541. s.next()
  542. s.tok.ch = int32(ARROW)
  543. default:
  544. s.tok.ch = int32(LSS)
  545. }
  546. case '|':
  547. s.next()
  548. switch s.c {
  549. case '|':
  550. s.next()
  551. s.tok.ch = int32(LOR)
  552. case '=':
  553. s.next()
  554. s.tok.ch = int32(OR_ASSIGN)
  555. default:
  556. s.tok.ch = int32(OR)
  557. }
  558. case '&':
  559. s.next()
  560. switch s.c {
  561. case '&':
  562. s.next()
  563. s.tok.ch = int32(LAND)
  564. case '^':
  565. s.next()
  566. switch s.c {
  567. case '=':
  568. s.next()
  569. s.tok.ch = int32(AND_NOT_ASSIGN)
  570. default:
  571. s.tok.ch = int32(AND_NOT)
  572. }
  573. case '=':
  574. s.next()
  575. s.tok.ch = int32(AND_ASSIGN)
  576. default:
  577. s.tok.ch = int32(AND)
  578. }
  579. default:
  580. switch {
  581. case isIDFirst(s.c):
  582. s.next()
  583. s.identifierOrKeyword()
  584. case isDigit(s.c):
  585. s.numericLiteral()
  586. case s.c >= 0x80:
  587. off := s.off
  588. switch r := s.rune(); {
  589. case unicode.IsLetter(r):
  590. s.identifierOrKeyword()
  591. case r == 0xfeff:
  592. if off == 0 { // Ignore BOM, but only at buffer start.
  593. return true
  594. }
  595. s.err(off, "illegal byte order mark")
  596. s.tok.ch = int32(ILLEGAL)
  597. default:
  598. s.err(s.off, "illegal character %#U", r)
  599. s.tok.ch = int32(ILLEGAL)
  600. }
  601. case s.eof:
  602. if s.injectSemi() {
  603. return true
  604. }
  605. s.close()
  606. s.tok.ch = int32(EOF)
  607. s.tok.sep = mathutil.MinInt32(s.tok.sep, s.tok.src)
  608. return false
  609. // case s.c == 0:
  610. // panic(todo("%v: %#U", s.position(), s.c))
  611. default:
  612. s.err(s.off, "illegal character %#U", s.c)
  613. s.next()
  614. s.tok.ch = int32(ILLEGAL)
  615. }
  616. }
  617. return true
  618. }
  619. func (s *scanner) runeLiteral(off int32) {
  620. // Leading ' consumed.
  621. ok := 0
  622. s.tok.ch = int32(CHAR)
  623. expOff := int32(-1)
  624. if s.eof {
  625. s.err(off, "rune literal not terminated")
  626. return
  627. }
  628. for {
  629. switch s.c {
  630. case '\\':
  631. ok++
  632. s.next()
  633. switch s.c {
  634. case '\'', '\\', 'a', 'b', 'f', 'n', 'r', 't', 'v':
  635. s.next()
  636. case 'x', 'X':
  637. s.next()
  638. for i := 0; i < 2; i++ {
  639. if s.c == '\'' {
  640. if i != 2 {
  641. s.err(s.off, "illegal character %#U in escape sequence", s.c)
  642. }
  643. s.next()
  644. return
  645. }
  646. if !isHexDigit(s.c) {
  647. s.err(s.off, "illegal character %#U in escape sequence", s.c)
  648. break
  649. }
  650. s.next()
  651. }
  652. case 'u':
  653. s.u(4)
  654. case 'U':
  655. s.u(8)
  656. default:
  657. switch {
  658. case s.eof:
  659. s.err(s.base+s.off, "escape sequence not terminated")
  660. return
  661. case isOctalDigit(s.c):
  662. for i := 0; i < 3; i++ {
  663. s.next()
  664. if s.c == '\'' {
  665. if i != 2 {
  666. s.err(s.off, "illegal character %#U in escape sequence", s.c)
  667. }
  668. s.next()
  669. return
  670. }
  671. if !isOctalDigit(s.c) {
  672. s.err(s.off, "illegal character %#U in escape sequence", s.c)
  673. break
  674. }
  675. }
  676. default:
  677. s.err(s.off, "unknown escape sequence")
  678. }
  679. }
  680. case '\'':
  681. s.next()
  682. if ok != 1 {
  683. s.err(off, "illegal rune literal")
  684. }
  685. return
  686. case '\t':
  687. s.next()
  688. ok++
  689. default:
  690. switch {
  691. case s.eof:
  692. switch {
  693. case ok != 0:
  694. s.err(expOff, "rune literal not terminated")
  695. default:
  696. s.err(s.base+s.off, "rune literal not terminated")
  697. }
  698. return
  699. case s.c == 0:
  700. panic(todo("%v: %#U", s.position(), s.c))
  701. case s.c < ' ':
  702. ok++
  703. s.err(s.off, "non-printable character: %#U", s.c)
  704. s.next()
  705. case s.c >= 0x80:
  706. ok++
  707. off := s.off
  708. if c := s.rune(); c == 0xfeff {
  709. s.err(off, "illegal byte order mark")
  710. }
  711. default:
  712. ok++
  713. s.next()
  714. }
  715. }
  716. if ok != 0 && expOff < 0 {
  717. expOff = s.off
  718. if s.eof {
  719. expOff++
  720. }
  721. }
  722. }
  723. }
  724. func (s *scanner) stringLiteral(off int32) {
  725. // Leadind " consumed.
  726. s.tok.ch = int32(STRING)
  727. for {
  728. switch {
  729. case s.c == '"':
  730. s.next()
  731. return
  732. case s.c == '\\':
  733. s.next()
  734. switch s.c {
  735. case '"', '\\', 'a', 'b', 'f', 'n', 'r', 't', 'v':
  736. s.next()
  737. continue
  738. case 'x', 'X':
  739. s.next()
  740. if !isHexDigit(s.c) {
  741. panic(todo("%v: %#U", s.position(), s.c))
  742. }
  743. s.next()
  744. if !isHexDigit(s.c) {
  745. panic(todo("%v: %#U", s.position(), s.c))
  746. }
  747. s.next()
  748. continue
  749. case 'u':
  750. s.u(4)
  751. continue
  752. case 'U':
  753. s.u(8)
  754. continue
  755. default:
  756. switch {
  757. case isOctalDigit(s.c):
  758. s.next()
  759. if isOctalDigit(s.c) {
  760. s.next()
  761. }
  762. if isOctalDigit(s.c) {
  763. s.next()
  764. }
  765. continue
  766. default:
  767. s.err(off-1, "unknown escape sequence")
  768. }
  769. }
  770. case s.c == '\n':
  771. fallthrough
  772. case s.eof:
  773. s.err(off, "string literal not terminated")
  774. return
  775. case s.c == 0:
  776. s.err(s.off, "illegal character NUL")
  777. }
  778. switch {
  779. case s.c >= 0x80:
  780. off := s.off
  781. if s.rune() == 0xfeff {
  782. s.err(off, "illegal byte order mark")
  783. }
  784. continue
  785. }
  786. s.next()
  787. }
  788. }
  789. func (s *scanner) u(n int) (r rune) {
  790. // Leading u/U not consumed.
  791. s.next()
  792. off := s.off
  793. for i := 0; i < n; i++ {
  794. switch {
  795. case isHexDigit(s.c):
  796. var n rune
  797. switch {
  798. case s.c >= '0' && s.c <= '9':
  799. n = rune(s.c) - '0'
  800. case s.c >= 'a' && s.c <= 'f':
  801. n = rune(s.c) - 'a' + 10
  802. case s.c >= 'A' && s.c <= 'F':
  803. n = rune(s.c) - 'A' + 10
  804. }
  805. r = 16*r + n
  806. default:
  807. switch {
  808. case s.eof:
  809. s.err(s.base+s.off, "escape sequence not terminated")
  810. default:
  811. s.err(s.off, "illegal character %#U in escape sequence", s.c)
  812. }
  813. return r
  814. }
  815. s.next()
  816. }
  817. if r < 0 || r > unicode.MaxRune || r >= 0xd800 && r <= 0xdfff {
  818. s.err(off-1, "escape sequence is invalid Unicode code point")
  819. }
  820. return r
  821. }
  822. func (s *scanner) identifierOrKeyword() {
  823. out:
  824. for {
  825. switch {
  826. case isIDNext(s.c):
  827. s.next()
  828. case s.c >= 0x80:
  829. off := s.off
  830. c := s.c
  831. switch r := s.rune(); {
  832. case unicode.IsLetter(r) || unicode.IsDigit(r):
  833. // already consumed
  834. default:
  835. s.off = off
  836. s.c = c
  837. break out
  838. }
  839. case s.eof:
  840. break out
  841. case s.c == 0:
  842. s.err(s.off, "illegal character NUL")
  843. break out
  844. default:
  845. break out
  846. }
  847. }
  848. if s.tok.ch = int32(keywords[string(s.buf[s.tok.src:s.off])]); s.tok.ch == 0 {
  849. s.tok.ch = int32(IDENT)
  850. }
  851. }
  852. func (s *scanner) numericLiteral() {
  853. // Leading decimal digit not consumed.
  854. var hasHexMantissa, needFrac bool
  855. more:
  856. switch s.c {
  857. case '0':
  858. s.next()
  859. switch s.c {
  860. case '.':
  861. // nop
  862. case 'b', 'B':
  863. s.next()
  864. s.binaryLiteral()
  865. return
  866. case 'e', 'E':
  867. s.exponent()
  868. s.tok.ch = int32(FLOAT)
  869. return
  870. case 'p', 'P':
  871. s.err(s.off, "'%c' exponent requires hexadecimal mantissa", s.c)
  872. s.exponent()
  873. s.tok.ch = int32(FLOAT)
  874. return
  875. case 'o', 'O':
  876. s.next()
  877. s.octalLiteral()
  878. return
  879. case 'x', 'X':
  880. hasHexMantissa = true
  881. needFrac = true
  882. s.tok.ch = int32(INT)
  883. s.next()
  884. if s.c == '.' {
  885. s.next()
  886. s.dot(hasHexMantissa, needFrac)
  887. return
  888. }
  889. if s.hexadecimals() == 0 {
  890. s.err(s.base+s.off, "hexadecimal literal has no digits")
  891. return
  892. }
  893. needFrac = false
  894. case 'i':
  895. s.next()
  896. s.tok.ch = int32(IMAG)
  897. return
  898. default:
  899. invalidOff := int32(-1)
  900. var invalidDigit byte
  901. for {
  902. if s.c == '_' {
  903. for n := 0; s.c == '_'; n++ {
  904. if n == 1 {
  905. s.err(s.off, "'_' must separate successive digits")
  906. }
  907. s.next()
  908. }
  909. if !isDigit(s.c) {
  910. s.err(s.off-1, "'_' must separate successive digits")
  911. }
  912. }
  913. if isOctalDigit(s.c) {
  914. s.next()
  915. continue
  916. }
  917. if isDigit(s.c) {
  918. if invalidOff < 0 {
  919. invalidOff = s.off
  920. invalidDigit = s.c
  921. }
  922. s.next()
  923. continue
  924. }
  925. break
  926. }
  927. switch s.c {
  928. case '.', 'e', 'E', 'i':
  929. break more
  930. }
  931. if isDigit(s.c) {
  932. break more
  933. }
  934. if invalidOff > 0 {
  935. s.err(invalidOff, "invalid digit '%c' in octal literal", invalidDigit)
  936. }
  937. s.tok.ch = int32(INT)
  938. return
  939. }
  940. default:
  941. s.decimals()
  942. }
  943. switch s.c {
  944. case '.':
  945. s.next()
  946. s.dot(hasHexMantissa, needFrac)
  947. case 'p', 'P':
  948. if !hasHexMantissa {
  949. s.err(s.off, "'%c' exponent requires hexadecimal mantissa", s.c)
  950. }
  951. fallthrough
  952. case 'e', 'E':
  953. s.exponent()
  954. if s.c == 'i' {
  955. s.next()
  956. s.tok.ch = int32(IMAG)
  957. return
  958. }
  959. s.tok.ch = int32(FLOAT)
  960. case 'i':
  961. s.next()
  962. s.tok.ch = int32(IMAG)
  963. default:
  964. s.tok.ch = int32(INT)
  965. }
  966. }
  967. func (s *scanner) octalLiteral() {
  968. // Leading 0o consumed.
  969. ok := false
  970. invalidOff := int32(-1)
  971. var invalidDigit byte
  972. s.tok.ch = int32(INT)
  973. for {
  974. for n := 0; s.c == '_'; n++ {
  975. if n == 1 {
  976. s.err(s.off, "'_' must separate successive digits")
  977. }
  978. s.next()
  979. }
  980. switch s.c {
  981. case '0', '1', '2', '3', '4', '5', '6', '7':
  982. s.next()
  983. ok = true
  984. case '8', '9':
  985. if invalidOff < 0 {
  986. invalidOff = s.off
  987. invalidDigit = s.c
  988. }
  989. s.next()
  990. case '.':
  991. s.tok.ch = int32(FLOAT)
  992. s.err(s.off, "invalid radix point in octal literal")
  993. s.next()
  994. case 'e', 'E':
  995. s.tok.ch = int32(FLOAT)
  996. s.err(s.off, "'%c' exponent requires decimal mantissa", s.c)
  997. s.exponent()
  998. case 'p', 'P':
  999. s.tok.ch = int32(FLOAT)
  1000. s.err(s.off, "'%c' exponent requires hexadecimal mantissa", s.c)
  1001. s.exponent()
  1002. default:
  1003. switch {
  1004. case !ok:
  1005. s.err(s.base+s.off, "octal literal has no digits")
  1006. case invalidOff > 0:
  1007. s.err(invalidOff, "invalid digit '%c' in octal literal", invalidDigit)
  1008. }
  1009. if s.c == 'i' {
  1010. s.next()
  1011. s.tok.ch = int32(IMAG)
  1012. }
  1013. return
  1014. }
  1015. }
  1016. }
  1017. func (s *scanner) binaryLiteral() {
  1018. // Leading 0b consumed.
  1019. ok := false
  1020. invalidOff := int32(-1)
  1021. var invalidDigit byte
  1022. s.tok.ch = int32(INT)
  1023. for {
  1024. for n := 0; s.c == '_'; n++ {
  1025. if n == 1 {
  1026. s.err(s.off, "'_' must separate successive digits")
  1027. }
  1028. s.next()
  1029. }
  1030. switch s.c {
  1031. case '0', '1':
  1032. s.next()
  1033. ok = true
  1034. case '.':
  1035. s.tok.ch = int32(FLOAT)
  1036. s.err(s.off, "invalid radix point in binary literal")
  1037. s.next()
  1038. case 'e', 'E':
  1039. s.tok.ch = int32(FLOAT)
  1040. s.err(s.off, "'%c' exponent requires decimal mantissa", s.c)
  1041. s.exponent()
  1042. case 'p', 'P':
  1043. s.tok.ch = int32(FLOAT)
  1044. s.err(s.off, "'%c' exponent requires hexadecimal mantissa", s.c)
  1045. s.exponent()
  1046. default:
  1047. if isDigit(s.c) {
  1048. if invalidOff < 0 {
  1049. invalidOff = s.off
  1050. invalidDigit = s.c
  1051. }
  1052. s.next()
  1053. continue
  1054. }
  1055. switch {
  1056. case !ok:
  1057. s.err(s.base+s.off, "binary literal has no digits")
  1058. case invalidOff > 0:
  1059. s.err(invalidOff, "invalid digit '%c' in binary literal", invalidDigit)
  1060. }
  1061. if s.c == 'i' {
  1062. s.next()
  1063. s.tok.ch = int32(IMAG)
  1064. }
  1065. return
  1066. }
  1067. }
  1068. }
  1069. func (s *scanner) generalComment(off int32) (injectSemi bool) {
  1070. // Leading /* consumed
  1071. off0 := s.off - 2
  1072. var nl bool
  1073. for {
  1074. switch {
  1075. case s.c == '*':
  1076. s.next()
  1077. switch s.c {
  1078. case '/':
  1079. s.lineInfo(off0, s.off+1)
  1080. s.next()
  1081. if nl {
  1082. return s.injectSemi()
  1083. }
  1084. return false
  1085. }
  1086. case s.c == '\n':
  1087. nl = true
  1088. s.next()
  1089. case s.eof:
  1090. s.tok.ch = 0
  1091. s.err(off, "comment not terminated")
  1092. return true
  1093. case s.c == 0:
  1094. panic(todo("%v: %#U", s.position(), s.c))
  1095. default:
  1096. s.next()
  1097. }
  1098. }
  1099. }
  1100. func (s *scanner) lineComment(off int32) (injectSemi bool) {
  1101. // Leading // consumed
  1102. off0 := s.off - 2
  1103. for {
  1104. switch {
  1105. case s.c == '\n':
  1106. s.lineInfo(off0, s.off+1)
  1107. if s.injectSemi() {
  1108. return true
  1109. }
  1110. s.next()
  1111. return false
  1112. case s.c >= 0x80:
  1113. if c := s.rune(); c == 0xfeff {
  1114. s.err(off+2, "illegal byte order mark")
  1115. }
  1116. case s.eof:
  1117. s.off++
  1118. if s.injectSemi() {
  1119. return true
  1120. }
  1121. return false
  1122. case s.c == 0:
  1123. return false
  1124. default:
  1125. s.next()
  1126. }
  1127. }
  1128. }
  1129. func (s *scanner) lineInfo(off, next int32) {
  1130. if off != 0 && s.buf[off+1] != '*' && s.buf[off-1] != '\n' && s.buf[off-1] != '\r' {
  1131. return
  1132. }
  1133. str := s.buf[off:next]
  1134. if !bytes.HasPrefix(str[len("//"):], lineCommentTag) {
  1135. return
  1136. }
  1137. switch {
  1138. case str[1] == '*':
  1139. str = str[:len(str)-len("*/")]
  1140. default:
  1141. str = str[:len(str)-len("\n")]
  1142. }
  1143. str = str[len("//"):]
  1144. str, ln, ok := s.lineInfoNum(str[len("line "):])
  1145. col := 0
  1146. if ok == liBadNum || ok == liNoNum {
  1147. return
  1148. }
  1149. hasCol := false
  1150. var n int
  1151. if str, n, ok = s.lineInfoNum(str); ok == liBadNum {
  1152. return
  1153. }
  1154. if ok != liNoNum {
  1155. col = ln
  1156. ln = n
  1157. hasCol = true
  1158. }
  1159. fn := strings.TrimSpace(string(str))
  1160. switch {
  1161. case fn == "" && hasCol:
  1162. fn = s.pos(off).Filename
  1163. case fn != "":
  1164. fn = filepath.Clean(fn)
  1165. if !filepath.IsAbs(fn) {
  1166. fn = filepath.Join(s.dir, fn)
  1167. }
  1168. }
  1169. // trc("set %v %q %v %v", next, fn, ln, col)
  1170. s.file.AddLineColumnInfo(int(next), fn, ln, col)
  1171. }
  1172. const (
  1173. liNoNum = iota
  1174. liBadNum
  1175. liOK
  1176. )
  1177. func (s *scanner) lineInfoNum(str []byte) (_ []byte, n, r int) {
  1178. // trc("==== %q", str)
  1179. x := len(str) - 1
  1180. if x < 0 || !isDigit(str[x]) {
  1181. return str, 0, liNoNum
  1182. }
  1183. mul := 1
  1184. for x > 0 && isDigit(str[x]) {
  1185. n += mul * (int(str[x]) - '0')
  1186. mul *= 10
  1187. x--
  1188. if n < 0 {
  1189. return str, 0, liBadNum
  1190. }
  1191. }
  1192. if x < 0 || str[x] != ':' {
  1193. return str, 0, liBadNum
  1194. }
  1195. // trc("---- %q %v %v", str[:x], n, liOK)
  1196. return str[:x], n, liOK
  1197. }
  1198. func (s *scanner) rune() rune {
  1199. switch r, sz := utf8.DecodeRune(s.buf[s.off:]); {
  1200. case r == utf8.RuneError && sz == 0:
  1201. panic(todo("%v: %#U", s.position(), s.c))
  1202. case r == utf8.RuneError && sz == 1:
  1203. s.err(s.off, "illegal UTF-8 encoding")
  1204. s.next()
  1205. return r
  1206. default:
  1207. s.nextN(sz)
  1208. return r
  1209. }
  1210. }
  1211. func (s *scanner) dot(hasHexMantissa, needFrac bool) {
  1212. // '.' already consumed
  1213. switch {
  1214. case hasHexMantissa:
  1215. if s.hexadecimals() == 0 && needFrac {
  1216. s.err(s.off, "hexadecimal literal has no digits")
  1217. }
  1218. switch s.c {
  1219. case 'p', 'P':
  1220. // ok
  1221. default:
  1222. s.err(s.off, "hexadecimal mantissa requires a 'p' exponent")
  1223. }
  1224. default:
  1225. if s.decimals() == 0 && needFrac {
  1226. panic(todo("%v: %#U", s.position(), s.c))
  1227. }
  1228. }
  1229. switch s.c {
  1230. case 'p', 'P':
  1231. if !hasHexMantissa {
  1232. s.err(s.off, "'%c' exponent requires hexadecimal mantissa", s.c)
  1233. }
  1234. fallthrough
  1235. case 'e', 'E':
  1236. s.exponent()
  1237. if s.c == 'i' {
  1238. s.next()
  1239. s.tok.ch = int32(IMAG)
  1240. return
  1241. }
  1242. s.tok.ch = int32(FLOAT)
  1243. case 'i':
  1244. s.next()
  1245. s.tok.ch = int32(IMAG)
  1246. default:
  1247. s.tok.ch = int32(FLOAT)
  1248. }
  1249. }
  1250. func (s *scanner) exponent() {
  1251. // Leanding e or E not consumed.
  1252. s.next()
  1253. switch s.c {
  1254. case '+', '-':
  1255. s.next()
  1256. }
  1257. if !isDigit(s.c) {
  1258. s.err(s.base+s.off, "exponent has no digits")
  1259. return
  1260. }
  1261. s.decimals()
  1262. }
  1263. func (s *scanner) decimals() (r int) {
  1264. first := true
  1265. for {
  1266. switch {
  1267. case isDigit(s.c):
  1268. first = false
  1269. s.next()
  1270. r++
  1271. case s.c == '_':
  1272. for n := 0; s.c == '_'; n++ {
  1273. if first || n == 1 {
  1274. s.err(s.off, "'_' must separate successive digits")
  1275. }
  1276. s.next()
  1277. }
  1278. if !isDigit(s.c) {
  1279. s.err(s.off-1, "'_' must separate successive digits")
  1280. }
  1281. default:
  1282. return r
  1283. }
  1284. }
  1285. }
  1286. func (s *scanner) hexadecimals() (r int) {
  1287. for {
  1288. switch {
  1289. case isHexDigit(s.c):
  1290. s.next()
  1291. r++
  1292. case s.c == '_':
  1293. for n := 0; s.c == '_'; n++ {
  1294. if n == 1 {
  1295. s.err(s.off, "'_' must separate successive digits")
  1296. }
  1297. s.next()
  1298. }
  1299. if !isHexDigit(s.c) {
  1300. s.err(s.off-1, "'_' must separate successive digits")
  1301. }
  1302. default:
  1303. return r
  1304. }
  1305. }
  1306. }
  1307. // When the input is broken into tokens, a semicolon is automatically inserted
  1308. // into the token stream immediately after a line's final token if that token
  1309. // is
  1310. //
  1311. // - an identifier
  1312. // - an integer, floating-point, imaginary, rune, or string literal
  1313. // - one of the keywords break, continue, fallthrough, or return
  1314. // - one of the operators and punctuation ++, --, ), ], or }
  1315. func (s *scanner) injectSemi() bool {
  1316. switch token.Token(s.last) {
  1317. case
  1318. IDENT, INT, FLOAT, IMAG, CHAR, STRING,
  1319. BREAK, CONTINUE, FALLTHROUGH, RETURN,
  1320. INC, DEC, RPAREN, RBRACK, RBRACE:
  1321. s.tok.ch = int32(SEMICOLON)
  1322. s.last = 0
  1323. if s.c == '\n' {
  1324. s.next()
  1325. }
  1326. return true
  1327. }
  1328. s.last = 0
  1329. return false
  1330. }