-
Notifications
You must be signed in to change notification settings - Fork 0
/
BASIC_Interpreter.cpp
961 lines (750 loc) · 22 KB
/
BASIC_Interpreter.cpp
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
/**
* @file BASIC_Interpreter.cpp
* @author William Weston
* @brief BASIC Interpreter Problem From Kattis
* @version 0.1
* @date 2023-09-23
*
* @copyright Copyright (c) 2023
*
* Link: https://open.kattis.com/problems/basicinterpreter
*/
// ------------------------------------------------------------------------------------------------
// -------------------------------------------- include -------------------------------------------
#include <cctype>
#include <cmath>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <limits>
#include <map>
#include <optional>
#include <stdexcept>
#include <sstream> // istringstream
#include <string>
#include <unordered_map>
#include <utility> // move
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------- Contants.h -----------------------------------------
constexpr auto let_t = '|';
constexpr auto if_t = '%';
constexpr auto print_t = 'p';
constexpr auto println_t = 'q';
constexpr auto then_t = 't';
constexpr auto goto_t = 'g';
constexpr auto literal_t = 's';
constexpr auto number_t = '#';
constexpr auto eol_t = '?';
constexpr auto le_t = '['; // less than or equal to
constexpr auto ge_t = ']'; // greater than or equal to
constexpr auto ne_t = '!'; // not equal to
constexpr auto letkey = "LET";
constexpr auto ifkey = "IF";
constexpr auto printkey = "PRINT";
constexpr auto printlnkey = "PRINTLN";
constexpr auto thenkey = "THEN";
constexpr auto gotokey = "GOTO";
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// -------------------------------------------- Error.h -------------------------------------------
namespace wjtw
{
inline void error ( std::string const& msg )
{
throw std::runtime_error( msg );
}
inline void error( std::string const& msg, int val )
{
throw std::runtime_error( msg + std::to_string( val ) );
}
inline void error( std::string const& msg, std::string const& val )
{
throw std::runtime_error( msg + val );
}
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------- safe_int_t.h ---------------------------------------
class safe_int_t final
{
public:
constexpr safe_int_t( int value = 0 ) noexcept
: value_{ value } {}
constexpr auto value() const noexcept -> int;
constexpr auto operator+= ( safe_int_t rhs ) -> safe_int_t&;
constexpr auto operator-= ( safe_int_t rhs ) -> safe_int_t&;
constexpr auto operator*= ( safe_int_t rhs ) -> safe_int_t&;
constexpr auto operator/= ( safe_int_t rhs ) -> safe_int_t&;
private:
int value_;
};
constexpr auto operator== ( safe_int_t lhs, safe_int_t rhs ) noexcept -> bool;
constexpr auto operator< ( safe_int_t lhs, safe_int_t rhs ) noexcept -> bool;
constexpr auto operator!= ( safe_int_t lhs, safe_int_t rhs ) noexcept -> bool;
constexpr auto operator> ( safe_int_t lhs, safe_int_t rhs ) noexcept -> bool;
constexpr auto operator<= ( safe_int_t lhs, safe_int_t rhs ) noexcept -> bool;
constexpr auto operator>= ( safe_int_t lhs, safe_int_t rhs ) noexcept -> bool;
constexpr auto operator+ ( safe_int_t lhs, safe_int_t rhs ) noexcept -> safe_int_t;
constexpr auto operator- ( safe_int_t lhs, safe_int_t rhs ) noexcept -> safe_int_t;
constexpr auto operator* ( safe_int_t lhs, safe_int_t rhs ) noexcept -> safe_int_t;
constexpr auto operator/ ( safe_int_t lhs, safe_int_t rhs ) noexcept -> safe_int_t;
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ----------------------------------------- Symbol_table.h ---------------------------------------
class Symbol_table final
{
public:
auto get_value( char symbol ) -> int;
auto set_value( char symbol, int value ) -> void;
auto add_symbol( char symbol, int value ) -> void;
auto is_declared( char symbol ) const -> bool;
private:
std::unordered_map<char, int> table_;
};
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------- Token.h --------------------------------------------
struct Token final
{
constexpr Token() noexcept = default;
Token( char aKind, int aValue = 0 )
: kind{ aKind }, value{ aValue } {}
Token( char aKind, std::string aName )
: kind{ aKind }, name{ std::move( aName ) } {}
char kind = eol_t; // end-of-line
int value = 0;
std::string name = {};
};
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ---------------------------------------- Token_stream.h ----------------------------------------
class Token_stream final
{
public:
auto reset( std::string const& expression ) -> void;
auto get() -> Token;
auto putback( Token token ) -> void;
auto ignore( char ch ) -> void;
private:
std::istringstream stream_ = {};
Token buffer_ = {};
bool is_full_ = false;
};
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ----------------------------------------- Interpreter.h ----------------------------------------
class Interpreter final
{
using line_pointer_t = std::map<int, std::string>::iterator;
public:
explicit Interpreter( std::istream& in = std::cin, std::ostream& out = std::cout );
private:
std::map<int, std::string> program_ = {};
line_pointer_t line_pointer_;
Symbol_table symbol_table_;
Token_stream token_stream_;
std::ostream& out_;
auto parse_input( std::istream& in ) -> void;
auto evaluate_program() -> void;
auto statement() -> std::optional<int>; // optional next line to evaluate
auto assignment() -> void;
auto if_block() -> std::optional<int>;
auto print() -> void;
auto println() -> void;
auto print_statement() -> std::string;
auto arithmetic_statment() -> int;
auto primary() -> int;
auto condition() -> bool;
};
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ---------------------------------------------- main ---------------------------------------------
auto
main() -> int
{
try
{
auto basic = Interpreter();
}
catch( std::exception const& e)
{
std::cerr << e.what() << '\n';
}
return EXIT_SUCCESS;
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// --------------------------------------- safe_int_t.inl -----------------------------------------
// ------------------------------------------ details ---------------------------------------------
namespace details
{
constexpr auto wrap( double n ) noexcept -> int;
}
auto
is_alpha( char ch ) -> bool
{
return std::isalpha( static_cast<unsigned char>( ch ) );
}
auto
is_upper( char ch ) -> bool
{
return std::isupper( static_cast<unsigned char>( ch ) );
}
auto
is_space( char ch ) -> bool
{
return std::isspace( static_cast<unsigned char>( ch ) );
}
// ----------------------------------------- Interface --------------------------------------------
constexpr auto
safe_int_t::value() const noexcept -> int
{
return value_;
}
constexpr auto
safe_int_t::operator+= ( safe_int_t rhs ) -> safe_int_t&
{
auto const n = static_cast<double>( value_ ) + static_cast<double>( rhs.value_ );
value_ = details::wrap( n );
return *this;
}
constexpr auto
safe_int_t::operator-= ( safe_int_t rhs ) -> safe_int_t&
{
auto const n = static_cast<double>( value_ ) - static_cast<double>( rhs.value_ );
value_ = details::wrap( n );
return *this;
}
constexpr auto
safe_int_t::operator*= ( safe_int_t rhs ) -> safe_int_t&
{
auto const n = static_cast<double>( value_ ) * static_cast<double>( rhs.value_ );
value_ = details::wrap( n );
return *this;
}
constexpr auto
safe_int_t::operator/= ( safe_int_t rhs ) -> safe_int_t&
{
value_ /= rhs.value_;
return *this;
}
// ------------------------------------- Non-Member Interface -------------------------------------
constexpr auto
operator== ( safe_int_t lhs, safe_int_t rhs ) noexcept -> bool
{
return lhs.value() == rhs.value();
}
constexpr auto
operator< ( safe_int_t lhs, safe_int_t rhs ) noexcept -> bool
{
return lhs.value() < rhs.value();
}
constexpr auto
operator!= ( safe_int_t lhs, safe_int_t rhs ) noexcept -> bool
{
return !( lhs == rhs );
}
constexpr auto
operator> ( safe_int_t lhs, safe_int_t rhs ) noexcept -> bool
{
return rhs < lhs;
}
constexpr auto
operator<= ( safe_int_t lhs, safe_int_t rhs ) noexcept -> bool
{
return !( rhs < lhs );
}
constexpr auto
operator>= ( safe_int_t lhs, safe_int_t rhs ) noexcept -> bool
{
return !( lhs < rhs );
}
constexpr auto
operator+ ( safe_int_t lhs, safe_int_t rhs ) noexcept -> safe_int_t
{
return lhs += rhs;
}
constexpr auto
operator- ( safe_int_t lhs, safe_int_t rhs ) noexcept -> safe_int_t
{
return lhs -= rhs;
}
constexpr auto
operator* ( safe_int_t lhs, safe_int_t rhs ) noexcept -> safe_int_t
{
return lhs *= rhs;
}
constexpr auto
operator/ ( safe_int_t lhs, safe_int_t rhs ) noexcept -> safe_int_t
{
return lhs /= rhs;
}
// ---------------------------------------- details ------------------------------------------------
constexpr auto
details::wrap( double n ) noexcept -> int
{
constexpr auto const min = std::numeric_limits<int>::min();
constexpr auto const max = std::numeric_limits<int>::max();
while ( n < min || n > max )
{
if ( n < 0 )
{
n = max + ( n - ( min - 1.0 ) );
}
else if ( n > 0 )
{
n = min + ( n - ( max + 1.0 ) );
}
}
return static_cast<int>( std::round( n ) );
}
// ------------------------------------------------------------------------------------------------
// ---------------------------------------- Interpreter.cpp ---------------------------------------
// ------------------------------------------------------------------------------------------------
Interpreter::Interpreter( std::istream& in, std::ostream& out )
: out_{ out }
{
parse_input( in );
line_pointer_ = program_.begin();
evaluate_program();
}
auto
Interpreter::parse_input( std::istream& in ) -> void
{
int line_no;
while ( in >> line_no )
{
auto line = std::string();
std::getline( in >> std::ws, line );
program_[line_no] = line;
}
}
auto
Interpreter::evaluate_program() -> void
{
while ( line_pointer_ != program_.end() )
{
token_stream_.reset( line_pointer_->second );
auto const opt_next_line = statement();
if ( opt_next_line )
line_pointer_ = program_.find( *opt_next_line );
else
++line_pointer_;
}
}
auto
Interpreter::statement() -> std::optional<int>
{
auto token = token_stream_.get();
switch ( token.kind )
{
case let_t:
{
assignment();
return std::nullopt;
}
case if_t:
{
return if_block();
}
case print_t:
{
print();
return std::nullopt;
}
case println_t:
{
println();
}
}
return std::nullopt;
}
auto
Interpreter::if_block() -> std::optional<int>
{
if ( condition() )
{
auto const then_token = token_stream_.get();
if ( then_token.kind != then_t )
{
wjtw::error( "THEN token expected after IF" );
}
auto const goto_token = token_stream_.get();
if ( goto_token.kind != goto_t )
{
wjtw::error( "GOTO token expected after THEN" );
}
auto const line_token = token_stream_.get();
if ( line_token.kind != number_t )
{
wjtw::error( "Line No. expected after GOTO" );
}
return line_token.value;
}
return std::nullopt;
}
auto
Interpreter::print() -> void
{
out_ << print_statement();
}
auto
Interpreter::println() -> void
{
out_ << print_statement() << '\n';
}
auto
Interpreter::print_statement() -> std::string
{
auto const token = token_stream_.get();
if ( is_upper( token.kind ) ) // variable name
{
auto const value = symbol_table_.get_value( token.kind );
return std::to_string( value );
}
switch ( token.kind )
{
case literal_t:
{
return token.name; // string literal
}
}
wjtw::error( "non-printable token" );
return {};
}
auto
Interpreter::assignment() -> void
{
auto const token = token_stream_.get();
if ( !is_upper( token.kind ) ) //
{
wjtw::error( "expected variable name in assignment" );
}
auto const equal_token = token_stream_.get();
if ( equal_token.kind != '=' )
{
wjtw::error( "assignment expects = sign" );
}
auto const var_name = token.kind;
auto const value = arithmetic_statment();
symbol_table_.set_value( var_name, value );
}
/**
* @brief
*
* @return int
*
* Grammar:
* Primary
* Primary + Primary
* Primary - Primary
* Primary * Primary
* Primary / Primary
*/
auto
Interpreter::arithmetic_statment() -> int
{
auto left = primary();
auto token = token_stream_.get();
while ( true )
switch ( token.kind ) // TODO: must alter to account for overflow/underflow
{
case '+':
{
auto const safe = safe_int_t( left ) + safe_int_t( primary() );
return safe.value();
}
case '-':
{
auto const safe = safe_int_t( left ) - safe_int_t( primary() );
return safe.value();
}
case '*':
{
auto const safe = safe_int_t( left ) * safe_int_t( primary() );
return safe.value();
}
case '/':
return left / primary();
default:
token_stream_.putback( std::move( token ) );
return left;
}
}
/**
* @brief
*
* @return int
*
* Grammar:
* Number
* Variable
*/
auto
Interpreter::primary() -> int
{
auto const token = token_stream_.get();
switch ( token.kind )
{
case number_t:
return token.value;
case '-':
return -primary();
case '+':
return primary();
}
if ( is_upper( token.kind ) ) // variable name
{
return symbol_table_.get_value( token.kind );
}
wjtw::error( "expected primary" );
return -1; //
}
/**
* @brief
*
* @return true
* @return false
*
* Grammar:
* Primary = Primary
* Primary <> Primary // inequality
* Primary > Primary
* Primary < Primary
* Primary <= Primary
* Primary >= Primary
*/
auto
Interpreter::condition() -> bool
{
auto const left = primary();
auto const compare = token_stream_.get();
switch ( compare.kind )
{
case '<':
{
auto const right = primary();
return left < right;
}
case le_t:
{
auto const right = primary();
return left <= right;
}
case '>':
{
auto const right = primary();
return left > right;
}
case ge_t:
{
auto const right = primary();
return left >= right;
}
case '=':
{
auto const right = primary();
return left == right;
}
case ne_t:
{
auto const right = primary();
return left != right;
}
default:
{
wjtw::error( "Condition requires comparison operator" );
return false;
}
}
}
// ------------------------------------------------------------------------------------------------
// --------------------------------------- Symbol_table.cpp ---------------------------------------
// ------------------------------------------------------------------------------------------------
/**
* @brief
*
* @param symbol
* @return int
* @note Any variable that doesn't exist will be entered into the table and zero initialized
*/
auto
Symbol_table::get_value(char symbol ) -> int
{
if ( is_declared( symbol ) )
{
return table_[symbol];
}
add_symbol( symbol, 0 );
return 0;
}
auto
Symbol_table::set_value( char symbol, int const value ) -> void
{
table_[symbol] = value;
}
auto
Symbol_table::add_symbol( char symbol, int const value ) -> void
{
table_[symbol] = value;
}
auto
Symbol_table::is_declared( char symbol ) const -> bool
{
return table_.count( symbol );
}
// ------------------------------------------------------------------------------------------------
// --------------------------------------- Token_stream.cpp ---------------------------------------
// ------------------------------------------------------------------------------------------------
auto
Token_stream::reset( std::string const& expression ) -> void
{
is_full_ = false;
stream_.str( expression ); // equivalent to stream_.rdbuf()->str(s);
stream_.clear(); // clear the flags
stream_.seekg( std::ios_base::beg ); // reposition the stream to the beginning
}
auto
Token_stream::get() -> Token
{
if ( is_full_ ) // if there is a token in the buffer
{
is_full_ = false;
return buffer_;
}
char tmp;
stream_ >> tmp;
if ( !stream_ )
return Token(); // default is end-of-line token
switch ( tmp )
{
case '=':
case '+':
case '-':
case '*':
case '/':
{
return Token( tmp ); // let each character represent itself
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
stream_.putback( tmp ); // put the digit back onto the input stream
int value;
stream_ >> value; // read an integer
return Token( number_t, value );
}
case '<': // could be <, <=, <>
{
if ( stream_.get( tmp ) )
{
switch ( tmp )
{
case '=':
{
return Token( le_t ); // less than or equal to
}
case '>':
{
return Token( ne_t ); // not equal to
}
default:
stream_.putback( tmp );
}
}
return Token( '<' ); // less than
}
case '>': // >, >=
{
if ( stream_.get( tmp ) )
{
if ( tmp == '=' )
return Token( ge_t ); // greater than or equal to
stream_.putback( tmp );
}
return Token( '>' ); // greater than
}
case '"':
{
auto str = std::string();
while ( stream_.get( tmp ) && tmp != '"' )
{
str += tmp;
}
if ( tmp != '"' )
wjtw::error( "no closing quote on string literal" );
return Token( literal_t, std::move( str ) );
}
default: // could be variable name, or keyword ( GOTO, PRINT, PRINTLN, IF, THEN )
{
if ( is_alpha( tmp ) )
{
// check if we have a single character variable
auto next = char{};
if ( !stream_.get( next ) || is_space( next ) )
{
return Token( tmp );
}
stream_.putback( next );
auto str = std::string();
str += tmp;
while ( stream_.get( tmp ) && is_alpha( tmp ) )
{
str += tmp;
}
stream_.putback( tmp ); // if we've read to far put the character back on the stream otherwise we're at eof and it doesn't matter
if ( str == letkey )
return Token( let_t );
if ( str == ifkey )
return Token( if_t );
if ( str == printkey )
return Token( print_t );
if ( str == printlnkey )
return Token( println_t );
if ( str == thenkey )
return Token( then_t );
if ( str == gotokey )
return Token( goto_t );
}
}
} // end switch
wjtw::error( "Bad Token" );
return {};
}
auto
Token_stream::putback( Token token ) -> void
{
if ( is_full_ )
{
wjtw::error( "putback() into a full buffer" );
}
buffer_ = std::move( token );
is_full_ = true;
}
auto
Token_stream::ignore( char const ch ) -> void
{
// first look in the buffer
if ( is_full_ && ch == buffer_.kind )
{
is_full_ = false;
return;
}
is_full_ = false;
char tmp;
while ( stream_ >> tmp ) // advance the stream until we've encountered the character we wish to ignore
{
if ( tmp == ch )
return;
}
}
// ------------------------------------------------------------------------------------------------