File: num.go

package info (click to toggle)
golang-github-cue-lang-cue 0.14.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 19,644 kB
  • sloc: makefile: 20; sh: 15
file content (361 lines) | stat: -rw-r--r-- 7,009 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// Copyright 2020 CUE Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package literal

import (
	"cuelang.org/go/cue/errors"
	"cuelang.org/go/cue/token"
	"github.com/cockroachdb/apd/v3"
)

// We avoid cuelang.org/go/internal.Context as that would be an import cycle.
var baseContext apd.Context

func init() {
	baseContext = apd.BaseContext
	baseContext.Precision = 34
}

// NumInfo contains information about a parsed numbers.
//
// Reusing a NumInfo across parses may avoid memory allocations.
type NumInfo struct {
	pos token.Pos
	src string
	p   int
	ch  byte
	buf []byte

	mul     Multiplier
	base    byte
	neg     bool
	UseSep  bool
	isFloat bool
	err     error
}

// String returns a canonical string representation of the number so that
// it can be parsed with math.Float.Parse.
func (p *NumInfo) String() string {
	if len(p.buf) > 0 && p.base == 10 && p.mul == 0 {
		return string(p.buf)
	}
	var d apd.Decimal
	_ = p.decimal(&d)
	return d.String()
}

type decimal = apd.Decimal

// Decimal is for internal use.
func (p *NumInfo) Decimal(v *decimal) error {
	return p.decimal(v)
}

func (p *NumInfo) decimal(v *apd.Decimal) error {
	if p.base != 10 {
		_, _, _ = v.SetString("0")
		b := p.buf
		if p.buf[0] == '-' {
			v.Negative = p.neg
			b = p.buf[1:]
		}
		v.Coeff.SetString(string(b), int(p.base))
		return nil
	}
	_ = v.UnmarshalText(p.buf)
	if p.mul != 0 {
		_, _ = baseContext.Mul(v, v, mulToRat[p.mul])
		cond, _ := baseContext.RoundToIntegralExact(v, v)
		if cond.Inexact() {
			return p.errorf("number cannot be represented as int")
		}
	}
	return nil
}

// Multiplier reports which multiplier was used in an integral number.
func (p *NumInfo) Multiplier() Multiplier {
	return p.mul
}

// IsInt reports whether the number is an integral number.
func (p *NumInfo) IsInt() bool {
	return !p.isFloat
}

// ParseNum parses s and populates NumInfo with the result.
func ParseNum(s string, n *NumInfo) error {
	*n = NumInfo{pos: n.pos, src: s, buf: n.buf[:0]}
	if !n.next() {
		return n.errorf("invalid number %q", s)
	}
	switch n.ch {
	case '-':
		n.neg = true
		n.buf = append(n.buf, '-')
		n.next()
	case '+':
		n.next()
	}
	seenDecimalPoint := false
	if n.ch == '.' {
		n.next()
		seenDecimalPoint = true
	}
	err := n.scanNumber(seenDecimalPoint)
	if err != nil {
		return err
	}
	if n.err != nil {
		return n.err
	}
	if n.p < len(n.src) {
		return n.errorf("invalid number %q", s)
	}
	if len(n.buf) == 0 {
		n.buf = append(n.buf, '0')
	}
	return nil
}

func (p *NumInfo) errorf(format string, args ...interface{}) error {
	return errors.Newf(p.pos, format, args...)
}

// A Multiplier indicates a multiplier indicator used in the literal.
type Multiplier byte

const (
	mul1 Multiplier = 1 + iota
	mul2
	mul3
	mul4
	mul5
	mul6
	mul7
	mul8

	mulBin = 0x10
	mulDec = 0x20

	K = mulDec | mul1
	M = mulDec | mul2
	G = mulDec | mul3
	T = mulDec | mul4
	P = mulDec | mul5
	E = mulDec | mul6
	Z = mulDec | mul7
	Y = mulDec | mul8

	Ki = mulBin | mul1
	Mi = mulBin | mul2
	Gi = mulBin | mul3
	Ti = mulBin | mul4
	Pi = mulBin | mul5
	Ei = mulBin | mul6
	Zi = mulBin | mul7
	Yi = mulBin | mul8
)

func (p *NumInfo) next() bool {
	if p.p >= len(p.src) {
		p.ch = 0
		return false
	}
	p.ch = p.src[p.p]
	p.p++
	if p.ch == '.' {
		if len(p.buf) == 0 {
			p.buf = append(p.buf, '0')
		}
		p.buf = append(p.buf, '.')
	}
	return true
}

func (p *NumInfo) digitVal(ch byte) (d int) {
	switch {
	case '0' <= ch && ch <= '9':
		d = int(ch - '0')
	case ch == '_':
		p.UseSep = true
		return 0
	case 'a' <= ch && ch <= 'f':
		d = int(ch - 'a' + 10)
	case 'A' <= ch && ch <= 'F':
		d = int(ch - 'A' + 10)
	default:
		return 16 // larger than any legal digit val
	}
	return d
}

func (p *NumInfo) scanMantissa(base int) bool {
	hasDigit := false
	var last byte
	for p.digitVal(p.ch) < base {
		if p.ch != '_' {
			p.buf = append(p.buf, p.ch)
			hasDigit = true
		}
		last = p.ch
		p.next()
	}
	if last == '_' {
		p.err = p.errorf("illegal '_' in number")
	}
	return hasDigit
}

func (p *NumInfo) scanNumber(seenDecimalPoint bool) error {
	p.base = 10

	if seenDecimalPoint {
		p.isFloat = true
		if !p.scanMantissa(10) {
			return p.errorf("illegal fraction %q", p.src)
		}
		goto exponent
	}

	if p.ch == '0' {
		// int or float
		p.next()
		switch p.ch {
		case 'x', 'X':
			p.base = 16
			// hexadecimal int
			p.next()
			if !p.scanMantissa(16) {
				// only scanned "0x" or "0X"
				return p.errorf("illegal hexadecimal number %q", p.src)
			}
		case 'b':
			p.base = 2
			// binary int
			p.next()
			if !p.scanMantissa(2) {
				// only scanned "0b"
				return p.errorf("illegal binary number %q", p.src)
			}
		case 'o':
			p.base = 8
			// octal int
			p.next()
			if !p.scanMantissa(8) {
				// only scanned "0o"
				return p.errorf("illegal octal number %q", p.src)
			}
		default:
			// int (base 8 or 10) or float
			p.scanMantissa(8)
			if p.ch == '8' || p.ch == '9' {
				p.scanMantissa(10)
				if p.ch != '.' && p.ch != 'e' && p.ch != 'E' {
					return p.errorf("illegal integer number %q", p.src)
				}
			}
			switch p.ch {
			case 'e', 'E':
				if len(p.buf) == 0 {
					p.buf = append(p.buf, '0')
				}
				fallthrough
			case '.':
				goto fraction
			}
			if len(p.buf) > 0 {
				p.base = 8
			}
		}
		goto exit
	}

	// decimal int or float
	if !p.scanMantissa(10) {
		return p.errorf("illegal number start %q", p.src)
	}

fraction:
	if p.ch == '.' {
		p.isFloat = true
		p.next()
		p.scanMantissa(10)
	}

exponent:
	switch p.ch {
	case 'K', 'M', 'G', 'T', 'P':
		p.mul = charToMul[p.ch]
		p.next()
		if p.ch == 'i' {
			p.mul |= mulBin
			p.next()
		} else {
			p.mul |= mulDec
		}
		var v apd.Decimal
		p.isFloat = false
		return p.decimal(&v)

	case 'e', 'E':
		p.isFloat = true
		p.next()
		p.buf = append(p.buf, 'e')
		if p.ch == '-' || p.ch == '+' {
			p.buf = append(p.buf, p.ch)
			p.next()
		}
		if !p.scanMantissa(10) {
			return p.errorf("illegal exponent %q", p.src)
		}
	}

exit:
	return nil
}

var charToMul = map[byte]Multiplier{
	'K': mul1,
	'M': mul2,
	'G': mul3,
	'T': mul4,
	'P': mul5,
	'E': mul6,
	'Z': mul7,
	'Y': mul8,
}

var mulToRat = map[Multiplier]*apd.Decimal{}

func init() {
	d := apd.New(1, 0)
	b := apd.New(1, 0)
	dm := apd.New(1000, 0)
	bm := apd.New(1024, 0)

	c := apd.BaseContext
	for i := Multiplier(1); int(i) < len(charToMul); i++ {
		// TODO: may we write to one of the sources?
		var bn, dn apd.Decimal
		_, _ = c.Mul(&dn, d, dm)
		d = &dn
		_, _ = c.Mul(&bn, b, bm)
		b = &bn
		mulToRat[mulDec|i] = d
		mulToRat[mulBin|i] = b
	}
}