aboutsummaryrefslogtreecommitdiff
path: root/token.go
blob: aa8047e65d0b6d400ebf3190259c735587658bab (plain) (blame)
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
package lexpr

type Token struct {
	typ       lexType
	value     string
	ivalue    int
	priority  int
	leftAssoc bool
}

func (t Token) Number() (int, bool) {
	return t.ivalue, t.typ == number
}

func (t Token) String() (string, bool) {
	return t.value, t.typ == str
}

func (t Token) Word() (string, bool) {
	return t.value, t.typ == word
}

func TokenFromAny(variable any) (Token, bool) {
	if s, ok := variable.(string); ok {
		return Token{
			typ:   str,
			value: s,
		}, true
	}
	if n, ok := variable.(int); ok {
		return Token{
			typ:    number,
			ivalue: n,
		}, true
	}
	if n, ok := variable.(float64); ok {
		return Token{
			typ:    number,
			ivalue: int(n),
		}, true
	}
	if n, ok := variable.(float32); ok {
		return Token{
			typ:    number,
			ivalue: int(n),
		}, true
	}
	if b, ok := variable.(bool); ok {
		n := 0
		if b {
			n = 1
		}
		return Token{
			typ:    number,
			ivalue: n,
		}, true
	}
	return Token{}, false
}

func TokenFromWord(wordName string) Token {
	return Token{
		typ:   word,
		value: wordName,
	}
}

func TokenFromString(s string) Token {
	return Token{
		typ:   str,
		value: s,
	}
}

func TokenFromInt(n int) Token {
	return Token{
		typ:    number,
		ivalue: n,
	}
}