blob: 06aa264d628d717ab76b37312a59d24ad43a1a4f [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 Boehm9c160b42016-12-02 11:55:12 -080030import java.util.Collections;
31import java.util.HashSet;
Hans Boehm4a6b7cb2015-04-03 18:41:52 -070032
Hans Boehm3666e632015-07-27 18:33:12 -070033/**
34 * A mathematical expression represented as a sequence of "tokens".
35 * Many tokens are represented by button ids for the corresponding operator.
36 * A token may also represent the result of a previously evaluated expression.
37 * The add() method adds a token to the end of the expression. The delete method() removes one.
38 * Clear() deletes the entire expression contents. Eval() evaluates the expression,
Hans Boehm995e5eb2016-02-08 11:03:01 -080039 * producing a UnifiedReal result.
Hans Boehm3666e632015-07-27 18:33:12 -070040 * Expressions are parsed only during evaluation; no explicit parse tree is maintained.
41 *
Hans Boehm995e5eb2016-02-08 11:03:01 -080042 * The write() method is used to save the current expression. Note that neither UnifiedReal
43 * nor the underlying CR provide a serialization facility. Thus we save all previously
44 * computed values by writing out the expression that was used to compute them, and reevaluate
45 * when reading it back in.
Hans Boehm3666e632015-07-27 18:33:12 -070046 */
Hans Boehm84614952014-11-25 18:46:17 -080047class CalculatorExpr {
Hans Boehm8f051c32016-10-03 16:53:58 -070048 /**
49 * An interface for resolving expression indices in embedded subexpressions to
50 * the associated CalculatorExpr, and associating a UnifiedReal result with it.
51 * All methods are thread-safe in the strong sense; they may be called asynchronously
52 * at any time from any thread.
53 */
54 public interface ExprResolver {
55 /*
56 * Retrieve the expression corresponding to index.
57 */
58 CalculatorExpr getExpr(long index);
59 /*
Hans Boehm9c160b42016-12-02 11:55:12 -080060 * Retrieve the degree mode associated with the expression at index i.
Hans Boehm8f051c32016-10-03 16:53:58 -070061 */
62 boolean getDegreeMode(long index);
63 /*
64 * Retrieve the stored result for the expression at index, or return null.
65 */
66 UnifiedReal getResult(long index);
67 /*
68 * Atomically test for an existing result, and set it if there was none.
69 * Return the prior result if there was one, or the new one if there was not.
70 * May only be called after getExpr.
71 */
72 UnifiedReal putResultIfAbsent(long index, UnifiedReal result);
73 // FIXME: Check that long timeouts for embedded expressions are propagated
74 // correctly.
75 }
76
Hans Boehm84614952014-11-25 18:46:17 -080077 private ArrayList<Token> mExpr; // The actual representation
78 // as a list of tokens. Constant
79 // tokens are always nonempty.
80
81 private static enum TokenKind { CONSTANT, OPERATOR, PRE_EVAL };
82 private static TokenKind[] tokenKindValues = TokenKind.values();
83 private final static BigInteger BIG_MILLION = BigInteger.valueOf(1000000);
84 private final static BigInteger BIG_BILLION = BigInteger.valueOf(1000000000);
85
86 private static abstract class Token {
87 abstract TokenKind kind();
Hans Boehm8a4f81c2015-07-09 10:41:25 -070088
89 /**
Hans Boehm8f051c32016-10-03 16:53:58 -070090 * Write token as either a very small Byte containing the TokenKind,
91 * followed by data needed by subclass constructor,
92 * or as a byte >= 0x20 directly describing the OPERATOR token.
Hans Boehm8a4f81c2015-07-09 10:41:25 -070093 */
Hans Boehm84614952014-11-25 18:46:17 -080094 abstract void write(DataOutput out) throws IOException;
Hans Boehm8a4f81c2015-07-09 10:41:25 -070095
96 /**
97 * Return a textual representation of the token.
98 * The result is suitable for either display as part od the formula or TalkBack use.
99 * It may be a SpannableString that includes added TalkBack information.
100 * @param context context used for converting button ids to strings
101 */
102 abstract CharSequence toCharSequence(Context context);
Hans Boehm84614952014-11-25 18:46:17 -0800103 }
104
Hans Boehm3666e632015-07-27 18:33:12 -0700105 /**
106 * Representation of an operator token
107 */
Hans Boehm84614952014-11-25 18:46:17 -0800108 private static class Operator extends Token {
Hans Boehm8f051c32016-10-03 16:53:58 -0700109 // TODO: rename id.
Hans Boehm3666e632015-07-27 18:33:12 -0700110 public final int id; // We use the button resource id
Hans Boehm84614952014-11-25 18:46:17 -0800111 Operator(int resId) {
Hans Boehm3666e632015-07-27 18:33:12 -0700112 id = resId;
Hans Boehm84614952014-11-25 18:46:17 -0800113 }
Hans Boehm8f051c32016-10-03 16:53:58 -0700114 Operator(byte op) throws IOException {
115 id = KeyMaps.fromByte(op);
Hans Boehm84614952014-11-25 18:46:17 -0800116 }
117 @Override
118 void write(DataOutput out) throws IOException {
Hans Boehm8f051c32016-10-03 16:53:58 -0700119 out.writeByte(KeyMaps.toByte(id));
Hans Boehm84614952014-11-25 18:46:17 -0800120 }
121 @Override
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700122 public CharSequence toCharSequence(Context context) {
Hans Boehm3666e632015-07-27 18:33:12 -0700123 String desc = KeyMaps.toDescriptiveString(context, id);
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700124 if (desc != null) {
Hans Boehm3666e632015-07-27 18:33:12 -0700125 SpannableString result = new SpannableString(KeyMaps.toString(context, id));
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700126 Object descSpan = new TtsSpan.TextBuilder(desc).build();
127 result.setSpan(descSpan, 0, result.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
128 return result;
129 } else {
Hans Boehm3666e632015-07-27 18:33:12 -0700130 return KeyMaps.toString(context, id);
Hans Boehm8a4f81c2015-07-09 10:41:25 -0700131 }
Hans Boehm84614952014-11-25 18:46:17 -0800132 }
133 @Override
134 TokenKind kind() { return TokenKind.OPERATOR; }
135 }
136
Hans Boehm3666e632015-07-27 18:33:12 -0700137 /**
138 * Representation of a (possibly incomplete) numerical constant.
139 * Supports addition and removal of trailing characters; hence mutable.
140 */
Hans Boehm84614952014-11-25 18:46:17 -0800141 private static class Constant extends Token implements Cloneable {
142 private boolean mSawDecimal;
Hans Boehm3666e632015-07-27 18:33:12 -0700143 private String mWhole; // String preceding decimal point.
Hans Boehm0b9806f2015-06-29 16:07:15 -0700144 private String mFraction; // String after decimal point.
145 private int mExponent; // Explicit exponent, only generated through addExponent.
Hans Boehm8f051c32016-10-03 16:53:58 -0700146 private static int SAW_DECIMAL = 0x1;
147 private static int HAS_EXPONENT = 0x2;
Hans Boehm84614952014-11-25 18:46:17 -0800148
149 Constant() {
150 mWhole = "";
151 mFraction = "";
Hans Boehm8f051c32016-10-03 16:53:58 -0700152 // mSawDecimal = false;
153 // mExponent = 0;
Hans Boehm84614952014-11-25 18:46:17 -0800154 };
155
156 Constant(DataInput in) throws IOException {
157 mWhole = in.readUTF();
Hans Boehm8f051c32016-10-03 16:53:58 -0700158 byte flags = in.readByte();
159 if ((flags & SAW_DECIMAL) != 0) {
160 mSawDecimal = true;
161 mFraction = in.readUTF();
162 } else {
163 // mSawDecimal = false;
164 mFraction = "";
165 }
166 if ((flags & HAS_EXPONENT) != 0) {
167 mExponent = in.readInt();
168 }
Hans Boehm84614952014-11-25 18:46:17 -0800169 }
170
171 @Override
172 void write(DataOutput out) throws IOException {
Hans Boehm8f051c32016-10-03 16:53:58 -0700173 byte flags = (byte)((mSawDecimal ? SAW_DECIMAL : 0)
174 | (mExponent != 0 ? HAS_EXPONENT : 0));
Hans Boehm84614952014-11-25 18:46:17 -0800175 out.writeByte(TokenKind.CONSTANT.ordinal());
176 out.writeUTF(mWhole);
Hans Boehm8f051c32016-10-03 16:53:58 -0700177 out.writeByte(flags);
178 if (mSawDecimal) {
179 out.writeUTF(mFraction);
180 }
181 if (mExponent != 0) {
182 out.writeInt(mExponent);
183 }
Hans Boehm84614952014-11-25 18:46:17 -0800184 }
185
186 // Given a button press, append corresponding digit.
187 // We assume id is a digit or decimal point.
188 // Just return false if this was the second (or later) decimal point
189 // in this constant.
Hans Boehm0b9806f2015-06-29 16:07:15 -0700190 // Assumes that this constant does not have an exponent.
Hans Boehm3666e632015-07-27 18:33:12 -0700191 public boolean add(int id) {
Hans Boehm84614952014-11-25 18:46:17 -0800192 if (id == R.id.dec_point) {
Hans Boehm0b9806f2015-06-29 16:07:15 -0700193 if (mSawDecimal || mExponent != 0) return false;
Hans Boehm84614952014-11-25 18:46:17 -0800194 mSawDecimal = true;
195 return true;
196 }
197 int val = KeyMaps.digVal(id);
Hans Boehm0b9806f2015-06-29 16:07:15 -0700198 if (mExponent != 0) {
199 if (Math.abs(mExponent) <= 10000) {
200 if (mExponent > 0) {
201 mExponent = 10 * mExponent + val;
202 } else {
203 mExponent = 10 * mExponent - val;
204 }
205 return true;
206 } else { // Too large; refuse
207 return false;
208 }
209 }
Hans Boehm84614952014-11-25 18:46:17 -0800210 if (mSawDecimal) {
211 mFraction += val;
212 } else {
213 mWhole += val;
214 }
215 return true;
216 }
217
Hans Boehm3666e632015-07-27 18:33:12 -0700218 public void addExponent(int exp) {
Hans Boehm0b9806f2015-06-29 16:07:15 -0700219 // Note that adding a 0 exponent is a no-op. That's OK.
220 mExponent = exp;
221 }
222
Hans Boehm3666e632015-07-27 18:33:12 -0700223 /**
224 * Undo the last add or remove last exponent digit.
225 * Assumes the constant is nonempty.
226 */
227 public void delete() {
Hans Boehm0b9806f2015-06-29 16:07:15 -0700228 if (mExponent != 0) {
229 mExponent /= 10;
230 // Once zero, it can only be added back with addExponent.
231 } else if (!mFraction.isEmpty()) {
Hans Boehm84614952014-11-25 18:46:17 -0800232 mFraction = mFraction.substring(0, mFraction.length() - 1);
233 } else if (mSawDecimal) {
234 mSawDecimal = false;
235 } else {
236 mWhole = mWhole.substring(0, mWhole.length() - 1);
237 }
238 }
239
Hans Boehm3666e632015-07-27 18:33:12 -0700240 public boolean isEmpty() {
Hans Boehm84614952014-11-25 18:46:17 -0800241 return (mSawDecimal == false && mWhole.isEmpty());
242 }
243
Hans Boehm3666e632015-07-27 18:33:12 -0700244 /**
245 * Produce human-readable string representation of constant, as typed.
Hans Boehm24c91ed2016-06-30 18:53:44 -0700246 * We do add digit grouping separators to the whole number, even if not typed.
Hans Boehm3666e632015-07-27 18:33:12 -0700247 * Result is internationalized.
248 */
Hans Boehm84614952014-11-25 18:46:17 -0800249 @Override
250 public String toString() {
Hans Boehm24c91ed2016-06-30 18:53:44 -0700251 String result;
252 if (mExponent != 0) {
253 result = mWhole;
254 } else {
255 result = StringUtils.addCommas(mWhole, 0, mWhole.length());
256 }
Hans Boehm84614952014-11-25 18:46:17 -0800257 if (mSawDecimal) {
Hans Boehm013969e2015-04-13 20:29:47 -0700258 result += '.';
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700259 result += mFraction;
260 }
Hans Boehm0b9806f2015-06-29 16:07:15 -0700261 if (mExponent != 0) {
262 result += "E" + mExponent;
263 }
Hans Boehm013969e2015-04-13 20:29:47 -0700264 return KeyMaps.translateResult(result);
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700265 }
266
Hans Boehm3666e632015-07-27 18:33:12 -0700267 /**
Hans Boehmfa5203c2015-08-17 16:14:52 -0700268 * Return BoundedRational representation of constant, if well-formed.
269 * Result is never null.
Hans Boehm3666e632015-07-27 18:33:12 -0700270 */
Hans Boehmfa5203c2015-08-17 16:14:52 -0700271 public BoundedRational toRational() throws SyntaxException {
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700272 String whole = mWhole;
Hans Boehmfa5203c2015-08-17 16:14:52 -0700273 if (whole.isEmpty()) {
274 if (mFraction.isEmpty()) {
275 // Decimal point without digits.
276 throw new SyntaxException();
277 } else {
278 whole = "0";
279 }
280 }
Hans Boehm4a6b7cb2015-04-03 18:41:52 -0700281 BigInteger num = new BigInteger(whole + mFraction);
Hans Boehm682ff5e2015-03-09 14:40:25 -0700282 BigInteger den = BigInteger.TEN.pow(mFraction.length());
Hans Boehm0b9806f2015-06-29 16:07:15 -0700283 if (mExponent > 0) {
284 num = num.multiply(BigInteger.TEN.pow(mExponent));
285 }
286 if (mExponent < 0) {
287 den = den.multiply(BigInteger.TEN.pow(-mExponent));
288 }
Hans Boehm682ff5e2015-03-09 14:40:25 -0700289 return new BoundedRational(num, den);
290 }
291
Hans Boehm84614952014-11-25 18:46:17 -0800292 @Override
Hans Boehm3666e632015-07-27 18:33:12 -0700293 public CharSequence toCharSequence(Context context) {
Hans Boehm84614952014-11-25 18:46:17 -0800294 return toString();
295 }
296
297 @Override
Hans Boehm3666e632015-07-27 18:33:12 -0700298 public TokenKind kind() {
299 return TokenKind.CONSTANT;
300 }
Hans Boehm84614952014-11-25 18:46:17 -0800301
302 // Override clone to make it public
303 @Override
304 public Object clone() {
Hans Boehm3666e632015-07-27 18:33:12 -0700305 Constant result = new Constant();
306 result.mWhole = mWhole;
307 result.mFraction = mFraction;
308 result.mSawDecimal = mSawDecimal;
309 result.mExponent = mExponent;
310 return result;
Hans Boehm84614952014-11-25 18:46:17 -0800311 }
312 }
313
Hans Boehm3666e632015-07-27 18:33:12 -0700314 /**
315 * The "token" class for previously evaluated subexpressions.
316 * We treat previously evaluated subexpressions as tokens. These are inserted when we either
317 * continue an expression after evaluating some of it, or copy an expression and paste it back
318 * in.
Hans Boehm8f051c32016-10-03 16:53:58 -0700319 * This only contains enough information to allow us to display the expression in a
320 * formula, or reevaluate the expression with the aid of an ExprResolver; we no longer
321 * cache the result. The expression corresponding to the index can be obtained through
322 * the ExprResolver, which looks it up in a subexpression database.
Hans Boehm995e5eb2016-02-08 11:03:01 -0800323 * The representation includes a UnifiedReal value. In order to
Hans Boehm3666e632015-07-27 18:33:12 -0700324 * support saving and restoring, we also include the underlying expression itself, and the
325 * context (currently just degree mode) used to evaluate it. The short string representation
326 * is also stored in order to avoid potentially expensive recomputation in the UI thread.
327 */
Hans Boehm84614952014-11-25 18:46:17 -0800328 private static class PreEval extends Token {
Hans Boehm8f051c32016-10-03 16:53:58 -0700329 public final long mIndex;
Hans Boehm50ed3202015-06-09 14:35:49 -0700330 private final String mShortRep; // Not internationalized.
Hans Boehm8f051c32016-10-03 16:53:58 -0700331 PreEval(long index, String shortRep) {
332 mIndex = index;
Hans Boehm84614952014-11-25 18:46:17 -0800333 mShortRep = shortRep;
334 }
Hans Boehm84614952014-11-25 18:46:17 -0800335 @Override
Hans Boehm8f051c32016-10-03 16:53:58 -0700336 // This writes out only a shallow representation of the result, without
337 // information about subexpressions. To write out a deep representation, we
338 // find referenced subexpressions, and iteratively write those as well.
Hans Boehm3666e632015-07-27 18:33:12 -0700339 public void write(DataOutput out) throws IOException {
Hans Boehm84614952014-11-25 18:46:17 -0800340 out.writeByte(TokenKind.PRE_EVAL.ordinal());
Hans Boehm8f051c32016-10-03 16:53:58 -0700341 if (mIndex > Integer.MAX_VALUE || mIndex < Integer.MIN_VALUE) {
342 // This would be millions of expressions per day for the life of the device.
343 throw new AssertionError("Expression index too big");
Hans Boehm84614952014-11-25 18:46:17 -0800344 }
Hans Boehm8f051c32016-10-03 16:53:58 -0700345 out.writeInt((int)mIndex);
346 out.writeUTF(mShortRep);
Hans Boehm84614952014-11-25 18:46:17 -0800347 }
348 PreEval(DataInput in) throws IOException {
Hans Boehm8f051c32016-10-03 16:53:58 -0700349 mIndex = in.readInt();
350 mShortRep = in.readUTF();
Hans Boehm84614952014-11-25 18:46:17 -0800351 }
352 @Override
Hans Boehm3666e632015-07-27 18:33:12 -0700353 public CharSequence toCharSequence(Context context) {
Hans Boehm50ed3202015-06-09 14:35:49 -0700354 return KeyMaps.translateResult(mShortRep);
Hans Boehm84614952014-11-25 18:46:17 -0800355 }
356 @Override
Hans Boehm3666e632015-07-27 18:33:12 -0700357 public TokenKind kind() {
Hans Boehm187d3e92015-06-09 18:04:26 -0700358 return TokenKind.PRE_EVAL;
359 }
Hans Boehm3666e632015-07-27 18:33:12 -0700360 public boolean hasEllipsis() {
Hans Boehm187d3e92015-06-09 18:04:26 -0700361 return mShortRep.lastIndexOf(KeyMaps.ELLIPSIS) != -1;
362 }
Hans Boehm84614952014-11-25 18:46:17 -0800363 }
364
Hans Boehm3666e632015-07-27 18:33:12 -0700365 /**
366 * Read token from in.
367 */
368 public static Token newToken(DataInput in) throws IOException {
Hans Boehm8f051c32016-10-03 16:53:58 -0700369 byte kindByte = in.readByte();
370 if (kindByte < 0x20) {
371 TokenKind kind = tokenKindValues[kindByte];
372 switch(kind) {
373 case CONSTANT:
374 return new Constant(in);
375 case PRE_EVAL:
376 return new PreEval(in);
377 default: throw new IOException("Bad save file format");
378 }
379 } else {
380 return new Operator(kindByte);
Hans Boehm84614952014-11-25 18:46:17 -0800381 }
382 }
383
384 CalculatorExpr() {
385 mExpr = new ArrayList<Token>();
386 }
387
388 private CalculatorExpr(ArrayList<Token> expr) {
389 mExpr = expr;
390 }
391
Hans Boehm3666e632015-07-27 18:33:12 -0700392 /**
393 * Construct CalculatorExpr, by reading it from in.
394 */
Hans Boehm84614952014-11-25 18:46:17 -0800395 CalculatorExpr(DataInput in) throws IOException {
396 mExpr = new ArrayList<Token>();
397 int size = in.readInt();
398 for (int i = 0; i < size; ++i) {
399 mExpr.add(newToken(in));
400 }
401 }
402
Hans Boehm3666e632015-07-27 18:33:12 -0700403 /**
404 * Write this expression to out.
405 */
406 public void write(DataOutput out) throws IOException {
Hans Boehm84614952014-11-25 18:46:17 -0800407 int size = mExpr.size();
408 out.writeInt(size);
409 for (int i = 0; i < size; ++i) {
410 mExpr.get(i).write(out);
411 }
412 }
413
Hans Boehm3666e632015-07-27 18:33:12 -0700414 /**
415 * Does this expression end with a numeric constant?
416 * As opposed to an operator or preevaluated expression.
417 */
Hans Boehm0b9806f2015-06-29 16:07:15 -0700418 boolean hasTrailingConstant() {
419 int s = mExpr.size();
420 if (s == 0) {
421 return false;
422 }
423 Token t = mExpr.get(s-1);
424 return t instanceof Constant;
425 }
426
Hans Boehm3666e632015-07-27 18:33:12 -0700427 /**
428 * Does this expression end with a binary operator?
429 */
Hans Boehm8f051c32016-10-03 16:53:58 -0700430 boolean hasTrailingBinary() {
Hans Boehm84614952014-11-25 18:46:17 -0800431 int s = mExpr.size();
432 if (s == 0) return false;
433 Token t = mExpr.get(s-1);
434 if (!(t instanceof Operator)) return false;
435 Operator o = (Operator)t;
Hans Boehm3666e632015-07-27 18:33:12 -0700436 return (KeyMaps.isBinary(o.id));
Hans Boehm84614952014-11-25 18:46:17 -0800437 }
438
Hans Boehm017de982015-06-10 17:46:03 -0700439 /**
440 * Append press of button with given id to expression.
441 * If the insertion would clearly result in a syntax error, either just return false
442 * and do nothing, or make an adjustment to avoid the problem. We do the latter only
443 * for unambiguous consecutive binary operators, in which case we delete the first
444 * operator.
445 */
Hans Boehm84614952014-11-25 18:46:17 -0800446 boolean add(int id) {
447 int s = mExpr.size();
Hans Boehm3666e632015-07-27 18:33:12 -0700448 final int d = KeyMaps.digVal(id);
449 final boolean binary = KeyMaps.isBinary(id);
Hans Boehm017de982015-06-10 17:46:03 -0700450 Token lastTok = s == 0 ? null : mExpr.get(s-1);
Hans Boehm3666e632015-07-27 18:33:12 -0700451 int lastOp = lastTok instanceof Operator ? ((Operator) lastTok).id : 0;
Hans Boehm017de982015-06-10 17:46:03 -0700452 // Quietly replace a trailing binary operator with another one, unless the second
453 // operator is minus, in which case we just allow it as a unary minus.
454 if (binary && !KeyMaps.isPrefix(id)) {
455 if (s == 0 || lastOp == R.id.lparen || KeyMaps.isFunc(lastOp)
456 || KeyMaps.isPrefix(lastOp) && lastOp != R.id.op_sub) {
457 return false;
458 }
459 while (hasTrailingBinary()) {
460 delete();
461 }
462 // s invalid and not used below.
Hans Boehm84614952014-11-25 18:46:17 -0800463 }
Hans Boehm3666e632015-07-27 18:33:12 -0700464 final boolean isConstPiece = (d != KeyMaps.NOT_DIGIT || id == R.id.dec_point);
Hans Boehm84614952014-11-25 18:46:17 -0800465 if (isConstPiece) {
Hans Boehm017de982015-06-10 17:46:03 -0700466 // Since we treat juxtaposition as multiplication, a constant can appear anywhere.
Hans Boehm84614952014-11-25 18:46:17 -0800467 if (s == 0) {
468 mExpr.add(new Constant());
469 s++;
470 } else {
471 Token last = mExpr.get(s-1);
472 if(!(last instanceof Constant)) {
Hans Boehm017de982015-06-10 17:46:03 -0700473 if (last instanceof PreEval) {
474 // Add explicit multiplication to avoid confusing display.
475 mExpr.add(new Operator(R.id.op_mul));
476 s++;
Hans Boehm84614952014-11-25 18:46:17 -0800477 }
478 mExpr.add(new Constant());
479 s++;
480 }
481 }
482 return ((Constant)(mExpr.get(s-1))).add(id);
483 } else {
484 mExpr.add(new Operator(id));
485 return true;
486 }
487 }
488
Hans Boehm017de982015-06-10 17:46:03 -0700489 /**
Hans Boehm0b9806f2015-06-29 16:07:15 -0700490 * Add exponent to the constant at the end of the expression.
491 * Assumes there is a constant at the end of the expression.
492 */
493 void addExponent(int exp) {
494 Token lastTok = mExpr.get(mExpr.size() - 1);
495 ((Constant) lastTok).addExponent(exp);
496 }
497
498 /**
Hans Boehm017de982015-06-10 17:46:03 -0700499 * Remove trailing op_add and op_sub operators.
500 */
501 void removeTrailingAdditiveOperators() {
502 while (true) {
503 int s = mExpr.size();
Hans Boehm3666e632015-07-27 18:33:12 -0700504 if (s == 0) {
505 break;
506 }
Hans Boehm017de982015-06-10 17:46:03 -0700507 Token lastTok = mExpr.get(s-1);
Hans Boehm3666e632015-07-27 18:33:12 -0700508 if (!(lastTok instanceof Operator)) {
509 break;
510 }
511 int lastOp = ((Operator) lastTok).id;
512 if (lastOp != R.id.op_add && lastOp != R.id.op_sub) {
513 break;
514 }
Hans Boehm017de982015-06-10 17:46:03 -0700515 delete();
516 }
517 }
518
Hans Boehm3666e632015-07-27 18:33:12 -0700519 /**
520 * Append the contents of the argument expression.
521 * It is assumed that the argument expression will not change, and thus its pieces can be
522 * reused directly.
523 */
524 public void append(CalculatorExpr expr2) {
Hans Boehmfbcef702015-04-27 18:07:47 -0700525 int s = mExpr.size();
Hans Boehm84614952014-11-25 18:46:17 -0800526 int s2 = expr2.mExpr.size();
Hans Boehm3666e632015-07-27 18:33:12 -0700527 // Check that we're not concatenating Constant or PreEval tokens, since the result would
528 // look like a single constant, with very mysterious results for the user.
Hans Boehmfbcef702015-04-27 18:07:47 -0700529 if (s != 0 && s2 != 0) {
530 Token last = mExpr.get(s-1);
531 Token first = expr2.mExpr.get(0);
532 if (!(first instanceof Operator) && !(last instanceof Operator)) {
Hans Boehm3666e632015-07-27 18:33:12 -0700533 // Fudge it by adding an explicit multiplication. We would have interpreted it as
534 // such anyway, and this makes it recognizable to the user.
Hans Boehmfbcef702015-04-27 18:07:47 -0700535 mExpr.add(new Operator(R.id.op_mul));
536 }
537 }
Hans Boehm84614952014-11-25 18:46:17 -0800538 for (int i = 0; i < s2; ++i) {
539 mExpr.add(expr2.mExpr.get(i));
540 }
541 }
542
Hans Boehm3666e632015-07-27 18:33:12 -0700543 /**
544 * Undo the last key addition, if any.
545 * Or possibly remove a trailing exponent digit.
546 */
547 public void delete() {
548 final int s = mExpr.size();
549 if (s == 0) {
550 return;
551 }
Hans Boehm84614952014-11-25 18:46:17 -0800552 Token last = mExpr.get(s-1);
553 if (last instanceof Constant) {
554 Constant c = (Constant)last;
555 c.delete();
Hans Boehm3666e632015-07-27 18:33:12 -0700556 if (!c.isEmpty()) {
557 return;
558 }
Hans Boehm84614952014-11-25 18:46:17 -0800559 }
560 mExpr.remove(s-1);
561 }
562
Hans Boehm3666e632015-07-27 18:33:12 -0700563 /**
564 * Remove all tokens from the expression.
565 */
566 public void clear() {
Hans Boehm84614952014-11-25 18:46:17 -0800567 mExpr.clear();
568 }
569
Hans Boehm3666e632015-07-27 18:33:12 -0700570 public boolean isEmpty() {
Hans Boehm84614952014-11-25 18:46:17 -0800571 return mExpr.isEmpty();
572 }
573
Hans Boehm3666e632015-07-27 18:33:12 -0700574 /**
575 * Returns a logical deep copy of the CalculatorExpr.
576 * Operator and PreEval tokens are immutable, and thus aren't really copied.
577 */
Hans Boehm84614952014-11-25 18:46:17 -0800578 public Object clone() {
Hans Boehm3666e632015-07-27 18:33:12 -0700579 CalculatorExpr result = new CalculatorExpr();
Hans Boehm9c160b42016-12-02 11:55:12 -0800580 for (Token t : mExpr) {
Hans Boehm84614952014-11-25 18:46:17 -0800581 if (t instanceof Constant) {
Hans Boehm3666e632015-07-27 18:33:12 -0700582 result.mExpr.add((Token)(((Constant)t).clone()));
Hans Boehm84614952014-11-25 18:46:17 -0800583 } else {
Hans Boehm3666e632015-07-27 18:33:12 -0700584 result.mExpr.add(t);
Hans Boehm84614952014-11-25 18:46:17 -0800585 }
586 }
Hans Boehm3666e632015-07-27 18:33:12 -0700587 return result;
Hans Boehm84614952014-11-25 18:46:17 -0800588 }
589
590 // Am I just a constant?
Hans Boehm3666e632015-07-27 18:33:12 -0700591 public boolean isConstant() {
592 if (mExpr.size() != 1) {
593 return false;
594 }
Hans Boehm84614952014-11-25 18:46:17 -0800595 return mExpr.get(0) instanceof Constant;
596 }
597
Hans Boehm3666e632015-07-27 18:33:12 -0700598 /**
599 * Return a new expression consisting of a single token representing the current pre-evaluated
600 * expression.
Hans Boehm8f051c32016-10-03 16:53:58 -0700601 * The caller supplies the expression index and short string representation.
602 * The expression must have been previously evaluated.
Hans Boehm3666e632015-07-27 18:33:12 -0700603 */
Hans Boehm8f051c32016-10-03 16:53:58 -0700604 public CalculatorExpr abbreviate(long index, String sr) {
Hans Boehm84614952014-11-25 18:46:17 -0800605 CalculatorExpr result = new CalculatorExpr();
Justin Klaassen0ace4eb2016-02-05 11:38:12 -0800606 @SuppressWarnings("unchecked")
Hans Boehm8f051c32016-10-03 16:53:58 -0700607 Token t = new PreEval(index, sr);
Hans Boehm84614952014-11-25 18:46:17 -0800608 result.mExpr.add(t);
609 return result;
610 }
611
Hans Boehm3666e632015-07-27 18:33:12 -0700612 /**
Hans Boehm995e5eb2016-02-08 11:03:01 -0800613 * Internal evaluation functions return an EvalRet pair.
Hans Boehm3666e632015-07-27 18:33:12 -0700614 * We compute rational (BoundedRational) results when possible, both as a performance
615 * optimization, and to detect errors exactly when we can.
616 */
617 private static class EvalRet {
618 public int pos; // Next position (expression index) to be parsed.
Hans Boehm995e5eb2016-02-08 11:03:01 -0800619 public final UnifiedReal val; // Constructive Real result of evaluating subexpression.
620 EvalRet(int p, UnifiedReal v) {
Hans Boehm3666e632015-07-27 18:33:12 -0700621 pos = p;
622 val = v;
Hans Boehm84614952014-11-25 18:46:17 -0800623 }
624 }
625
Hans Boehm3666e632015-07-27 18:33:12 -0700626 /**
627 * Internal evaluation functions take an EvalContext argument.
628 */
Hans Boehm84614952014-11-25 18:46:17 -0800629 private static class EvalContext {
Hans Boehm3666e632015-07-27 18:33:12 -0700630 public final int mPrefixLength; // Length of prefix to evaluate. Not explicitly saved.
Hans Boehmc023b732015-04-29 11:30:47 -0700631 public final boolean mDegreeMode;
Hans Boehm8f051c32016-10-03 16:53:58 -0700632 public final ExprResolver mExprResolver; // Reconstructed, not saved.
Hans Boehm84614952014-11-25 18:46:17 -0800633 // If we add any other kinds of evaluation modes, they go here.
Hans Boehm8f051c32016-10-03 16:53:58 -0700634 EvalContext(boolean degreeMode, int len, ExprResolver er) {
Hans Boehm84614952014-11-25 18:46:17 -0800635 mDegreeMode = degreeMode;
Hans Boehmc023b732015-04-29 11:30:47 -0700636 mPrefixLength = len;
Hans Boehm8f051c32016-10-03 16:53:58 -0700637 mExprResolver = er;
Hans Boehm84614952014-11-25 18:46:17 -0800638 }
Hans Boehm8f051c32016-10-03 16:53:58 -0700639 EvalContext(DataInput in, int len, ExprResolver er) throws IOException {
Hans Boehm84614952014-11-25 18:46:17 -0800640 mDegreeMode = in.readBoolean();
Hans Boehmc023b732015-04-29 11:30:47 -0700641 mPrefixLength = len;
Hans Boehm8f051c32016-10-03 16:53:58 -0700642 mExprResolver = er;
Hans Boehm84614952014-11-25 18:46:17 -0800643 }
644 void write(DataOutput out) throws IOException {
645 out.writeBoolean(mDegreeMode);
646 }
647 }
648
Hans Boehm995e5eb2016-02-08 11:03:01 -0800649 private UnifiedReal toRadians(UnifiedReal x, EvalContext ec) {
Hans Boehm84614952014-11-25 18:46:17 -0800650 if (ec.mDegreeMode) {
Hans Boehm995e5eb2016-02-08 11:03:01 -0800651 return x.multiply(UnifiedReal.RADIANS_PER_DEGREE);
Hans Boehm84614952014-11-25 18:46:17 -0800652 } else {
653 return x;
654 }
655 }
656
Hans Boehm995e5eb2016-02-08 11:03:01 -0800657 private UnifiedReal fromRadians(UnifiedReal x, EvalContext ec) {
Hans Boehm84614952014-11-25 18:46:17 -0800658 if (ec.mDegreeMode) {
Hans Boehm995e5eb2016-02-08 11:03:01 -0800659 return x.divide(UnifiedReal.RADIANS_PER_DEGREE);
Hans Boehm84614952014-11-25 18:46:17 -0800660 } else {
661 return x;
662 }
663 }
664
Hans Boehm3666e632015-07-27 18:33:12 -0700665 // The following methods can all throw IndexOutOfBoundsException in the event of a syntax
666 // error. We expect that to be caught in eval below.
Hans Boehm84614952014-11-25 18:46:17 -0800667
Hans Boehmc023b732015-04-29 11:30:47 -0700668 private boolean isOperatorUnchecked(int i, int op) {
Hans Boehm84614952014-11-25 18:46:17 -0800669 Token t = mExpr.get(i);
Hans Boehm3666e632015-07-27 18:33:12 -0700670 if (!(t instanceof Operator)) {
671 return false;
672 }
673 return ((Operator)(t)).id == op;
Hans Boehm84614952014-11-25 18:46:17 -0800674 }
675
Hans Boehmc023b732015-04-29 11:30:47 -0700676 private boolean isOperator(int i, int op, EvalContext ec) {
Hans Boehm3666e632015-07-27 18:33:12 -0700677 if (i >= ec.mPrefixLength) {
678 return false;
679 }
Hans Boehmc023b732015-04-29 11:30:47 -0700680 return isOperatorUnchecked(i, op);
681 }
682
Hans Boehm3666e632015-07-27 18:33:12 -0700683 public static class SyntaxException extends Exception {
Hans Boehmc023b732015-04-29 11:30:47 -0700684 public SyntaxException() {
Hans Boehm84614952014-11-25 18:46:17 -0800685 super();
686 }
Hans Boehmc023b732015-04-29 11:30:47 -0700687 public SyntaxException(String s) {
Hans Boehm84614952014-11-25 18:46:17 -0800688 super(s);
689 }
690 }
691
Hans Boehm3666e632015-07-27 18:33:12 -0700692 // The following functions all evaluate some kind of expression starting at position i in
693 // mExpr in a specified evaluation context. They return both the expression value (as
694 // constructive real and, if applicable, as BoundedRational) and the position of the next token
Hans Boehm84614952014-11-25 18:46:17 -0800695 // that was not used as part of the evaluation.
Hans Boehm3666e632015-07-27 18:33:12 -0700696 // This is essentially a simple recursive descent parser combined with expression evaluation.
697
Hans Boehmc023b732015-04-29 11:30:47 -0700698 private EvalRet evalUnary(int i, EvalContext ec) throws SyntaxException {
Hans Boehm3666e632015-07-27 18:33:12 -0700699 final Token t = mExpr.get(i);
Hans Boehm84614952014-11-25 18:46:17 -0800700 if (t instanceof Constant) {
701 Constant c = (Constant)t;
Hans Boehm995e5eb2016-02-08 11:03:01 -0800702 return new EvalRet(i+1,new UnifiedReal(c.toRational()));
Hans Boehm84614952014-11-25 18:46:17 -0800703 }
704 if (t instanceof PreEval) {
Hans Boehm8f051c32016-10-03 16:53:58 -0700705 final long index = ((PreEval)t).mIndex;
706 UnifiedReal res = ec.mExprResolver.getResult(index);
707 if (res == null) {
Hans Boehm9c160b42016-12-02 11:55:12 -0800708 // We try to minimize this recursive evaluation case, but currently don't
709 // completely avoid it.
710 res = nestedEval(index, ec.mExprResolver);
Hans Boehm8f051c32016-10-03 16:53:58 -0700711 }
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() {
Hans Boehm9c160b42016-12-02 11:55:12 -0800985 for (Token t : mExpr) {
Hans Boehm52d477a2016-04-01 17:42:50 -0700986 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 Boehm9c160b42016-12-02 11:55:12 -0800997 * Add the indices of unevaluated PreEval expressions embedded in the current expression to
998 * argument. This includes only directly referenced expressions e, not those indirectly
999 * referenced by e. If the index was already present, it is not added. If the argument
1000 * contained no duplicates, the result will not either. New indices are added to the end of
1001 * the list.
1002 */
1003 private void addReferencedExprs(ArrayList<Long> list, ExprResolver er) {
1004 for (Token t : mExpr) {
1005 if (t instanceof PreEval) {
1006 Long index = ((PreEval) t).mIndex;
1007 if (er.getResult(index) == null && !list.contains(index)) {
1008 list.add(index);
1009 }
1010 }
1011 }
1012 }
1013
1014 /**
1015 * Return a list of unevaluated expressions transitively referenced by the current one.
1016 * All expressions in the resulting list will have had er.getExpr() called on them.
1017 * The resulting list is ordered such that evaluating expressions in list order
1018 * should trigger few recursive evaluations.
1019 */
1020 public ArrayList<Long> getTransitivelyReferencedExprs(ExprResolver er) {
1021 // We could avoid triggering any recursive evaluations by actually building the
1022 // dependency graph and topologically sorting it. Note that sorting by index works
1023 // for positive and negative indices separately, but not their union. Currently we
1024 // just settle for reverse breadth-first-search order, which handles the common case
1025 // of simple dependency chains well.
1026 ArrayList<Long> list = new ArrayList<Long>();
1027 int scanned = 0; // We've added expressions referenced by [0, scanned) to the list
1028 addReferencedExprs(list, er);
1029 while (scanned != list.size()) {
1030 er.getExpr(list.get(scanned++)).addReferencedExprs(list, er);
1031 }
1032 Collections.reverse(list);
1033 return list;
1034 }
1035
1036 /**
1037 * Evaluate the expression at the given index to a UnifiedReal.
1038 * Both saves and returns the result.
1039 */
1040 UnifiedReal nestedEval(long index, ExprResolver er) throws SyntaxException {
1041 CalculatorExpr nestedExpr = er.getExpr(index);
1042 EvalContext newEc = new EvalContext(er.getDegreeMode(index),
1043 nestedExpr.trailingBinaryOpsStart(), er);
1044 EvalRet new_res = nestedExpr.evalExpr(0, newEc);
1045 return er.putResultIfAbsent(index, new_res.val);
1046 }
1047
1048 /**
Hans Boehme8553762015-06-26 17:56:52 -07001049 * Evaluate the expression excluding trailing binary operators.
Hans Boehm3666e632015-07-27 18:33:12 -07001050 * Errors result in exceptions, most of which are unchecked. Should not be called
1051 * concurrently with modification of the expression. May take a very long time; avoid calling
1052 * from UI thread.
Hans Boehme8553762015-06-26 17:56:52 -07001053 *
1054 * @param degreeMode use degrees rather than radians
1055 */
Hans Boehm8f051c32016-10-03 16:53:58 -07001056 UnifiedReal eval(boolean degreeMode, ExprResolver er) throws SyntaxException
Hans Boehm995e5eb2016-02-08 11:03:01 -08001057 // And unchecked exceptions thrown by UnifiedReal, CR,
Hans Boehmc023b732015-04-29 11:30:47 -07001058 // and BoundedRational.
Hans Boehm84614952014-11-25 18:46:17 -08001059 {
Hans Boehm9c160b42016-12-02 11:55:12 -08001060 // First evaluate all indirectly referenced expressions in increasing index order.
1061 // This ensures that subsequent evaluation never encounters an embedded PreEval
1062 // expression that has not been previously evaluated.
1063 // We could do the embedded evaluations recursively, but that risks running out of
1064 // stack space.
1065 ArrayList<Long> referenced = getTransitivelyReferencedExprs(er);
1066 for (long index : referenced) {
1067 nestedEval(index, er);
1068 }
Hans Boehm84614952014-11-25 18:46:17 -08001069 try {
Hans Boehm3666e632015-07-27 18:33:12 -07001070 // We currently never include trailing binary operators, but include other trailing
1071 // operators. Thus we usually, but not always, display results for prefixes of valid
1072 // expressions, and don't generate an error where we previously displayed an instant
1073 // result. This reflects the Android L design.
Hans Boehme8553762015-06-26 17:56:52 -07001074 int prefixLen = trailingBinaryOpsStart();
Hans Boehm8f051c32016-10-03 16:53:58 -07001075 EvalContext ec = new EvalContext(degreeMode, prefixLen, er);
Hans Boehm84614952014-11-25 18:46:17 -08001076 EvalRet res = evalExpr(0, ec);
Hans Boehm3666e632015-07-27 18:33:12 -07001077 if (res.pos != prefixLen) {
Hans Boehmc023b732015-04-29 11:30:47 -07001078 throw new SyntaxException("Failed to parse full expression");
Hans Boehmfbcef702015-04-27 18:07:47 -07001079 }
Hans Boehm995e5eb2016-02-08 11:03:01 -08001080 return res.val;
Hans Boehm84614952014-11-25 18:46:17 -08001081 } catch (IndexOutOfBoundsException e) {
Hans Boehmc023b732015-04-29 11:30:47 -07001082 throw new SyntaxException("Unexpected expression end");
Hans Boehm84614952014-11-25 18:46:17 -08001083 }
1084 }
1085
1086 // Produce a string representation of the expression itself
Hans Boehm8a4f81c2015-07-09 10:41:25 -07001087 SpannableStringBuilder toSpannableStringBuilder(Context context) {
1088 SpannableStringBuilder ssb = new SpannableStringBuilder();
Hans Boehm9c160b42016-12-02 11:55:12 -08001089 for (Token t : mExpr) {
Hans Boehm8a4f81c2015-07-09 10:41:25 -07001090 ssb.append(t.toCharSequence(context));
Hans Boehm84614952014-11-25 18:46:17 -08001091 }
Hans Boehm8a4f81c2015-07-09 10:41:25 -07001092 return ssb;
Hans Boehm84614952014-11-25 18:46:17 -08001093 }
1094}