Expression.cpp 13.2 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
typedef Mantid::Kernel::StringTokenizer tokenizer;
13

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

17
Expression::Expression() {
18
19

  m_operators.reset(new Operators());
20
21
22
  // 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);
23
24
25
26

  add_operators(ops);

  // Define unary operators
27
  std::unordered_set<std::string> unary;
28
29
30
31
32
33
34
  unary.insert("+");
  unary.insert("-");

  add_unary(unary);
}

/// contructor
35
Expression::Expression(const std::vector<std::string> &ops) {
36
37
38
39
40
  m_operators.reset(new Operators());
  add_operators(ops);
}

/// contructor
41
Expression::Expression(const std::vector<std::string> &binary,
42
                       const std::unordered_set<std::string> &unary) {
43
44
45
46
47
  m_operators.reset(new Operators());
  add_operators(binary);
  add_unary(unary);
}

48
49
50
51
52
53
54
Expression::Expression(const Expression &expr)
    : // m_tokens(expr.m_tokens),
      // m_expr(expr.m_expr),
      m_funct(expr.m_funct),
      m_op(expr.m_op), m_terms(expr.m_terms), m_operators(expr.m_operators) {}
Expression::Expression(const Expression *pexpr)
    : m_operators(pexpr->m_operators) {}
55
56

/// Assignment operator
57
Expression &Expression::operator=(const Expression &expr) {
58
59
60
61
  m_operators = expr.m_operators;
  m_funct = expr.m_funct;
  m_op = expr.m_op;
  m_terms = expr.m_terms;
62
63
  // m_expr = expr.m_expr;
  // m_tokens = expr.m_tokens;
64
65
66
  return *this;
}

67
void Expression::add_operators(const std::vector<std::string> &ops) {
68
69
  m_operators->binary = ops;
  // Fill in the precedence table (m_op_precedence)
70
  for (size_t i = 0; i < m_operators->binary.size(); i++) {
71
    char j = 0;
72
73
    tokenizer tkz(m_operators->binary[i], " ",
                  tokenizer::TOK_IGNORE_EMPTY | tokenizer::TOK_TRIM);
Hahn, Steven's avatar
Hahn, Steven committed
74
75
76
    for (const auto &index : tkz) {
      m_operators->precedence[index] = i + 1;
      m_operators->op_number[index] = j++;
77
78
79
    }
  }

80
81
  for (auto str : ops) {
    for (char c : str) {
82
83
      if (c == ' ')
        continue;
84
85
86
87
88
      m_operators->symbols.insert(c);
    }
  }
}

89
void Expression::add_unary(const std::unordered_set<std::string> &ops) {
90
  m_operators->unary = ops;
91
92
  for (const auto &op : ops) {
    m_operators->symbols.insert(op.cbegin(), op.cend());
93
94
95
  }
}

96
97
98
99
100
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;
101
102
103
  return i->second;
}

104
bool Expression::is_unary(const std::string &op) const {
105
  return m_operators->unary.find(op) != m_operators->unary.end();
106
107
}

108
bool Expression::is_op_symbol(const char c) const {
109
  return m_operators->symbols.find(c) != m_operators->symbols.end();
110
111
}

112
void Expression::trim(std::string &str) {
113
114
  size_t i = str.find_first_not_of(" \t\n\r");
  size_t j = str.find_last_not_of(" \t\n\r");
115
  if (i == std::string::npos || j == std::string::npos || j < i) {
116
    str = "";
117
118
  } else {
    str = str.substr(i, j - i + 1);
119
120
121
  }
}

122
void Expression::parse(const std::string &str) {
123
124
125
  m_expr = str;
  trim(m_expr);

126
  if (m_expr.size() > 1 && m_expr.front() == '(' && m_expr.back() == ')') {
127
128
129
    if (m_expr.find('(', 1) == std::string::npos) {
      m_expr.erase(0, 1);
      m_expr.erase(m_expr.size() - 1, 1);
130
131
132
133
134
135
      trim(m_expr);
    }
  }

  tokenize();

136
  if (m_tokens.empty()) {
137
138
139
140
141
    setFunct(m_expr);
    return;
  }

  std::string op = GetOp(0);
142
  // size_t prec = m_operators->precedence[op];
143
  size_t prec = op_prec(op);
144
145
  tokenizer tkz(m_operators->binary[prec - 1], " ",
                tokenizer::TOK_IGNORE_EMPTY | tokenizer::TOK_TRIM);
146
147
148

  setFunct(*tkz.begin());

149
  for (size_t i = 0; i <= m_tokens.size(); i++) {
150
    m_terms.push_back(Expression(this));
151
    Expression &t = m_terms.back();
152
    if (i)
153
      t.m_op = GetOp(i - 1);
154
155
156
157
158
159
    t.parse(GetToken(i));
  }
  m_expr = "";
  m_tokens.clear();
}

160
void Expression::tokenize() {
161
162
  m_tokens.clear();

Peterson, Peter's avatar
Peterson, Peter committed
163
  size_t min_prec = 1000;
164
165
166
167
168
169
170
  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;
171
172
  bool isNumber =
      false; // if parser is inside a number (important case is 123.45e+67)
173
174
175
  bool canDotBeAdded = false;
  bool canEBeAdded = false;
  bool canPlusBeAdded = false;
176
  Tokens tokens;
177
  for (size_t i = 0; i < m_expr.size(); i++) {
178
    char c = m_expr[i];
179

180
181
182
183
    if (!inString && skip == 0) {
      if (isNumber) {
        if (c == '.') {
          if (canDotBeAdded) {
184
            canDotBeAdded = false;
185
          } else {
186
187
            isNumber = false;
          }
188
189
        } else if (c == 'e' || c == 'E') {
          if (canEBeAdded) {
190
191
192
            canEBeAdded = false;
            canDotBeAdded = false;
            canPlusBeAdded = true;
193
          } else {
194
195
            isNumber = false;
          }
196
197
        } else if (c == '+' || c == '-') {
          if (canPlusBeAdded) {
198
199
200
            canPlusBeAdded = false;
            canEBeAdded = false;
            canDotBeAdded = false;
201
          } else {
202
203
            isNumber = false;
          }
204
        } else if (!isdigit(c)) {
205
206
          isNumber = false;
        }
207
      } else if (isdigit(c)) {
208
209
210
211
212
        isNumber = true;
        canDotBeAdded = true;
        canEBeAdded = true;
        canPlusBeAdded = false;
      }
213
      if (lvl == 0 && !isNumber && is_op_symbol(c)) // insert new token
214
      {
215
        if (i == last) {
216
          break;
217
          // throw std::runtime_error("Expression: syntax error");
218
219
        }

220
        if (is_op_symbol(m_expr[i + 1])) {
221
          is1 = i + 2;
222
        } else {
223
224
225
          is1 = i + 1;
        }

226
        if (is1 > last) {
227
228
229
          throw std::runtime_error("Expression: syntax error");
        }

230
231
        std::string op = m_expr.substr(i, is1 - i);
        size_t prec = canBeBinary ? m_operators->precedence[op] : 0;
232
233
234
235
236
        if (!prec) // operator does not exist
        {
          std::ostringstream mess;
          bool error = true;
          // check if it's a binary and a unary operators together
237
238
          if (op.size() == 2) {
            if (is_unary(op)) {
239
240
241
242
              is1 -= 2;
              skip = 2;
              prec = min_prec + 1; // do not add token
              error = false;
243
            } else {
244
              is1 -= 1;
245
              std::string uop = op.substr(1, 1);
246
              op = op[0];
247
248
249
250
              if (is_op_symbol(m_expr[is1 + 1])) {
                uop += m_expr[is1 + 1];
                if (is1 + 2 > last) {
                  mess << "Expression: syntax error at " << is1 + 1;
251
252
253
                  throw std::runtime_error(mess.str());
                }
              }
254
              if (is_unary(uop)) {
255
                prec = m_operators->precedence[op];
256
257
                if (prec) { // we don't want to create a new token with unary
                            // operator. it is processed in SetFunct()
258
259
260
261
262
                  skip = 1;
                  error = false;
                }
              }
            }
263
264
265
          } // op.size == 2
          else if (op.size() == 1) {
            // skip = 1;
266
267
268
            prec = min_prec + 1; // do not add token
            error = false;
          }
269
          if (error) {
270
271
272
273
274
            mess << "Expression: unrecognized operator " << op;
            throw std::runtime_error(mess.str());
          }
        }

275
        if (prec <= min_prec) {
Peterson, Peter's avatar
Peterson, Peter committed
276
          if (prec < min_prec)
277
278
            min_prec = prec;
          Token tok(is, i - 1, is1, prec);
279
280
281
282
283
284
285
286
          tokens.push_back(tok);
          is = is1;
        }

        i = is1 - 1;

        canBeBinary = false;

287
288
      } // insert new token
      else if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
289
290
291
        canBeBinary = true;
      }

292
293
294
295
296
297
      if (c == '(')
        lvl++;
      if (c == ')') {
        if (lvl)
          lvl--;
        else {
298
299
300
301
          throw std::runtime_error("Unmatched brackets");
        }
      }
    } // !inString || skip
302
303
    else if (skip > 0) {
      skip--;
304
305
    }

306
    if (c == '"') {
307
      inString = !inString;
308
309
310
311
    }

  } // for i

312
  if (!tokens.empty()) {
313
    // remove operators of higher prec
314
    m_tokens.emplace_back(tokens[0]);
315
316
317
318
319
    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();
320
        last_tok.ie = tok.ie;
321
322
        last_tok.is1 = tok.is1;
        if (i != tokens.size() - 1)
323
          m_tokens.emplace_back(tokens[i + 1]);
324
325
326
327
328
      }
    }
  }
}

329
std::string Expression::GetToken(size_t i) {
330
  if (m_tokens.empty())
331
    return m_expr;
332

333
334
335
  if (i < m_tokens.size()) {
    Token &tok = m_tokens[i];
    return m_expr.substr(tok.is, tok.ie - tok.is + 1);
336
337
  }

338
339
  if (i == m_tokens.size()) {
    Token &tok = m_tokens[i - 1];
340
341
342
343
344
345
    return m_expr.substr(tok.is1);
  }

  return "";
}

346
std::string Expression::GetOp(size_t i) {
347
  if (m_tokens.empty() || i >= m_tokens.size())
348
    return "";
349

350
351
  Token &tok = m_tokens[i];
  return m_expr.substr(tok.ie + 1, tok.is1 - tok.ie - 1);
352
353
}

354
void Expression::logPrint(const std::string &pads) const {
355
  std::string myPads = pads + "   ";
356
  if (!m_terms.empty()) {
Hahn, Steven's avatar
Hahn, Steven committed
357
    std::cerr << myPads << m_op << '[' << m_funct << ']' << "(\n";
Hahn, Steven's avatar
Hahn, Steven committed
358
359
    for (const auto &term : m_terms)
      term.logPrint(myPads);
Hahn, Steven's avatar
Hahn, Steven committed
360
    std::cerr << myPads << ")\n";
361
362
  } else
    std::cerr << myPads << m_op << m_funct << '\n';
363
364
}

365
366
void Expression::setFunct(const std::string &name) {
  if (!op_prec(name)) {
367
    std::string op;
368
369
370
    if (name.size() > 1 && is_op_symbol(name[0])) {
      op = name.substr(0, 1);
      if (name.size() > 2 && is_op_symbol(name[1])) {
371
372
373
        op += name[1];
      }
    }
374
    if (!op.empty() && is_unary(op)) {
375
376
377
378
379
380
381
382
383
384
      m_funct = op;
      Expression tmp(this);
      tmp.parse(name.substr(op.size()));
      m_terms.push_back(tmp);
      return;
    }
  }

  m_funct = name;
  trim(m_funct);
385
  if (m_funct.empty()) {
386
387
388
389
390
391
392
    throw std::runtime_error("Expression: Syntax error");
  }

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

  bool inQuotes = false;
393
394
  for (std::string::const_iterator c = name.begin(); c != name.end(); ++c) {
    if (*c == '"') {
395
      inQuotes = !inQuotes;
396
397
398
      continue;
    }

399
    if (!inQuotes && *c == '(') {
400
401
402
403
404
      i = c - name.begin();
      break;
    }
  }

405
  if (i != std::string::npos) {
406
    std::string::size_type j = name.find_last_of(')');
407
    if (j == std::string::npos || j < i) {
408
409
410
      throw std::runtime_error("Unmatched brackets");
    }

411
    if (j > i + 1) // nonzero argument list
412
    {
413
      std::string args = name.substr(i + 1, j - i - 1); //?
414
      trim(args);
415
      std::string f = name.substr(0, i);
416
417
      Expression tmp(this);
      tmp.parse(args);
418
      if (!tmp.isFunct() || tmp.name() != ",") {
419
        m_terms.push_back(tmp);
420
      } else {
421
422
423
424
425
426
427
428
429
        std::string my_op = m_op;
        *this = tmp;
        m_op = my_op;
      }
      m_funct = f;
    }
  }
}

430
std::string Expression::str() const {
431
432
433
  bool brackets = false;
  std::ostringstream res;
  size_t prec = op_prec(m_funct);
434
  if (size() == 1 && is_unary(m_funct)) { // unary operator
435
    res << m_funct;
436
    if (op_prec(m_terms[0].m_funct) > 0) {
437
438
      brackets = true;
    }
439
  } else if (!prec) { // function with a name
440
441
442
443
    res << m_funct;
    brackets = true;
  }

444
  if (!m_terms.empty()) {
445
446
    if (brackets)
      res << '(';
Hahn, Steven's avatar
Hahn, Steven committed
447
448
449
    for (const auto &term : m_terms) {
      res << term.operator_name();
      size_t prec1 = op_prec(term.m_funct);
450
      bool isItUnary = false;
Hahn, Steven's avatar
Hahn, Steven committed
451
      if (term.size() == 1 && is_unary(term.m_funct)) {
452
453
454
        prec1 = 0; // unary operator
        isItUnary = true;
      }
455
456
457
458
459
      bool bk = prec > 0 && prec1 > 0 && prec > prec1;
      if (bk)
        res << '(';
      if (isItUnary)
        res << ' ';
Hahn, Steven's avatar
Hahn, Steven committed
460
      res << term.str();
461
462
      if (bk)
        res << ')';
463
    }
464
465
    if (brackets)
      res << ')';
466
467
468
469
  }
  return res.str();
}

470
471
472
const Expression &Expression::bracketsRemoved() const {
  const Expression *e = this;
  while (e->name().empty() && e->size() == 1) {
473
474
475
476
477
    e = &e->m_terms[0];
  }
  return *e;
}

478
479
480
/**
 * Return a list of all variable names in this expression
 */
481
482
std::unordered_set<std::string> Expression::getVariables() const {
  std::unordered_set<std::string> out;
483
  if (!isFunct()) {
484
    std::string s = name();
485
    if (!s.empty() && !isdigit(s[0])) {
486
487
      out.insert(s);
    }
488
  } else {
489
490
    for (const auto &e : *this) {
      if (e.isFunct()) {
491
        std::unordered_set<std::string> tout = e.getVariables();
492
493
        out.insert(tout.begin(), tout.end());
      } else {
494
        std::string s = e.name();
495
        if (!s.empty() && !isdigit(s[0])) {
496
497
          out.insert(s);
        }
498
499
500
501
502
503
      }
    }
  }
  return out;
}

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

506
507
508
void Expression::renameAll(const std::string &oldName,
                           const std::string &newName) {
  if (!isFunct() && name() == oldName) {
509
    rename(newName);
510
  } else {
511
512
    for (auto &term : m_terms) {
      term.renameAll(oldName, newName);
513
514
515
516
    }
  }
}

517
518
519
void Expression::toList(const std::string &sep) {
  if (name() == sep)
    return;
520
521
522
523
524
525
  Expression term(*this);
  m_terms.resize(1);
  m_terms[0] = term;
  setFunct(sep);
}

526
527
} // API
} // Mantid