-
Notifications
You must be signed in to change notification settings - Fork 2
/
Abaci0.lit
5386 lines (4742 loc) · 261 KB
/
Abaci0.lit
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
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Abaci0: A JIT-compiled, statically-typed, and interactive scripting language
*Programming language design has to be an art as well as a science. The ability to appeal to (human) coders is not something which always comes naturally to computer scientists, while the science element may be too technically complex for the amateur coder to venture into. Surely the skill lies in compromising the least to both accessibility, and implementation limitations? Abaci0 achieves this by having several, usually contradictory, features. It is statically typed, but variable assignments and function calls do not require type annotations. It is whitespace-neutral, without requiring semi-colons or other statement delimiters. It does not have a hand-written scanner/parser, or even a machine generated one, relying purely on the Boost Spirit X3 library to parse input rapidly. It is not another transpiler (to C or JavaScript), but produces native code dynamically via the LLVM backend.*
The source code for this program is organized in a logical fashion, with six directories each containing a small number of C++ header and implementation files. In general, all of the code within each file is within a namespace named after the directory, for example `abaci::ast`—the major exceptions to this convention are the files `lib/Abaci.hpp` and `lib/Abaci.cpp`, where the functions declared are at global scope (and use C-linkage) for ease of referencing within the generated code.
The source code presented in this literate program is discussed in the following sequence:
* `utility`: Code to facilitate the static type system and symbol table, manage lexical scoping and report errors (with a source location).
* `lib`: Functions directly exposed to the JIT engine at runtime, depending only upon the source files in `utility` as well as the C++ standard library and libfmt.
* `ast`: Two C++ headers which define all of the classes used to hold the Abstract Syntax Tree.
* `parser`: All of the Boost Spirit X3 parsing code logic is within this directory, together with header files declaring all of the Abaci keywords and other symbols, and diagnostic error messages used throughout the code.
* `codegen`: Translation of the constructed AST into LLVM API calls is performed by the code within this directory.
* `engine`: Handles management of the function cache and creation of a standalone function to execute the generated code.
* `main.cpp`: The simple frontend and driver presented allows per-file and per-statement JIT compilation and execution.
Notes added to the descriptions take the form [Note: ...] and may be of a different style to the rest of the discussion. They are often intended to clarify the state of functionality and completeness of the project so far, as well as outline the future direction of code improvements.
## Directory `utility`
### `Utility.hpp`
The class `AbaciValue` is the foundation of the static type system for Abaci0, providing support for seven different types. The basis for the class is a "tagged union" where the size of the `value` union is guaranteed to be 64 bits wide. The `type` field is based upon a (plain) enum, and is always initialized when an `AbaciValue` is first created. [Note: The need for this type field is possibly questionable as Abaci0 is a statically-typed language and type information for each symbol is held in the various `DefineScope`s constructed at compile-time. A future improvement could be to omit this field, however it is not clear whether this is technically possible.]
```cpp
//@src/utility/Utility.hpp@+10,-0
#ifndef Utility_hpp
#define Utility_hpp
#include <string>
#include <sstream>
#include <unordered_map>
#include <vector>
#include <ostream>
#include <cstring>
namespace abaci::utility {
struct AbaciValue;
```
The `Complex`, `String` and `Object` types are intended to be able to be created using LLVM API calls and so are plain structs. Two constructors are provided for `String`—one for the parser to create string constants and one for use by the `clone()` function. The composite `Object` class has its constructor and destructor in `lib/Abaci.cpp` due to the fact it references an incomplete `AbaciType`. Class `Variable` is a wrapper around a `std::string` and exists to hold a variable name.
```cpp
struct Complex {
double real{}, imag{};
};
struct String {
char8_t *ptr{ nullptr };
std::size_t len{};
String(const std::string& s) {
ptr = new char8_t[s.size() + 1];
strcpy(reinterpret_cast<char*>(ptr), s.c_str());
len = s.size();
}
String(const char8_t *p, std::size_t l) {
ptr = new char8_t[l + 1];
strcpy(reinterpret_cast<char*>(ptr), reinterpret_cast<const char*>(p));
len = l;
}
~String() { delete[] ptr; ptr = nullptr; len = 0; }
};
struct Object {
char8_t *class_name;
std::size_t variables_sz;
AbaciValue *variables;
Object(const char8_t *s, std::size_t sz, AbaciValue *data);
~Object();
};
class Variable {
std::string name;
public:
Variable() = default;
Variable(const Variable&) = default;
Variable& operator=(const Variable&) = default;
Variable(const std::string& name) : name{ name } {}
const auto& get() const { return name; }
bool operator==(const Variable& rhs) const { return name == rhs.name; }
};
```
Class `AbaciValue`'s `Type` enum lists all of the possible types (in approximate order of "complexity"), as well as a `Constant` bit used for `let =`, and a `TypeMask` to mask out this bit when constants are dereferenced. The type `Unset` is only used when attempting to determine a function's return type. The `value` union is intended to be set to all zero bits when an `AbaciValue` is created; setting of the `type` field is always mandatory. The default constructor creates a `Nil` type, the other six are declared `explicit` to avoid unwanted type conversions; these constructors are only intended to be called from the parser to utilize constant values declared within the Abaci0 program. The `value.integer` field stores 64-bit integers in unsigned form even though signed Math takes place during code generation; this allows input and correct parsing of large positive values (such as `0x8000000000000000`) which are then treated as two's-complement signed.
```cpp
struct AbaciValue {
enum Type { Nil, Boolean, Integer, Float, Complex, String, Object, TypeMask = 15, Constant = 16, Real = 98, Imaginary, Unset = 127 };
union {
void *nil{ nullptr };
bool boolean;
unsigned long long integer;
double floating;
abaci::utility::Complex *complex;
abaci::utility::String *str;
abaci::utility::Object *object;
} value;
Type type;
AbaciValue() : type{ Nil } {}
explicit AbaciValue(bool b) : type{ Boolean } { value.boolean = b; }
explicit AbaciValue(unsigned long long ull) : type{ Integer } { value.integer = ull; }
explicit AbaciValue(double d) : type{ Float } { value.floating = d; }
explicit AbaciValue(double real, double imag) : type{ Complex } { value.complex = new abaci::utility::Complex{ real, imag }; }
explicit AbaciValue(const std::string& s) : type{ String } { value.str = new abaci::utility::String(s); }
explicit AbaciValue(const char8_t *s, std::size_t sz, AbaciValue *data) : type{ Object } { value.object = new abaci::utility::Object(s, sz, data); }
```
The copy constructor and copy-assignment operator both perform a deep copy on types that need it (`Complex`, `String` and `Object`), calling private member function `clone()` to do this. The destructor is required in order to correctly release memory used by these types, and is explicitly invoked for the copy-assignment operator.
```cpp
AbaciValue(const AbaciValue& rhs) { clone(rhs); }
AbaciValue& operator=(const AbaciValue& rhs) { if (this != &rhs) { this->~AbaciValue(); clone(rhs); } return *this; }
~AbaciValue();
private:
void clone(const AbaciValue&);
};
static_assert(sizeof(AbaciValue::value) == 8, "AbaciValue::value must be exactly 64 bits");
```
The scoped enum `Operator` lists all of the operators used by Abaci0. A mapping of the string values to these tokens is held in the map `Operators`, with the string values as the keys. There is a `TypeConversions` map declared here whose only client is `parser/Parse.cpp`.
```cpp
//#@+0,-2
enum class Operator { None, Plus, Minus, Times, Divide, Modulo, FloorDivide, Exponent,
Equal, NotEqual, Less, LessEqual, GreaterEqual, Greater,
Not, And, Or, Compl, BitAnd, BitOr, BitXor,
Comma, SemiColon, From, To };
extern const std::unordered_map<std::string,Operator> Operators;
extern const std::unordered_map<std::string,AbaciValue::Type> TypeConversions;
} // namespace abaci::utility
#endif
```
### `Utility.cpp`
Global container `Operators` is defined in this implementation file as a `std::unordered_map`, with the keys being string representations defined in `parser/Keywords.hpp` and the only client being `parser/Parse.cpp`. Container `TypeConversions` similarly uses keys of string representations of target types and values of type `AbaciValue::Type`.
```cpp
//@src/utility/Utility.cpp@+4,-0
#include "Utility.hpp"
#include "Report.hpp"
#include "parser/Keywords.hpp"
namespace abaci::utility {
const std::unordered_map<std::string,Operator> Operators{
{ PLUS, Operator::Plus },
{ MINUS, Operator::Minus },
{ TIMES, Operator::Times },
{ DIVIDE, Operator::Divide },
{ MODULO, Operator::Modulo },
{ FLOOR_DIVIDE, Operator::FloorDivide },
{ EXPONENT, Operator::Exponent },
{ EQUAL, Operator::Equal },
{ NOT_EQUAL, Operator::NotEqual },
{ LESS, Operator::Less },
{ LESS_EQUAL, Operator::LessEqual },
{ GREATER_EQUAL, Operator::GreaterEqual },
{ GREATER, Operator::Greater },
{ NOT, Operator::Not },
{ AND, Operator::And },
{ OR, Operator::Or },
{ BITWISE_COMPL, Operator::Compl },
{ BITWISE_AND, Operator::BitAnd },
{ BITWISE_OR, Operator::BitOr },
{ BITWISE_XOR, Operator::BitXor },
{ COMMA, Operator::Comma },
{ SEMICOLON, Operator::SemiColon },
{ FROM, Operator::From },
{ TO, Operator::To }
};
const std::unordered_map<std::string,AbaciValue::Type> TypeConversions{
{ INT, AbaciValue::Integer },
{ FLOAT, AbaciValue::Float },
{ COMPLEX, AbaciValue::Complex },
{ STR, AbaciValue::String },
{ REAL, AbaciValue::Real },
{ IMAG, AbaciValue::Imaginary }
};
```
Function `AbaciValue::clone()` needs to mask out the `Constant` bit before performing a deep copy, ensuring to not copy null `Complex`, `String` or `Object` types other than as `nullptr`. Class `Object`'s constructor also makes a deep copy, which may possibly include recursive copying.
```cpp
void AbaciValue::clone(const AbaciValue& rhs) {
switch (rhs.type & TypeMask) {
case Nil:
break;
case Boolean:
value.boolean = rhs.value.boolean;
break;
case Integer:
value.integer = rhs.value.integer;
break;
case Float:
value.floating = rhs.value.floating;
break;
case Complex:
value.complex = rhs.value.complex ? new abaci::utility::Complex{ rhs.value.complex->real, rhs.value.complex->imag } : nullptr;
break;
case String:
value.str = rhs.value.str ? new abaci::utility::String(rhs.value.str->ptr, rhs.value.str->len) : nullptr;
break;
case Object:
value.object = rhs.value.object ? new abaci::utility::Object(rhs.value.object->class_name, rhs.value.object->variables_sz, rhs.value.object->variables) : nullptr;
break;
default:
break;
}
type = rhs.type;
}
Object::Object(const char8_t *s, std::size_t sz, AbaciValue *data) {
class_name = new char8_t[strlen(reinterpret_cast<const char*>(s)) + 1];
strcpy(reinterpret_cast<char*>(class_name), reinterpret_cast<const char*>(s));
variables_sz = sz;
variables = new AbaciValue[variables_sz];
for (std::size_t i = 0; i != variables_sz; ++i) {
variables[i] = AbaciValue(data[i]);
}
}
```
Similarly the destructor for `AbaciValue` needs only perform cleanup on types which allocate heap memory. The destructor for `Object` also performs cleanup on all of its heap memory usage.
```cpp
AbaciValue::~AbaciValue() {
switch (type & TypeMask) {
case Complex:
delete value.complex;
value.complex = nullptr;
break;
case String:
delete value.str;
value.str = nullptr;
break;
case Object:
delete value.object;
value.object = nullptr;
break;
default:
break;
}
}
Object::~Object() {
for (std::size_t i = 0; i != variables_sz; ++i) {
variables[i].~AbaciValue();
}
delete[] variables;
variables_sz = 0;
delete[] class_name;
class_name = nullptr;
}
} // namespace abaci::utility
```
### `Environment.hpp`
The class `Environment` forms the basis for lexical and per-function scoping in the Abaci0 language. Only a single instance of `Environment` is intended to be created for a program session (per-statement or whole-file compilation) and this object holds the state of the program during parsing and execution. The two types of state are distinct, only type information for each scope is needed during parsing and type-checking, and this is held in `Environment::DefineScope` instances, while value and type information held in `Environment::Scope` instances is used by the running program (via calls to functions declared in `lib/Abaci.hpp`).
Both class `Environment::DefineScope` and class `Environment::Scope` hold a shared pointer to their parent, which is `nullptr` in the case of global scope. `Environment`'s `current_define_scope`, `global_define_scope` and `current_scope` are initialized in the constructor as global scope holders. Method `Environment::beginDefineScope()` creates a new sub-scope with either a named parent as the enclosing scope, or the current scope as the enclosing scope, assigning this to `current_define_scope`. Method `Environment::endDefineScope()` sets the `current_define_scope` to its enclosing scope, causing the ending scope to be deleted as no more shared pointers will refer to it. Methods `Environment::beginScope()` and `Environment::endScope()` provide similar behaviour for runtime scopes.
```cpp
//@src/utility/Environment.hpp@+10,-2
#ifndef Environment_hpp
#define Environment_hpp
#include "Utility.hpp"
#include <string>
#include <unordered_map>
#include <vector>
#include <variant>
#include <memory>
namespace abaci::utility {
class Environment {
public:
class DefineScope {
public:
struct Object {
std::string class_name;
std::vector<std::variant<AbaciValue::Type,Object>> object_types;
};
using Type = std::variant<AbaciValue::Type,Object>;
private:
std::unordered_map<std::string,Type> types;
std::shared_ptr<DefineScope> enclosing;
public:
DefineScope(std::shared_ptr<DefineScope> enclosing = nullptr) : enclosing{ enclosing } {}
void setType(const std::string& name, const Type& type);
Type getType(const std::string& name) const;
bool isDefined(const std::string& name) const;
std::shared_ptr<DefineScope> getEnclosing() { return enclosing; }
int getDepth() const;
};
class Scope {
std::unordered_map<std::string,AbaciValue> variables;
std::shared_ptr<Scope> enclosing;
public:
Scope(std::shared_ptr<Scope> enclosing = nullptr) : enclosing{ enclosing } {}
void defineValue(const std::string& name, const AbaciValue& value);
void setValue(const std::string& name, const AbaciValue& value);
AbaciValue *getValue(const std::string& name);
std::shared_ptr<Scope> getEnclosing() { return enclosing; }
};
Environment() {
current_define_scope = global_define_scope = std::make_unique<DefineScope>();
current_scope = std::make_unique<Scope>();
}
void beginDefineScope(std::shared_ptr<DefineScope> parent = nullptr) {
if (parent) {
current_define_scope = std::make_unique<DefineScope>(parent);
}
else {
current_define_scope = std::make_unique<DefineScope>(current_define_scope);
}
}
void endDefineScope() {
current_define_scope = current_define_scope->getEnclosing();
}
void beginScope() {
current_scope = std::make_unique<Scope>(current_scope);
}
void endScope() {
current_scope = current_scope->getEnclosing();
}
```
The purpose of `Environment::setCurrentDefineScope()` is to allow function instantiations to only access global and parameter variables, thus the `DefineScope` is a subset of the `Scope` and local functions are therefore disallowed. The `DefineScope` needs to be reset (using a call to the same function) once the function instantiation is complete.
A getter for the current `Scope` is provided for client code in `lib/Abaci.cpp` to lookup/set values in the current scope. The function `Environment::reset()` deletes all scopes except for global in case of an exception being thrown in an interactive session.
Three access functions for handling nested "this pointers" are provided, and are used by client code again in `lib/Abaci.cpp`.
```cpp
std::shared_ptr<DefineScope> getCurrentDefineScope() { return current_define_scope; }
std::shared_ptr<DefineScope> getGlobalDefineScope() { return global_define_scope; }
void setCurrentDefineScope(std::shared_ptr<DefineScope> scope) { current_define_scope = scope; }
std::shared_ptr<Scope> getCurrentScope() { return current_scope; }
void reset() {
while (current_scope->getEnclosing()) {
endScope();
}
while (current_define_scope->getEnclosing()) {
endDefineScope();
}
this_ptrs.clear();
}
void setThisPtr(AbaciValue *ptr) { this_ptrs.push_back(ptr); }
void unsetThisPtr() { this_ptrs.pop_back(); }
AbaciValue *getThisPtr() { return this_ptrs.empty() ? nullptr : this_ptrs.back(); }
private:
std::shared_ptr<Scope> current_scope;
std::shared_ptr<DefineScope> current_define_scope, global_define_scope;
std::vector<AbaciValue*> this_ptrs;
};
```
The function `mangled()` takes a function name and its input parameter types and returns a unique mangled name, used for Abaci0 function instantiation as unique LLVM functions, while `environmentTypeToType()` converts a (possibly composite) `DefineScope` type to a simple integer value. The equality-comparison operator for `DefineScope::Type` is also declared here, as are aliases for an object's "this pointer" and return value name.
```cpp
std::string mangled(const std::string& name, const std::vector<Environment::DefineScope::Type>& types);
AbaciValue::Type environmentTypeToType(const Environment::DefineScope::Type& env_type);
bool operator==(const Environment::DefineScope::Type& lhs, const Environment::DefineScope::Type& rhs);
} // namespace abaci::utility
inline const char *RETURN_VAR = "_return", *THIS_VAR = "_this";
#endif
```
### `Environment.cpp`
Method `setType()` only allows creation of new variables in the current `DefineScope`, and reports an error if it finds one with the same name.
```cpp
//@src/utility/Environment.cpp@+6,-0
#include "Environment.hpp"
#include "utility/Report.hpp"
#include "parser/Messages.hpp"
#include <charconv>
#include <cctype>
namespace abaci::utility {
void Environment::DefineScope::setType(const std::string& name, const Environment::DefineScope::Type& type) {
auto iter = types.find(name);
if (iter == types.end()) {
types.insert({ name, type });
}
else {
UnexpectedError1(VarExists, name);
}
}
```
Method `getType()` searches recursively down the `DefineScope` hierarchy for a variable with the required name, stopping and reporting an error only at global scope.
```cpp
Environment::DefineScope::Type Environment::DefineScope::getType(const std::string& name) const {
auto iter = types.find(name);
if (iter != types.end()) {
return iter->second;
}
else if (enclosing) {
return enclosing->getType(name);
}
else {
UnexpectedError1(VarNotExist, name);
}
}
```
Method `isDefined()` allows the code generation functions to trap the error that would be generated by `getType()` on a non-existent variable.
```cpp
bool Environment::DefineScope::isDefined(const std::string& name) const {
auto iter = types.find(name);
if (iter != types.end()) {
return true;
}
else if (enclosing) {
return enclosing->isDefined(name);
}
else {
return false;
}
}
```
Method `getDepth()` returns a nesting depth (starting at zero) of the current `DefineScope`, which is used by Abaci0 return statements within lexical scopes, to generate the correct number of runtime library `endScope()` calls.
```cpp
int Environment::DefineScope::getDepth() const {
if (!enclosing) {
return 0;
}
else {
return 1 + enclosing->getDepth();
}
}
```
Moving on to `Scope` methods, `defineValue()` sets the initial value of a variable in the current scope, reporting an error if a variable already exists.
```cpp
void Environment::Scope::defineValue(const std::string& name, const AbaciValue& value) {
auto iter = variables.find(name);
if (iter == variables.end()) {
variables.insert({ name, value });
}
else {
UnexpectedError1(VarExists, name);
}
}
```
Method `setValue()` recursively looks for a variable with the requested name, reporting an error if none is found, or the existing variable has a different type.
```cpp
void Environment::Scope::setValue(const std::string& name, const AbaciValue& value) {
auto iter = variables.find(name);
if (iter != variables.end()) {
if (value.type == iter->second.type) {
iter->second = value;
}
else {
UnexpectedError1(VarType, name);
}
}
else if (enclosing) {
enclosing->setValue(name, value);
}
else {
UnexpectedError1(VarNotExist, name);
}
}
```
Method `getValue()` returns the address of a variable with the requested name, reporting an error if none is found. The fact that no new object is created (returned) is the basis for the memory management of the Abaci0 JIT, which uses the symbol table in the `Environment::Scope` as the method of releasing memory used by variables going out of scope.
```cpp
AbaciValue *Environment::Scope::getValue(const std::string& name) {
auto iter = variables.find(name);
if (iter != variables.end()) {
return &iter->second;
}
else if (enclosing) {
return enclosing->getValue(name);
}
else {
UnexpectedError1(VarNotExist, name);
}
}
```
Global function `mangled()` creates a unique function name based upon the types of its parameters. A call to `f(a,b)` where `a` is an `AbaciValue::Integer` and `b` is an `AbaciValue::Floating` would be given the name `f_2_3`. Mangling for top-bit-set character strings, intended for use with UTF-8 identifiers, is also supported by translation to hexadecimal; this function is used to allow per-type function instantiation by `engine/Cache.cpp` and `engine/JIT.cpp`.
```cpp
std::string mangled(const std::string& name, const std::vector<Environment::DefineScope::Type>& types) {
std::string function_name;
for (unsigned char ch : name) {
if (ch >= 0x80 || ch == '\'') {
function_name.push_back('.');
char buffer[16];
auto [ptr, ec] = std::to_chars(buffer, buffer + sizeof(buffer), static_cast<int>(ch), 16);
if (ec != std::errc()) {
UnexpectedError0(BadNumericConv);
}
*ptr = '\0';
function_name.append(buffer);
}
else if (isalnum(ch) || ch == '_' || ch == '.') {
function_name.push_back(ch);
}
else {
UnexpectedError0(BadChar);
}
}
for (const auto& parameter_type : types) {
function_name.push_back('.');
if (std::holds_alternative<AbaciValue::Type>(parameter_type)) {
char buffer[16];
auto [ptr, ec] = std::to_chars(buffer, buffer + sizeof(buffer),
static_cast<int>(std::get<AbaciValue::Type>(parameter_type) & AbaciValue::TypeMask), 10);
if (ec != std::errc()) {
UnexpectedError0(BadNumericConv);
}
*ptr = '\0';
function_name.append(buffer);
}
else if (std::holds_alternative<Environment::DefineScope::Object>(parameter_type)) {
function_name.append(mangled(std::get<Environment::DefineScope::Object>(parameter_type).class_name, {}));
function_name.push_back('_');
function_name.append(mangled("", std::get<Environment::DefineScope::Object>(parameter_type).object_types));
function_name.push_back('_');
}
}
return function_name;
}
```
Function `environmentTypeToType()` is defined in full, returning an integer value based on its parameter, while `operator==` for `Environment::DefineScope::Type` only returns true if all type(s) and nested type(s), plus class names (if any) match exactly.
```cpp
AbaciValue::Type environmentTypeToType(const Environment::DefineScope::Type& env_type) {
if (std::holds_alternative<AbaciValue::Type>(env_type)) {
return static_cast<AbaciValue::Type>(std::get<AbaciValue::Type>(env_type) & AbaciValue::TypeMask);
}
else if (std::holds_alternative<Environment::DefineScope::Object>(env_type)) {
return AbaciValue::Object;
}
else {
UnexpectedError0(BadType);
}
}
bool operator==(const Environment::DefineScope::Type& lhs, const Environment::DefineScope::Type& rhs) {
if (lhs.index() != rhs.index()) {
return false;
}
else if (std::holds_alternative<AbaciValue::Type>(lhs)) {
return (std::get<AbaciValue::Type>(lhs) & AbaciValue::TypeMask) == (std::get<AbaciValue::Type>(rhs) & AbaciValue::TypeMask);
}
else if (std::holds_alternative<Environment::DefineScope::Object>(lhs)) {
if (std::get<Environment::DefineScope::Object>(lhs).class_name
!= std::get<Environment::DefineScope::Object>(rhs).class_name) {
return false;
}
else if (std::get<Environment::DefineScope::Object>(lhs).object_types.size()
!= std::get<Environment::DefineScope::Object>(rhs).object_types.size()) {
return false;
}
else {
for (auto lhs_iter = std::get<Environment::DefineScope::Object>(lhs).object_types.cbegin(),
rhs_iter = std::get<Environment::DefineScope::Object>(rhs).object_types.cbegin();
lhs_iter != std::get<Environment::DefineScope::Object>(lhs).object_types.end();
++lhs_iter, ++rhs_iter) {
if (!(*lhs_iter == *rhs_iter)) {
return false;
}
}
return true;
}
}
UnexpectedError0(BadType);
}
} // namespace abaci::utility
```
### `Report.hpp`
The error classes `AbaciError`, `CompilerError` and `AssertError` all inherit from `std::exception`, overriding the `what()` function to provide error diagnostics in client code's `catch` clause. Both `CompilerError` and `AssertError` store the source filename and line number in their `message` member.
```cpp
//@src/utility/Report.hpp@+9,-0
#ifndef Report_hpp
#define Report_hpp
#include <exception>
#include <string>
#include <fmt/format.h>
using fmt::format;
using fmt::runtime;
template<typename... Ts>
class AbaciError : public std::exception {
private:
std::string message{};
public:
AbaciError(const char *error_string, Ts... args) : message{ format(runtime(error_string), std::forward<Ts>(args)...) } {}
virtual const char *what() const noexcept override { return message.c_str(); }
};
template<typename... Ts>
class CompilerError : public std::exception {
private:
std::string message{};
public:
CompilerError(const char* source_file, const int line_number, const char *error_string, Ts... args)
: message{ format(runtime(error_string), std::forward<Ts>(args)...) }
{
message.append(" Compiler inconsistency detected!");
if (source_file != std::string{}) {
message.append("\nSource filename: ");
message.append(source_file);
if (line_number != -1) {
message.append(", line: ");
message.append(std::to_string(line_number));
}
}
}
virtual const char *what() const noexcept override { return message.c_str(); }
};
class AssertError : public std::exception {
private:
std::string message{};
public:
AssertError(const char* source_file, const int line_number, const char *assertion)
: message{ format(runtime("Assertion failed: {}"), assertion) }
{
if (source_file != std::string{}) {
message.append("\nSource filename: ");
message.append(source_file);
if (line_number != -1) {
message.append(", Line number: ");
message.append(std::to_string(line_number));
}
}
}
virtual const char *what() const noexcept override { return message.c_str(); }
};
```
Convenience macros `LogicErrorN()`, `UnexpectedErrorN()` and `Assert()` allow for population of all of the constructor parameterss of these classes. `LogicError()` is intended for reporting errors due to ill-formed Abaci0 programs, while `UnexpectedError()` and `Assert()` are intended to pinpoint problems in the compiler itself. [Note: Adaptation of the source code to prefer `LogicError()` is not yet complete.]
```cpp
//#@+0,-2
#define LogicError0(error_string) throw AbaciError(error_string)
#define LogicError1(error_string, arg1) throw AbaciError(error_string, arg1)
#define LogicError2(error_string, arg1, arg2) throw AbaciError(error_string, arg1, arg2)
#define UnexpectedError0(error_string) throw CompilerError(__FILE__, __LINE__, error_string)
#define UnexpectedError1(error_string, arg1) throw CompilerError(__FILE__, __LINE__, error_string, arg1)
#define UnexpectedError2(error_string, arg1, arg2) throw CompilerError(__FILE__, __LINE__, error_string, arg1, arg2)
#define Assert(condition) if (!(condition)) throw AssertError(__FILE__, __LINE__, #condition)
#endif
```
## Directory `lib`
### `Abaci.hpp`
The functionality of the compiler which needs to be made available to the JIT-compiled code at execution time are listed in this header file. The functions are C++ functions declared with C-linkage, ensuring that the unmangled names can be used in the client code. This library is intentionally small, comprising of three output-related functions, one related to operations on complex numbers, eight functions related to run-time environment operations and two functions related to user input of strings and type conversions.
```cpp
//@src/lib/Abaci.hpp@+6,-2
#ifndef Abaci_hpp
#define Abaci_hpp
#include "utility/Utility.hpp"
#include "utility/Environment.hpp"
extern "C" {
void printValue(abaci::utility::AbaciValue *value);
void printComma();
void printLn();
void complexMath(abaci::utility::Complex *result, abaci::utility::Operator op, abaci::utility::Complex *operand1, abaci::utility::Complex *operand2 = nullptr);
void setVariable(abaci::utility::Environment *environment, char *name, abaci::utility::AbaciValue *value, bool new_variable);
abaci::utility::AbaciValue *getVariable(abaci::utility::Environment *environment, char *name);
void setObjectData(abaci::utility::Environment *environment, char *name, int *indices, abaci::utility::AbaciValue *value);
abaci::utility::AbaciValue *getObjectData(abaci::utility::Environment *environment, char *name, int *indices);
void beginScope(abaci::utility::Environment *environment);
void endScope(abaci::utility::Environment *environment);
void setThisPtr(abaci::utility::Environment *environment, abaci::utility::AbaciValue *ptr);
void unsetThisPtr(abaci::utility::Environment *environment);
void getUserInput(abaci::utility::String *str);
void convertType(abaci::utility::AbaciValue *to, abaci::utility::AbaciValue *from);
}
#endif
```
### `Abaci.cpp`
Function `printValue()` allows the compiled code to output values and variables at execution time. Whilst the type of the value is always known at compile-time, this fact is not (yet) taken advantage of. Instead a switch is used, allowing all of the possible values of the `type` member, togther with formatted `print()` calls outputting to `stdout`, or `fwrite()` in the case of `abaci::utility::String`.
```cpp
//@src/lib/Abaci.cpp@+20,-1
#include "Abaci.hpp"
#include "utility/Report.hpp"
#include "parser/Keywords.hpp"
#include "parser/Messages.hpp"
#include <charconv>
#include <complex>
#include <string>
#include <cstring>
#include <cstdio>
#include <fmt/core.h>
#include <fmt/format.h>
using fmt::print;
using fmt::format;
using fmt::runtime;
using abaci::utility::AbaciValue;
using abaci::utility::Complex;
using abaci::utility::Operator;
using abaci::utility::String;
using abaci::utility::Environment;
void printValue(AbaciValue *value) {
switch (value->type) {
case AbaciValue::Nil:
print("{}", NIL);
break;
case AbaciValue::Boolean:
print("{}", value->value.boolean ? TRUE : FALSE);
break;
case AbaciValue::Integer:
print("{}", static_cast<long long>(value->value.integer));
break;
case AbaciValue::Float:
print("{:.10g}", value->value.floating);
break;
case AbaciValue::Complex:
print("{:.10g}", value->value.complex->real);
if (value->value.complex->imag != 0) {
print("{:+.10g}{}", value->value.complex->imag, IMAGINARY);
}
break;
case AbaciValue::String:
fwrite(reinterpret_cast<const char*>(value->value.str->ptr), value->value.str->len, 1, stdout);
break;
case AbaciValue::Object:
print(runtime(InstanceOf), reinterpret_cast<const char*>(value->value.object->class_name));
break;
default:
UnexpectedError1(UnknownType, static_cast<int>(value->type));
break;
}
}
```
Function `printComma()` is intended to pad and separate fields after a `print <value>,` command (where more than one comma is permitted), however currently only a single space character is output. Function `printLn()` simply outputs a newline character, this is suppressed with a trailing semi-colon, as in `print <value>;`.
```cpp
void printComma() {
print("{}", ' ');
}
void printLn() {
print("{}", '\n');
}
```
Support for operations on type `abaci::utility::Complex` are provided by function `complexMath()`. Even though this struct is likely to be bit-compatible with `std::complex<double>`, this is not relied upon. Creation of `std::complex<double>` from `operand1` and `operand2` are performed, followed by an arithmetic operation specified by `op` (of type `abaci::utility::Operator`). The result is then copied into an uninitialized `Complex` which is assumed allocated on the heap by the caller (this responsibility of the caller is the memory management technique used to avoid leaks).
```cpp
void complexMath(Complex *result, Operator op, Complex *operand1, Complex *operand2) {
std::complex<double> a(operand1->real, operand1->imag), b, r;
if (operand2) {
b = std::complex<double>(operand2->real, operand2->imag);
}
switch (op) {
case Operator::Plus:
r = a + b;
break;
case Operator::Minus:
if (operand2) {
r = a - b;
}
else {
r = -a;
}
break;
case Operator::Times:
r = a * b;
break;
case Operator::Divide:
r = a / b;
break;
case Operator::Exponent:
r = std::pow(a, b);
break;
default:
UnexpectedError0(BadOperator);
}
result->real = r.real();
result->imag = r.imag();
}
```
Functions `setVariable()` and `getVariable()` call member functions of the `environment` parameter, with the value of `new_variable` being known and fixed at code compilation time. All parameters other than `new_variable` are passed and returned by pointer.
```cpp
void setVariable(Environment *environment, char *name, AbaciValue *value, bool new_variable) {
if (new_variable) {
environment->getCurrentScope()->defineValue(name, *value);
}
else {
environment->getCurrentScope()->setValue(name, *value);
}
}
AbaciValue *getVariable(Environment *environment, char *name) {
return environment->getCurrentScope()->getValue(name);
}
```
Functions `setObjectData()` and `getObjectData()` perform lookup of an object by name (which may be `this`), and travel down as many levels of nesting as are specified by the `indices` array. The `data` value thus obtained is then assigned to or returned by pointer, respectively.
```cpp
void setObjectData(Environment *environment, char *name, int *indices, AbaciValue *value) {
auto data = (strcmp(name, THIS_VAR) == 0) ? environment->getThisPtr() : environment->getCurrentScope()->getValue(name);
while (*indices != -1) {
data = &data->value.object->variables[*indices];
++indices;
}
*data = *value;
}
AbaciValue *getObjectData(Environment *environment, char *name, int *indices) {
auto data = (strcmp(name, THIS_VAR) == 0) ? environment->getThisPtr() : environment->getCurrentScope()->getValue(name);
while (*indices != -1) {
data = &data->value.object->variables[*indices];
++indices;
}
return data;
}
```
Functions `beginScope()` and `endScope()` are called by code at execution time when entering and leaving a lexical scope, respectively.
```cpp
void beginScope(Environment *environment) {
environment->beginScope();
}
void endScope(Environment *environment) {
environment->endScope();
}
```
Functions `setThisPtr()` and `unsetThisPtr()` are used to manage the stack of "this pointers" held in the `Environment`, and are called when entering and leaving a method invocation.
```cpp
void setThisPtr(Environment *environment, AbaciValue *ptr) {
environment->setThisPtr(ptr);
}
void unsetThisPtr(Environment *environment) {
environment->unsetThisPtr();
}
```
Function `getUserInput()` is called with a pointer to an already-constructed `String` object, and reads newline-terminated input into the pointer member, setting the length member to the input string length and removing the newline character.
```cpp
void getUserInput(String *str) {
fgets(reinterpret_cast<char*>(str->ptr), str->len, stdin);
str->len = strlen(reinterpret_cast<char*>(str->ptr));
if (*(str->ptr + str->len - 1) == '\n') {
--str->len;
}
fflush(stdin);
}
```
A nested switch statement is used to provide all of the supported type conversions in function `convertType()` with the outer being the "to" type and the inner begin the "from" type. No memory allocations are made as the input parameters are assumed to point to suitably allocated `AbaciValue` objects. Conversions to `String` are as for `printValue()` with the buffer size set in `Expr.hpp`, while conversion from `String` use `std::from_chars()` and support base prefixes for integer types.
```cpp
void convertType(AbaciValue *to, AbaciValue *from) {
switch (to->type) {
case AbaciValue::Integer:
switch(from->type) {
case AbaciValue::Boolean:
to->value.integer = static_cast<long long>(from->value.boolean);
break;
case AbaciValue::Integer:
to->value.integer = from->value.integer;
break;
case AbaciValue::Float:
to->value.integer = static_cast<long long>(from->value.floating);
break;
case AbaciValue::String: {
auto *str = reinterpret_cast<const char*>(from->value.str->ptr);
if (strncmp(HEX_PREFIX, str, strlen(HEX_PREFIX)) == 0) {
std::from_chars(str + strlen(HEX_PREFIX), str + from->value.str->len, to->value.integer, 16);
}
else if (strncmp(BIN_PREFIX, str, strlen(BIN_PREFIX)) == 0) {
std::from_chars(str + strlen(BIN_PREFIX), str + from->value.str->len, to->value.integer, 2);
}
else if (strncmp(OCT_PREFIX, str, strlen(OCT_PREFIX)) == 0) {
std::from_chars(str + strlen(OCT_PREFIX), str + from->value.str->len, to->value.integer, 8);
}
else {
std::from_chars(str, str + from->value.str->len, to->value.integer, 10);
}
break;
}
default:
LogicError1(BadConvType, INT);
}
break;
case AbaciValue::Float:
switch(from->type) {
case AbaciValue::Boolean:
to->value.floating = static_cast<double>(from->value.boolean);
break;
case AbaciValue::Integer:
to->value.floating = static_cast<double>(from->value.integer);
break;
case AbaciValue::Float:
to->value.floating = from->value.floating;
break;
case AbaciValue::String: {
auto *str = reinterpret_cast<const char*>(from->value.str->ptr);
std::from_chars(str, str + from->value.str->len, to->value.floating);
break;
}
default:
LogicError1(BadConvType, FLOAT);
}
break;
case AbaciValue::Complex:
switch(from->type) {
case AbaciValue::Boolean:
to->value.complex->real = static_cast<double>(from->value.boolean);