blob: c6eb9af7899e607308e9b0a3c2a750d0f7eb7fb6 [file] [log] [blame]
Hans Boehm84614952014-11-25 18:46:17 -08001/*
Hans Boehme4579122015-05-26 17:52:32 -07002 * Copyright (C) 2015 The Android Open Source Project
Hans Boehm84614952014-11-25 18:46:17 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.calculator2;
18
Hans Boehm84614952014-11-25 18:46:17 -080019import android.content.Context;
Hans Boehm8a4f81c2015-07-09 10:41:25 -070020import android.text.SpannableString;
21import android.text.SpannableStringBuilder;
22import android.text.Spanned;
23import android.text.style.TtsSpan;
Hans Boehm84614952014-11-25 18:46:17 -080024
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070025import java.io.DataInput;
26import java.io.DataOutput;
27import java.io.IOException;
Annie Chin06fd3cf2016-11-07 16:04:33 -080028import java.math.BigInteger;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070029import java.util.ArrayList;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070030
Hans Boehm3666e632015-07-27 18:33:12 -070031/**
32 * A mathematical expression represented as a sequence of "tokens".
33 * Many tokens are represented by button ids for the corresponding operator.
34 * A token may also represent the result of a previously evaluated expression.
35 * The add() method adds a token to the end of the expression. The delete method() removes one.
36 * Clear() deletes the entire expression contents. Eval() evaluates the expression,
Hans Boehm995e5eb2016-02-08 11:03:01 -080037 * producing a UnifiedReal result.
Hans Boehm3666e632015-07-27 18:33:12 -070038 * Expressions are parsed only during evaluation; no explicit parse tree is maintained.
39 *
Hans Boehm995e5eb2016-02-08 11:03:01 -080040 * The write() method is used to save the current expression. Note that neither UnifiedReal
41 * nor the underlying CR provide a serialization facility. Thus we save all previously
42 * computed values by writing out the expression that was used to compute them, and reevaluate
43 * when reading it back in.
Hans Boehm3666e632015-07-27 18:33:12 -070044 */
Hans Boehm84614952014-11-25 18:46:17 -080045class CalculatorExpr {
Hans Boehm8f051c32016-10-03 16:53:58 -070046 /**
47 * An interface for resolving expression indices in embedded subexpressions to
48 * the associated CalculatorExpr, and associating a UnifiedReal result with it.
49 * All methods are thread-safe in the strong sense; they may be called asynchronously
50 * at any time from any thread.
51 */
52 public interface ExprResolver {
53 /*
54 * Retrieve the expression corresponding to index.
55 */
56 CalculatorExpr getExpr(long index);
57 /*
58 * Retrive the degree mode associated with the expression at index i.
59 */
60 boolean getDegreeMode(long index);
61 /*
62 * Retrieve the stored result for the expression at index, or return null.
63 */
64 UnifiedReal getResult(long index);
65 /*
66 * Atomically test for an existing result, and set it if there was none.
67 * Return the prior result if there was one, or the new one if there was not.
68 * May only be called after getExpr.
69 */
70 UnifiedReal putResultIfAbsent(long index, UnifiedReal result);
71 // FIXME: Check that long timeouts for embedded expressions are propagated
72 // correctly.
73 }
74
Hans Boehm84614952014-11-25 18:46:17 -080075 private ArrayList<Token> mExpr; // The actual representation
76 // as a list of tokens. Constant
77 // tokens are always nonempty.
78
79 private static enum TokenKind { CONSTANT, OPERATOR, PRE_EVAL };
80 private static TokenKind[] tokenKindValues = TokenKind.values();
81 private final static BigInteger BIG_MILLION = BigInteger.valueOf(1000000);
82 private final static BigInteger BIG_BILLION = BigInteger.valueOf(1000000000);
83
84 private static abstract class Token {
85 abstract TokenKind kind();
Hans Boehm8a4f81c2015-07-09 10:41:25 -070086
87 /**
Hans Boehm8f051c32016-10-03 16:53:58 -070088 * Write token as either a very small Byte containing the TokenKind,
89 * followed by data needed by subclass constructor,
90 * or as a byte >= 0x20 directly describing the OPERATOR token.
Hans Boehm8a4f81c2015-07-09 10:41:25 -070091 */
Hans Boehm84614952014-11-25 18:46:17 -080092 abstract void write(DataOutput out) throws IOException;
Hans Boehm8a4f81c2015-07-09 10:41:25 -070093
94 /**
95 * Return a textual representation of the token.
96 * The result is suitable for either display as part od the formula or TalkBack use.
97 * It may be a SpannableString that includes added TalkBack information.
98 * @param context context used for converting button ids to strings
99 */
100 abstract CharSequence toCharSequence(Context context);
Hans Boehm84614952014-11-25 18:46:17 -0800101 }
102
Hans Boehm3666e632015-07-27 18:33:12 -0700103 /**
104 * Representation of an operator token
105 */
Hans Boehm84614952014-11-25 18:46:17 -0800106 private static class Operator extends Token {
Hans Boehm8f051c32016-10-03 16:53:58 -0700107 // TODO: rename id.
Hans Boehm3666e632015-07-27 18:33:12 -0700108 public final int id; // We use the button resource id
Hans Boehm84614952014-11-25 18:46:17 -0800109 Operator(int resId) {
Hans Boehm3666e632015-07-27 18:33:12 -0700110 id = resId;
Hans Boehm84614952014-11-25 18:46:17 -0800111 }
Hans Boehm8f051c32016-10-03 16:53:58 -0700112 Operator(byte op) throws IOException {
113 id = KeyMaps.fromByte(op);
Hans Boehm84614952014-11-25 18:46:17 -0800114 }
115 @Override
116 void write(DataOutput out) throws IOException {
Hans Boehm8f051c32016-10-03 16:53:58 -0700117 out.writeByte(KeyMaps.toByte(id));
Hans Boehm84614952014-11-25 18:46:17 -0800118 }
119 @Override
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700120 public CharSequence toCharSequence(Context context) {
Hans Boehm3666e632015-07-27 18:33:12 -0700121 String desc = KeyMaps.toDescriptiveString(context, id);
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700122 if (desc != null) {
Hans Boehm3666e632015-07-27 18:33:12 -0700123 SpannableString result = new SpannableString(KeyMaps.toString(context, id));
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700124 Object descSpan = new TtsSpan.TextBuilder(desc).build();
125 result.setSpan(descSpan, 0, result.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
126 return result;
127 } else {
Hans Boehm3666e632015-07-27 18:33:12 -0700128 return KeyMaps.toString(context, id);
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700129 }
Hans Boehm84614952014-11-25 18:46:17 -0800130 }
131 @Override
132 TokenKind kind() { return TokenKind.OPERATOR; }
133 }
134
Hans Boehm3666e632015-07-27 18:33:12 -0700135 /**
136 * Representation of a (possibly incomplete) numerical constant.
137 * Supports addition and removal of trailing characters; hence mutable.
138 */
Hans Boehm84614952014-11-25 18:46:17 -0800139 private static class Constant extends Token implements Cloneable {
140 private boolean mSawDecimal;
Hans Boehm3666e632015-07-27 18:33:12 -0700141 private String mWhole; // String preceding decimal point.
Hans Boehm0b9806f2015-06-29 16:07:15 -0700142 private String mFraction; // String after decimal point.
143 private int mExponent; // Explicit exponent, only generated through addExponent.
Hans Boehm8f051c32016-10-03 16:53:58 -0700144 private static int SAW_DECIMAL = 0x1;
145 private static int HAS_EXPONENT = 0x2;
Hans Boehm84614952014-11-25 18:46:17 -0800146
147 Constant() {
148 mWhole = "";
149 mFraction = "";
Hans Boehm8f051c32016-10-03 16:53:58 -0700150 // mSawDecimal = false;
151 // mExponent = 0;
Hans Boehm84614952014-11-25 18:46:17 -0800152 };
153
154 Constant(DataInput in) throws IOException {
155 mWhole = in.readUTF();
Hans Boehm8f051c32016-10-03 16:53:58 -0700156 byte flags = in.readByte();
157 if ((flags & SAW_DECIMAL) != 0) {
158 mSawDecimal = true;
159 mFraction = in.readUTF();
160 } else {
161 // mSawDecimal = false;
162 mFraction = "";
163 }
164 if ((flags & HAS_EXPONENT) != 0) {
165 mExponent = in.readInt();
166 }
Hans Boehm84614952014-11-25 18:46:17 -0800167 }
168
169 @Override
170 void write(DataOutput out) throws IOException {
Hans Boehm8f051c32016-10-03 16:53:58 -0700171 byte flags = (byte)((mSawDecimal ? SAW_DECIMAL : 0)
172 | (mExponent != 0 ? HAS_EXPONENT : 0));
Hans Boehm84614952014-11-25 18:46:17 -0800173 out.writeByte(TokenKind.CONSTANT.ordinal());
174 out.writeUTF(mWhole);
Hans Boehm8f051c32016-10-03 16:53:58 -0700175 out.writeByte(flags);
176 if (mSawDecimal) {
177 out.writeUTF(mFraction);
178 }
179 if (mExponent != 0) {
180 out.writeInt(mExponent);
181 }
Hans Boehm84614952014-11-25 18:46:17 -0800182 }
183
184 // Given a button press, append corresponding digit.
185 // We assume id is a digit or decimal point.
186 // Just return false if this was the second (or later) decimal point
187 // in this constant.
Hans Boehm0b9806f2015-06-29 16:07:15 -0700188 // Assumes that this constant does not have an exponent.
Hans Boehm3666e632015-07-27 18:33:12 -0700189 public boolean add(int id) {
Hans Boehm84614952014-11-25 18:46:17 -0800190 if (id == R.id.dec_point) {
Hans Boehm0b9806f2015-06-29 16:07:15 -0700191 if (mSawDecimal || mExponent != 0) return false;
Hans Boehm84614952014-11-25 18:46:17 -0800192 mSawDecimal = true;
193 return true;
194 }
195 int val = KeyMaps.digVal(id);
Hans Boehm0b9806f2015-06-29 16:07:15 -0700196 if (mExponent != 0) {
197 if (Math.abs(mExponent) <= 10000) {
198 if (mExponent > 0) {
199 mExponent = 10 * mExponent + val;
200 } else {
201 mExponent = 10 * mExponent - val;
202 }
203 return true;
204 } else { // Too large; refuse
205 return false;
206 }
207 }
Hans Boehm84614952014-11-25 18:46:17 -0800208 if (mSawDecimal) {
209 mFraction += val;
210 } else {
211 mWhole += val;
212 }
213 return true;
214 }
215
Hans Boehm3666e632015-07-27 18:33:12 -0700216 public void addExponent(int exp) {
Hans Boehm0b9806f2015-06-29 16:07:15 -0700217 // Note that adding a 0 exponent is a no-op. That's OK.
218 mExponent = exp;
219 }
220
Hans Boehm3666e632015-07-27 18:33:12 -0700221 /**
222 * Undo the last add or remove last exponent digit.
223 * Assumes the constant is nonempty.
224 */
225 public void delete() {
Hans Boehm0b9806f2015-06-29 16:07:15 -0700226 if (mExponent != 0) {
227 mExponent /= 10;
228 // Once zero, it can only be added back with addExponent.
229 } else if (!mFraction.isEmpty()) {
Hans Boehm84614952014-11-25 18:46:17 -0800230 mFraction = mFraction.substring(0, mFraction.length() - 1);
231 } else if (mSawDecimal) {
232 mSawDecimal = false;
233 } else {
234 mWhole = mWhole.substring(0, mWhole.length() - 1);
235 }
236 }
237
Hans Boehm3666e632015-07-27 18:33:12 -0700238 public boolean isEmpty() {
Hans Boehm84614952014-11-25 18:46:17 -0800239 return (mSawDecimal == false && mWhole.isEmpty());
240 }
241
Hans Boehm3666e632015-07-27 18:33:12 -0700242 /**
243 * Produce human-readable string representation of constant, as typed.
Hans Boehm24c91ed2016-06-30 18:53:44 -0700244 * We do add digit grouping separators to the whole number, even if not typed.
Hans Boehm3666e632015-07-27 18:33:12 -0700245 * Result is internationalized.
246 */
Hans Boehm84614952014-11-25 18:46:17 -0800247 @Override
248 public String toString() {
Hans Boehm24c91ed2016-06-30 18:53:44 -0700249 String result;
250 if (mExponent != 0) {
251 result = mWhole;
252 } else {
253 result = StringUtils.addCommas(mWhole, 0, mWhole.length());
254 }
Hans Boehm84614952014-11-25 18:46:17 -0800255 if (mSawDecimal) {
Hans Boehm013969e2015-04-13 20:29:47 -0700256 result += '.';
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700257 result += mFraction;
258 }
Hans Boehm0b9806f2015-06-29 16:07:15 -0700259 if (mExponent != 0) {
260 result += "E" + mExponent;
261 }
Hans Boehm013969e2015-04-13 20:29:47 -0700262 return KeyMaps.translateResult(result);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700263 }
264
Hans Boehm3666e632015-07-27 18:33:12 -0700265 /**
Hans Boehmfa5203c2015-08-17 16:14:52 -0700266 * Return BoundedRational representation of constant, if well-formed.
267 * Result is never null.
Hans Boehm3666e632015-07-27 18:33:12 -0700268 */
Hans Boehmfa5203c2015-08-17 16:14:52 -0700269 public BoundedRational toRational() throws SyntaxException {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700270 String whole = mWhole;
Hans Boehmfa5203c2015-08-17 16:14:52 -0700271 if (whole.isEmpty()) {
272 if (mFraction.isEmpty()) {
273 // Decimal point without digits.
274 throw new SyntaxException();
275 } else {
276 whole = "0";
277 }
278 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700279 BigInteger num = new BigInteger(whole + mFraction);
Hans Boehm682ff5e2015-03-09 14:40:25 -0700280 BigInteger den = BigInteger.TEN.pow(mFraction.length());
Hans Boehm0b9806f2015-06-29 16:07:15 -0700281 if (mExponent > 0) {
282 num = num.multiply(BigInteger.TEN.pow(mExponent));
283 }
284 if (mExponent < 0) {
285 den = den.multiply(BigInteger.TEN.pow(-mExponent));
286 }
Hans Boehm682ff5e2015-03-09 14:40:25 -0700287 return new BoundedRational(num, den);
288 }
289
Hans Boehm84614952014-11-25 18:46:17 -0800290 @Override
Hans Boehm3666e632015-07-27 18:33:12 -0700291 public CharSequence toCharSequence(Context context) {
Hans Boehm84614952014-11-25 18:46:17 -0800292 return toString();
293 }
294
295 @Override
Hans Boehm3666e632015-07-27 18:33:12 -0700296 public TokenKind kind() {
297 return TokenKind.CONSTANT;
298 }
Hans Boehm84614952014-11-25 18:46:17 -0800299
300 // Override clone to make it public
301 @Override
302 public Object clone() {
Hans Boehm3666e632015-07-27 18:33:12 -0700303 Constant result = new Constant();
304 result.mWhole = mWhole;
305 result.mFraction = mFraction;
306 result.mSawDecimal = mSawDecimal;
307 result.mExponent = mExponent;
308 return result;
Hans Boehm84614952014-11-25 18:46:17 -0800309 }
310 }
311
Hans Boehm3666e632015-07-27 18:33:12 -0700312 /**
313 * The "token" class for previously evaluated subexpressions.
314 * We treat previously evaluated subexpressions as tokens. These are inserted when we either
315 * continue an expression after evaluating some of it, or copy an expression and paste it back
316 * in.
Hans Boehm8f051c32016-10-03 16:53:58 -0700317 * This only contains enough information to allow us to display the expression in a
318 * formula, or reevaluate the expression with the aid of an ExprResolver; we no longer
319 * cache the result. The expression corresponding to the index can be obtained through
320 * the ExprResolver, which looks it up in a subexpression database.
Hans Boehm995e5eb2016-02-08 11:03:01 -0800321 * The representation includes a UnifiedReal value. In order to
Hans Boehm3666e632015-07-27 18:33:12 -0700322 * support saving and restoring, we also include the underlying expression itself, and the
323 * context (currently just degree mode) used to evaluate it. The short string representation
324 * is also stored in order to avoid potentially expensive recomputation in the UI thread.
325 */
Hans Boehm84614952014-11-25 18:46:17 -0800326 private static class PreEval extends Token {
Hans Boehm8f051c32016-10-03 16:53:58 -0700327 public final long mIndex;
Hans Boehm50ed3202015-06-09 14:35:49 -0700328 private final String mShortRep; // Not internationalized.
Hans Boehm8f051c32016-10-03 16:53:58 -0700329 PreEval(long index, String shortRep) {
330 mIndex = index;
Hans Boehm84614952014-11-25 18:46:17 -0800331 mShortRep = shortRep;
332 }
Hans Boehm84614952014-11-25 18:46:17 -0800333 @Override
Hans Boehm8f051c32016-10-03 16:53:58 -0700334 // This writes out only a shallow representation of the result, without
335 // information about subexpressions. To write out a deep representation, we
336 // find referenced subexpressions, and iteratively write those as well.
Hans Boehm3666e632015-07-27 18:33:12 -0700337 public void write(DataOutput out) throws IOException {
Hans Boehm84614952014-11-25 18:46:17 -0800338 out.writeByte(TokenKind.PRE_EVAL.ordinal());
Hans Boehm8f051c32016-10-03 16:53:58 -0700339 if (mIndex > Integer.MAX_VALUE || mIndex < Integer.MIN_VALUE) {
340 // This would be millions of expressions per day for the life of the device.
341 throw new AssertionError("Expression index too big");
Hans Boehm84614952014-11-25 18:46:17 -0800342 }
Hans Boehm8f051c32016-10-03 16:53:58 -0700343 out.writeInt((int)mIndex);
344 out.writeUTF(mShortRep);
Hans Boehm84614952014-11-25 18:46:17 -0800345 }
346 PreEval(DataInput in) throws IOException {
Hans Boehm8f051c32016-10-03 16:53:58 -0700347 mIndex = in.readInt();
348 mShortRep = in.readUTF();
Hans Boehm84614952014-11-25 18:46:17 -0800349 }
350 @Override
Hans Boehm3666e632015-07-27 18:33:12 -0700351 public CharSequence toCharSequence(Context context) {
Hans Boehm50ed3202015-06-09 14:35:49 -0700352 return KeyMaps.translateResult(mShortRep);
Hans Boehm84614952014-11-25 18:46:17 -0800353 }
354 @Override
Hans Boehm3666e632015-07-27 18:33:12 -0700355 public TokenKind kind() {
Hans Boehm187d3e92015-06-09 18:04:26 -0700356 return TokenKind.PRE_EVAL;
357 }
Hans Boehm3666e632015-07-27 18:33:12 -0700358 public boolean hasEllipsis() {
Hans Boehm187d3e92015-06-09 18:04:26 -0700359 return mShortRep.lastIndexOf(KeyMaps.ELLIPSIS) != -1;
360 }
Hans Boehm84614952014-11-25 18:46:17 -0800361 }
362
Hans Boehm3666e632015-07-27 18:33:12 -0700363 /**
364 * Read token from in.
365 */
366 public static Token newToken(DataInput in) throws IOException {
Hans Boehm8f051c32016-10-03 16:53:58 -0700367 byte kindByte = in.readByte();
368 if (kindByte < 0x20) {
369 TokenKind kind = tokenKindValues[kindByte];
370 switch(kind) {
371 case CONSTANT:
372 return new Constant(in);
373 case PRE_EVAL:
374 return new PreEval(in);
375 default: throw new IOException("Bad save file format");
376 }
377 } else {
378 return new Operator(kindByte);
Hans Boehm84614952014-11-25 18:46:17 -0800379 }
380 }
381
382 CalculatorExpr() {
383 mExpr = new ArrayList<Token>();
384 }
385
386 private CalculatorExpr(ArrayList<Token> expr) {
387 mExpr = expr;
388 }
389
Hans Boehm3666e632015-07-27 18:33:12 -0700390 /**
391 * Construct CalculatorExpr, by reading it from in.
392 */
Hans Boehm84614952014-11-25 18:46:17 -0800393 CalculatorExpr(DataInput in) throws IOException {
394 mExpr = new ArrayList<Token>();
395 int size = in.readInt();
396 for (int i = 0; i < size; ++i) {
397 mExpr.add(newToken(in));
398 }
399 }
400
Hans Boehm3666e632015-07-27 18:33:12 -0700401 /**
402 * Write this expression to out.
403 */
404 public void write(DataOutput out) throws IOException {
Hans Boehm84614952014-11-25 18:46:17 -0800405 int size = mExpr.size();
406 out.writeInt(size);
407 for (int i = 0; i < size; ++i) {
408 mExpr.get(i).write(out);
409 }
410 }
411
Hans Boehm3666e632015-07-27 18:33:12 -0700412 /**
413 * Does this expression end with a numeric constant?
414 * As opposed to an operator or preevaluated expression.
415 */
Hans Boehm0b9806f2015-06-29 16:07:15 -0700416 boolean hasTrailingConstant() {
417 int s = mExpr.size();
418 if (s == 0) {
419 return false;
420 }
421 Token t = mExpr.get(s-1);
422 return t instanceof Constant;
423 }
424
Hans Boehm3666e632015-07-27 18:33:12 -0700425 /**
426 * Does this expression end with a binary operator?
427 */
Hans Boehm8f051c32016-10-03 16:53:58 -0700428 boolean hasTrailingBinary() {
Hans Boehm84614952014-11-25 18:46:17 -0800429 int s = mExpr.size();
430 if (s == 0) return false;
431 Token t = mExpr.get(s-1);
432 if (!(t instanceof Operator)) return false;
433 Operator o = (Operator)t;
Hans Boehm3666e632015-07-27 18:33:12 -0700434 return (KeyMaps.isBinary(o.id));
Hans Boehm84614952014-11-25 18:46:17 -0800435 }
436
Hans Boehm017de982015-06-10 17:46:03 -0700437 /**
438 * Append press of button with given id to expression.
439 * If the insertion would clearly result in a syntax error, either just return false
440 * and do nothing, or make an adjustment to avoid the problem. We do the latter only
441 * for unambiguous consecutive binary operators, in which case we delete the first
442 * operator.
443 */
Hans Boehm84614952014-11-25 18:46:17 -0800444 boolean add(int id) {
445 int s = mExpr.size();
Hans Boehm3666e632015-07-27 18:33:12 -0700446 final int d = KeyMaps.digVal(id);
447 final boolean binary = KeyMaps.isBinary(id);
Hans Boehm017de982015-06-10 17:46:03 -0700448 Token lastTok = s == 0 ? null : mExpr.get(s-1);
Hans Boehm3666e632015-07-27 18:33:12 -0700449 int lastOp = lastTok instanceof Operator ? ((Operator) lastTok).id : 0;
Hans Boehm017de982015-06-10 17:46:03 -0700450 // Quietly replace a trailing binary operator with another one, unless the second
451 // operator is minus, in which case we just allow it as a unary minus.
452 if (binary && !KeyMaps.isPrefix(id)) {
453 if (s == 0 || lastOp == R.id.lparen || KeyMaps.isFunc(lastOp)
454 || KeyMaps.isPrefix(lastOp) && lastOp != R.id.op_sub) {
455 return false;
456 }
457 while (hasTrailingBinary()) {
458 delete();
459 }
460 // s invalid and not used below.
Hans Boehm84614952014-11-25 18:46:17 -0800461 }
Hans Boehm3666e632015-07-27 18:33:12 -0700462 final boolean isConstPiece = (d != KeyMaps.NOT_DIGIT || id == R.id.dec_point);
Hans Boehm84614952014-11-25 18:46:17 -0800463 if (isConstPiece) {
Hans Boehm017de982015-06-10 17:46:03 -0700464 // Since we treat juxtaposition as multiplication, a constant can appear anywhere.
Hans Boehm84614952014-11-25 18:46:17 -0800465 if (s == 0) {
466 mExpr.add(new Constant());
467 s++;
468 } else {
469 Token last = mExpr.get(s-1);
470 if(!(last instanceof Constant)) {
Hans Boehm017de982015-06-10 17:46:03 -0700471 if (last instanceof PreEval) {
472 // Add explicit multiplication to avoid confusing display.
473 mExpr.add(new Operator(R.id.op_mul));
474 s++;
Hans Boehm84614952014-11-25 18:46:17 -0800475 }
476 mExpr.add(new Constant());
477 s++;
478 }
479 }
480 return ((Constant)(mExpr.get(s-1))).add(id);
481 } else {
482 mExpr.add(new Operator(id));
483 return true;
484 }
485 }
486
Hans Boehm017de982015-06-10 17:46:03 -0700487 /**
Hans Boehm0b9806f2015-06-29 16:07:15 -0700488 * Add exponent to the constant at the end of the expression.
489 * Assumes there is a constant at the end of the expression.
490 */
491 void addExponent(int exp) {
492 Token lastTok = mExpr.get(mExpr.size() - 1);
493 ((Constant) lastTok).addExponent(exp);
494 }
495
496 /**
Hans Boehm017de982015-06-10 17:46:03 -0700497 * Remove trailing op_add and op_sub operators.
498 */
499 void removeTrailingAdditiveOperators() {
500 while (true) {
501 int s = mExpr.size();
Hans Boehm3666e632015-07-27 18:33:12 -0700502 if (s == 0) {
503 break;
504 }
Hans Boehm017de982015-06-10 17:46:03 -0700505 Token lastTok = mExpr.get(s-1);
Hans Boehm3666e632015-07-27 18:33:12 -0700506 if (!(lastTok instanceof Operator)) {
507 break;
508 }
509 int lastOp = ((Operator) lastTok).id;
510 if (lastOp != R.id.op_add && lastOp != R.id.op_sub) {
511 break;
512 }
Hans Boehm017de982015-06-10 17:46:03 -0700513 delete();
514 }
515 }
516
Hans Boehm3666e632015-07-27 18:33:12 -0700517 /**
518 * Append the contents of the argument expression.
519 * It is assumed that the argument expression will not change, and thus its pieces can be
520 * reused directly.
521 */
522 public void append(CalculatorExpr expr2) {
Hans Boehmfbcef702015-04-27 18:07:47 -0700523 int s = mExpr.size();
Hans Boehm84614952014-11-25 18:46:17 -0800524 int s2 = expr2.mExpr.size();
Hans Boehm3666e632015-07-27 18:33:12 -0700525 // Check that we're not concatenating Constant or PreEval tokens, since the result would
526 // look like a single constant, with very mysterious results for the user.
Hans Boehmfbcef702015-04-27 18:07:47 -0700527 if (s != 0 && s2 != 0) {
528 Token last = mExpr.get(s-1);
529 Token first = expr2.mExpr.get(0);
530 if (!(first instanceof Operator) && !(last instanceof Operator)) {
Hans Boehm3666e632015-07-27 18:33:12 -0700531 // Fudge it by adding an explicit multiplication. We would have interpreted it as
532 // such anyway, and this makes it recognizable to the user.
Hans Boehmfbcef702015-04-27 18:07:47 -0700533 mExpr.add(new Operator(R.id.op_mul));
534 }
535 }
Hans Boehm84614952014-11-25 18:46:17 -0800536 for (int i = 0; i < s2; ++i) {
537 mExpr.add(expr2.mExpr.get(i));
538 }
539 }
540
Hans Boehm3666e632015-07-27 18:33:12 -0700541 /**
542 * Undo the last key addition, if any.
543 * Or possibly remove a trailing exponent digit.
544 */
545 public void delete() {
546 final int s = mExpr.size();
547 if (s == 0) {
548 return;
549 }
Hans Boehm84614952014-11-25 18:46:17 -0800550 Token last = mExpr.get(s-1);
551 if (last instanceof Constant) {
552 Constant c = (Constant)last;
553 c.delete();
Hans Boehm3666e632015-07-27 18:33:12 -0700554 if (!c.isEmpty()) {
555 return;
556 }
Hans Boehm84614952014-11-25 18:46:17 -0800557 }
558 mExpr.remove(s-1);
559 }
560
Hans Boehm3666e632015-07-27 18:33:12 -0700561 /**
562 * Remove all tokens from the expression.
563 */
564 public void clear() {
Hans Boehm84614952014-11-25 18:46:17 -0800565 mExpr.clear();
566 }
567
Hans Boehm3666e632015-07-27 18:33:12 -0700568 public boolean isEmpty() {
Hans Boehm84614952014-11-25 18:46:17 -0800569 return mExpr.isEmpty();
570 }
571
Hans Boehm3666e632015-07-27 18:33:12 -0700572 /**
573 * Returns a logical deep copy of the CalculatorExpr.
574 * Operator and PreEval tokens are immutable, and thus aren't really copied.
575 */
Hans Boehm84614952014-11-25 18:46:17 -0800576 public Object clone() {
Hans Boehm3666e632015-07-27 18:33:12 -0700577 CalculatorExpr result = new CalculatorExpr();
Hans Boehm84614952014-11-25 18:46:17 -0800578 for (Token t: mExpr) {
579 if (t instanceof Constant) {
Hans Boehm3666e632015-07-27 18:33:12 -0700580 result.mExpr.add((Token)(((Constant)t).clone()));
Hans Boehm84614952014-11-25 18:46:17 -0800581 } else {
Hans Boehm3666e632015-07-27 18:33:12 -0700582 result.mExpr.add(t);
Hans Boehm84614952014-11-25 18:46:17 -0800583 }
584 }
Hans Boehm3666e632015-07-27 18:33:12 -0700585 return result;
Hans Boehm84614952014-11-25 18:46:17 -0800586 }
587
588 // Am I just a constant?
Hans Boehm3666e632015-07-27 18:33:12 -0700589 public boolean isConstant() {
590 if (mExpr.size() != 1) {
591 return false;
592 }
Hans Boehm84614952014-11-25 18:46:17 -0800593 return mExpr.get(0) instanceof Constant;
594 }
595
Hans Boehm3666e632015-07-27 18:33:12 -0700596 /**
597 * Return a new expression consisting of a single token representing the current pre-evaluated
598 * expression.
Hans Boehm8f051c32016-10-03 16:53:58 -0700599 * The caller supplies the expression index and short string representation.
600 * The expression must have been previously evaluated.
Hans Boehm3666e632015-07-27 18:33:12 -0700601 */
Hans Boehm8f051c32016-10-03 16:53:58 -0700602 public CalculatorExpr abbreviate(long index, String sr) {
Hans Boehm84614952014-11-25 18:46:17 -0800603 CalculatorExpr result = new CalculatorExpr();
Justin Klaassen0ace4eb2016-02-05 11:38:12 -0800604 @SuppressWarnings("unchecked")
Hans Boehm8f051c32016-10-03 16:53:58 -0700605 Token t = new PreEval(index, sr);
Hans Boehm84614952014-11-25 18:46:17 -0800606 result.mExpr.add(t);
607 return result;
608 }
609
Hans Boehm3666e632015-07-27 18:33:12 -0700610 /**
Hans Boehm995e5eb2016-02-08 11:03:01 -0800611 * Internal evaluation functions return an EvalRet pair.
Hans Boehm3666e632015-07-27 18:33:12 -0700612 * We compute rational (BoundedRational) results when possible, both as a performance
613 * optimization, and to detect errors exactly when we can.
614 */
615 private static class EvalRet {
616 public int pos; // Next position (expression index) to be parsed.
Hans Boehm995e5eb2016-02-08 11:03:01 -0800617 public final UnifiedReal val; // Constructive Real result of evaluating subexpression.
618 EvalRet(int p, UnifiedReal v) {
Hans Boehm3666e632015-07-27 18:33:12 -0700619 pos = p;
620 val = v;
Hans Boehm84614952014-11-25 18:46:17 -0800621 }
622 }
623
Hans Boehm3666e632015-07-27 18:33:12 -0700624 /**
625 * Internal evaluation functions take an EvalContext argument.
626 */
Hans Boehm84614952014-11-25 18:46:17 -0800627 private static class EvalContext {
Hans Boehm3666e632015-07-27 18:33:12 -0700628 public final int mPrefixLength; // Length of prefix to evaluate. Not explicitly saved.
Hans Boehmc023b732015-04-29 11:30:47 -0700629 public final boolean mDegreeMode;
Hans Boehm8f051c32016-10-03 16:53:58 -0700630 public final ExprResolver mExprResolver; // Reconstructed, not saved.
Hans Boehm84614952014-11-25 18:46:17 -0800631 // If we add any other kinds of evaluation modes, they go here.
Hans Boehm8f051c32016-10-03 16:53:58 -0700632 EvalContext(boolean degreeMode, int len, ExprResolver er) {
Hans Boehm84614952014-11-25 18:46:17 -0800633 mDegreeMode = degreeMode;
Hans Boehmc023b732015-04-29 11:30:47 -0700634 mPrefixLength = len;
Hans Boehm8f051c32016-10-03 16:53:58 -0700635 mExprResolver = er;
Hans Boehm84614952014-11-25 18:46:17 -0800636 }
Hans Boehm8f051c32016-10-03 16:53:58 -0700637 EvalContext(DataInput in, int len, ExprResolver er) throws IOException {
Hans Boehm84614952014-11-25 18:46:17 -0800638 mDegreeMode = in.readBoolean();
Hans Boehmc023b732015-04-29 11:30:47 -0700639 mPrefixLength = len;
Hans Boehm8f051c32016-10-03 16:53:58 -0700640 mExprResolver = er;
Hans Boehm84614952014-11-25 18:46:17 -0800641 }
642 void write(DataOutput out) throws IOException {
643 out.writeBoolean(mDegreeMode);
644 }
645 }
646
Hans Boehm995e5eb2016-02-08 11:03:01 -0800647 private UnifiedReal toRadians(UnifiedReal x, EvalContext ec) {
Hans Boehm84614952014-11-25 18:46:17 -0800648 if (ec.mDegreeMode) {
Hans Boehm995e5eb2016-02-08 11:03:01 -0800649 return x.multiply(UnifiedReal.RADIANS_PER_DEGREE);
Hans Boehm84614952014-11-25 18:46:17 -0800650 } else {
651 return x;
652 }
653 }
654
Hans Boehm995e5eb2016-02-08 11:03:01 -0800655 private UnifiedReal fromRadians(UnifiedReal x, EvalContext ec) {
Hans Boehm84614952014-11-25 18:46:17 -0800656 if (ec.mDegreeMode) {
Hans Boehm995e5eb2016-02-08 11:03:01 -0800657 return x.divide(UnifiedReal.RADIANS_PER_DEGREE);
Hans Boehm84614952014-11-25 18:46:17 -0800658 } else {
659 return x;
660 }
661 }
662
Hans Boehm3666e632015-07-27 18:33:12 -0700663 // The following methods can all throw IndexOutOfBoundsException in the event of a syntax
664 // error. We expect that to be caught in eval below.
Hans Boehm84614952014-11-25 18:46:17 -0800665
Hans Boehmc023b732015-04-29 11:30:47 -0700666 private boolean isOperatorUnchecked(int i, int op) {
Hans Boehm84614952014-11-25 18:46:17 -0800667 Token t = mExpr.get(i);
Hans Boehm3666e632015-07-27 18:33:12 -0700668 if (!(t instanceof Operator)) {
669 return false;
670 }
671 return ((Operator)(t)).id == op;
Hans Boehm84614952014-11-25 18:46:17 -0800672 }
673
Hans Boehmc023b732015-04-29 11:30:47 -0700674 private boolean isOperator(int i, int op, EvalContext ec) {
Hans Boehm3666e632015-07-27 18:33:12 -0700675 if (i >= ec.mPrefixLength) {
676 return false;
677 }
Hans Boehmc023b732015-04-29 11:30:47 -0700678 return isOperatorUnchecked(i, op);
679 }
680
Hans Boehm3666e632015-07-27 18:33:12 -0700681 public static class SyntaxException extends Exception {
Hans Boehmc023b732015-04-29 11:30:47 -0700682 public SyntaxException() {
Hans Boehm84614952014-11-25 18:46:17 -0800683 super();
684 }
Hans Boehmc023b732015-04-29 11:30:47 -0700685 public SyntaxException(String s) {
Hans Boehm84614952014-11-25 18:46:17 -0800686 super(s);
687 }
688 }
689
Hans Boehm3666e632015-07-27 18:33:12 -0700690 // The following functions all evaluate some kind of expression starting at position i in
691 // mExpr in a specified evaluation context. They return both the expression value (as
692 // constructive real and, if applicable, as BoundedRational) and the position of the next token
Hans Boehm84614952014-11-25 18:46:17 -0800693 // that was not used as part of the evaluation.
Hans Boehm3666e632015-07-27 18:33:12 -0700694 // This is essentially a simple recursive descent parser combined with expression evaluation.
695
Hans Boehmc023b732015-04-29 11:30:47 -0700696 private EvalRet evalUnary(int i, EvalContext ec) throws SyntaxException {
Hans Boehm3666e632015-07-27 18:33:12 -0700697 final Token t = mExpr.get(i);
Hans Boehm84614952014-11-25 18:46:17 -0800698 if (t instanceof Constant) {
699 Constant c = (Constant)t;
Hans Boehm995e5eb2016-02-08 11:03:01 -0800700 return new EvalRet(i+1,new UnifiedReal(c.toRational()));
Hans Boehm84614952014-11-25 18:46:17 -0800701 }
702 if (t instanceof PreEval) {
Hans Boehm8f051c32016-10-03 16:53:58 -0700703 final long index = ((PreEval)t).mIndex;
704 UnifiedReal res = ec.mExprResolver.getResult(index);
705 if (res == null) {
706 CalculatorExpr nestedExpr = ec.mExprResolver.getExpr(index);
707 EvalContext newEc = new EvalContext(ec.mExprResolver.getDegreeMode(index),
708 nestedExpr.trailingBinaryOpsStart(), ec.mExprResolver);
709 EvalRet new_res = nestedExpr.evalExpr(0, newEc);
710 res = ec.mExprResolver.putResultIfAbsent(index, new_res.val);
711 }
712 return new EvalRet(i+1, res);
Hans Boehm84614952014-11-25 18:46:17 -0800713 }
714 EvalRet argVal;
Hans Boehm3666e632015-07-27 18:33:12 -0700715 switch(((Operator)(t)).id) {
Hans Boehm84614952014-11-25 18:46:17 -0800716 case R.id.const_pi:
Hans Boehm995e5eb2016-02-08 11:03:01 -0800717 return new EvalRet(i+1, UnifiedReal.PI);
Hans Boehm84614952014-11-25 18:46:17 -0800718 case R.id.const_e:
Hans Boehm995e5eb2016-02-08 11:03:01 -0800719 return new EvalRet(i+1, UnifiedReal.E);
Hans Boehm84614952014-11-25 18:46:17 -0800720 case R.id.op_sqrt:
Hans Boehmfbcef702015-04-27 18:07:47 -0700721 // Seems to have highest precedence.
722 // Does not add implicit paren.
723 // Does seem to accept a leading minus.
Hans Boehmc023b732015-04-29 11:30:47 -0700724 if (isOperator(i+1, R.id.op_sub, ec)) {
Hans Boehmfbcef702015-04-27 18:07:47 -0700725 argVal = evalUnary(i+2, ec);
Hans Boehm995e5eb2016-02-08 11:03:01 -0800726 return new EvalRet(argVal.pos, argVal.val.negate().sqrt());
Hans Boehmfbcef702015-04-27 18:07:47 -0700727 } else {
728 argVal = evalUnary(i+1, ec);
Hans Boehm995e5eb2016-02-08 11:03:01 -0800729 return new EvalRet(argVal.pos, argVal.val.sqrt());
Hans Boehmfbcef702015-04-27 18:07:47 -0700730 }
Hans Boehm84614952014-11-25 18:46:17 -0800731 case R.id.lparen:
732 argVal = evalExpr(i+1, ec);
Hans Boehm3666e632015-07-27 18:33:12 -0700733 if (isOperator(argVal.pos, R.id.rparen, ec)) {
734 argVal.pos++;
735 }
Hans Boehm995e5eb2016-02-08 11:03:01 -0800736 return new EvalRet(argVal.pos, argVal.val);
Hans Boehm84614952014-11-25 18:46:17 -0800737 case R.id.fun_sin:
738 argVal = evalExpr(i+1, ec);
Hans Boehm3666e632015-07-27 18:33:12 -0700739 if (isOperator(argVal.pos, R.id.rparen, ec)) {
740 argVal.pos++;
741 }
Hans Boehm995e5eb2016-02-08 11:03:01 -0800742 return new EvalRet(argVal.pos, toRadians(argVal.val, ec).sin());
Hans Boehm84614952014-11-25 18:46:17 -0800743 case R.id.fun_cos:
744 argVal = evalExpr(i+1, ec);
Hans Boehm3666e632015-07-27 18:33:12 -0700745 if (isOperator(argVal.pos, R.id.rparen, ec)) {
746 argVal.pos++;
747 }
Hans Boehm995e5eb2016-02-08 11:03:01 -0800748 return new EvalRet(argVal.pos, toRadians(argVal.val,ec).cos());
Hans Boehm84614952014-11-25 18:46:17 -0800749 case R.id.fun_tan:
750 argVal = evalExpr(i+1, ec);
Hans Boehm3666e632015-07-27 18:33:12 -0700751 if (isOperator(argVal.pos, R.id.rparen, ec)) {
752 argVal.pos++;
753 }
Hans Boehm995e5eb2016-02-08 11:03:01 -0800754 UnifiedReal arg = toRadians(argVal.val, ec);
755 return new EvalRet(argVal.pos, arg.sin().divide(arg.cos()));
Hans Boehm84614952014-11-25 18:46:17 -0800756 case R.id.fun_ln:
757 argVal = evalExpr(i+1, ec);
Hans Boehm3666e632015-07-27 18:33:12 -0700758 if (isOperator(argVal.pos, R.id.rparen, ec)) {
759 argVal.pos++;
760 }
Hans Boehm995e5eb2016-02-08 11:03:01 -0800761 return new EvalRet(argVal.pos, argVal.val.ln());
Hans Boehm4db31b42015-05-31 12:19:05 -0700762 case R.id.fun_exp:
763 argVal = evalExpr(i+1, ec);
Hans Boehm3666e632015-07-27 18:33:12 -0700764 if (isOperator(argVal.pos, R.id.rparen, ec)) {
765 argVal.pos++;
766 }
Hans Boehm995e5eb2016-02-08 11:03:01 -0800767 return new EvalRet(argVal.pos, argVal.val.exp());
Hans Boehm84614952014-11-25 18:46:17 -0800768 case R.id.fun_log:
769 argVal = evalExpr(i+1, ec);
Hans Boehm3666e632015-07-27 18:33:12 -0700770 if (isOperator(argVal.pos, R.id.rparen, ec)) {
771 argVal.pos++;
772 }
Hans Boehm995e5eb2016-02-08 11:03:01 -0800773 return new EvalRet(argVal.pos, argVal.val.ln().divide(UnifiedReal.TEN.ln()));
Hans Boehm84614952014-11-25 18:46:17 -0800774 case R.id.fun_arcsin:
775 argVal = evalExpr(i+1, ec);
Hans Boehm3666e632015-07-27 18:33:12 -0700776 if (isOperator(argVal.pos, R.id.rparen, ec)) {
777 argVal.pos++;
778 }
Hans Boehm995e5eb2016-02-08 11:03:01 -0800779 return new EvalRet(argVal.pos, fromRadians(argVal.val.asin(), ec));
Hans Boehm84614952014-11-25 18:46:17 -0800780 case R.id.fun_arccos:
781 argVal = evalExpr(i+1, ec);
Hans Boehm3666e632015-07-27 18:33:12 -0700782 if (isOperator(argVal.pos, R.id.rparen, ec)) {
783 argVal.pos++;
784 }
Hans Boehm79f273c2016-06-09 11:00:27 -0700785 return new EvalRet(argVal.pos, fromRadians(argVal.val.acos(), ec));
Hans Boehm84614952014-11-25 18:46:17 -0800786 case R.id.fun_arctan:
787 argVal = evalExpr(i+1, ec);
Hans Boehm3666e632015-07-27 18:33:12 -0700788 if (isOperator(argVal.pos, R.id.rparen, ec)) {
789 argVal.pos++;
790 }
Hans Boehm995e5eb2016-02-08 11:03:01 -0800791 return new EvalRet(argVal.pos, fromRadians(argVal.val.atan(),ec));
Hans Boehm84614952014-11-25 18:46:17 -0800792 default:
Hans Boehmc023b732015-04-29 11:30:47 -0700793 throw new SyntaxException("Unrecognized token in expression");
Hans Boehm84614952014-11-25 18:46:17 -0800794 }
Hans Boehm84614952014-11-25 18:46:17 -0800795 }
796
Hans Boehm995e5eb2016-02-08 11:03:01 -0800797 private static final UnifiedReal ONE_HUNDREDTH = new UnifiedReal(100).inverse();
Hans Boehm682ff5e2015-03-09 14:40:25 -0700798
Hans Boehm4db31b42015-05-31 12:19:05 -0700799 private EvalRet evalSuffix(int i, EvalContext ec) throws SyntaxException {
Hans Boehm3666e632015-07-27 18:33:12 -0700800 final EvalRet tmp = evalUnary(i, ec);
801 int cpos = tmp.pos;
Hans Boehm995e5eb2016-02-08 11:03:01 -0800802 UnifiedReal val = tmp.val;
803
Hans Boehm4db31b42015-05-31 12:19:05 -0700804 boolean isFact;
805 boolean isSquared = false;
806 while ((isFact = isOperator(cpos, R.id.op_fact, ec)) ||
807 (isSquared = isOperator(cpos, R.id.op_sqr, ec)) ||
808 isOperator(cpos, R.id.op_pct, ec)) {
809 if (isFact) {
Hans Boehm995e5eb2016-02-08 11:03:01 -0800810 val = val.fact();
Hans Boehm4db31b42015-05-31 12:19:05 -0700811 } else if (isSquared) {
Hans Boehm995e5eb2016-02-08 11:03:01 -0800812 val = val.multiply(val);
Hans Boehm4db31b42015-05-31 12:19:05 -0700813 } else /* percent */ {
Hans Boehm995e5eb2016-02-08 11:03:01 -0800814 val = val.multiply(ONE_HUNDREDTH);
Hans Boehm84614952014-11-25 18:46:17 -0800815 }
Hans Boehm84614952014-11-25 18:46:17 -0800816 ++cpos;
817 }
Hans Boehm995e5eb2016-02-08 11:03:01 -0800818 return new EvalRet(cpos, val);
Hans Boehm84614952014-11-25 18:46:17 -0800819 }
820
Hans Boehmc023b732015-04-29 11:30:47 -0700821 private EvalRet evalFactor(int i, EvalContext ec) throws SyntaxException {
Hans Boehm4db31b42015-05-31 12:19:05 -0700822 final EvalRet result1 = evalSuffix(i, ec);
Hans Boehm3666e632015-07-27 18:33:12 -0700823 int cpos = result1.pos; // current position
Hans Boehm995e5eb2016-02-08 11:03:01 -0800824 UnifiedReal val = result1.val; // value so far
Hans Boehmc023b732015-04-29 11:30:47 -0700825 if (isOperator(cpos, R.id.op_pow, ec)) {
Hans Boehm3666e632015-07-27 18:33:12 -0700826 final EvalRet exp = evalSignedFactor(cpos + 1, ec);
827 cpos = exp.pos;
Hans Boehm995e5eb2016-02-08 11:03:01 -0800828 val = val.pow(exp.val);
Hans Boehm84614952014-11-25 18:46:17 -0800829 }
Hans Boehm995e5eb2016-02-08 11:03:01 -0800830 return new EvalRet(cpos, val);
Hans Boehm84614952014-11-25 18:46:17 -0800831 }
832
Hans Boehmc023b732015-04-29 11:30:47 -0700833 private EvalRet evalSignedFactor(int i, EvalContext ec) throws SyntaxException {
834 final boolean negative = isOperator(i, R.id.op_sub, ec);
Hans Boehm08e8f322015-04-21 13:18:38 -0700835 int cpos = negative ? i + 1 : i;
Hans Boehm84614952014-11-25 18:46:17 -0800836 EvalRet tmp = evalFactor(cpos, ec);
Hans Boehm3666e632015-07-27 18:33:12 -0700837 cpos = tmp.pos;
Hans Boehm995e5eb2016-02-08 11:03:01 -0800838 final UnifiedReal result = negative ? tmp.val.negate() : tmp.val;
839 return new EvalRet(cpos, result);
Hans Boehm84614952014-11-25 18:46:17 -0800840 }
841
842 private boolean canStartFactor(int i) {
843 if (i >= mExpr.size()) return false;
844 Token t = mExpr.get(i);
845 if (!(t instanceof Operator)) return true;
Hans Boehm3666e632015-07-27 18:33:12 -0700846 int id = ((Operator)(t)).id;
Hans Boehm84614952014-11-25 18:46:17 -0800847 if (KeyMaps.isBinary(id)) return false;
848 switch (id) {
849 case R.id.op_fact:
850 case R.id.rparen:
851 return false;
852 default:
853 return true;
854 }
855 }
856
Hans Boehmc023b732015-04-29 11:30:47 -0700857 private EvalRet evalTerm(int i, EvalContext ec) throws SyntaxException {
Hans Boehm84614952014-11-25 18:46:17 -0800858 EvalRet tmp = evalSignedFactor(i, ec);
859 boolean is_mul = false;
860 boolean is_div = false;
Hans Boehm3666e632015-07-27 18:33:12 -0700861 int cpos = tmp.pos; // Current position in expression.
Hans Boehm995e5eb2016-02-08 11:03:01 -0800862 UnifiedReal val = tmp.val; // Current value.
Hans Boehmc023b732015-04-29 11:30:47 -0700863 while ((is_mul = isOperator(cpos, R.id.op_mul, ec))
864 || (is_div = isOperator(cpos, R.id.op_div, ec))
Hans Boehm84614952014-11-25 18:46:17 -0800865 || canStartFactor(cpos)) {
866 if (is_mul || is_div) ++cpos;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700867 tmp = evalSignedFactor(cpos, ec);
Hans Boehm84614952014-11-25 18:46:17 -0800868 if (is_div) {
Hans Boehm995e5eb2016-02-08 11:03:01 -0800869 val = val.divide(tmp.val);
Hans Boehm84614952014-11-25 18:46:17 -0800870 } else {
Hans Boehm995e5eb2016-02-08 11:03:01 -0800871 val = val.multiply(tmp.val);
Hans Boehm84614952014-11-25 18:46:17 -0800872 }
Hans Boehm3666e632015-07-27 18:33:12 -0700873 cpos = tmp.pos;
Hans Boehm84614952014-11-25 18:46:17 -0800874 is_mul = is_div = false;
875 }
Hans Boehm995e5eb2016-02-08 11:03:01 -0800876 return new EvalRet(cpos, val);
Hans Boehm84614952014-11-25 18:46:17 -0800877 }
878
Hans Boehm8afd0f82015-07-30 17:00:33 -0700879 /**
880 * Is the subexpression starting at pos a simple percent constant?
881 * This is used to recognize exppressions like 200+10%, which we handle specially.
882 * This is defined as a Constant or PreEval token, followed by a percent sign, and followed
883 * by either nothing or an additive operator.
884 * Note that we are intentionally far more restrictive in recognizing such expressions than
885 * e.g. http://blogs.msdn.com/b/oldnewthing/archive/2008/01/10/7047497.aspx .
886 * When in doubt, we fall back to the the naive interpretation of % as 1/100.
887 * Note that 100+(10)% yields 100.1 while 100+10% yields 110. This may be controversial,
888 * but is consistent with Google web search.
889 */
890 private boolean isPercent(int pos) {
891 if (mExpr.size() < pos + 2 || !isOperatorUnchecked(pos + 1, R.id.op_pct)) {
892 return false;
893 }
894 Token number = mExpr.get(pos);
895 if (number instanceof Operator) {
896 return false;
897 }
898 if (mExpr.size() == pos + 2) {
899 return true;
900 }
901 if (!(mExpr.get(pos + 2) instanceof Operator)) {
902 return false;
903 }
904 Operator op = (Operator) mExpr.get(pos + 2);
Hans Boehm64d1cdb2016-03-08 19:14:07 -0800905 return op.id == R.id.op_add || op.id == R.id.op_sub || op.id == R.id.rparen;
Hans Boehm8afd0f82015-07-30 17:00:33 -0700906 }
907
908 /**
909 * Compute the multiplicative factor corresponding to an N% addition or subtraction.
Hans Boehm995e5eb2016-02-08 11:03:01 -0800910 * @param pos position of Constant or PreEval expression token corresponding to N.
911 * @param isSubtraction this is a subtraction, as opposed to addition.
912 * @param ec usable evaluation contex; only length matters.
913 * @return UnifiedReal value and position, which is pos + 2, i.e. after percent sign
Hans Boehm8afd0f82015-07-30 17:00:33 -0700914 */
915 private EvalRet getPercentFactor(int pos, boolean isSubtraction, EvalContext ec)
916 throws SyntaxException {
917 EvalRet tmp = evalUnary(pos, ec);
Hans Boehm995e5eb2016-02-08 11:03:01 -0800918 UnifiedReal val = isSubtraction ? tmp.val.negate() : tmp.val;
919 val = UnifiedReal.ONE.add(val.multiply(ONE_HUNDREDTH));
920 return new EvalRet(pos + 2 /* after percent sign */, val);
Hans Boehm8afd0f82015-07-30 17:00:33 -0700921 }
922
Hans Boehmc023b732015-04-29 11:30:47 -0700923 private EvalRet evalExpr(int i, EvalContext ec) throws SyntaxException {
Hans Boehm84614952014-11-25 18:46:17 -0800924 EvalRet tmp = evalTerm(i, ec);
925 boolean is_plus;
Hans Boehm3666e632015-07-27 18:33:12 -0700926 int cpos = tmp.pos;
Hans Boehm995e5eb2016-02-08 11:03:01 -0800927 UnifiedReal val = tmp.val;
Hans Boehmc023b732015-04-29 11:30:47 -0700928 while ((is_plus = isOperator(cpos, R.id.op_add, ec))
929 || isOperator(cpos, R.id.op_sub, ec)) {
Hans Boehm8afd0f82015-07-30 17:00:33 -0700930 if (isPercent(cpos + 1)) {
931 tmp = getPercentFactor(cpos + 1, !is_plus, ec);
Hans Boehm995e5eb2016-02-08 11:03:01 -0800932 val = val.multiply(tmp.val);
Hans Boehm84614952014-11-25 18:46:17 -0800933 } else {
Hans Boehm8afd0f82015-07-30 17:00:33 -0700934 tmp = evalTerm(cpos + 1, ec);
935 if (is_plus) {
Hans Boehm995e5eb2016-02-08 11:03:01 -0800936 val = val.add(tmp.val);
Hans Boehm682ff5e2015-03-09 14:40:25 -0700937 } else {
Hans Boehm995e5eb2016-02-08 11:03:01 -0800938 val = val.subtract(tmp.val);
Hans Boehm84614952014-11-25 18:46:17 -0800939 }
940 }
Hans Boehm3666e632015-07-27 18:33:12 -0700941 cpos = tmp.pos;
Hans Boehm84614952014-11-25 18:46:17 -0800942 }
Hans Boehm995e5eb2016-02-08 11:03:01 -0800943 return new EvalRet(cpos, val);
Hans Boehm84614952014-11-25 18:46:17 -0800944 }
945
Hans Boehme8553762015-06-26 17:56:52 -0700946 /**
947 * Return the starting position of the sequence of trailing binary operators.
948 */
949 private int trailingBinaryOpsStart() {
Hans Boehmc023b732015-04-29 11:30:47 -0700950 int result = mExpr.size();
951 while (result > 0) {
952 Token last = mExpr.get(result - 1);
953 if (!(last instanceof Operator)) break;
954 Operator o = (Operator)last;
Hans Boehm3666e632015-07-27 18:33:12 -0700955 if (!KeyMaps.isBinary(o.id)) break;
Hans Boehmc023b732015-04-29 11:30:47 -0700956 --result;
957 }
958 return result;
959 }
960
Hans Boehm3666e632015-07-27 18:33:12 -0700961 /**
962 * Is the current expression worth evaluating?
963 */
Hans Boehmc023b732015-04-29 11:30:47 -0700964 public boolean hasInterestingOps() {
Hans Boehme8553762015-06-26 17:56:52 -0700965 int last = trailingBinaryOpsStart();
Hans Boehmc023b732015-04-29 11:30:47 -0700966 int first = 0;
967 if (last > first && isOperatorUnchecked(first, R.id.op_sub)) {
968 // Leading minus is not by itself interesting.
969 first++;
970 }
971 for (int i = first; i < last; ++i) {
972 Token t1 = mExpr.get(i);
Hans Boehm187d3e92015-06-09 18:04:26 -0700973 if (t1 instanceof Operator
974 || t1 instanceof PreEval && ((PreEval)t1).hasEllipsis()) {
975 return true;
976 }
Hans Boehmc023b732015-04-29 11:30:47 -0700977 }
978 return false;
979 }
980
Hans Boehme8553762015-06-26 17:56:52 -0700981 /**
Hans Boehm52d477a2016-04-01 17:42:50 -0700982 * Does the expression contain trig operations?
983 */
984 public boolean hasTrigFuncs() {
985 for (Token t: mExpr) {
986 if (t instanceof Operator) {
987 Operator o = (Operator)t;
988 if (KeyMaps.isTrigFunc(o.id)) {
989 return true;
990 }
991 }
992 }
993 return false;
994 }
995
996 /**
Hans Boehme8553762015-06-26 17:56:52 -0700997 * Evaluate the expression excluding trailing binary operators.
Hans Boehm3666e632015-07-27 18:33:12 -0700998 * Errors result in exceptions, most of which are unchecked. Should not be called
999 * concurrently with modification of the expression. May take a very long time; avoid calling
1000 * from UI thread.
Hans Boehme8553762015-06-26 17:56:52 -07001001 *
1002 * @param degreeMode use degrees rather than radians
1003 */
Hans Boehm8f051c32016-10-03 16:53:58 -07001004 UnifiedReal eval(boolean degreeMode, ExprResolver er) throws SyntaxException
Hans Boehm995e5eb2016-02-08 11:03:01 -08001005 // And unchecked exceptions thrown by UnifiedReal, CR,
Hans Boehmc023b732015-04-29 11:30:47 -07001006 // and BoundedRational.
Hans Boehm84614952014-11-25 18:46:17 -08001007 {
1008 try {
Hans Boehm3666e632015-07-27 18:33:12 -07001009 // We currently never include trailing binary operators, but include other trailing
1010 // operators. Thus we usually, but not always, display results for prefixes of valid
1011 // expressions, and don't generate an error where we previously displayed an instant
1012 // result. This reflects the Android L design.
Hans Boehme8553762015-06-26 17:56:52 -07001013 int prefixLen = trailingBinaryOpsStart();
Hans Boehm8f051c32016-10-03 16:53:58 -07001014 EvalContext ec = new EvalContext(degreeMode, prefixLen, er);
Hans Boehm84614952014-11-25 18:46:17 -08001015 EvalRet res = evalExpr(0, ec);
Hans Boehm3666e632015-07-27 18:33:12 -07001016 if (res.pos != prefixLen) {
Hans Boehmc023b732015-04-29 11:30:47 -07001017 throw new SyntaxException("Failed to parse full expression");
Hans Boehmfbcef702015-04-27 18:07:47 -07001018 }
Hans Boehm995e5eb2016-02-08 11:03:01 -08001019 return res.val;
Hans Boehm84614952014-11-25 18:46:17 -08001020 } catch (IndexOutOfBoundsException e) {
Hans Boehmc023b732015-04-29 11:30:47 -07001021 throw new SyntaxException("Unexpected expression end");
Hans Boehm84614952014-11-25 18:46:17 -08001022 }
1023 }
1024
1025 // Produce a string representation of the expression itself
Hans Boehm8a4f81c2015-07-09 10:41:25 -07001026 SpannableStringBuilder toSpannableStringBuilder(Context context) {
1027 SpannableStringBuilder ssb = new SpannableStringBuilder();
Hans Boehm84614952014-11-25 18:46:17 -08001028 for (Token t: mExpr) {
Hans Boehm8a4f81c2015-07-09 10:41:25 -07001029 ssb.append(t.toCharSequence(context));
Hans Boehm84614952014-11-25 18:46:17 -08001030 }
Hans Boehm8a4f81c2015-07-09 10:41:25 -07001031 return ssb;
Hans Boehm84614952014-11-25 18:46:17 -08001032 }
1033}