vx11 / examples / calc / model.v
246 lines · 233 sloc · 5.8 KB · c4bc47d81a04ec4c69336c7c85575735cb003365
Raw
1// Calculator state and a small recursive-descent arithmetic parser.
2module calc
3
4import math
5import strconv
6
7pub struct Model {
8pub mut:
9 expression string
10 message string
11 evaluated bool
12}
13
14pub fn (m &Model) display() string { return if m.expression == '' { '0' } else { m.expression } }
15
16fn operator(c u8) bool { return c in [`+`, `-`, `*`, `/`] }
17
18// Locate the final number or balanced group, including postfix operators and sign.
19fn operand_start(s string) int {
20 mut end := s.len
21 for end > 0 {
22 if s[..end].ends_with('^2') {
23 end -= 2
24 } else if s[end - 1] == `%` {
25 end--
26 } else {
27 break
28 }
29 }
30 if end == 0 { return s.len }
31 mut start := end
32 if s[end - 1] == `)` {
33 mut depth := 1
34 start = end - 1
35 for start > 0 && depth > 0 {
36 start--
37 if s[start] == `)` { depth++ }
38 if s[start] == `(` { depth-- }
39 }
40 if depth != 0 { return s.len }
41 } else {
42 for start > 0 {
43 c := s[start - 1]
44 if c.is_digit() || c in [`.`, `e`, `E`] {
45 start--
46 continue
47 }
48 if c in [`+`, `-`] && start >= 2 && s[start - 2] in [`e`, `E`] {
49 start--
50 continue
51 }
52 break
53 }
54 }
55 if start == end { return s.len }
56 if start > 0 && s[start - 1] == `-` && (start == 1 || operator(s[start - 2]) || s[start - 2] == `(`) {
57 start--
58 }
59 return start
60}
61
62pub fn (mut m Model) press(key string) {
63 m.message = ''
64 match key {
65 'C' {
66 m.expression = ''
67 m.evaluated = false
68 }
69 'CE' {
70 start := operand_start(m.expression)
71 m.expression = m.expression[..start]
72 m.evaluated = false
73 }
74 '<' {
75 if m.expression.ends_with('^2') {
76 m.expression = m.expression[..m.expression.len - 2]
77 } else if m.expression.len > 0 {
78 m.expression = m.expression[..m.expression.len - 1]
79 }
80 m.evaluated = false
81 }
82 '+-' {
83 if m.expression == '' {
84 m.expression = '-'
85 return
86 }
87 start := operand_start(m.expression)
88 if start == m.expression.len {
89 m.expression += '-'
90 return
91 }
92 operand := m.expression[start..]
93 m.expression = m.expression[..start] + if operand.starts_with('-') {
94 operand[1..]
95 } else {
96 '-' + operand
97 }
98 m.evaluated = false
99 }
100 '=' {
101 value := evaluate(m.expression) or {
102 m.message = err.msg()
103 return
104 }
105 m.expression = if value == 0 { '0' } else { '${value:.12g}' }
106 m.evaluated = true
107 }
108 '%', 'x2' {
109 if operand_start(m.expression) == m.expression.len { return }
110 // Parenthesize the signed operand so (-3)^2 yields +9.
111 start := operand_start(m.expression)
112 operand := m.expression[start..]
113 m.expression = m.expression[..start] + '(' + operand + ')' + if key == '%' {
114 '%'
115 } else {
116 '^2'
117 }
118 m.evaluated = false
119 }
120 else {
121 mut input := if key == 'x' { '*' } else { key }
122 if input.len != 1 || !(input[0].is_digit() || input[0] in [`.`, `+`, `-`, `*`, `/`,
123 `(`, `)`]) {
124 return
125 }
126 if m.evaluated && (input[0].is_digit() || input in ['.', '(']) { m.expression = '' }
127 m.evaluated = false
128 if m.expression.len >= 160 {
129 m.message = 'Expression too long'
130 return
131 }
132 if input == '.' {
133 start := operand_start(m.expression)
134 if start < m.expression.len && m.expression[start..].contains('.') { return }
135 if m.expression == '' || operator(m.expression[m.expression.len - 1]) || m.expression.ends_with('(') {
136 input = '0.'
137 }
138 }
139 m.expression += input
140 }
141 }
142}
143
144struct Parser {
145 text string
146mut:
147 position int
148}
149
150pub fn evaluate(text string) !f64 {
151 if text.len == 0 { return error('Enter an expression') }
152 if text.len > 200 { return error('Expression too long') }
153 mut p := Parser{ text: text }
154 value := p.sum()!
155 if p.position != text.len { return error('Check operators and parentheses') }
156 if math.is_nan(value) || math.is_inf(value, 0) { return error('Result is out of range') }
157 return value
158}
159
160fn (mut p Parser) sum() !f64 {
161 mut value := p.product()!
162 for p.position < p.text.len && p.text[p.position] in [`+`, `-`] {
163 op := p.text[p.position]
164 p.position++
165 rhs := p.product()!
166 value = if op == `+` { value + rhs } else { value - rhs }
167 }
168 return value
169}
170
171fn (mut p Parser) product() !f64 {
172 mut value := p.unary()!
173 for p.position < p.text.len && p.text[p.position] in [`*`, `/`] {
174 op := p.text[p.position]
175 p.position++
176 rhs := p.unary()!
177 if op == `/` && rhs == 0 { return error('Cannot divide by zero') }
178 value = if op == `*` { value * rhs } else { value / rhs }
179 }
180 return value
181}
182
183fn (mut p Parser) unary() !f64 {
184 if p.position < p.text.len && p.text[p.position] in [`+`, `-`] {
185 op := p.text[p.position]
186 p.position++
187 value := p.unary()!
188 return if op == `-` { -value } else { value }
189 }
190 return p.postfix()
191}
192
193fn (mut p Parser) postfix() !f64 {
194 mut value := p.primary()!
195 for p.position < p.text.len {
196 if p.text[p.position] == `%` {
197 value /= 100
198 p.position++
199 } else if p.text[p.position..].starts_with('^2') {
200 value *= value
201 p.position += 2
202 } else {
203 break
204 }
205 }
206 return value
207}
208
209fn (mut p Parser) primary() !f64 {
210 if p.position >= p.text.len { return error('Finish the expression') }
211 if p.text[p.position] == `(` {
212 p.position++
213 value := p.sum()!
214 if p.position >= p.text.len || p.text[p.position] != `)` {
215 return error('Close the parentheses')
216 }
217 p.position++
218 return value
219 }
220 start := p.position
221 mut dot := false
222 mut digits := 0
223 for p.position < p.text.len {
224 ch := p.text[p.position]
225 if ch.is_digit() {
226 digits++
227 p.position++
228 continue
229 }
230 if ch == `.` && !dot {
231 dot = true
232 p.position++
233 continue
234 }
235 break
236 }
237 if digits == 0 { return error('Expected a number') }
238 if p.position < p.text.len && p.text[p.position] in [`e`, `E`] {
239 p.position++
240 if p.position < p.text.len && p.text[p.position] in [`+`, `-`] { p.position++ }
241 exponent := p.position
242 for p.position < p.text.len && p.text[p.position].is_digit() { p.position++ }
243 if exponent == p.position { return error('Invalid exponent') }
244 }
245 return strconv.atof64(p.text[start..p.position])
246}
247