scan.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  1. // Copyright 2010 The Go 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 fmt
  5. import (
  6. "errors"
  7. "io"
  8. "math"
  9. "os"
  10. "reflect"
  11. "strconv"
  12. "sync"
  13. "unicode/utf8"
  14. )
  15. // runeUnreader is the interface to something that can unread runes.
  16. // If the object provided to Scan does not satisfy this interface,
  17. // a local buffer will be used to back up the input, but its contents
  18. // will be lost when Scan returns.
  19. type runeUnreader interface {
  20. UnreadRune() error
  21. }
  22. // ScanState represents the scanner state passed to custom scanners.
  23. // Scanners may do rune-at-a-time scanning or ask the ScanState
  24. // to discover the next space-delimited token.
  25. type ScanState interface {
  26. // ReadRune reads the next rune (Unicode code point) from the input.
  27. // If invoked during Scanln, Fscanln, or Sscanln, ReadRune() will
  28. // return EOF after returning the first '\n' or when reading beyond
  29. // the specified width.
  30. ReadRune() (r rune, size int, err error)
  31. // UnreadRune causes the next call to ReadRune to return the same rune.
  32. UnreadRune() error
  33. // SkipSpace skips space in the input. Newlines are treated as space
  34. // unless the scan operation is Scanln, Fscanln or Sscanln, in which case
  35. // a newline is treated as EOF.
  36. SkipSpace()
  37. // Token skips space in the input if skipSpace is true, then returns the
  38. // run of Unicode code points c satisfying f(c). If f is nil,
  39. // !unicode.IsSpace(c) is used; that is, the token will hold non-space
  40. // characters. Newlines are treated as space unless the scan operation
  41. // is Scanln, Fscanln or Sscanln, in which case a newline is treated as
  42. // EOF. The returned slice points to shared data that may be overwritten
  43. // by the next call to Token, a call to a Scan function using the ScanState
  44. // as input, or when the calling Scan method returns.
  45. Token(skipSpace bool, f func(rune) bool) (token []byte, err error)
  46. // Width returns the value of the width option and whether it has been set.
  47. // The unit is Unicode code points.
  48. Width() (wid int, ok bool)
  49. // Because ReadRune is implemented by the interface, Read should never be
  50. // called by the scanning routines and a valid implementation of
  51. // ScanState may choose always to return an error from Read.
  52. Read(buf []byte) (n int, err error)
  53. }
  54. // Scanner is implemented by any value that has a Scan method, which scans
  55. // the input for the representation of a value and stores the result in the
  56. // receiver, which must be a pointer to be useful. The Scan method is called
  57. // for any argument to Scan, Scanf, or Scanln that implements it.
  58. type Scanner interface {
  59. Scan(state ScanState, verb rune) error
  60. }
  61. // Scan scans text read from standard input, storing successive
  62. // space-separated values into successive arguments. Newlines count
  63. // as space. It returns the number of items successfully scanned.
  64. // If that is less than the number of arguments, err will report why.
  65. func Scan(a ...interface{}) (n int, err error) {
  66. return Fscan(os.Stdin, a...)
  67. }
  68. // Scanln is similar to Scan, but stops scanning at a newline and
  69. // after the final item there must be a newline or EOF.
  70. func Scanln(a ...interface{}) (n int, err error) {
  71. return Fscanln(os.Stdin, a...)
  72. }
  73. // Scanf scans text read from standard input, storing successive
  74. // space-separated values into successive arguments as determined by
  75. // the format. It returns the number of items successfully scanned.
  76. func Scanf(format string, a ...interface{}) (n int, err error) {
  77. return Fscanf(os.Stdin, format, a...)
  78. }
  79. type stringReader string
  80. func (r *stringReader) Read(b []byte) (n int, err error) {
  81. n = copy(b, *r)
  82. *r = (*r)[n:]
  83. if n == 0 {
  84. err = io.EOF
  85. }
  86. return
  87. }
  88. // Sscan scans the argument string, storing successive space-separated
  89. // values into successive arguments. Newlines count as space. It
  90. // returns the number of items successfully scanned. If that is less
  91. // than the number of arguments, err will report why.
  92. func Sscan(str string, a ...interface{}) (n int, err error) {
  93. return Fscan((*stringReader)(&str), a...)
  94. }
  95. // Sscanln is similar to Sscan, but stops scanning at a newline and
  96. // after the final item there must be a newline or EOF.
  97. func Sscanln(str string, a ...interface{}) (n int, err error) {
  98. return Fscanln((*stringReader)(&str), a...)
  99. }
  100. // Sscanf scans the argument string, storing successive space-separated
  101. // values into successive arguments as determined by the format. It
  102. // returns the number of items successfully parsed.
  103. func Sscanf(str string, format string, a ...interface{}) (n int, err error) {
  104. return Fscanf((*stringReader)(&str), format, a...)
  105. }
  106. // Fscan scans text read from r, storing successive space-separated
  107. // values into successive arguments. Newlines count as space. It
  108. // returns the number of items successfully scanned. If that is less
  109. // than the number of arguments, err will report why.
  110. func Fscan(r io.Reader, a ...interface{}) (n int, err error) {
  111. s, old := newScanState(r, true, false)
  112. n, err = s.doScan(a)
  113. s.free(old)
  114. return
  115. }
  116. // Fscanln is similar to Fscan, but stops scanning at a newline and
  117. // after the final item there must be a newline or EOF.
  118. func Fscanln(r io.Reader, a ...interface{}) (n int, err error) {
  119. s, old := newScanState(r, false, true)
  120. n, err = s.doScan(a)
  121. s.free(old)
  122. return
  123. }
  124. // Fscanf scans text read from r, storing successive space-separated
  125. // values into successive arguments as determined by the format. It
  126. // returns the number of items successfully parsed.
  127. func Fscanf(r io.Reader, format string, a ...interface{}) (n int, err error) {
  128. s, old := newScanState(r, false, false)
  129. n, err = s.doScanf(format, a)
  130. s.free(old)
  131. return
  132. }
  133. // scanError represents an error generated by the scanning software.
  134. // It's used as a unique signature to identify such errors when recovering.
  135. type scanError struct {
  136. err error
  137. }
  138. const eof = -1
  139. // ss is the internal implementation of ScanState.
  140. type ss struct {
  141. rr io.RuneReader // where to read input
  142. buf buffer // token accumulator
  143. peekRune rune // one-rune lookahead
  144. prevRune rune // last rune returned by ReadRune
  145. count int // runes consumed so far.
  146. atEOF bool // already read EOF
  147. ssave
  148. }
  149. // ssave holds the parts of ss that need to be
  150. // saved and restored on recursive scans.
  151. type ssave struct {
  152. validSave bool // is or was a part of an actual ss.
  153. nlIsEnd bool // whether newline terminates scan
  154. nlIsSpace bool // whether newline counts as white space
  155. argLimit int // max value of ss.count for this arg; argLimit <= limit
  156. limit int // max value of ss.count.
  157. maxWid int // width of this arg.
  158. }
  159. // The Read method is only in ScanState so that ScanState
  160. // satisfies io.Reader. It will never be called when used as
  161. // intended, so there is no need to make it actually work.
  162. func (s *ss) Read(buf []byte) (n int, err error) {
  163. return 0, errors.New("ScanState's Read should not be called. Use ReadRune")
  164. }
  165. func (s *ss) ReadRune() (r rune, size int, err error) {
  166. if s.peekRune >= 0 {
  167. s.count++
  168. r = s.peekRune
  169. size = utf8.RuneLen(r)
  170. s.prevRune = r
  171. s.peekRune = -1
  172. return
  173. }
  174. if s.atEOF || s.nlIsEnd && s.prevRune == '\n' || s.count >= s.argLimit {
  175. err = io.EOF
  176. return
  177. }
  178. r, size, err = s.rr.ReadRune()
  179. if err == nil {
  180. s.count++
  181. s.prevRune = r
  182. } else if err == io.EOF {
  183. s.atEOF = true
  184. }
  185. return
  186. }
  187. func (s *ss) Width() (wid int, ok bool) {
  188. if s.maxWid == hugeWid {
  189. return 0, false
  190. }
  191. return s.maxWid, true
  192. }
  193. // The public method returns an error; this private one panics.
  194. // If getRune reaches EOF, the return value is EOF (-1).
  195. func (s *ss) getRune() (r rune) {
  196. r, _, err := s.ReadRune()
  197. if err != nil {
  198. if err == io.EOF {
  199. return eof
  200. }
  201. s.error(err)
  202. }
  203. return
  204. }
  205. // mustReadRune turns io.EOF into a panic(io.ErrUnexpectedEOF).
  206. // It is called in cases such as string scanning where an EOF is a
  207. // syntax error.
  208. func (s *ss) mustReadRune() (r rune) {
  209. r = s.getRune()
  210. if r == eof {
  211. s.error(io.ErrUnexpectedEOF)
  212. }
  213. return
  214. }
  215. func (s *ss) UnreadRune() error {
  216. if u, ok := s.rr.(runeUnreader); ok {
  217. u.UnreadRune()
  218. } else {
  219. s.peekRune = s.prevRune
  220. }
  221. s.prevRune = -1
  222. s.count--
  223. return nil
  224. }
  225. func (s *ss) error(err error) {
  226. panic(scanError{err})
  227. }
  228. func (s *ss) errorString(err string) {
  229. panic(scanError{errors.New(err)})
  230. }
  231. func (s *ss) Token(skipSpace bool, f func(rune) bool) (tok []byte, err error) {
  232. defer func() {
  233. if e := recover(); e != nil {
  234. if se, ok := e.(scanError); ok {
  235. err = se.err
  236. } else {
  237. panic(e)
  238. }
  239. }
  240. }()
  241. if f == nil {
  242. f = notSpace
  243. }
  244. s.buf = s.buf[:0]
  245. tok = s.token(skipSpace, f)
  246. return
  247. }
  248. // space is a copy of the unicode.White_Space ranges,
  249. // to avoid depending on package unicode.
  250. var space = [][2]uint16{
  251. {0x0009, 0x000d},
  252. {0x0020, 0x0020},
  253. {0x0085, 0x0085},
  254. {0x00a0, 0x00a0},
  255. {0x1680, 0x1680},
  256. {0x2000, 0x200a},
  257. {0x2028, 0x2029},
  258. {0x202f, 0x202f},
  259. {0x205f, 0x205f},
  260. {0x3000, 0x3000},
  261. }
  262. func isSpace(r rune) bool {
  263. if r >= 1<<16 {
  264. return false
  265. }
  266. rx := uint16(r)
  267. for _, rng := range space {
  268. if rx < rng[0] {
  269. return false
  270. }
  271. if rx <= rng[1] {
  272. return true
  273. }
  274. }
  275. return false
  276. }
  277. // notSpace is the default scanning function used in Token.
  278. func notSpace(r rune) bool {
  279. return !isSpace(r)
  280. }
  281. // SkipSpace provides Scan methods the ability to skip space and newline
  282. // characters in keeping with the current scanning mode set by format strings
  283. // and Scan/Scanln.
  284. func (s *ss) SkipSpace() {
  285. s.skipSpace(false)
  286. }
  287. // readRune is a structure to enable reading UTF-8 encoded code points
  288. // from an io.Reader. It is used if the Reader given to the scanner does
  289. // not already implement io.RuneReader.
  290. type readRune struct {
  291. reader io.Reader
  292. buf [utf8.UTFMax]byte // used only inside ReadRune
  293. pending int // number of bytes in pendBuf; only >0 for bad UTF-8
  294. pendBuf [utf8.UTFMax]byte // bytes left over
  295. }
  296. // readByte returns the next byte from the input, which may be
  297. // left over from a previous read if the UTF-8 was ill-formed.
  298. func (r *readRune) readByte() (b byte, err error) {
  299. if r.pending > 0 {
  300. b = r.pendBuf[0]
  301. copy(r.pendBuf[0:], r.pendBuf[1:])
  302. r.pending--
  303. return
  304. }
  305. n, err := io.ReadFull(r.reader, r.pendBuf[0:1])
  306. if n != 1 {
  307. return 0, err
  308. }
  309. return r.pendBuf[0], err
  310. }
  311. // unread saves the bytes for the next read.
  312. func (r *readRune) unread(buf []byte) {
  313. copy(r.pendBuf[r.pending:], buf)
  314. r.pending += len(buf)
  315. }
  316. // ReadRune returns the next UTF-8 encoded code point from the
  317. // io.Reader inside r.
  318. func (r *readRune) ReadRune() (rr rune, size int, err error) {
  319. r.buf[0], err = r.readByte()
  320. if err != nil {
  321. return 0, 0, err
  322. }
  323. if r.buf[0] < utf8.RuneSelf { // fast check for common ASCII case
  324. rr = rune(r.buf[0])
  325. size = 1 // Known to be 1.
  326. return
  327. }
  328. var n int
  329. for n = 1; !utf8.FullRune(r.buf[0:n]); n++ {
  330. r.buf[n], err = r.readByte()
  331. if err != nil {
  332. if err == io.EOF {
  333. err = nil
  334. break
  335. }
  336. return
  337. }
  338. }
  339. rr, size = utf8.DecodeRune(r.buf[0:n])
  340. if size < n { // an error
  341. r.unread(r.buf[size:n])
  342. }
  343. return
  344. }
  345. var ssFree = sync.Pool{
  346. New: func() interface{} { return new(ss) },
  347. }
  348. // newScanState allocates a new ss struct or grab a cached one.
  349. func newScanState(r io.Reader, nlIsSpace, nlIsEnd bool) (s *ss, old ssave) {
  350. // If the reader is a *ss, then we've got a recursive
  351. // call to Scan, so re-use the scan state.
  352. s, ok := r.(*ss)
  353. if ok {
  354. old = s.ssave
  355. s.limit = s.argLimit
  356. s.nlIsEnd = nlIsEnd || s.nlIsEnd
  357. s.nlIsSpace = nlIsSpace
  358. return
  359. }
  360. s = ssFree.Get().(*ss)
  361. if rr, ok := r.(io.RuneReader); ok {
  362. s.rr = rr
  363. } else {
  364. s.rr = &readRune{reader: r}
  365. }
  366. s.nlIsSpace = nlIsSpace
  367. s.nlIsEnd = nlIsEnd
  368. s.prevRune = -1
  369. s.peekRune = -1
  370. s.atEOF = false
  371. s.limit = hugeWid
  372. s.argLimit = hugeWid
  373. s.maxWid = hugeWid
  374. s.validSave = true
  375. s.count = 0
  376. return
  377. }
  378. // free saves used ss structs in ssFree; avoid an allocation per invocation.
  379. func (s *ss) free(old ssave) {
  380. // If it was used recursively, just restore the old state.
  381. if old.validSave {
  382. s.ssave = old
  383. return
  384. }
  385. // Don't hold on to ss structs with large buffers.
  386. if cap(s.buf) > 1024 {
  387. return
  388. }
  389. s.buf = s.buf[:0]
  390. s.rr = nil
  391. ssFree.Put(s)
  392. }
  393. // skipSpace skips spaces and maybe newlines.
  394. func (s *ss) skipSpace(stopAtNewline bool) {
  395. for {
  396. r := s.getRune()
  397. if r == eof {
  398. return
  399. }
  400. if r == '\r' && s.peek("\n") {
  401. continue
  402. }
  403. if r == '\n' {
  404. if stopAtNewline {
  405. break
  406. }
  407. if s.nlIsSpace {
  408. continue
  409. }
  410. s.errorString("unexpected newline")
  411. return
  412. }
  413. if !isSpace(r) {
  414. s.UnreadRune()
  415. break
  416. }
  417. }
  418. }
  419. // token returns the next space-delimited string from the input. It
  420. // skips white space. For Scanln, it stops at newlines. For Scan,
  421. // newlines are treated as spaces.
  422. func (s *ss) token(skipSpace bool, f func(rune) bool) []byte {
  423. if skipSpace {
  424. s.skipSpace(false)
  425. }
  426. // read until white space or newline
  427. for {
  428. r := s.getRune()
  429. if r == eof {
  430. break
  431. }
  432. if !f(r) {
  433. s.UnreadRune()
  434. break
  435. }
  436. s.buf.WriteRune(r)
  437. }
  438. return s.buf
  439. }
  440. var complexError = errors.New("syntax error scanning complex number")
  441. var boolError = errors.New("syntax error scanning boolean")
  442. func indexRune(s string, r rune) int {
  443. for i, c := range s {
  444. if c == r {
  445. return i
  446. }
  447. }
  448. return -1
  449. }
  450. // consume reads the next rune in the input and reports whether it is in the ok string.
  451. // If accept is true, it puts the character into the input token.
  452. func (s *ss) consume(ok string, accept bool) bool {
  453. r := s.getRune()
  454. if r == eof {
  455. return false
  456. }
  457. if indexRune(ok, r) >= 0 {
  458. if accept {
  459. s.buf.WriteRune(r)
  460. }
  461. return true
  462. }
  463. if r != eof && accept {
  464. s.UnreadRune()
  465. }
  466. return false
  467. }
  468. // peek reports whether the next character is in the ok string, without consuming it.
  469. func (s *ss) peek(ok string) bool {
  470. r := s.getRune()
  471. if r != eof {
  472. s.UnreadRune()
  473. }
  474. return indexRune(ok, r) >= 0
  475. }
  476. func (s *ss) notEOF() {
  477. // Guarantee there is data to be read.
  478. if r := s.getRune(); r == eof {
  479. panic(io.EOF)
  480. }
  481. s.UnreadRune()
  482. }
  483. // accept checks the next rune in the input. If it's a byte (sic) in the string, it puts it in the
  484. // buffer and returns true. Otherwise it return false.
  485. func (s *ss) accept(ok string) bool {
  486. return s.consume(ok, true)
  487. }
  488. // okVerb verifies that the verb is present in the list, setting s.err appropriately if not.
  489. func (s *ss) okVerb(verb rune, okVerbs, typ string) bool {
  490. for _, v := range okVerbs {
  491. if v == verb {
  492. return true
  493. }
  494. }
  495. s.errorString("bad verb %" + string(verb) + " for " + typ)
  496. return false
  497. }
  498. // scanBool returns the value of the boolean represented by the next token.
  499. func (s *ss) scanBool(verb rune) bool {
  500. s.skipSpace(false)
  501. s.notEOF()
  502. if !s.okVerb(verb, "tv", "boolean") {
  503. return false
  504. }
  505. // Syntax-checking a boolean is annoying. We're not fastidious about case.
  506. switch s.getRune() {
  507. case '0':
  508. return false
  509. case '1':
  510. return true
  511. case 't', 'T':
  512. if s.accept("rR") && (!s.accept("uU") || !s.accept("eE")) {
  513. s.error(boolError)
  514. }
  515. return true
  516. case 'f', 'F':
  517. if s.accept("aA") && (!s.accept("lL") || !s.accept("sS") || !s.accept("eE")) {
  518. s.error(boolError)
  519. }
  520. return false
  521. }
  522. return false
  523. }
  524. // Numerical elements
  525. const (
  526. binaryDigits = "01"
  527. octalDigits = "01234567"
  528. decimalDigits = "0123456789"
  529. hexadecimalDigits = "0123456789aAbBcCdDeEfF"
  530. sign = "+-"
  531. period = "."
  532. exponent = "eEp"
  533. )
  534. // getBase returns the numeric base represented by the verb and its digit string.
  535. func (s *ss) getBase(verb rune) (base int, digits string) {
  536. s.okVerb(verb, "bdoUxXv", "integer") // sets s.err
  537. base = 10
  538. digits = decimalDigits
  539. switch verb {
  540. case 'b':
  541. base = 2
  542. digits = binaryDigits
  543. case 'o':
  544. base = 8
  545. digits = octalDigits
  546. case 'x', 'X', 'U':
  547. base = 16
  548. digits = hexadecimalDigits
  549. }
  550. return
  551. }
  552. // scanNumber returns the numerical string with specified digits starting here.
  553. func (s *ss) scanNumber(digits string, haveDigits bool) string {
  554. if !haveDigits {
  555. s.notEOF()
  556. if !s.accept(digits) {
  557. s.errorString("expected integer")
  558. }
  559. }
  560. for s.accept(digits) {
  561. }
  562. return string(s.buf)
  563. }
  564. // scanRune returns the next rune value in the input.
  565. func (s *ss) scanRune(bitSize int) int64 {
  566. s.notEOF()
  567. r := int64(s.getRune())
  568. n := uint(bitSize)
  569. x := (r << (64 - n)) >> (64 - n)
  570. if x != r {
  571. s.errorString("overflow on character value " + string(r))
  572. }
  573. return r
  574. }
  575. // scanBasePrefix reports whether the integer begins with a 0 or 0x,
  576. // and returns the base, digit string, and whether a zero was found.
  577. // It is called only if the verb is %v.
  578. func (s *ss) scanBasePrefix() (base int, digits string, found bool) {
  579. if !s.peek("0") {
  580. return 10, decimalDigits, false
  581. }
  582. s.accept("0")
  583. found = true // We've put a digit into the token buffer.
  584. // Special cases for '0' && '0x'
  585. base, digits = 8, octalDigits
  586. if s.peek("xX") {
  587. s.consume("xX", false)
  588. base, digits = 16, hexadecimalDigits
  589. }
  590. return
  591. }
  592. // scanInt returns the value of the integer represented by the next
  593. // token, checking for overflow. Any error is stored in s.err.
  594. func (s *ss) scanInt(verb rune, bitSize int) int64 {
  595. if verb == 'c' {
  596. return s.scanRune(bitSize)
  597. }
  598. s.skipSpace(false)
  599. s.notEOF()
  600. base, digits := s.getBase(verb)
  601. haveDigits := false
  602. if verb == 'U' {
  603. if !s.consume("U", false) || !s.consume("+", false) {
  604. s.errorString("bad unicode format ")
  605. }
  606. } else {
  607. s.accept(sign) // If there's a sign, it will be left in the token buffer.
  608. if verb == 'v' {
  609. base, digits, haveDigits = s.scanBasePrefix()
  610. }
  611. }
  612. tok := s.scanNumber(digits, haveDigits)
  613. i, err := strconv.ParseInt(tok, base, 64)
  614. if err != nil {
  615. s.error(err)
  616. }
  617. n := uint(bitSize)
  618. x := (i << (64 - n)) >> (64 - n)
  619. if x != i {
  620. s.errorString("integer overflow on token " + tok)
  621. }
  622. return i
  623. }
  624. // scanUint returns the value of the unsigned integer represented
  625. // by the next token, checking for overflow. Any error is stored in s.err.
  626. func (s *ss) scanUint(verb rune, bitSize int) uint64 {
  627. if verb == 'c' {
  628. return uint64(s.scanRune(bitSize))
  629. }
  630. s.skipSpace(false)
  631. s.notEOF()
  632. base, digits := s.getBase(verb)
  633. haveDigits := false
  634. if verb == 'U' {
  635. if !s.consume("U", false) || !s.consume("+", false) {
  636. s.errorString("bad unicode format ")
  637. }
  638. } else if verb == 'v' {
  639. base, digits, haveDigits = s.scanBasePrefix()
  640. }
  641. tok := s.scanNumber(digits, haveDigits)
  642. i, err := strconv.ParseUint(tok, base, 64)
  643. if err != nil {
  644. s.error(err)
  645. }
  646. n := uint(bitSize)
  647. x := (i << (64 - n)) >> (64 - n)
  648. if x != i {
  649. s.errorString("unsigned integer overflow on token " + tok)
  650. }
  651. return i
  652. }
  653. // floatToken returns the floating-point number starting here, no longer than swid
  654. // if the width is specified. It's not rigorous about syntax because it doesn't check that
  655. // we have at least some digits, but Atof will do that.
  656. func (s *ss) floatToken() string {
  657. s.buf = s.buf[:0]
  658. // NaN?
  659. if s.accept("nN") && s.accept("aA") && s.accept("nN") {
  660. return string(s.buf)
  661. }
  662. // leading sign?
  663. s.accept(sign)
  664. // Inf?
  665. if s.accept("iI") && s.accept("nN") && s.accept("fF") {
  666. return string(s.buf)
  667. }
  668. // digits?
  669. for s.accept(decimalDigits) {
  670. }
  671. // decimal point?
  672. if s.accept(period) {
  673. // fraction?
  674. for s.accept(decimalDigits) {
  675. }
  676. }
  677. // exponent?
  678. if s.accept(exponent) {
  679. // leading sign?
  680. s.accept(sign)
  681. // digits?
  682. for s.accept(decimalDigits) {
  683. }
  684. }
  685. return string(s.buf)
  686. }
  687. // complexTokens returns the real and imaginary parts of the complex number starting here.
  688. // The number might be parenthesized and has the format (N+Ni) where N is a floating-point
  689. // number and there are no spaces within.
  690. func (s *ss) complexTokens() (real, imag string) {
  691. // TODO: accept N and Ni independently?
  692. parens := s.accept("(")
  693. real = s.floatToken()
  694. s.buf = s.buf[:0]
  695. // Must now have a sign.
  696. if !s.accept("+-") {
  697. s.error(complexError)
  698. }
  699. // Sign is now in buffer
  700. imagSign := string(s.buf)
  701. imag = s.floatToken()
  702. if !s.accept("i") {
  703. s.error(complexError)
  704. }
  705. if parens && !s.accept(")") {
  706. s.error(complexError)
  707. }
  708. return real, imagSign + imag
  709. }
  710. // convertFloat converts the string to a float64value.
  711. func (s *ss) convertFloat(str string, n int) float64 {
  712. if p := indexRune(str, 'p'); p >= 0 {
  713. // Atof doesn't handle power-of-2 exponents,
  714. // but they're easy to evaluate.
  715. f, err := strconv.ParseFloat(str[:p], n)
  716. if err != nil {
  717. // Put full string into error.
  718. if e, ok := err.(*strconv.NumError); ok {
  719. e.Num = str
  720. }
  721. s.error(err)
  722. }
  723. m, err := strconv.Atoi(str[p+1:])
  724. if err != nil {
  725. // Put full string into error.
  726. if e, ok := err.(*strconv.NumError); ok {
  727. e.Num = str
  728. }
  729. s.error(err)
  730. }
  731. return math.Ldexp(f, m)
  732. }
  733. f, err := strconv.ParseFloat(str, n)
  734. if err != nil {
  735. s.error(err)
  736. }
  737. return f
  738. }
  739. // convertComplex converts the next token to a complex128 value.
  740. // The atof argument is a type-specific reader for the underlying type.
  741. // If we're reading complex64, atof will parse float32s and convert them
  742. // to float64's to avoid reproducing this code for each complex type.
  743. func (s *ss) scanComplex(verb rune, n int) complex128 {
  744. if !s.okVerb(verb, floatVerbs, "complex") {
  745. return 0
  746. }
  747. s.skipSpace(false)
  748. s.notEOF()
  749. sreal, simag := s.complexTokens()
  750. real := s.convertFloat(sreal, n/2)
  751. imag := s.convertFloat(simag, n/2)
  752. return complex(real, imag)
  753. }
  754. // convertString returns the string represented by the next input characters.
  755. // The format of the input is determined by the verb.
  756. func (s *ss) convertString(verb rune) (str string) {
  757. if !s.okVerb(verb, "svqx", "string") {
  758. return ""
  759. }
  760. s.skipSpace(false)
  761. s.notEOF()
  762. switch verb {
  763. case 'q':
  764. str = s.quotedString()
  765. case 'x':
  766. str = s.hexString()
  767. default:
  768. str = string(s.token(true, notSpace)) // %s and %v just return the next word
  769. }
  770. return
  771. }
  772. // quotedString returns the double- or back-quoted string represented by the next input characters.
  773. func (s *ss) quotedString() string {
  774. s.notEOF()
  775. quote := s.getRune()
  776. switch quote {
  777. case '`':
  778. // Back-quoted: Anything goes until EOF or back quote.
  779. for {
  780. r := s.mustReadRune()
  781. if r == quote {
  782. break
  783. }
  784. s.buf.WriteRune(r)
  785. }
  786. return string(s.buf)
  787. case '"':
  788. // Double-quoted: Include the quotes and let strconv.Unquote do the backslash escapes.
  789. s.buf.WriteRune(quote)
  790. for {
  791. r := s.mustReadRune()
  792. s.buf.WriteRune(r)
  793. if r == '\\' {
  794. // In a legal backslash escape, no matter how long, only the character
  795. // immediately after the escape can itself be a backslash or quote.
  796. // Thus we only need to protect the first character after the backslash.
  797. s.buf.WriteRune(s.mustReadRune())
  798. } else if r == '"' {
  799. break
  800. }
  801. }
  802. result, err := strconv.Unquote(string(s.buf))
  803. if err != nil {
  804. s.error(err)
  805. }
  806. return result
  807. default:
  808. s.errorString("expected quoted string")
  809. }
  810. return ""
  811. }
  812. // hexDigit returns the value of the hexadecimal digit
  813. func (s *ss) hexDigit(d rune) int {
  814. digit := int(d)
  815. switch digit {
  816. case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  817. return digit - '0'
  818. case 'a', 'b', 'c', 'd', 'e', 'f':
  819. return 10 + digit - 'a'
  820. case 'A', 'B', 'C', 'D', 'E', 'F':
  821. return 10 + digit - 'A'
  822. }
  823. s.errorString("illegal hex digit")
  824. return 0
  825. }
  826. // hexByte returns the next hex-encoded (two-character) byte from the input.
  827. // There must be either two hexadecimal digits or a space character in the input.
  828. func (s *ss) hexByte() (b byte, ok bool) {
  829. rune1 := s.getRune()
  830. if rune1 == eof {
  831. return
  832. }
  833. if isSpace(rune1) {
  834. s.UnreadRune()
  835. return
  836. }
  837. rune2 := s.mustReadRune()
  838. return byte(s.hexDigit(rune1)<<4 | s.hexDigit(rune2)), true
  839. }
  840. // hexString returns the space-delimited hexpair-encoded string.
  841. func (s *ss) hexString() string {
  842. s.notEOF()
  843. for {
  844. b, ok := s.hexByte()
  845. if !ok {
  846. break
  847. }
  848. s.buf.WriteByte(b)
  849. }
  850. if len(s.buf) == 0 {
  851. s.errorString("no hex data for %x string")
  852. return ""
  853. }
  854. return string(s.buf)
  855. }
  856. const floatVerbs = "beEfFgGv"
  857. const hugeWid = 1 << 30
  858. // scanOne scans a single value, deriving the scanner from the type of the argument.
  859. func (s *ss) scanOne(verb rune, arg interface{}) {
  860. s.buf = s.buf[:0]
  861. var err error
  862. // If the parameter has its own Scan method, use that.
  863. if v, ok := arg.(Scanner); ok {
  864. err = v.Scan(s, verb)
  865. if err != nil {
  866. if err == io.EOF {
  867. err = io.ErrUnexpectedEOF
  868. }
  869. s.error(err)
  870. }
  871. return
  872. }
  873. switch v := arg.(type) {
  874. case *bool:
  875. *v = s.scanBool(verb)
  876. case *complex64:
  877. *v = complex64(s.scanComplex(verb, 64))
  878. case *complex128:
  879. *v = s.scanComplex(verb, 128)
  880. case *int:
  881. *v = int(s.scanInt(verb, intBits))
  882. case *int8:
  883. *v = int8(s.scanInt(verb, 8))
  884. case *int16:
  885. *v = int16(s.scanInt(verb, 16))
  886. case *int32:
  887. *v = int32(s.scanInt(verb, 32))
  888. case *int64:
  889. *v = s.scanInt(verb, 64)
  890. case *uint:
  891. *v = uint(s.scanUint(verb, intBits))
  892. case *uint8:
  893. *v = uint8(s.scanUint(verb, 8))
  894. case *uint16:
  895. *v = uint16(s.scanUint(verb, 16))
  896. case *uint32:
  897. *v = uint32(s.scanUint(verb, 32))
  898. case *uint64:
  899. *v = s.scanUint(verb, 64)
  900. case *uintptr:
  901. *v = uintptr(s.scanUint(verb, uintptrBits))
  902. // Floats are tricky because you want to scan in the precision of the result, not
  903. // scan in high precision and convert, in order to preserve the correct error condition.
  904. case *float32:
  905. if s.okVerb(verb, floatVerbs, "float32") {
  906. s.skipSpace(false)
  907. s.notEOF()
  908. *v = float32(s.convertFloat(s.floatToken(), 32))
  909. }
  910. case *float64:
  911. if s.okVerb(verb, floatVerbs, "float64") {
  912. s.skipSpace(false)
  913. s.notEOF()
  914. *v = s.convertFloat(s.floatToken(), 64)
  915. }
  916. case *string:
  917. *v = s.convertString(verb)
  918. case *[]byte:
  919. // We scan to string and convert so we get a copy of the data.
  920. // If we scanned to bytes, the slice would point at the buffer.
  921. *v = []byte(s.convertString(verb))
  922. default:
  923. val := reflect.ValueOf(v)
  924. ptr := val
  925. if ptr.Kind() != reflect.Ptr {
  926. s.errorString("type not a pointer: " + val.Type().String())
  927. return
  928. }
  929. switch v := ptr.Elem(); v.Kind() {
  930. case reflect.Bool:
  931. v.SetBool(s.scanBool(verb))
  932. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  933. v.SetInt(s.scanInt(verb, v.Type().Bits()))
  934. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  935. v.SetUint(s.scanUint(verb, v.Type().Bits()))
  936. case reflect.String:
  937. v.SetString(s.convertString(verb))
  938. case reflect.Slice:
  939. // For now, can only handle (renamed) []byte.
  940. typ := v.Type()
  941. if typ.Elem().Kind() != reflect.Uint8 {
  942. s.errorString("can't scan type: " + val.Type().String())
  943. }
  944. str := s.convertString(verb)
  945. v.Set(reflect.MakeSlice(typ, len(str), len(str)))
  946. for i := 0; i < len(str); i++ {
  947. v.Index(i).SetUint(uint64(str[i]))
  948. }
  949. case reflect.Float32, reflect.Float64:
  950. s.skipSpace(false)
  951. s.notEOF()
  952. v.SetFloat(s.convertFloat(s.floatToken(), v.Type().Bits()))
  953. case reflect.Complex64, reflect.Complex128:
  954. v.SetComplex(s.scanComplex(verb, v.Type().Bits()))
  955. default:
  956. s.errorString("can't scan type: " + val.Type().String())
  957. }
  958. }
  959. }
  960. // errorHandler turns local panics into error returns.
  961. func errorHandler(errp *error) {
  962. if e := recover(); e != nil {
  963. if se, ok := e.(scanError); ok { // catch local error
  964. *errp = se.err
  965. } else if eof, ok := e.(error); ok && eof == io.EOF { // out of input
  966. *errp = eof
  967. } else {
  968. panic(e)
  969. }
  970. }
  971. }
  972. // doScan does the real work for scanning without a format string.
  973. func (s *ss) doScan(a []interface{}) (numProcessed int, err error) {
  974. defer errorHandler(&err)
  975. for _, arg := range a {
  976. s.scanOne('v', arg)
  977. numProcessed++
  978. }
  979. // Check for newline if required.
  980. if !s.nlIsSpace {
  981. for {
  982. r := s.getRune()
  983. if r == '\n' || r == eof {
  984. break
  985. }
  986. if !isSpace(r) {
  987. s.errorString("expected newline")
  988. break
  989. }
  990. }
  991. }
  992. return
  993. }
  994. // advance determines whether the next characters in the input match
  995. // those of the format. It returns the number of bytes (sic) consumed
  996. // in the format. Newlines included, all runs of space characters in
  997. // either input or format behave as a single space. This routine also
  998. // handles the %% case. If the return value is zero, either format
  999. // starts with a % (with no following %) or the input is empty.
  1000. // If it is negative, the input did not match the string.
  1001. func (s *ss) advance(format string) (i int) {
  1002. for i < len(format) {
  1003. fmtc, w := utf8.DecodeRuneInString(format[i:])
  1004. if fmtc == '%' {
  1005. // %% acts like a real percent
  1006. nextc, _ := utf8.DecodeRuneInString(format[i+w:]) // will not match % if string is empty
  1007. if nextc != '%' {
  1008. return
  1009. }
  1010. i += w // skip the first %
  1011. }
  1012. sawSpace := false
  1013. for isSpace(fmtc) && i < len(format) {
  1014. sawSpace = true
  1015. i += w
  1016. fmtc, w = utf8.DecodeRuneInString(format[i:])
  1017. }
  1018. if sawSpace {
  1019. // There was space in the format, so there should be space (EOF)
  1020. // in the input.
  1021. inputc := s.getRune()
  1022. if inputc == eof || inputc == '\n' {
  1023. // If we've reached a newline, stop now; don't read ahead.
  1024. return
  1025. }
  1026. if !isSpace(inputc) {
  1027. // Space in format but not in input: error
  1028. s.errorString("expected space in input to match format")
  1029. }
  1030. s.skipSpace(true)
  1031. continue
  1032. }
  1033. inputc := s.mustReadRune()
  1034. if fmtc != inputc {
  1035. s.UnreadRune()
  1036. return -1
  1037. }
  1038. i += w
  1039. }
  1040. return
  1041. }
  1042. // doScanf does the real work when scanning with a format string.
  1043. // At the moment, it handles only pointers to basic types.
  1044. func (s *ss) doScanf(format string, a []interface{}) (numProcessed int, err error) {
  1045. defer errorHandler(&err)
  1046. end := len(format) - 1
  1047. // We process one item per non-trivial format
  1048. for i := 0; i <= end; {
  1049. w := s.advance(format[i:])
  1050. if w > 0 {
  1051. i += w
  1052. continue
  1053. }
  1054. // Either we failed to advance, we have a percent character, or we ran out of input.
  1055. if format[i] != '%' {
  1056. // Can't advance format. Why not?
  1057. if w < 0 {
  1058. s.errorString("input does not match format")
  1059. }
  1060. // Otherwise at EOF; "too many operands" error handled below
  1061. break
  1062. }
  1063. i++ // % is one byte
  1064. // do we have 20 (width)?
  1065. var widPresent bool
  1066. s.maxWid, widPresent, i = parsenum(format, i, end)
  1067. if !widPresent {
  1068. s.maxWid = hugeWid
  1069. }
  1070. s.argLimit = s.limit
  1071. if f := s.count + s.maxWid; f < s.argLimit {
  1072. s.argLimit = f
  1073. }
  1074. c, w := utf8.DecodeRuneInString(format[i:])
  1075. i += w
  1076. if numProcessed >= len(a) { // out of operands
  1077. s.errorString("too few operands for format %" + format[i-w:])
  1078. break
  1079. }
  1080. arg := a[numProcessed]
  1081. s.scanOne(c, arg)
  1082. numProcessed++
  1083. s.argLimit = s.limit
  1084. }
  1085. if numProcessed < len(a) {
  1086. s.errorString("too many operands")
  1087. }
  1088. return
  1089. }