https://rentry.org/PPP2_p242

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 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
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// Code derived from Stroustrup's PPP2 book
// § 7.8.1 Variables and definitions
//  -and beginning on p 242

/*
    Simple calculator

    Revision history:

        Revised by Bjarne Stroustrup May 2007
        Revised by Bjarne Stroustrup August 2006
        Revised by Bjarne Stroustrup August 2004
        Originally written by Bjarne Stroustrup
            (bs@cs.tamu.edu) Spring 2004.

    This program implements a basic expression calculator.
    Input from cin; output to cout.

    The grammar for input is:

    Calculation:
        Statement
        Print
        Quit
        Calculation Statement

    Statement:
        Declaration
        Expression

    Declaration:
        "let" Name "=" Expression

    Print:
        ;

    Quit:
        q

    Expression:
        Term
        Expression + Term
        Expression - Term
    Term:
        Primary
        Term * Primary
        Term / Primary
        Term % Primary
    Primary:
        Number
        Name
        ( Expression )
        - Primary
        + Primary
    Number:
        floating-point-literal


        Input comes from cin through the Token_stream called ts.
*/

#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

using namespace std;

void error(string const& s) { throw runtime_error(s); }
void error(string const& s1, string const& s2) { error(s1 + s2); }

// run-time checked narrowing cast (type conversion)
template <class R, class A>
R narrow_cast(A const& a)
{
  R r = R(a);
  if (A(r) != a)
    error("narrow_cast() info loss");

  return r;
}

//------------------------------------------------------------------------------

const char   number  = '8';    // t.kind==number means that t is a number Token
const char   quit    = 'q';    // t.kind==quit means that t is a quit Token
const char   print   = ';';    // t.kind==print means that t is a print Token
const char   name    = 'a';    // name token
const char   let     = 'L';    // declaration token
const string declkey = "let";  // declaration keyword
const string prompt  = "> ";   // used to indicate we're waiting on user input
const string result  = "= ";   // used to indicate that what follows is a result

//------------------------------------------------------------------------------
class Token {
 public:
  Token(char ch) : kind{ch} {}

  Token(char ch, double val) : kind{ch}, value{val} {}

  Token(char ch, string n) : kind{ch}, name{n} {}

  char   kind  = '0';
  double value = 0.0;
  string name;  // for names: name itself
};

//------------------------------------------------------------------------------
class Token_stream {
 public:
  Token_stream();

  Token get();
  void  putback(Token t);
  void  ignore(char c);

 private:
  bool  full;
  Token buffer;
};

//------------------------------------------------------------------------------
Token_stream::Token_stream() : full{false}, buffer{0} {}

//------------------------------------------------------------------------------
// read a token from cin
Token Token_stream::get()
{
  if (full) {  // check if we already have a Token ready
    full = false;
    return buffer;
  }

  char ch;
  cin >> ch;

  // clang-format off
  switch (ch) {
    case print:
    case quit:
    case '(':
    case ')':
    case '+':
    case '-':
    case '*':
    case '/':
    case '%':
    case '=':
      return Token{ch};
      break;
    case '.':
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9': {
      cin.putback(ch);  // put digit back into the input stream
      double val;
      cin >> val;
      return Token{number, val};
      break;
    }
    default:
      if (isalpha(ch)) {
        cin.putback(ch);
        string s;
        cin>>s;

        if (s == declkey)
          return Token{let};  // keyword "let"

        return Token{name, s};
      }
      error("Bad token");
      return Token{'K'};  // invalid, shouldn't reach here
  }
  // clang-format on
}

//------------------------------------------------------------------------------
// put token back into stream
void Token_stream::putback(Token t)
{
  if (full)
    error("putback() into a full buffer");

  buffer = t;
  full   = true;
}

//------------------------------------------------------------------------------
// c represents the kind of a Token
void Token_stream::ignore(char c)
{
  // first look in buffer:
  if (full && c == buffer.kind) {
    full = false;
    return;
  }

  full = false;

  // now search input:
  char ch = 0;
  while (cin >> ch)
    if (ch == c)
      return;
}

//------------------------------------------------------------------------------
class Variable {
 public:
  Variable(string n, double v) : name{n}, value{v} {}

  string name;
  double value;
};

//------------------------------------------------------------------------------

vector<Variable> var_table;

//------------------------------------------------------------------------------

// return the value of the Variable names s
double get_value(string s)
{
  for (unsigned i = 0; i < var_table.size(); ++i)
    if (var_table[i].name == s)
      return var_table[i].value;

  error("get: undefined variable ", s);
  return 0.0;  // shouldn't reach here
}

// set the Variable named s to d
void set_value(string s, double d)
{
  for (unsigned i = 0; i < var_table.size(); ++i)
    if (var_table[i].name == s) {
      var_table[i].value = d;
      return;
    }

  error("set: undefined variable ", s);
}

// is var already in var_table?
bool is_declared(string var)
{
  for (unsigned i = 0; i < var_table.size(); ++i)
    if (var_table[i].name == var)
      return true;

  return false;
}

// add (var,val) to var_table
double define_name(string var, double val)
{
  if (is_declared(var))
    error(var, " declared twice");

  var_table.push_back(Variable{var, val});
  return val;
}

//------------------------------------------------------------------------------

Token_stream ts;

double expression();

//------------------------------------------------------------------------------
// deal with numbers, parentheses, unary -, unary +, and named vars
double primary()
{
  Token t = ts.get();

  switch (t.kind) {
    case '(': {
      double d = expression();

      t = ts.get();
      if (t.kind != ')')
        error("')' expected");

      return d;
      break;
    }
    case number: return t.value; break;
    case name:
      return get_value(t.name);  // return the variable's value
      break;
    case '-': return -primary(); break;
    case '+': return primary(); break;
    default:
      error("primary expected");
      // shouldn't reach here
      return 0.0;
  }
}

//------------------------------------------------------------------------------
// deal with *, /, and %
double term()
{
  double left = primary();

  Token t = ts.get();

  while (true) {
    switch (t.kind) {
      case '*': left *= primary(); break;
      case '/': {
        double d = primary();
        if (d == 0)
          error("divide by zero");

        left /= d;
        break;
      }
      case '%': {
        int i1 = narrow_cast<int>(left);
        int i2 = narrow_cast<int>(primary());
        if (i2 == 0)
          error("%: divide by zero");

        left = i1 % i2;
        break;
      }
      default: ts.putback(t); return left;
    }

    t = ts.get();
  }
}

//------------------------------------------------------------------------------
// deal with + and -
double expression()
{
  double left = term();

  Token t = ts.get();

  while (true) {
    switch (t.kind) {
      case '+': left += term(); break;
      case '-': left -= term(); break;
      default: ts.putback(t); return left;
    }

    t = ts.get();
  }
}
//------------------------------------------------------------------------------
// deal with name = expression
// declare a variable called "name" with the initial value "expression"
double declaration()
{
  Token t = ts.get();
  if (t.kind != name)
    error("name expected in declaration");

  string var_name = t.name;

  Token t2 = ts.get();
  if (t2.kind != '=')
    error("= missing in declaration of ", var_name);

  double d = expression();
  define_name(var_name, d);

  return d;
}

//------------------------------------------------------------------------------
double statement()
{
  Token t = ts.get();

  switch (t.kind) {
    case let: return declaration();
    default: ts.putback(t); return expression();
  }
}

//------------------------------------------------------------------------------
void clean_up_mess() { ts.ignore(print); }

//------------------------------------------------------------------------------
// expression evaluation loop
void calculate()
{
  while (cin)
    try {
      cout << prompt;

      Token t = ts.get();

      while (t.kind == print)
        t = ts.get();

      if (t.kind == quit) {
        cout << "\b\b";
        return;
      }

      ts.putback(t);

      cout << result << statement() << '\n';

    } catch (exception& e) {
      cerr << e.what() << '\n';

      clean_up_mess();
    }
}

//------------------------------------------------------------------------------
int main()
try {
  calculate();

} catch (exception& e) {
  cerr << e.what() << '\n';
  return 1;

} catch (...) {
  cerr << "exception \n";
  return 2;
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_07/main_p242.cpp && ./a.out

PrevUpNext

Edit
Pub: 02 Apr 2023 09:58 UTC
Edit: 02 May 2023 22:02 UTC
Views: 378