Expression.cpp 15.3 KB
Newer Older
1
2
3
4
#include <iostream>
#include <locale>
#include <sstream>

5
6
#include "MantidAPI/Expression.h"

7
#include <MantidKernel/StringTokenizer.h>
8

9
10
namespace Mantid {
namespace API {
11

12
using tokenizer = Mantid::Kernel::StringTokenizer;
13

LamarMoore's avatar
LamarMoore committed
14
15
const std::string DEFAULT_OPS_STR[] = {
    ";", ",", "=", "== != > < <= >=", "&& || ^^", "+ -", "* /", "^"};
16

17
18
const std::string EMPTY_EXPRESSION_NAME = "EMPTY";

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
namespace {
/// Make the full text of the error message
/// @param msg :: The text of the error message.
/// @param expr :: An expression string that caused the error.
/// @param i :: An index of a symbol in expr that may help identify the location
///             of the error.
std::string makeErrorMessage(const std::string &msg, const std::string &expr,
                             size_t i) {
  const size_t MAX_LEFT_SIZE = 10;
  const size_t MAX_RIGHT_SIZE = 10;
  std::ostringstream res;
  res << msg << " at\n\n";
  size_t j = i;
  size_t skip = 0;
  size_t n = expr.size();
  std::string leftEllipsis = "";
  if (i > MAX_LEFT_SIZE) {
    skip = i - MAX_LEFT_SIZE;
    leftEllipsis = "...";
    j = MAX_LEFT_SIZE + leftEllipsis.size();
    n -= skip;
  }
  std::string rightEllipsis = "";
  if (n - j > MAX_RIGHT_SIZE) {
    n = i + MAX_RIGHT_SIZE;
    rightEllipsis = "...";
  }
  // Write a substring of expr around the error indicator at symbol #i.
  res << leftEllipsis << expr.substr(skip, n) << rightEllipsis << '\n';
  res << std::string(j, ' ') << '^' << '\n';
  return res.str();
}

} // namespace

/// Constructor
/// @param msg :: The text of the error message.
/// @param expr :: An expression string that caused the error.
/// @param i :: An index of a symbol in expr that may help identify the location
///             of the error.
Expression::ParsingError::ParsingError(const std::string &msg,
                                       const std::string &expr, size_t i)
    : std::runtime_error(makeErrorMessage(msg, expr, i)) {}

/// Constructor
/// @param msg :: The text of the error message.
Expression::ParsingError::ParsingError(const std::string &msg)
    : std::runtime_error(msg) {}

68
Expression::Expression() {
69
70

  m_operators.reset(new Operators());
71
72
73
  // Define binary operators. Put them in the reverse precedence order (from
  // lower to higher prec.)
  std::vector<std::string> ops(DEFAULT_OPS_STR, DEFAULT_OPS_STR + 8);
74
75
76
77

  add_operators(ops);

  // Define unary operators
78
  std::unordered_set<std::string> unary;
79
80
81
82
83
84
85
  unary.insert("+");
  unary.insert("-");

  add_unary(unary);
}

/// contructor
86
Expression::Expression(const std::vector<std::string> &ops) {
87
88
89
90
91
  m_operators.reset(new Operators());
  add_operators(ops);
}

/// contructor
92
Expression::Expression(const std::vector<std::string> &binary,
93
                       const std::unordered_set<std::string> &unary) {
94
95
96
97
98
  m_operators.reset(new Operators());
  add_operators(binary);
  add_unary(unary);
}

99
100
101
Expression::Expression(const Expression &expr)
    : // m_tokens(expr.m_tokens),
      // m_expr(expr.m_expr),
LamarMoore's avatar
LamarMoore committed
102
103
      m_funct(expr.m_funct), m_op(expr.m_op), m_terms(expr.m_terms),
      m_operators(expr.m_operators) {}
104
105
Expression::Expression(const Expression *pexpr)
    : m_operators(pexpr->m_operators) {}
106
107

/// Assignment operator
108
Expression &Expression::operator=(const Expression &expr) {
109
110
111
112
  m_operators = expr.m_operators;
  m_funct = expr.m_funct;
  m_op = expr.m_op;
  m_terms = expr.m_terms;
113
114
  // m_expr = expr.m_expr;
  // m_tokens = expr.m_tokens;
115
116
117
  return *this;
}

118
void Expression::add_operators(const std::vector<std::string> &ops) {
119
120
  m_operators->binary = ops;
  // Fill in the precedence table (m_op_precedence)
121
  for (size_t i = 0; i < m_operators->binary.size(); i++) {
122
    char j = 0;
123
124
    tokenizer tkz(m_operators->binary[i], " ",
                  tokenizer::TOK_IGNORE_EMPTY | tokenizer::TOK_TRIM);
Hahn, Steven's avatar
Hahn, Steven committed
125
126
127
    for (const auto &index : tkz) {
      m_operators->precedence[index] = i + 1;
      m_operators->op_number[index] = j++;
128
129
130
    }
  }

131
132
  for (auto str : ops) {
    for (char c : str) {
133
134
      if (c == ' ')
        continue;
135
136
137
138
139
      m_operators->symbols.insert(c);
    }
  }
}

140
void Expression::add_unary(const std::unordered_set<std::string> &ops) {
141
  m_operators->unary = ops;
142
143
  for (const auto &op : ops) {
    m_operators->symbols.insert(op.cbegin(), op.cend());
144
145
146
  }
}

147
148
149
150
151
size_t Expression::op_prec(const std::string &op) const {
  std::map<std::string, size_t>::const_iterator i =
      m_operators->precedence.find(op);
  if (i == m_operators->precedence.end())
    return 0;
152
153
154
  return i->second;
}

155
bool Expression::is_unary(const std::string &op) const {
156
  return m_operators->unary.find(op) != m_operators->unary.end();
157
158
}

159
bool Expression::is_op_symbol(const char c) const {
160
  return m_operators->symbols.find(c) != m_operators->symbols.end();
161
162
}

163
void Expression::trim(std::string &str) {
164
165
  size_t i = str.find_first_not_of(" \t\n\r");
  size_t j = str.find_last_not_of(" \t\n\r");
166
  if (i == std::string::npos || j == std::string::npos || j < i) {
167
    str = "";
168
169
  } else {
    str = str.substr(i, j - i + 1);
170
171
172
  }
}

173
void Expression::parse(const std::string &str) {
174
175
176
  m_expr = str;
  trim(m_expr);

177
  if (m_expr.size() > 1 && m_expr.front() == '(' && m_expr.back() == ')') {
178
179
180
    if (m_expr.find('(', 1) == std::string::npos) {
      m_expr.erase(0, 1);
      m_expr.erase(m_expr.size() - 1, 1);
181
182
183
184
185
186
      trim(m_expr);
    }
  }

  tokenize();

187
  if (m_tokens.empty()) {
188
189
190
191
192
    setFunct(m_expr);
    return;
  }

  std::string op = GetOp(0);
193
  // size_t prec = m_operators->precedence[op];
194
  size_t prec = op_prec(op);
195
196
  tokenizer tkz(m_operators->binary[prec - 1], " ",
                tokenizer::TOK_IGNORE_EMPTY | tokenizer::TOK_TRIM);
197
198
199

  setFunct(*tkz.begin());

200
  for (size_t i = 0; i <= m_tokens.size(); i++) {
201
    m_terms.push_back(Expression(this));
202
    Expression &t = m_terms.back();
203
    if (i)
204
      t.m_op = GetOp(i - 1);
205
206
207
208
209
210
    t.parse(GetToken(i));
  }
  m_expr = "";
  m_tokens.clear();
}

211
void Expression::tokenize() {
212
213
  m_tokens.clear();

Peterson, Peter's avatar
Peterson, Peter committed
214
  size_t min_prec = 1000;
215
216
217
218
219
220
221
  size_t is = 0;
  size_t is1 = 0;
  unsigned int lvl = 0;
  size_t last = m_expr.size() - 1;
  bool inString = false;
  int skip = 0;
  bool canBeBinary = false;
222
223
  bool isNumber =
      false; // if parser is inside a number (important case is 123.45e+67)
224
225
226
  bool canDotBeAdded = false;
  bool canEBeAdded = false;
  bool canPlusBeAdded = false;
227
  Tokens tokens;
228
  for (size_t i = 0; i < m_expr.size(); i++) {
229
    char c = m_expr[i];
230

231
232
233
234
    if (!inString && skip == 0) {
      if (isNumber) {
        if (c == '.') {
          if (canDotBeAdded) {
235
            canDotBeAdded = false;
236
          } else {
237
238
            isNumber = false;
          }
239
240
        } else if (c == 'e' || c == 'E') {
          if (canEBeAdded) {
241
242
243
            canEBeAdded = false;
            canDotBeAdded = false;
            canPlusBeAdded = true;
244
          } else {
245
246
            isNumber = false;
          }
247
248
        } else if (c == '+' || c == '-') {
          if (canPlusBeAdded) {
249
250
251
            canPlusBeAdded = false;
            canEBeAdded = false;
            canDotBeAdded = false;
252
          } else {
253
254
            isNumber = false;
          }
255
        } else if (!isdigit(c)) {
256
257
          isNumber = false;
        }
258
      } else if (isdigit(c)) {
259
260
261
262
263
        isNumber = true;
        canDotBeAdded = true;
        canEBeAdded = true;
        canPlusBeAdded = false;
      }
264
      if (lvl == 0 && !isNumber && is_op_symbol(c)) // insert new token
265
      {
266
        if (i == last) {
267
268
269
270
          if (c == ',' || c == ';') {
            m_expr.resize(last);
            break;
          } else {
271
272
            throw ParsingError("A binary operator isn't followed by a value",
                               m_expr, i);
273
          }
274
275
        }

276
        if (is_op_symbol(m_expr[i + 1])) {
277
          is1 = i + 2;
278
        } else {
279
280
281
          is1 = i + 1;
        }

282
        if (is1 > last) {
283
          throw ParsingError("Syntax error", m_expr, last);
284
285
        }

286
287
        std::string op = m_expr.substr(i, is1 - i);
        size_t prec = canBeBinary ? m_operators->precedence[op] : 0;
288
289
290
291
        if (!prec) // operator does not exist
        {
          bool error = true;
          // check if it's a binary and a unary operators together
292
293
          if (op.size() == 2) {
            if (is_unary(op)) {
294
295
296
297
              is1 -= 2;
              skip = 2;
              prec = min_prec + 1; // do not add token
              error = false;
298
            } else {
299
              is1 -= 1;
300
              std::string uop = op.substr(1, 1);
301
              op = op[0];
302
303
304
              if (is_op_symbol(m_expr[is1 + 1])) {
                uop += m_expr[is1 + 1];
                if (is1 + 2 > last) {
305
                  throw ParsingError("Syntax error", m_expr, is1 + 1);
306
307
                }
              }
308
              if (is_unary(uop)) {
309
                prec = m_operators->precedence[op];
310
311
                if (prec) { // we don't want to create a new token with unary
                            // operator. it is processed in SetFunct()
312
313
314
315
316
                  skip = 1;
                  error = false;
                }
              }
            }
317
318
319
          } // op.size == 2
          else if (op.size() == 1) {
            // skip = 1;
320
321
322
            prec = min_prec + 1; // do not add token
            error = false;
          }
323
          if (error) {
324
            throw ParsingError("Unrecognized operator", m_expr, i);
325
326
327
          }
        }

328
        if (prec <= min_prec) {
Peterson, Peter's avatar
Peterson, Peter committed
329
          if (prec < min_prec)
330
331
            min_prec = prec;
          Token tok(is, i - 1, is1, prec);
332
333
334
335
336
337
338
339
          tokens.push_back(tok);
          is = is1;
        }

        i = is1 - 1;

        canBeBinary = false;

340
341
      } // insert new token
      else if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
342
343
344
        canBeBinary = true;
      }

345
346
347
348
349
350
      if (c == '(')
        lvl++;
      if (c == ')') {
        if (lvl)
          lvl--;
        else {
351
          throw ParsingError("Unmatched bracket", m_expr, 0);
352
353
354
        }
      }
    } // !inString || skip
355
356
    else if (skip > 0) {
      skip--;
357
358
    }

359
    if (c == '"') {
360
      inString = !inString;
361
362
363
364
    }

  } // for i

365
  if (!tokens.empty()) {
366
    // remove operators of higher prec
367
    m_tokens.emplace_back(tokens[0]);
368
369
370
371
372
    for (size_t i = 0; i < tokens.size(); i++) {
      Token &tok = tokens[i];
      std::string op = m_expr.substr(tok.ie + 1, tok.is1 - tok.ie - 1); //?
      if (m_operators->precedence[op] == min_prec) {
        Token &last_tok = m_tokens.back();
373
        last_tok.ie = tok.ie;
374
375
        last_tok.is1 = tok.is1;
        if (i != tokens.size() - 1)
376
          m_tokens.emplace_back(tokens[i + 1]);
377
378
379
380
381
      }
    }
  }
}

382
std::string Expression::GetToken(size_t i) {
383
  if (m_tokens.empty())
384
    return m_expr;
385

386
387
388
  if (i < m_tokens.size()) {
    Token &tok = m_tokens[i];
    return m_expr.substr(tok.is, tok.ie - tok.is + 1);
389
390
  }

391
392
  if (i == m_tokens.size()) {
    Token &tok = m_tokens[i - 1];
393
394
395
396
397
398
    return m_expr.substr(tok.is1);
  }

  return "";
}

399
std::string Expression::GetOp(size_t i) {
400
  if (m_tokens.empty() || i >= m_tokens.size())
401
    return "";
402

403
404
  Token &tok = m_tokens[i];
  return m_expr.substr(tok.ie + 1, tok.is1 - tok.ie - 1);
405
406
}

407
void Expression::logPrint(const std::string &pads) const {
408
  std::string myPads = pads + "   ";
409
  if (!m_terms.empty()) {
Hahn, Steven's avatar
Hahn, Steven committed
410
    std::cerr << myPads << m_op << '[' << m_funct << ']' << "(\n";
Hahn, Steven's avatar
Hahn, Steven committed
411
412
    for (const auto &term : m_terms)
      term.logPrint(myPads);
Hahn, Steven's avatar
Hahn, Steven committed
413
    std::cerr << myPads << ")\n";
414
415
  } else
    std::cerr << myPads << m_op << m_funct << '\n';
416
417
}

418
419
void Expression::setFunct(const std::string &name) {
  if (!op_prec(name)) {
420
    std::string op;
421
422
423
    if (name.size() > 1 && is_op_symbol(name[0])) {
      op = name.substr(0, 1);
      if (name.size() > 2 && is_op_symbol(name[1])) {
424
425
426
        op += name[1];
      }
    }
427
    if (!op.empty() && is_unary(op)) {
428
429
430
431
432
433
434
435
436
437
      m_funct = op;
      Expression tmp(this);
      tmp.parse(name.substr(op.size()));
      m_terms.push_back(tmp);
      return;
    }
  }

  m_funct = name;
  trim(m_funct);
438

439
  if (m_funct.empty()) {
440
441
    m_funct = EMPTY_EXPRESSION_NAME;
    return;
442
443
444
445
446
447
  }

  // Check if the function has arguments
  std::string::size_type i = std::string::npos;

  bool inQuotes = false;
448
449
  for (std::string::const_iterator c = name.begin(); c != name.end(); ++c) {
    if (*c == '"') {
450
      inQuotes = !inQuotes;
451
452
453
      continue;
    }

454
    if (!inQuotes && *c == '(') {
455
456
457
458
459
      i = c - name.begin();
      break;
    }
  }

460
  if (i != std::string::npos) {
461
    std::string::size_type j = name.find_last_of(')');
462
    if (j == std::string::npos || j < i) {
463
      throw ParsingError("Unmatched bracket", name, i);
464
465
    }

466
    if (j > i + 1) // nonzero argument list
467
    {
468
      std::string args = name.substr(i + 1, j - i - 1); //?
469
      trim(args);
470
      std::string f = name.substr(0, i);
471
472
      Expression tmp(this);
      tmp.parse(args);
473
474
      if (tmp.name() != EMPTY_EXPRESSION_NAME &&
          (!tmp.isFunct() || tmp.name() != ",")) {
475
        m_terms.push_back(tmp);
476
      } else {
477
478
479
        if (f.empty() && tmp.name() == ",") {
          f = ",";
        }
480
481
482
483
484
        std::string my_op = m_op;
        *this = tmp;
        m_op = my_op;
      }
      m_funct = f;
485
486
487
      if (m_funct.empty() && m_terms.empty()) {
        m_funct = EMPTY_EXPRESSION_NAME;
      }
488
489
490
491
    }
  }
}

492
std::string Expression::str() const {
493
494
495
  bool brackets = false;
  std::ostringstream res;
  size_t prec = op_prec(m_funct);
496
  if (size() == 1 && is_unary(m_funct)) { // unary operator
497
    res << m_funct;
498
    if (op_prec(m_terms[0].m_funct) > 0) {
499
500
      brackets = true;
    }
501
  } else if (!prec) { // function with a name
502
503
    res << m_funct;
    brackets = true;
504
505
  } else if (m_op == "-" && m_funct == "+") {
    brackets = true;
506
507
  } else if (m_op == "/" && m_funct == "*") {
    brackets = true;
508
509
  }

510
  if (!m_terms.empty()) {
511
512
    if (brackets)
      res << '(';
Hahn, Steven's avatar
Hahn, Steven committed
513
514
515
    for (const auto &term : m_terms) {
      res << term.operator_name();
      size_t prec1 = op_prec(term.m_funct);
516
      bool isItUnary = false;
Hahn, Steven's avatar
Hahn, Steven committed
517
      if (term.size() == 1 && is_unary(term.m_funct)) {
518
519
520
        prec1 = 0; // unary operator
        isItUnary = true;
      }
521
522
523
524
525
      bool bk = prec > 0 && prec1 > 0 && prec > prec1;
      if (bk)
        res << '(';
      if (isItUnary)
        res << ' ';
Hahn, Steven's avatar
Hahn, Steven committed
526
      res << term.str();
527
528
      if (bk)
        res << ')';
529
    }
530
531
    if (brackets)
      res << ')';
532
533
534
535
  }
  return res.str();
}

536
537
538
const Expression &Expression::bracketsRemoved() const {
  const Expression *e = this;
  while (e->name().empty() && e->size() == 1) {
539
540
541
542
543
    e = &e->m_terms[0];
  }
  return *e;
}

544
545
546
/**
 * Return a list of all variable names in this expression
 */
547
548
std::unordered_set<std::string> Expression::getVariables() const {
  std::unordered_set<std::string> out;
549
  if (!isFunct()) {
550
    std::string s = name();
551
    if (!s.empty() && !isdigit(s[0])) {
552
553
      out.insert(s);
    }
554
  } else {
555
556
    for (const auto &e : *this) {
      if (e.isFunct()) {
557
        std::unordered_set<std::string> tout = e.getVariables();
558
559
        out.insert(tout.begin(), tout.end());
      } else {
560
        std::string s = e.name();
561
        if (!s.empty() && !isdigit(s[0])) {
562
563
          out.insert(s);
        }
564
565
566
567
568
569
      }
    }
  }
  return out;
}

570
void Expression::rename(const std::string &newName) { m_funct = newName; }
571

572
573
574
void Expression::renameAll(const std::string &oldName,
                           const std::string &newName) {
  if (!isFunct() && name() == oldName) {
575
    rename(newName);
576
  } else {
577
578
    for (auto &term : m_terms) {
      term.renameAll(oldName, newName);
579
580
581
582
    }
  }
}

583
584
585
void Expression::toList(const std::string &sep) {
  if (name() == sep)
    return;
586
587
588
589
590
591
  Expression term(*this);
  m_terms.resize(1);
  m_terms[0] = term;
  setFunct(sep);
}

LamarMoore's avatar
LamarMoore committed
592
593
} // namespace API
} // namespace Mantid