-
Notifications
You must be signed in to change notification settings - Fork 3
/
MinScriptLang.hpp
3687 lines (3388 loc) · 144 KB
/
MinScriptLang.hpp
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
/*
MinScriptLang - minimalistic scripting language
Version: 0.0.1-development, 2021-11
Homepage: https://github.com/sawickiap/MinScriptLang
Author: Adam Sawicki, adam__REMOVE_THIS__@asawicki.info, https://asawicki.info
================================================================================
MIT License
Copyright (c) 2019-2021 Adam Sawicki
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef MINLS_H
#define MINLS_H
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//
// Public interface
//
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
#include <string>
#include <string_view>
#include <exception>
#include <memory>
#include <vector>
#include <unordered_map>
#include <variant>
#include <cstdint>
#include <cassert>
namespace MinScriptLang {
struct PlaceInCode
{
uint32_t Index, Row, Column;
};
class Error : public std::exception
{
public:
Error(const PlaceInCode& place) : m_Place{place} { }
const PlaceInCode& GetPlace() const { return m_Place; }
virtual const char* what() const override;
virtual std::string_view GetMessage_() const = 0;
private:
const PlaceInCode m_Place;
mutable std::string m_What;
};
class ParsingError : public Error
{
public:
ParsingError(const PlaceInCode& place, const std::string_view& message) : Error{place}, m_Message{message} { }
virtual std::string_view GetMessage_() const override { return m_Message; }
private:
const std::string_view m_Message; // Externally owned
};
class ExecutionError : public Error
{
public:
ExecutionError(const PlaceInCode& place, std::string&& message) : Error{place}, m_Message{std::move(message)} { }
ExecutionError(const PlaceInCode& place, const std::string_view& message) : Error{place}, m_Message{message} { }
virtual std::string_view GetMessage_() const override { return m_Message; }
private:
const std::string m_Message;
};
namespace AST { struct FunctionDefinition; }
class Value;
class Object;
class Array;
class Environment;
enum class SystemFunction;
using HostFunction = Value(Environment& env, const PlaceInCode& place, std::vector<Value>&& args);
enum class ValueType { Null, Number, String, Function, SystemFunction, HostFunction, Object, Array, Type, Count };
class Value
{
public:
Value() { }
explicit Value(double number) : m_Type(ValueType::Number), m_Variant(number) { }
explicit Value(std::string&& str) : m_Type(ValueType::String), m_Variant(std::move(str)) { }
explicit Value(const AST::FunctionDefinition* func) : m_Type{ValueType::Function}, m_Variant{func} { }
explicit Value(SystemFunction func) : m_Type{ValueType::SystemFunction}, m_Variant{func} { }
explicit Value(HostFunction func) : m_Type{ValueType::HostFunction}, m_Variant{func} { assert(func); }
explicit Value(std::shared_ptr<Object> &&obj) : m_Type{ValueType::Object}, m_Variant(obj) { }
explicit Value(std::shared_ptr<Array> &&arr) : m_Type{ValueType::Array}, m_Variant(arr) { }
explicit Value(ValueType typeVal) : m_Type{ValueType::Type}, m_Variant(typeVal) { }
ValueType GetType() const { return m_Type; }
double GetNumber() const
{
assert(m_Type == ValueType::Number);
return std::get<double>(m_Variant);
}
std::string& GetString()
{
assert(m_Type == ValueType::String);
return std::get<std::string>(m_Variant);
}
const std::string& GetString() const
{
assert(m_Type == ValueType::String);
return std::get<std::string>(m_Variant);
}
const AST::FunctionDefinition* GetFunction() const
{
assert(m_Type == ValueType::Function && std::get<const AST::FunctionDefinition*>(m_Variant));
return std::get<const AST::FunctionDefinition*>(m_Variant);
}
SystemFunction GetSystemFunction() const
{
assert(m_Type == ValueType::SystemFunction);
return std::get<SystemFunction>(m_Variant);
}
HostFunction* GetHostFunction() const
{
assert(m_Type == ValueType::HostFunction);
return std::get<HostFunction*>(m_Variant);
}
Object* GetObject_() const // Using underscore because the %^#& WinAPI defines GetObject as a macro.
{
assert(m_Type == ValueType::Object && std::get<std::shared_ptr<Object>>(m_Variant));
return std::get<std::shared_ptr<Object>>(m_Variant).get();
}
std::shared_ptr<Object> GetObjectPtr() const
{
assert(m_Type == ValueType::Object && std::get<std::shared_ptr<Object>>(m_Variant));
return std::get<std::shared_ptr<Object>>(m_Variant);
}
Array* GetArray() const
{
assert(m_Type == ValueType::Array && std::get<std::shared_ptr<Array>>(m_Variant));
return std::get<std::shared_ptr<Array>>(m_Variant).get();
}
std::shared_ptr<Array> GetArrayPtr() const
{
assert(m_Type == ValueType::Array && std::get<std::shared_ptr<Array>>(m_Variant));
return std::get<std::shared_ptr<Array>>(m_Variant);
}
ValueType GetTypeValue() const
{
assert(m_Type == ValueType::Type);
return std::get<ValueType>(m_Variant);
}
bool IsEqual(const Value& rhs) const;
bool IsTrue() const;
void ChangeNumber(double number) { assert(m_Type == ValueType::Number); std::get<double>(m_Variant) = number; }
private:
ValueType m_Type = ValueType::Null;
using VariantType = std::variant<
std::monostate, // ValueType::Null
double, // ValueType::Number
std::string, // ValueType::String
const AST::FunctionDefinition*, // ValueType::Function
SystemFunction, // ValueType::SystemFunction
HostFunction*, // ValueType::HostFunction
std::shared_ptr<Object>, // ValueType::Object
std::shared_ptr<Array>, // ValueType::Array
ValueType>; // ValueType::Type
VariantType m_Variant;
};
class Object
{
public:
using MapType = std::unordered_map<std::string, Value>;
MapType m_Items;
size_t GetCount() const { return m_Items.size(); }
bool HasKey(const std::string& key) const { return m_Items.find(key) != m_Items.end(); }
Value& GetOrCreateValue(const std::string& key) { return m_Items[key]; }; // Creates new null value if doesn't exist.
Value* TryGetValue(const std::string& key); // Returns null if doesn't exist.
const Value* TryGetValue(const std::string& key) const; // Returns null if doesn't exist.
bool Remove(const std::string& key); // Returns true if has been found and removed.
};
class Array
{
public:
std::vector<Value> Items;
};
#define MINSL_EXECUTION_CHECK(condition, place, errorMessage) \
do { if(!(condition)) throw ExecutionError((place), (errorMessage)); } while(false)
#define MINSL_EXECUTION_FAIL(place, errorMessage) \
do { throw ExecutionError((place), (errorMessage)); } while(false)
// Convenience macros for loading function arguments
// They require to have following available: env, place, args.
#define MINSL_LOAD_ARG_BEGIN(functionNameStr) \
const char* minsl_functionName = (functionNameStr); \
size_t minsl_argIndex = 0; \
size_t minsl_argCount = (args).size(); \
ValueType minsl_argType;
#define MINSL_LOAD_ARG_NUMBER(dstVarName) \
MINSL_EXECUTION_CHECK(minsl_argIndex < minsl_argCount, place, \
Format("Function %s received too few arguments. Number expected as argument %zu.", \
minsl_functionName, minsl_argIndex)); \
minsl_argType = args[minsl_argIndex].GetType(); \
MINSL_EXECUTION_CHECK(minsl_argType == ValueType::Number, place, \
Format("Function %s received incorrect argument %zu. Expected: Number, actual: %.*s.", \
minsl_functionName, minsl_argIndex, \
(int)env.GetTypeName(minsl_argType).length(), env.GetTypeName(minsl_argType).data())); \
double dstVarName = args[minsl_argIndex++].GetNumber();
#define MINSL_LOAD_ARG_STRING(dstVarName) \
MINSL_EXECUTION_CHECK(minsl_argIndex < minsl_argCount, place, \
Format("Function %s received too few arguments. String expected as argument %zu.", \
minsl_functionName, minsl_argIndex)); \
minsl_argType = args[minsl_argIndex].GetType(); \
MINSL_EXECUTION_CHECK(minsl_argType == ValueType::String, place, \
Format("Function %s received incorrect argument %zu. Expected: String, actual: %.*s.", \
minsl_functionName, minsl_argIndex, \
(int)env.GetTypeName(minsl_argType).length(), env.GetTypeName(minsl_argType).data())); \
std::string dstVarName = std::move(args[minsl_argIndex++].GetString());
#define MINSL_LOAD_ARG_END() \
MINSL_EXECUTION_CHECK(minsl_argIndex == minsl_argCount, place, \
Format("Function %s requires %zu arguments, %zu provided.", \
minsl_functionName, minsl_argIndex, minsl_argCount));
#define MINSL_LOAD_ARGS_0(functionNameStr) \
MINSL_LOAD_ARG_BEGIN(functionNameStr); \
MINSL_LOAD_ARG_END();
#define MINSL_LOAD_ARGS_1_NUMBER(functionNameStr, dstVarName) \
MINSL_LOAD_ARG_BEGIN(functionNameStr); \
MINSL_LOAD_ARG_NUMBER(dstVarName); \
MINSL_LOAD_ARG_END();
#define MINSL_LOAD_ARGS_1_STRING(functionNameStr, dstVarName) \
MINSL_LOAD_ARG_BEGIN(functionNameStr); \
MINSL_LOAD_ARG_STRING(dstVarName); \
MINSL_LOAD_ARG_END();
#define MINSL_LOAD_ARGS_2_NUMBERS(functionNameStr, dstVarName1, dstVarName2) \
MINSL_LOAD_ARG_BEGIN(functionNameStr); \
MINSL_LOAD_ARG_NUMBER(dstVarName1); \
MINSL_LOAD_ARG_NUMBER(dstVarName2); \
MINSL_LOAD_ARG_END();
std::string VFormat(const char* format, va_list argList);
std::string Format(const char* format, ...);
class EnvironmentPimpl;
class Environment
{
public:
Object GlobalScope;
void* UserData = nullptr;
Environment();
~Environment();
Value Execute(const std::string_view& code);
const std::string& GetOutput() const;
std::string_view GetTypeName(ValueType type) const;
private:
EnvironmentPimpl* pimpl;
};
} // namespace MinScriptLang
#endif // #ifndef MINLS_H
// For Visual Studio IntelliSense.
#ifdef __INTELLISENSE__
#define MINSL_IMPLEMENTATION
#endif
#ifdef MINSL_IMPLEMENTATION
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//
// Private implementation
//
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
#include <map>
#include <algorithm>
#include <initializer_list>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctype.h>
using std::unique_ptr;
using std::shared_ptr;
using std::make_unique;
using std::make_shared;
using std::string;
using std::string_view;
using std::vector;
// F***k Windows.h macros!
#undef min
#undef max
namespace MinScriptLang {
////////////////////////////////////////////////////////////////////////////////
// Basic facilities
// I would like it to be higher, but above that, even at 128, it crashes with
// native "stack overflow" in Debug configuration.
static const size_t LOCAL_SCOPE_STACK_MAX_SIZE = 100;
static constexpr string_view ERROR_MESSAGE_PARSING_ERROR = "Parsing error.";
static constexpr string_view ERROR_MESSAGE_INVALID_NUMBER = "Invalid number.";
static constexpr string_view ERROR_MESSAGE_INVALID_STRING = "Invalid string.";
static constexpr string_view ERROR_MESSAGE_INVALID_ESCAPE_SEQUENCE = "Invalid escape sequence in a string.";
static constexpr string_view ERROR_MESSAGE_INVALID_TYPE = "Invalid type.";
static constexpr string_view ERROR_MESSAGE_INVALID_MEMBER = "Invalid member.";
static constexpr string_view ERROR_MESSAGE_INVALID_INDEX = "Invalid index.";
static constexpr string_view ERROR_MESSAGE_INVALID_LVALUE = "Invalid l-value.";
static constexpr string_view ERROR_MESSAGE_INVALID_FUNCTION = "Invalid function.";
static constexpr string_view ERROR_MESSAGE_INVALID_NUMBER_OF_ARGUMENTS = "Invalid number of arguments.";
static constexpr string_view ERROR_MESSAGE_UNRECOGNIZED_TOKEN = "Unrecognized token.";
static constexpr string_view ERROR_MESSAGE_UNEXPECTED_END_OF_FILE_IN_MULTILINE_COMMENT = "Unexpected end of file inside multiline comment.";
static constexpr string_view ERROR_MESSAGE_UNEXPECTED_END_OF_FILE_IN_STRING = "Unexpected end of file inside string.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_EXPRESSION = "Expected expression.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_STATEMENT = "Expected statement.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_CONSTANT_VALUE = "Expected constant value.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_IDENTIFIER = "Expected identifier.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_LVALUE = "Expected l-value.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_NUMBER = "Expected number.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_STRING = "Expected string.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_OBJECT = "Expected object.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_ARRAY = "Expected array.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_OBJECT_MEMBER = "Expected object member.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_SINGLE_CHARACTER_STRING = "Expected single character string.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_SYMBOL = "Expected symbol.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_SYMBOL_COLON = "Expected symbol ':'.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_SYMBOL_SEMICOLON = "Expected symbol ';'.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_SYMBOL_ROUND_BRACKET_OPEN = "Expected symbol '('.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_SYMBOL_ROUND_BRACKET_CLOSE = "Expected symbol ')'.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_SYMBOL_CURLY_BRACKET_OPEN = "Expected symbol '{'.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_SYMBOL_CURLY_BRACKET_CLOSE = "Expected symbol '}'.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_SYMBOL_SQUARE_BRACKET_CLOSE = "Expected symbol ']'.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_SYMBOL_DOT = "Expected symbol '.'.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_SYMBOL_WHILE = "Expected 'while'.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_UNIQUE_CONSTANT = "Expected unique constant.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_1_ARGUMENT = "Expected 1 argument.";
static constexpr string_view ERROR_MESSAGE_EXPECTED_2_ARGUMENTS = "Expected 2 arguments.";
static constexpr string_view ERROR_MESSAGE_VARIABLE_DOESNT_EXIST = "Variable doesn't exist.";
static constexpr string_view ERROR_MESSAGE_OBJECT_MEMBER_DOESNT_EXIST = "Object member doesn't exist.";
static constexpr string_view ERROR_MESSAGE_NOT_IMPLEMENTED = "Not implemented.";
static constexpr string_view ERROR_MESSAGE_BREAK_WITHOUT_LOOP = "Break without a loop.";
static constexpr string_view ERROR_MESSAGE_CONTINUE_WITHOUT_LOOP = "Continue without a loop.";
static constexpr string_view ERROR_MESSAGE_INCOMPATIBLE_TYPES = "Incompatible types.";
static constexpr string_view ERROR_MESSAGE_INDEX_OUT_OF_BOUNDS = "Index out of bounds.";
static constexpr string_view ERROR_MESSAGE_PARAMETER_NAMES_MUST_BE_UNIQUE = "Parameter naems must be unique.";
static constexpr string_view ERROR_MESSAGE_NO_LOCAL_SCOPE = "There is no local scope here.";
static constexpr string_view ERROR_MESSAGE_NO_THIS = "There is no 'this' here.";
static constexpr string_view ERROR_MESSAGE_REPEATING_KEY_IN_OBJECT = "Repeating key in object.";
static constexpr string_view ERROR_MESSAGE_STACK_OVERFLOW = "Stack overflow.";
static constexpr string_view ERROR_MESSAGE_BASE_MUST_BE_OBJECT = "Base must be object.";
static constexpr string_view VALUE_TYPE_NAMES[] = { "Null", "Number", "String", "Function", "Function", "Function", "Object", "Array", "Type" };
static_assert(_countof(VALUE_TYPE_NAMES) == (size_t)ValueType::Count);
enum class Symbol
{
// Token types
None,
Identifier,
Number,
String,
End,
// Symbols
Comma, // ,
QuestionMark, // ?
Colon, // :
Semicolon, // ;
RoundBracketOpen, // (
RoundBracketClose, // )
SquareBracketOpen, // [
SquareBracketClose, // ]
CurlyBracketOpen, // {
CurlyBracketClose, // }
Asterisk, // *
Slash, // /
Percent, // %
Plus, // +
Dash, // -
Equals, // =
ExclamationMark, // !
Tilde, // ~
Less, // <
Greater, // >
Amperstand, // &
Caret, // ^
Pipe, // |
Dot, // .
// Multiple character symbols
DoublePlus, // ++
DoubleDash, // --
PlusEquals, // +=
DashEquals, // -=
AsteriskEquals, // *=
SlashEquals, // /=
PercentEquals, // %=
DoubleLessEquals, // <<=
DoubleGreaterEquals, // >>=
AmperstandEquals, // &=
CaretEquals, // ^=
PipeEquals, // |=
DoubleLess, // <<
DoubleGreater, // >>
LessEquals, // <=
GreaterEquals, // >=
DoubleEquals, // ==
ExclamationEquals, // !=
DoubleAmperstand, // &&
DoublePipe, // ||
// Keywords
Null, False, True, If, Else, While, Do, For, Break, Continue,
Switch, Case, Default, Function, Return,
Local, This, Global, Class, Throw, Try, Catch, Finally, Count
};
static constexpr string_view SYMBOL_STR[] = {
// Token types
"", "", "", "", "",
// Symbols
",", "?", ":", ";", "(", ")", "[", "]", "{", "}", "*", "/", "%", "+", "-", "=", "!", "~", "<", ">", "&", "^", "|", ".",
// Multiple character symbols
"++", "--", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", "&=", "^=", "|=", "<<", ">>", "<=", ">=", "==", "!=", "&&", "||",
// Keywords
"null", "false", "true", "if", "else", "while", "do", "for", "break", "continue",
"switch", "case", "default", "function", "return",
"local", "this", "global", "class", "throw", "try", "catch", "finally"
};
struct Token
{
PlaceInCode Place;
Symbol Symbol;
double Number; // Only when Symbol == Symbol::Number
string String; // Only when Symbol == Symbol::Identifier or String
};
static inline bool IsDecimalNumber(char ch) { return ch >= '0' && ch <= '9'; }
static inline bool IsHexadecimalNumber(char ch) { return ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'F' || ch >= 'a' && ch <= 'f'; }
static inline bool IsAlpha(char ch) { return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '_'; }
static inline bool IsAlphaNumeric(char ch) { return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9' || ch == '_'; }
static const char* GetDebugPrintIndent(uint32_t indentLevel)
{
return " "
+ (256 - std::min<uint32_t>(indentLevel, 128) * 2);
}
std::string VFormat(const char* format, va_list argList)
{
size_t dstLen = (size_t)_vscprintf(format, argList);
if(dstLen)
{
std::vector<char> buf(dstLen + 1);
vsprintf_s(&buf[0], dstLen + 1, format, argList);
return string{&buf[0], &buf[dstLen]};
}
else
return {};
}
std::string Format(const char* format, ...)
{
va_list argList;
va_start(argList, format);
auto result = VFormat(format, argList);
va_end(argList);
return result;
}
static bool NumberToIndex(size_t& outIndex, double number)
{
if(!isfinite(number) || number < 0.f)
return false;
outIndex = (size_t)number;
return (double)outIndex == number;
}
struct BreakException { };
struct ContinueException { };
////////////////////////////////////////////////////////////////////////////////
// class Value definition
bool Value::IsEqual(const Value& rhs) const
{
if(m_Type != rhs.m_Type)
return false;
switch(m_Type)
{
case ValueType::Null: return true;
case ValueType::Number: return std::get<double>(m_Variant) == std::get<double>(rhs.m_Variant);
case ValueType::String: return std::get<std::string>(m_Variant) == std::get<std::string>(rhs.m_Variant);
case ValueType::Function: return std::get<const AST::FunctionDefinition*>(m_Variant) == std::get<const AST::FunctionDefinition*>(rhs.m_Variant);
case ValueType::SystemFunction: return std::get<SystemFunction>(m_Variant) == std::get<SystemFunction>(rhs.m_Variant);
case ValueType::HostFunction: return std::get<HostFunction*>(m_Variant) == std::get<HostFunction*>(rhs.m_Variant);
case ValueType::Object: return std::get<std::shared_ptr<Object>>(m_Variant).get() == std::get<std::shared_ptr<Object>>(rhs.m_Variant).get();
case ValueType::Array: return std::get<std::shared_ptr<Array>>(m_Variant).get() == std::get<std::shared_ptr<Array>>(rhs.m_Variant).get();
case ValueType::Type: return std::get<ValueType>(m_Variant) == std::get<ValueType>(rhs.m_Variant);
default: assert(0); return false;
}
}
bool Value::IsTrue() const
{
switch(m_Type)
{
case ValueType::Null: return false;
case ValueType::Number: return std::get<double>(m_Variant) != 0.f;
case ValueType::String: return !std::get<std::string>(m_Variant).empty();
case ValueType::Function: return true;
case ValueType::SystemFunction: return true;
case ValueType::HostFunction: return true;
case ValueType::Object: return true;
case ValueType::Array: return true;
case ValueType::Type: return std::get<ValueType>(m_Variant) != ValueType::Null;
default: assert(0); return false;
}
}
////////////////////////////////////////////////////////////////////////////////
// class CodeReader definition
class CodeReader
{
public:
CodeReader(const string_view& code) :
m_Code{code},
m_Place{0, 1, 1}
{
}
bool IsEnd() const { return m_Place.Index >= m_Code.length(); }
const PlaceInCode& GetCurrentPlace() const { return m_Place; }
const char* GetCurrentCode() const { return m_Code.data() + m_Place.Index; }
size_t GetCurrentLen() const { return m_Code.length() - m_Place.Index; }
char GetCurrentChar() const { return m_Code[m_Place.Index]; }
bool Peek(char ch) const { return m_Place.Index < m_Code.length() && m_Code[m_Place.Index] == ch; }
bool Peek(const char* s, size_t sLen) const { return m_Place.Index + sLen <= m_Code.length() && memcmp(m_Code.data() + m_Place.Index, s, sLen) == 0; }
void MoveOneChar()
{
if(m_Code[m_Place.Index++] == '\n')
++m_Place.Row, m_Place.Column = 1;
else
++m_Place.Column;
}
void MoveChars(size_t n)
{
for(size_t i = 0; i < n; ++i)
MoveOneChar();
}
private:
const string_view m_Code;
PlaceInCode m_Place;
};
////////////////////////////////////////////////////////////////////////////////
// class Tokenizer definition
class Tokenizer
{
public:
Tokenizer(const string_view& code) : m_Code{code} { }
void GetNextToken(Token& out);
private:
static bool ParseCharHex(uint8_t& out, char ch);
static bool ParseCharsHex(uint32_t& out, const string_view& chars);
static bool AppendUtf8Char(string& inout, uint32_t charVal);
CodeReader m_Code;
void SkipSpacesAndComments();
bool ParseNumber(Token& out);
bool ParseString(Token& out);
};
////////////////////////////////////////////////////////////////////////////////
// class Value definition
enum class SystemFunction {
TypeOf, Print, Min, Max,
String_resize,
Array_add, Array_insert, Array_remove,
Count
};
static constexpr string_view SYSTEM_FUNCTION_NAMES[] = {
"typeOf", "print", "min", "max",
"resize",
"add", "insert", "remove",
};
static_assert(_countof(SYSTEM_FUNCTION_NAMES) == (size_t)SystemFunction::Count);
struct ObjectMemberLValue
{
Object* Obj;
string Key;
};
struct StringCharacterLValue
{
string* Str;
size_t Index;
};
struct ArrayItemLValue
{
Array* Arr;
size_t Index;
};
struct LValue : public std::variant<ObjectMemberLValue, StringCharacterLValue, ArrayItemLValue>
{
Value* GetValueRef(const PlaceInCode& place) const; // Always returns non-null or throws exception.
Value GetValue(const PlaceInCode& place) const;
};
struct ReturnException
{
const PlaceInCode Place;
Value ThrownValue;
};
////////////////////////////////////////////////////////////////////////////////
// namespace AST
namespace AST
{
struct ThisType : public std::variant<
std::monostate,
shared_ptr<Object>,
shared_ptr<Array>>
{
bool IsEmpty() const { return std::get_if<std::monostate>(this) != nullptr; }
Object* GetObject_() const
{
const shared_ptr<Object>* objectPtr = std::get_if<shared_ptr<Object>>(this);
return objectPtr ? objectPtr->get() : nullptr;
}
Array* GetArray() const
{
const shared_ptr<Array>* arrayPtr = std::get_if<shared_ptr<Array>>(this);
return arrayPtr ? arrayPtr->get() : nullptr;
}
void Clear() { *this = ThisType{}; }
};
struct ExecuteContext
{
public:
EnvironmentPimpl& Env;
Object& GlobalScope;
struct LocalScopePush
{
LocalScopePush(ExecuteContext& ctx, Object* localScope, ThisType&& thisObj, const PlaceInCode& place) :
m_Ctx{ctx}
{
if(ctx.LocalScopes.size() == LOCAL_SCOPE_STACK_MAX_SIZE)
throw ExecutionError{place, ERROR_MESSAGE_STACK_OVERFLOW};
ctx.LocalScopes.push_back(localScope);
ctx.Thises.push_back(std::move(thisObj));
}
~LocalScopePush()
{
m_Ctx.Thises.pop_back();
m_Ctx.LocalScopes.pop_back();
}
private:
ExecuteContext& m_Ctx;
};
ExecuteContext(EnvironmentPimpl& env, Object& globalScope) : Env{env}, GlobalScope{globalScope} { }
bool IsLocal() const { return !LocalScopes.empty(); }
Object* GetCurrentLocalScope() { assert(IsLocal()); return LocalScopes.back(); }
const ThisType& GetThis() { assert(IsLocal()); return Thises.back(); }
Object& GetInnermostScope() const { return IsLocal() ? *LocalScopes.back() : GlobalScope; }
private:
vector<Object*> LocalScopes;
vector<ThisType> Thises;
};
struct Statement
{
explicit Statement(const PlaceInCode& place) : m_Place{place} { }
virtual ~Statement() { }
const PlaceInCode& GetPlace() const { return m_Place; }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const = 0;
virtual void Execute(ExecuteContext& ctx) const = 0;
protected:
void Assign(const LValue& lhs, Value&& rhs) const;
private:
const PlaceInCode m_Place;
};
struct EmptyStatement : public Statement
{
explicit EmptyStatement(const PlaceInCode& place) : Statement{place} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual void Execute(ExecuteContext& ctx) const { }
};
struct Expression;
struct Condition : public Statement
{
unique_ptr<Expression> ConditionExpression;
unique_ptr<Statement> Statements[2]; // [0] executed if true, [1] executed if false, optional.
explicit Condition(const PlaceInCode& place) : Statement{place} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual void Execute(ExecuteContext& ctx) const;
};
const enum WhileLoopType { While, DoWhile };
struct WhileLoop : public Statement
{
WhileLoopType Type;
unique_ptr<Expression> ConditionExpression;
unique_ptr<Statement> Body;
explicit WhileLoop(const PlaceInCode& place, WhileLoopType type) : Statement{place}, Type{type} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual void Execute(ExecuteContext& ctx) const;
};
struct ForLoop : public Statement
{
unique_ptr<Expression> InitExpression; // Optional
unique_ptr<Expression> ConditionExpression; // Optional
unique_ptr<Expression> IterationExpression; // Optional
unique_ptr<Statement> Body;
explicit ForLoop(const PlaceInCode& place) : Statement{place} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual void Execute(ExecuteContext& ctx) const;
};
struct RangeBasedForLoop : public Statement
{
string KeyVarName; // Can be empty.
string ValueVarName; // Cannot be empty.
unique_ptr<Expression> RangeExpression;
unique_ptr<Statement> Body;
explicit RangeBasedForLoop(const PlaceInCode& place) : Statement{place} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual void Execute(ExecuteContext& ctx) const;
};
enum class LoopBreakType { Break, Continue, Count };
struct LoopBreakStatement : public Statement
{
LoopBreakType Type;
explicit LoopBreakStatement(const PlaceInCode& place, LoopBreakType type) : Statement{place}, Type{type} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual void Execute(ExecuteContext& ctx) const;
};
struct ReturnStatement : public Statement
{
unique_ptr<Expression> ReturnedValue; // Can be null.
explicit ReturnStatement(const PlaceInCode& place) : Statement{place} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual void Execute(ExecuteContext& ctx) const;
};
struct Block : public Statement
{
explicit Block(const PlaceInCode& place) : Statement{place} { }
vector<unique_ptr<Statement>> Statements;
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual void Execute(ExecuteContext& ctx) const;
};
struct ConstantValue;
struct SwitchStatement : public Statement
{
unique_ptr<Expression> Condition;
vector<unique_ptr<AST::ConstantValue>> ItemValues; // null means default block.
vector<unique_ptr<AST::Block>> ItemBlocks; // Can be null if empty.
explicit SwitchStatement(const PlaceInCode& place) : Statement{place} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual void Execute(ExecuteContext& ctx) const;
};
struct ThrowStatement : public Statement
{
unique_ptr<Expression> ThrownExpression;
explicit ThrowStatement(const PlaceInCode& place) : Statement{place} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual void Execute(ExecuteContext& ctx) const;
};
struct TryStatement : public Statement
{
unique_ptr<Statement> TryBlock;
unique_ptr<Statement> CatchBlock; // Optional
unique_ptr<Statement> FinallyBlock; // Optional
string ExceptionVarName;
explicit TryStatement(const PlaceInCode& place) : Statement{place} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual void Execute(ExecuteContext& ctx) const;
};
struct Script : Block
{
explicit Script(const PlaceInCode& place) : Block{place} { }
virtual void Execute(ExecuteContext& ctx) const;
};
struct Expression : Statement
{
explicit Expression(const PlaceInCode& place) : Statement{place} { }
virtual Value Evaluate(ExecuteContext& ctx, ThisType* outThis) const { return GetLValue(ctx).GetValue(GetPlace()); }
virtual LValue GetLValue(ExecuteContext& ctx) const { MINSL_EXECUTION_CHECK( false, GetPlace(), ERROR_MESSAGE_EXPECTED_LVALUE ); }
virtual void Execute(ExecuteContext& ctx) const { Evaluate(ctx, nullptr); }
};
struct ConstantExpression : Expression
{
explicit ConstantExpression(const PlaceInCode& place) : Expression{place} { }
virtual void Execute(ExecuteContext& ctx) const { /* Nothing - just ignore its value. */ }
};
struct ConstantValue : ConstantExpression
{
Value Val;
ConstantValue(const PlaceInCode& place, Value&& val) : ConstantExpression{place}, Val{std::move(val)}
{
assert(Val.GetType() == ValueType::Null || Val.GetType() == ValueType::Number || Val.GetType() == ValueType::String);
}
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual Value Evaluate(ExecuteContext& ctx, ThisType* outThis) const { return Value{Val}; }
};
enum class IdentifierScope { None, Local, Global, Count };
struct Identifier : ConstantExpression
{
IdentifierScope Scope = IdentifierScope::Count;
string S;
Identifier(const PlaceInCode& place, IdentifierScope scope, string&& s) : ConstantExpression{place}, Scope(scope), S(std::move(s)) { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual Value Evaluate(ExecuteContext& ctx, ThisType* outThis) const;
virtual LValue GetLValue(ExecuteContext& ctx) const;
};
struct ThisExpression : ConstantExpression
{
ThisExpression(const PlaceInCode& place) : ConstantExpression{place} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual Value Evaluate(ExecuteContext& ctx, ThisType* outThis) const;
};
struct Operator : Expression
{
explicit Operator(const PlaceInCode& place) : Expression{place} { }
};
enum class UnaryOperatorType
{
Preincrementation, Predecrementation, Postincrementation, Postdecrementation,
Plus, Minus, LogicalNot, BitwiseNot, Count,
};
struct UnaryOperator : Operator
{
UnaryOperatorType Type;
unique_ptr<Expression> Operand;
UnaryOperator(const PlaceInCode& place, UnaryOperatorType type) : Operator{place}, Type(type) { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual Value Evaluate(ExecuteContext& ctx, ThisType* outThis) const;
virtual LValue GetLValue(ExecuteContext& ctx) const;
private:
Value BitwiseNot(Value&& operand) const;
};
struct MemberAccessOperator : Operator
{
unique_ptr<Expression> Operand;
string MemberName;
MemberAccessOperator(const PlaceInCode& place) : Operator{place} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual Value Evaluate(ExecuteContext& ctx, ThisType* outThis) const;
virtual LValue GetLValue(ExecuteContext& ctx) const;
};
enum class BinaryOperatorType
{
Mul, Div, Mod, Add, Sub, ShiftLeft, ShiftRight,
Assignment, AssignmentAdd, AssignmentSub, AssignmentMul, AssignmentDiv, AssignmentMod, AssignmentShiftLeft, AssignmentShiftRight,
AssignmentBitwiseAnd, AssignmentBitwiseXor, AssignmentBitwiseOr,
Less, Greater, LessEqual, GreaterEqual, Equal, NotEqual,
BitwiseAnd, BitwiseXor, BitwiseOr, LogicalAnd, LogicalOr,
Comma, Indexing, Count
};
struct BinaryOperator : Operator
{
BinaryOperatorType Type;
unique_ptr<Expression> Operands[2];
BinaryOperator(const PlaceInCode& place, BinaryOperatorType type) : Operator{place}, Type(type) { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual Value Evaluate(ExecuteContext& ctx, ThisType* outThis) const;
virtual LValue GetLValue(ExecuteContext& ctx) const;
private:
Value ShiftLeft(const Value& lhs, const Value& rhs) const;
Value ShiftRight(const Value& lhs, const Value& rhs) const;
Value Assignment(LValue&& lhs, Value&& rhs) const;
};
struct TernaryOperator : Operator
{
unique_ptr<Expression> Operands[3];
explicit TernaryOperator(const PlaceInCode& place) : Operator{place} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual Value Evaluate(ExecuteContext& ctx, ThisType* outThis) const;
};
struct CallOperator : Operator
{
vector<unique_ptr<Expression>> Operands;
CallOperator(const PlaceInCode& place) : Operator{place} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual Value Evaluate(ExecuteContext& ctx, ThisType* outThis) const;
};
struct FunctionDefinition : public Expression
{
vector<string> Parameters;
Block Body;
FunctionDefinition(const PlaceInCode& place) : Expression{place}, Body{place} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual Value Evaluate(ExecuteContext& ctx, ThisType* outThis) const { return Value{this}; }
bool AreParameterNamesUnique() const;
};
struct ObjectExpression : public Expression
{
unique_ptr<Expression> BaseExpression;
using ItemMap = std::map<string, unique_ptr<Expression>>;
ItemMap Items;
ObjectExpression(const PlaceInCode& place) : Expression{place} { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual Value Evaluate(ExecuteContext& ctx, ThisType* outThis) const;
};
struct ArrayExpression : public Expression
{
vector<unique_ptr<Expression>> Items;
ArrayExpression(const PlaceInCode& place) : Expression{ place } { }
virtual void DebugPrint(uint32_t indentLevel, const string_view& prefix) const;
virtual Value Evaluate(ExecuteContext& ctx, ThisType* outThis) const;
};
} // namespace AST
static inline void CheckNumberOperand(const AST::Expression* operand, const Value& value)
{
MINSL_EXECUTION_CHECK( value.GetType() == ValueType::Number, operand->GetPlace(), ERROR_MESSAGE_EXPECTED_NUMBER );
}
////////////////////////////////////////////////////////////////////////////////
// class Parser definition
class Parser
{
public:
Parser(Tokenizer& tokenizer) : m_Tokenizer(tokenizer) { }
void ParseScript(AST::Script& outScript);