OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [fmt/] [scan.go] - Blame information for rev 860

Go to most recent revision | Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.