-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdirective.cpp
More file actions
5787 lines (5563 loc) · 298 KB
/
Copy pathdirective.cpp
File metadata and controls
5787 lines (5563 loc) · 298 KB
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
// ============================================================================
// Directive (Open Directive / Directive Script)
// A small, dynamically-typed scripting language, in one C++17 file.
//
// - Lexer + recursive-descent parser + tree-walking evaluator
// - Variant-style dynamic value type (Empty/Null/Bool/Int/Double/String/
// Object/Array) with dynamic coercion rules
// - 100+ built-in functions, classes, error handling (On Error / Err),
// Sub/Function with ByRef/ByVal, Select Case, Do/For/While, With, etc.
// - Native objects created with New: Dictionary, List, RegExp, FileSystem
// (+ File/Folder/TextStream), Sound, Shell, Mouse, Screen, Keyboard,
// Clipboard. They work on every platform (Windows-only ones raise otherwise).
// - CreateObject("...") is reserved for REAL ActiveX/COM automation via
// IDispatch on Windows (see #ifdef _WIN32 section): CreateObject("Excel.Application").
// - The host object is "Directive": Directive.Echo, Directive.StdOut.Write,
// Directive.StdIn.ReadLine, Directive.Quit, ...
//
// Build (console, console-style stdio):
// Linux/macOS : g++ -std=c++17 -O2 directive.cpp -o directive
// Windows MSVC: cl /std:c++17 /EHsc directive.cpp
// Windows MinGW: g++ -std=c++17 directive.cpp -o directive.exe -lole32 -loleaut32 -luuid -lwinmm -lgdi32 -luser32 -ladvapi32 -lshell32
// Build (GUI, GUI-style dialogs) - add -DDIRECTIVE_GUI and a windowed subsystem:
// Windows MSVC : cl /std:c++17 /EHsc /DDIRECTIVE_GUI directive.cpp /Fe:directivew.exe /link /SUBSYSTEM:WINDOWS
// Windows MinGW: g++ -std=c++17 -DDIRECTIVE_GUI directive.cpp -o directivew.exe -mwindows -lole32 -loleaut32 -luuid -lwinmm -lgdi32 -luser32 -ladvapi32 -lshell32
// (advapi32 = registry for Shell.Reg*, shell32 = Shell.SpecialFolders; MSVC links these via #pragma below.)
//
// Run: ./directive script.ds (or: ./directive -e "Directive.Echo 1+2")
//
// License: MIT.
// ============================================================================
#include <string>
#include <vector>
#include <memory>
#include <unordered_map>
#include <map>
#include <chrono>
#include <list>
#include <iterator>
#include <functional>
#include <variant>
#include <cstdint>
#include <cmath>
#include <cctype>
#include <sstream>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <stdexcept>
#include <ctime>
#include <regex>
#include <set>
#include <filesystem>
namespace fs = std::filesystem;
#include <cerrno>
#include <iomanip>
#include <cstdio> // popen/_popen for Shell.Exec
#include <cstdlib> // getenv/putenv, system
#ifndef _WIN32
#include <sys/wait.h> // WIFEXITED/WEXITSTATUS for Shell.Run/Exec exit codes
#include <unistd.h>
#include <termios.h> // raw-mode key input for Console.ReadKey/Pause
#include <sys/ioctl.h> // TIOCGWINSZ for Console.Width/Height
#include <fcntl.h> // open("/dev/tty") when stdin is redirected
extern char** environ; // process environment (Shell.Environment enumeration)
#endif
// ------------------------------------------------------------------ platform libs
#if defined(_WIN32) && defined(_MSC_VER)
#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleaut32.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "winmm.lib")
#pragma comment(lib, "advapi32.lib") // registry (Shell.RegRead/RegWrite/RegDelete)
#pragma comment(lib, "shell32.lib") // SHGetFolderPath (Shell.SpecialFolders)
#ifdef DIRECTIVE_GUI
#pragma comment(lib, "shell32.lib")
#endif
#endif
// ------------------------------------------------------------------ ui layer
// Console builds route MsgBox/InputBox/Echo through stdio.
// GUI builds (compiled with -DDIRECTIVE_GUI on Windows) show real dialogs.
// Definitions live at the bottom of the file, next to the Win32 code.
namespace ui {
void echo(const std::string& text); // console echo
long msgBox(const std::string& prompt, long flags, const std::string& title); // returns button code
bool inputBox(const std::string& prompt, const std::string& title,
const std::string& def, std::string& out); // false == cancelled
void error(const std::string& text); // fatal error surface
}
// ------------------------------------------------------------------ utilities
static std::string toLower(const std::string& s) {
std::string r = s;
std::transform(r.begin(), r.end(), r.begin(),
[](unsigned char c){ return (char)std::tolower(c); });
return r;
}
// ------------------------------------------------------------------ forwards
class Interpreter;
struct IObject;
using ObjectPtr = std::shared_ptr<IObject>;
struct ArrayData;
using ArrayPtr = std::shared_ptr<ArrayData>;
// -------------------------------------------------------------- error / signal
// A Directive runtime error. Number/description map onto the Err object.
struct DirectiveError {
long number;
std::string source;
std::string description;
long line = 0; // source line where the error occurred (0 = unknown)
long col = 0; // source column (0 = unknown)
DirectiveError(long n, std::string d, std::string src = "Directive runtime error")
: number(n), source(std::move(src)), description(std::move(d)) {}
};
[[noreturn]] static void raiseErr(long n, const std::string& d) { throw DirectiveError(n, d); }
// Non-local control flow used to implement Exit Sub/Function/For/Do/Property.
struct ExitSignal { enum K { Sub, Function, For, Do, Property, DoAll } kind; };
// ---------------------------------------------------------------- Value type
// The dynamic "Variant". Kept as plain members (not std::variant) so the rest
// of the code reads clearly. Object==null pointer with type Object encodes the
// Directive value "Nothing".
class Value {
public:
enum class Type { Empty, Null, Bool, Int, Int64, Date, Double, String, Object, Array };
Type type = Type::Empty;
// VBScript distinguishes a 16-bit Integer from a 32-bit Long from a Byte.
// All three live in Type::Int; this says which one, and it is observable
// through TypeName, VarType, Hex and Oct.
enum class ISub : unsigned char { Long, Integer, Byte };
ISub isub = ISub::Long;
bool single = false; // a Type::Double holding a Single (VarType 4)
bool b = false;
int32_t i = 0;
long long i64 = 0; // Type::Int64 (a Directive extension, VarType 20)
double d = 0.0;
std::string s;
ObjectPtr obj; // Object; nullptr => Nothing
ArrayPtr arr;
Value() = default;
static Value empty() { return Value(); }
static Value null() { Value v; v.type = Type::Null; return v; }
static Value nothing() { Value v; v.type = Type::Object; v.obj = nullptr; return v; }
static Value boolean(bool x) { Value v; v.type = Type::Bool; v.b = x; return v; }
static Value integer(int32_t x) { Value v; v.type = Type::Int; v.i = x; return v; }
static Value int16(int16_t x) { Value v; v.type = Type::Int; v.i = x; v.isub = ISub::Integer; return v; }
static Value big(long long x) { Value v; v.type = Type::Int64; v.i64 = x; return v; }
static Value date(double x) { Value v; v.type = Type::Date; v.d = x; return v; } // OLE serial
bool isDate() const { return type == Type::Date; }
static Value byteVal(unsigned char x) { Value v; v.type = Type::Int; v.i = x; v.isub = ISub::Byte; return v; }
// True for the subtypes VBScript promotes as 16-bit in arithmetic.
bool isNarrowInt() const { return (type == Type::Int && isub != ISub::Long) || type == Type::Bool || type == Type::Empty; }
bool isIntish() const { return type == Type::Int || type == Type::Int64 || type == Type::Bool || type == Type::Empty; }
static Value number(double x) { Value v; v.type = Type::Double; v.d = x; return v; }
static Value sng(double x) { Value v; v.type = Type::Double; v.d = (double)(float)x; v.single = true; return v; }
static Value str(std::string x) { Value v; v.type = Type::String; v.s = std::move(x); return v; }
static Value object(ObjectPtr o){ Value v; v.type = Type::Object; v.obj = std::move(o); return v; }
static Value array(ArrayPtr a) { Value v; v.type = Type::Array; v.arr = std::move(a); return v; }
bool isEmpty() const { return type == Type::Empty; }
bool isNull() const { return type == Type::Null; }
bool isObject() const { return type == Type::Object; }
bool isArray() const { return type == Type::Array; }
bool isNothing()const { return type == Type::Object && !obj; }
// ---- coercions (Directive semantics) ----
bool toBool() const;
double toDouble() const;
int32_t toInt() const; // round-half-to-even, then int32
long long toI64() const;
std::string toStr() const; // used by CStr / display
std::string toConcatStr() const; // used by & (Null -> "")
bool looksNumeric() const; // for IsNumeric
std::string typeNameStr() const; // for TypeName()
int varType() const; // for VarType()
};
// -------------------------------------------------------------- ArrayData
// N-dimensional array with 0-based lower bounds (Directive arrays are 0-based).
// `uppers[k]` is the inclusive upper bound of dimension k.
struct ArrayData {
std::vector<int> uppers;
std::vector<Value> data;
size_t total() const {
size_t n = 1;
for (int u : uppers) n *= (size_t)(u + 1);
return n;
}
size_t flatIndex(const std::vector<int>& idx) const {
if (idx.size() != uppers.size())
raiseErr(9, "Subscript out of range (wrong number of dimensions)");
size_t flat = 0;
for (size_t k = 0; k < uppers.size(); ++k) {
if (idx[k] < 0 || idx[k] > uppers[k])
raiseErr(9, "Subscript out of range");
flat = flat * (size_t)(uppers[k] + 1) + (size_t)idx[k];
}
return flat;
}
void redim(const std::vector<int>& newUppers, bool preserve) {
if (!preserve) {
uppers = newUppers;
data.assign(total(), Value::empty());
return;
}
// Preserve: Directive only allows resizing the last dimension. We copy
// element-by-element for the overlapping region (works for 1-D, which
// is the overwhelmingly common case).
ArrayData old = *this;
uppers = newUppers;
std::vector<Value> nd(total(), Value::empty());
if (uppers.size() == old.uppers.size()) {
std::vector<int> idx(uppers.size(), 0);
std::function<void(size_t)> rec = [&](size_t dim) {
if (dim == uppers.size()) {
bool inOld = true;
for (size_t k = 0; k < idx.size(); ++k)
if (idx[k] > old.uppers[k]) { inOld = false; break; }
if (inOld) nd[flatIndex(idx)] = old.data[old.flatIndex(idx)];
return;
}
for (int v = 0; v <= uppers[dim]; ++v) { idx[dim] = v; rec(dim + 1); }
};
if (total() > 0) rec(0);
}
data.swap(nd);
}
};
// -------------------------------------------------------------- IObject
// Everything you can put a "." after implements this. Both script-defined
// classes and COM/native objects use it, so member access is uniform.
struct IObject : std::enable_shared_from_this<IObject> {
virtual ~IObject() = default;
virtual std::string typeName() const { return "Object"; }
// Property-get OR method-call-returning-value (COM merges these; we do too).
virtual Value get(Interpreter& in, const std::string& name, std::vector<Value>& args) = 0;
// Property assignment: `obj.Name = v` (isSet=false, "Let") or
// `Set obj.Name = v` (isSet=true).
virtual void set(Interpreter& in, const std::string& name,
std::vector<Value>& args, const Value& val, bool isSet) {
(void)in;(void)args;(void)val;(void)isSet;
raiseErr(438, "Object doesn't support this property or method: " + name);
}
// Default property/value, for `x = obj` or coercions. Return false if none.
virtual bool tryDefault(Interpreter& in, Value& out) { (void)in;(void)out; return false; }
// For..Each enumeration. Fill `out` with the elements. Return false if the
// object is not enumerable.
virtual bool enumerate(Interpreter& in, std::vector<Value>& out) {
(void)in;(void)out; return false;
}
// True only for COM/ActiveX wrappers. Such objects can be thin accessors whose
// validity depends on their parent staying alive (Illustrator etc.), so the
// evaluator keeps them anchored for the duration of a statement.
virtual bool isComRef() const { return false; }
};
// -------------------------------------------------- number formatting helpers
// ------------------------------------------------------------------- LOCALE
// VBScript formats and parses numbers and dates through the Windows locale, so
// on a Belgian machine CStr(2.5) is "2,5" and CDbl("1.5") is 15 (the dot being a
// thousands separator). Directive mirrors that: on Windows the OS is asked, on
// POSIX a small table is used so behaviour stays deterministic and testable.
struct LocaleInfo {
int lcid = 1033;
std::string decimalSep = ".";
std::string thousandsSep = ",";
std::string currencySym = "$";
int currencyPos = 0; // LOCALE_ICURRENCY: 0 pre, 1 post, 2 pre+space, 3 post+space
bool fromOS = true; // adopted from the machine rather than SetLocale
bool dayFirst = false; // d/m/y rather than m/d/y
};
static LocaleInfo g_loc;
static std::string dateToDisplayString(double serial);
static void localeApply(int lcid); // 0 = the OS user default
static std::string osFormatDate(int y, int mo, int d);
static std::string osFormatTime(int h, int mi, int se);
static std::string osFormatDateLong(int y, int mo, int d);
static std::string osFormatTimeShort(int h, int mi);
static std::string osMonthName(int mo, bool abbrev); // mo 1-12
static std::string osDayName(int idx, bool abbrev); // idx 0 = Sunday
static std::string numToStrPrec(double v, int prec) {
if (std::isnan(v)) return "NaN";
if (std::isinf(v)) return v < 0 ? "-1.#INF" : "1.#INF";
if (std::floor(v) == v && std::fabs(v) < ((prec >= 15) ? 1e15 : 1e7))
return std::to_string((long long)v);
std::ostringstream os;
os << std::uppercase << std::setprecision(prec) << v; // VBScript prints 1E+18, not 1e+18
std::string out = os.str();
if (g_loc.decimalSep != ".") {
size_t dot = out.find('.');
if (dot != std::string::npos) out.replace(dot, 1, g_loc.decimalSep);
}
return out;
}
static std::string numToStr(double v) { return numToStrPrec(v, 15); }
// VBScript's default date-to-string: date only when there is no time part, time
// only when there is no date part, otherwise both -- all in the locale's format.
static void ymdhmsFromSerial(double s, int& y, int& mo, int& d, int& h, int& mi, int& se);
static std::string dateToDisplayString(double serial) {
int y, mo, d, h, mi, se;
ymdhmsFromSerial(serial, y, mo, d, h, mi, se);
bool hasDate = std::floor(serial) != 0.0;
bool hasTime = (serial - std::floor(serial)) != 0.0;
if (hasDate && !hasTime) return osFormatDate(y, mo, d);
if (!hasDate) return osFormatTime(h, mi, se);
return osFormatDate(y, mo, d) + " " + osFormatTime(h, mi, se);
}
static double roundHalfEven(double v) {
double fl = std::floor(v);
double diff = v - fl;
if (diff < 0.5) return fl;
if (diff > 0.5) return fl + 1.0;
return (std::fmod(fl, 2.0) == 0.0) ? fl : fl + 1.0; // .5 -> nearest even
}
// Parse a numeric prefix the way Directive coercion does; strict=true requires
// the WHOLE string to be numeric (used by IsNumeric).
static bool parseNumber(const std::string& in, double& out, bool strict) {
std::string s = in;
size_t a = s.find_first_not_of(" \t");
if (a == std::string::npos) { if (strict) return false; out = 0; return true; }
size_t z = s.find_last_not_of(" \t");
s = s.substr(a, z - a + 1);
if (s.empty()) { if (strict) return false; out = 0; return true; }
// hex / octal literals
if (s.size() > 2 && (s[0] == '&')) {
char t = (char)std::tolower(s[1]);
try {
if (t == 'h') { out = (double)std::stoll(s.substr(2), nullptr, 16); return true; }
if (t == 'o') { out = (double)std::stoll(s.substr(2), nullptr, 8); return true; }
} catch (...) { return false; }
}
// Locale-aware, matching VBScript exactly: the thousands separator is simply
// removed, then the decimal separator becomes a point. On a comma-decimal
// locale that makes "1.5" fifteen and "1.000,5" one thousand and a half.
if (g_loc.decimalSep != "." || g_loc.thousandsSep != ",") {
if (!g_loc.thousandsSep.empty()) {
size_t f;
while ((f = s.find(g_loc.thousandsSep)) != std::string::npos)
s.erase(f, g_loc.thousandsSep.size());
}
if (g_loc.decimalSep != ".") {
size_t f = s.find(g_loc.decimalSep);
if (f != std::string::npos) s.replace(f, g_loc.decimalSep.size(), ".");
}
}
const char* p = s.c_str();
char* end = nullptr;
errno = 0;
double val = std::strtod(p, &end);
if (end == p) return false;
if (strict) { while (*end == ' ' || *end == '\t') ++end; if (*end != '\0') return false; }
out = val;
return true;
}
// ----------------------------------------------------------- Value coercions
double Value::toDouble() const {
switch (type) {
case Type::Empty: return 0.0;
case Type::Null: raiseErr(94, "Invalid use of Null");
case Type::Bool: return b ? -1.0 : 0.0; // True == -1 in Directive
case Type::Int: return (double)i;
case Type::Int64: return (double)i64;
case Type::Date: return d;
case Type::Double: return d;
case Type::String: { double v; if (!parseNumber(s, v, true)) raiseErr(13, "Type mismatch"); return v; }
case Type::Object: { /* default property */ return 0.0; }
case Type::Array: raiseErr(13, "Type mismatch");
}
return 0.0;
}
long long Value::toI64() const {
if (type == Type::Int64) return i64; // exact, no double round-trip
if (type == Type::Int) return i;
return (long long)roundHalfEven(toDouble());
}
int32_t Value::toInt() const {
long long v = toI64();
return (int32_t)v;
}
bool Value::toBool() const {
switch (type) {
case Type::Empty: return false;
case Type::Null: raiseErr(94, "Invalid use of Null");
case Type::Bool: return b;
case Type::Int: return i != 0;
case Type::Int64: return i64 != 0;
case Type::Date: return d != 0.0;
case Type::Double: return d != 0.0;
case Type::String: {
std::string t = toLower(s);
if (t == "true") return true;
if (t == "false") return false;
double v; if (!parseNumber(s, v, true)) raiseErr(13, "Type mismatch");
return v != 0.0;
}
case Type::Object: if (!obj) return false; return true;
case Type::Array: raiseErr(13, "Type mismatch");
}
return false;
}
std::string Value::toStr() const {
switch (type) {
case Type::Empty: return "";
case Type::Null: raiseErr(94, "Invalid use of Null");
case Type::Bool: return b ? "True" : "False";
case Type::Int: return std::to_string(i);
case Type::Int64: return std::to_string(i64);
case Type::Date: return dateToDisplayString(d);
case Type::Double: return single ? numToStrPrec(d, 7) : numToStr(d); // a Single shows 7 digits
case Type::String: return s;
case Type::Object: if (!obj) raiseErr(13, "Type mismatch"); return "[object]";
case Type::Array: raiseErr(13, "Type mismatch");
}
return "";
}
std::string Value::toConcatStr() const { // & operator: Null becomes ""
if (type == Type::Null || type == Type::Empty) return "";
return toStr();
}
bool Value::looksNumeric() const {
if (type == Type::Int || type == Type::Int64 || type == Type::Double || type == Type::Bool) return true;
if (type == Type::String) { double v; return parseNumber(s, v, true); }
return false;
}
std::string Value::typeNameStr() const {
switch (type) {
case Type::Empty: return "Empty";
case Type::Null: return "Null";
case Type::Bool: return "Boolean";
case Type::Int: return isub == ISub::Integer ? "Integer" : (isub == ISub::Byte ? "Byte" : "Long");
case Type::Int64: return "LongLong";
case Type::Date: return "Date";
case Type::Double: return single ? "Single" : "Double";
case Type::String: return "String";
case Type::Array: return "Variant()";
case Type::Object: return obj ? obj->typeName() : "Nothing";
}
return "Empty";
}
int Value::varType() const { // subset of VarType constants
switch (type) {
case Type::Empty: return 0; // Empty
case Type::Null: return 1; // Null
case Type::Int: return isub == ISub::Integer ? 2 : (isub == ISub::Byte ? 17 : 3);
case Type::Int64: return 20; // VT_I8, as VBA reports for LongLong
case Type::Date: return 7;
case Type::Double: return single ? 4 : 5;
case Type::String: return 8; // String
case Type::Bool: return 11; // Boolean
case Type::Object: return 9; // VarType is 9 for an object even when it is Nothing
case Type::Array: return 8192 + 12; // Array + Variant
}
return 0;
}
// ================================================================== LEXER
enum class Tok {
End, Eol, Colon, Ident, Number, String, DateLit,
Plus, Minus, Star, Slash, Backslash, Caret, Amp,
Eq, Ne, Lt, Gt, Le, Ge,
LParen, RParen, Comma, Dot
};
struct Token {
Tok kind;
std::string text; // identifiers keep original case; lower is precomputed
std::string lower;
Value num; // for Number
std::string str; // for String
int line;
int col = 1; // 1-based column where the token starts
bool bracketed = false; // [ident]: a literal identifier, never a keyword (Directive / COM interop)
};
class Lexer {
const std::string& src;
size_t pos = 0;
int line = 1;
size_t lineStart = 0; // byte offset of the current line's first char
int tokCol = 1; // column of the token currently being read
public:
explicit Lexer(const std::string& s) : src(s) {}
std::vector<Token> tokenize() {
std::vector<Token> out;
while (true) {
skipInline();
if (pos >= src.size()) { push(out, Tok::End); break; }
char c = src[pos];
tokCol = (int)(pos - lineStart) + 1; // column where this token begins
// comments: ' ... to EOL
if (c == '\'') { while (pos < src.size() && src[pos] != '\n') pos++; continue; }
// end of statement
if (c == '\n') { pos++; lineStart = pos; push(out, Tok::Eol); line++; continue; }
if (c == '\r') { pos++; continue; }
if (c == ':') { pos++; push(out, Tok::Colon); continue; }
// identifiers / keywords / Rem-comments
if (std::isalpha((unsigned char)c) || c == '_') {
std::string id;
while (pos < src.size() &&
(std::isalnum((unsigned char)src[pos]) || src[pos] == '_'))
id += src[pos++];
std::string lo = toLower(id);
if (lo == "rem") { while (pos < src.size() && src[pos] != '\n') pos++; continue; }
Token t; t.kind = Tok::Ident; t.text = id; t.lower = lo; t.line = line; t.col = tokCol;
out.push_back(t);
continue;
}
// bracket identifiers: [any text] is a literal identifier, even when it
// is a keyword, contains spaces, or starts with a digit. Mainly for COM
// interop with members whose names collide with keywords.
if (c == '[') {
pos++; // consume '['
std::string id;
while (pos < src.size() && src[pos] != ']' && src[pos] != '\n') id += src[pos++];
if (pos >= src.size() || src[pos] != ']') raiseErr(1057, "Unterminated '[' identifier");
pos++; // consume ']'
if (id.empty()) raiseErr(1057, "Empty '[]' identifier");
Token t; t.kind = Tok::Ident; t.text = id; t.lower = toLower(id);
t.bracketed = true; t.line = line; t.col = tokCol;
out.push_back(t);
continue;
}
// numbers (decimal + &H hex + &O octal)
if (std::isdigit((unsigned char)c) || (c == '.' && pos + 1 < src.size() &&
std::isdigit((unsigned char)src[pos + 1]))) {
out.push_back(readNumber());
continue;
}
if (c == '&' && pos + 1 < src.size() &&
(std::tolower(src[pos + 1]) == 'h' || std::tolower(src[pos + 1]) == 'o')) {
out.push_back(readNumber());
continue;
}
// strings
if (c == '"') { out.push_back(readString()); continue; }
// date literals: #2020-03-15#, #1/15/2020 3:45:00 PM#, #13:45:00#
if (c == '#') { out.push_back(readDate()); continue; }
// operators / punctuation
switch (c) {
case '+': pos++; push(out, Tok::Plus); break;
case '-': pos++; push(out, Tok::Minus); break;
case '*': pos++; push(out, Tok::Star); break;
case '/': pos++; push(out, Tok::Slash); break;
case '\\':pos++; push(out, Tok::Backslash); break;
case '^': pos++; push(out, Tok::Caret); break;
case '&': pos++; push(out, Tok::Amp); break;
case '(': pos++; push(out, Tok::LParen); break;
case ')': pos++; push(out, Tok::RParen); break;
case ',': pos++; push(out, Tok::Comma); break;
case '.': pos++; push(out, Tok::Dot); break;
case '=': pos++; push(out, Tok::Eq); break;
case '<':
pos++;
if (peek() == '>') { pos++; push(out, Tok::Ne); }
else if (peek() == '=') { pos++; push(out, Tok::Le); }
else push(out, Tok::Lt);
break;
case '>':
pos++;
if (peek() == '=') { pos++; push(out, Tok::Ge); }
else push(out, Tok::Gt);
break;
default:
raiseErr(1057, std::string("Unexpected character '") + c + "'");
}
}
return out;
}
private:
char peek() const { return pos < src.size() ? src[pos] : '\0'; }
void push(std::vector<Token>& out, Tok k) {
Token t; t.kind = k; t.line = line; t.col = tokCol; out.push_back(t);
}
// Skip spaces/tabs; honor the "_" line-continuation (underscore then EOL).
void skipInline() {
while (pos < src.size()) {
char c = src[pos];
if (c == ' ' || c == '\t') { pos++; continue; }
if (c == '_') {
size_t q = pos + 1;
while (q < src.size() && (src[q] == ' ' || src[q] == '\t' || src[q] == '\r')) q++;
if (q < src.size() && src[q] == '\n') { pos = q + 1; lineStart = pos; line++; continue; }
if (q >= src.size()) { pos = q; continue; }
}
break;
}
}
Token readNumber() {
Token t; t.kind = Tok::Number; t.line = line; t.col = tokCol;
std::string n;
if (src[pos] == '&') {
n += src[pos++]; // &
n += src[pos++]; // h / o
while (pos < src.size() && std::isalnum((unsigned char)src[pos])) n += src[pos++];
double v; parseNumber(n, v, false);
t.num = Value::integer((int32_t)v);
return t;
}
bool isFloat = false;
while (pos < src.size()) {
char c = src[pos];
if (std::isdigit((unsigned char)c)) n += src[pos++];
else if (c == '.') { isFloat = true; n += src[pos++]; }
else if (c == 'e' || c == 'E') {
isFloat = true; n += src[pos++];
if (pos < src.size() && (src[pos] == '+' || src[pos] == '-')) n += src[pos++];
} else break;
}
if (isFloat) t.num = Value::number(std::stod(n));
else {
try { long long v = std::stoll(n);
// VBScript types a literal as the smallest that fits.
if (v >= -32768 && v <= 32767) t.num = Value::int16((int16_t)v);
else if (v >= INT32_MIN && v <= INT32_MAX) t.num = Value::integer((int32_t)v);
else t.num = Value::big(v); } // LongLong rung: exact past 2^31
catch (...) { t.num = Value::number(std::stod(n)); }
}
return t;
}
Token readString() {
Token t; t.kind = Tok::String; t.line = line; t.col = tokCol;
pos++; // opening quote
std::string s;
while (pos < src.size()) {
char c = src[pos++];
if (c == '"') {
if (pos < src.size() && src[pos] == '"') { s += '"'; pos++; } // "" -> "
else break;
} else s += c;
}
t.str = s;
return t;
}
Token readDate() {
Token t; t.kind = Tok::DateLit; t.line = line; t.col = tokCol;
pos++; // opening #
std::string s;
while (pos < src.size() && src[pos] != '#' && src[pos] != '\n') s += src[pos++];
if (pos < src.size() && src[pos] == '#') pos++; // closing #
t.str = s; // raw contents; parser converts via parseDateToSerial
return t;
}
};
// =================================================================== AST
struct Expr;
struct Stmt;
using ExprP = std::shared_ptr<Expr>;
using StmtP = std::shared_ptr<Stmt>;
struct Expr {
enum K { Lit, Var, Unary, Binary, Index, Member, New } k;
Value lit; // Lit
std::string name; // Var name / Member name / New classname / operator
std::string lname; // precomputed lowercase of name (Var/Member/New) - avoids per-access toLower
ExprP a, b; // Unary:a Binary:a,b Index:a(target) Member:a(target)
std::vector<ExprP> args; // Index args
int line = 0;
};
static ExprP mkLit(Value v) { auto e=std::make_shared<Expr>(); e->k=Expr::Lit; e->lit=std::move(v); return e; }
static ExprP mkVar(std::string n) { auto e=std::make_shared<Expr>(); e->k=Expr::Var; e->lname=toLower(n); e->name=std::move(n); return e; }
static ExprP mkUnary(std::string op, ExprP a) { auto e=std::make_shared<Expr>(); e->k=Expr::Unary; e->name=std::move(op); e->a=std::move(a); return e; }
static ExprP mkBinary(std::string op,ExprP a,ExprP b){ auto e=std::make_shared<Expr>(); e->k=Expr::Binary; e->name=std::move(op); e->a=std::move(a); e->b=std::move(b); return e; }
static ExprP mkMember(ExprP t, std::string n) { auto e=std::make_shared<Expr>(); e->k=Expr::Member; e->a=std::move(t); e->lname=toLower(n); e->name=std::move(n); return e; }
static ExprP mkIndex(ExprP t, std::vector<ExprP> a){ auto e=std::make_shared<Expr>(); e->k=Expr::Index; e->a=std::move(t); e->args=std::move(a); return e; }
static ExprP mkNew(std::string cls) { auto e=std::make_shared<Expr>(); e->k=Expr::New; e->lname=toLower(cls); e->name=std::move(cls); return e; }
struct Param { std::string name; std::string lname; bool byVal = false; };
// One "Case" label: a plain value, an "Is <op> value", or "lo To hi".
struct CaseTest {
enum K { Val, Is, Range } k = Val;
ExprP e1, e2;
std::string op; // for Is
};
struct CaseClause {
std::vector<CaseTest> tests; // empty => Case Else
std::vector<StmtP> body;
};
struct Stmt {
enum K {
DimS, ReDimS, Assign, SetAssign, IfS, ForS, ForEachS, DoLoopS, WhileS,
SelectS, SubDecl, FuncDecl, ClassDecl, CallS, ExitS, OnErrorS, ConstS,
OptionS, PropDecl, WithS, EraseS, MidS
} k;
int line = 0;
int col = 0;
// Dim / Const
std::vector<std::pair<std::string, std::vector<ExprP>>> decls; // name + optional dims
std::vector<std::pair<std::string, ExprP>> consts;
// ReDim
bool preserve = false;
std::string name; // ReDim target / For var / class or proc name / Exit-what
std::string lname; // precomputed lowercase of name (For/ForEach loop var)
std::vector<ExprP> dims;
// Assign / SetAssign
ExprP target, value;
// If
ExprP cond;
std::vector<StmtP> body; // then / loop body / else-less
std::vector<std::pair<ExprP, std::vector<StmtP>>> elifs;
std::vector<StmtP> elseBody;
// For
ExprP fromE, toE, stepE;
// ForEach / With / Select
ExprP coll; // For Each collection, With object, Select expr
// DoLoop
int testPos = 0; // 0 none, 1 pre (Do While/Until), 2 post (Loop While/Until)
bool isUntil = false;
// Select
std::vector<CaseClause> cases;
// Sub/Function/Property
std::vector<Param> params;
bool isFunction = false;
int propKind = 0; // 0 Get, 1 Let, 2 Set
bool isDefault = false; // marked with the Default keyword (class default member)
// Class
std::vector<StmtP> members;
// Call
ExprP callee;
std::vector<ExprP> callArgs;
// OnError: 1 = Resume Next, 0 = Goto 0
int errMode = 0;
// Option Explicit
bool optExplicit = false;
};
// ================================================================== PARSER
// parseDateToSerial is defined in the interpreter section; the parser needs it for #date# literals.
static bool parseDateToSerial(const std::string& in, double& out);
class Parser {
std::vector<Token> t;
size_t p = 0;
bool inProc = false; // currently inside a Sub/Function/Property body
bool inClass = false; // currently inside a Class body
std::string baseDir_; // directory of the file being parsed (for relative Include)
std::shared_ptr<std::set<std::string>> included_; // canonical paths already included (guard against dupes/cycles)
public:
explicit Parser(std::vector<Token> toks, std::string baseDir = std::string(),
std::shared_ptr<std::set<std::string>> included = nullptr)
: t(std::move(toks)), baseDir_(std::move(baseDir)),
included_(included ? included : std::make_shared<std::set<std::string>>()) {}
ExprP parseOneExpr() { return parseExpr(); } // used by Eval()
std::vector<StmtP> parseProgram() {
auto prog = parseStatements({});
if (cur().kind != Tok::End)
err("Unexpected '" + cur().text + "'");
return prog;
}
private:
// ---- token helpers ----
const Token& cur() const { return t[p]; }
const Token& peek(size_t n = 1) const { return t[std::min(p + n, t.size() - 1)]; }
void adv() { if (p + 1 < t.size()) p++; }
bool is(Tok k) const { return cur().kind == k; }
// Is there whitespace between the previous token and this one? VBScript uses
// exactly this to tell `Echo .Member` (a With-member ARGUMENT) apart from
// `obj.Member` (member access) after a paren-less call target.
bool gapBefore() const {
if (p == 0 || p >= t.size()) return false;
const Token& pv = t[p - 1];
if (pv.line != t[p].line) return true;
int len = pv.text.empty() ? 1 : (int)pv.text.size();
if (pv.bracketed) len += 2;
return t[p].col > pv.col + len;
}
bool isKw(const char* kw) const { return cur().kind == Tok::Ident && !cur().bracketed && cur().lower == kw; }
bool peekKw(const char* kw) const { return peek().kind == Tok::Ident && !peek().bracketed && peek().lower == kw; }
[[noreturn]] void err(const std::string& m) {
DirectiveError e(1025, m, "Directive compilation error");
e.line = cur().line;
e.col = cur().col;
throw e;
}
void expect(Tok k, const char* what) { if (!is(k)) err(std::string("Expected ") + what); adv(); }
void expectKw(const char* kw) { if (!isKw(kw)) err(std::string("Expected '") + kw + "'"); adv(); }
void skipSeps() { while (is(Tok::Eol) || is(Tok::Colon)) adv(); }
void skipEol() { while (is(Tok::Eol)) adv(); }
std::string ident(const char* what) {
if (!is(Tok::Ident)) err(std::string("Expected ") + what);
std::string s = cur().text; adv(); return s;
}
static bool canStartExpr(const Token& tk) {
switch (tk.kind) {
case Tok::Number: case Tok::String: case Tok::DateLit: case Tok::LParen:
case Tok::Minus: case Tok::Plus: case Tok::Ident: case Tok::Dot:
return true;
default: return false;
}
}
// ---- block of statements until a terminator keyword ----
std::vector<StmtP> parseStatements(const std::set<std::string>& stop) {
std::vector<StmtP> out;
while (true) {
skipSeps();
if (is(Tok::End)) break;
if (is(Tok::Ident) && !cur().bracketed && stop.count(cur().lower)) break;
if (is(Tok::Ident) && !cur().bracketed && cur().lower == "include") { parseIncludeInto(out); continue; }
out.push_back(parseStatement());
}
return out;
}
// Include "file" — parse the referenced file at parse time and splice its
// top-level statements in here (so its Sub/Function/Class/Const hoist normally).
void parseIncludeInto(std::vector<StmtP>& out) {
if (inProc || inClass) err("Include is only allowed at the top level");
adv(); // 'include'
if (!is(Tok::String)) err("Include expects a quoted file path");
std::string rel = cur().str; adv();
fs::path pth(rel);
std::error_code ec;
if (pth.is_relative() && !baseDir_.empty()) pth = fs::path(baseDir_) / pth;
fs::path canon = fs::weakly_canonical(pth, ec);
if (ec || canon.empty()) canon = fs::absolute(pth, ec);
std::string key = canon.string();
if (included_->count(key)) return; // include guard: skip already-included files
included_->insert(key);
std::ifstream f(canon, std::ios::binary);
if (!f) err("Include: cannot open file '" + rel + "'");
std::string src((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
if (src.size() >= 3 && (unsigned char)src[0] == 0xEF &&
(unsigned char)src[1] == 0xBB && (unsigned char)src[2] == 0xBF)
src = src.substr(3); // strip UTF-8 BOM
Lexer lx(src);
Parser sub(lx.tokenize(), canon.parent_path().string(), included_);
std::vector<StmtP> inc;
try { inc = sub.parseProgram(); }
catch (DirectiveError& e) { e.description = "in included file '" + rel + "': " + e.description; throw; }
for (auto& s : inc) out.push_back(std::move(s));
}
// ---- statements separated by ':' on a single line (for one-line If) ----
std::vector<StmtP> parseInlineStmts(const std::set<std::string>& stop) {
std::vector<StmtP> out;
while (true) {
if (is(Tok::Eol) || is(Tok::End)) break;
if (is(Tok::Ident) && !cur().bracketed && stop.count(cur().lower)) break;
out.push_back(parseStatement());
if (is(Tok::Colon)) { adv(); continue; }
break;
}
return out;
}
// ---- dispatch a single statement ----
StmtP parseStatement() {
int ln = cur().line, col = cur().col;
StmtP s = parseStatementInner();
if (s) { if (!s->line) s->line = ln; if (!s->col) s->col = col; }
return s;
}
StmtP parseStatementInner() {
int ln = cur().line;
if (is(Tok::Dot)) return parseAssignOrCall(); // .Member inside With
if (is(Tok::Ident) && !cur().bracketed) { // bracketed [ident] is never a keyword -> falls through to assign/call
const std::string& kw = cur().lower;
if (kw == "dim") return parseDim(false);
if (kw == "redim") return parseReDim();
if (kw == "set") return parseSet();
if (kw == "if") return parseIf();
if (kw == "for") return parseFor();
if (kw == "do") return parseDo();
if (kw == "while") return parseWhile();
if (kw == "select") return parseSelect();
if (kw == "sub") { if (inProc) err("a Sub cannot be defined inside another procedure"); return parseProc(false); }
if (kw == "function") { if (inProc) err("a Function cannot be defined inside another procedure"); return parseProc(true); }
if (kw == "property") { if (inProc) err("a Property cannot be defined inside another procedure"); if (!inClass) err("Property Get/Let/Set is only valid inside a Class"); return parseProperty(); }
if (kw == "class") { if (inProc || inClass) err("a Class cannot be defined inside a procedure or another Class"); return parseClass(); }
if (kw == "with") return parseWith();
if (kw == "call") { adv(); auto e = parsePostfix();
auto s = mk(Stmt::CallS, ln); s->callee = e; return s; }
if (kw == "exit") { adv(); auto s = mk(Stmt::ExitS, ln); s->name = toLower(ident("Sub/Function/For/Do/Property")); return s; }
if (kw == "const") return parseConst();
if (kw == "option") { adv(); expectKw("explicit"); auto s = mk(Stmt::OptionS, ln); s->optExplicit = true; return s; }
if (kw == "on") return parseOnError();
if (kw == "erase") { adv(); auto s = mk(Stmt::EraseS, ln);
while (true) { s->callArgs.push_back(parsePostfix()); if (is(Tok::Comma)) { adv(); continue; } break; }
return s; }
if (kw == "public" || kw == "private") {
adv();
bool isDef = false;
if (isKw("default")) { adv(); isDef = true; } // Public Default Property/Function/Sub
if (isKw("sub")) { if (inProc) err("a Sub cannot be defined inside another procedure"); return parseProc(false, isDef); }
if (isKw("function")) { if (inProc) err("a Function cannot be defined inside another procedure"); return parseProc(true, isDef); }
if (isKw("property")) { if (inProc) err("a Property cannot be defined inside another procedure"); if (!inClass) err("Property Get/Let/Set is only valid inside a Class"); return parseProperty(isDef); }
if (isKw("class")) { if (inProc || inClass) err("a Class cannot be defined inside a procedure or another Class"); return parseClass(); }
if (isKw("const")) return parseConst();
return parseDim(false); // Public/Private x, y (treated like Dim)
}
if (kw == "default") { // Default [on its own] implies Public
adv();
if (isKw("property")) { if (inProc) err("a Property cannot be defined inside another procedure"); if (!inClass) err("Property Get/Let/Set is only valid inside a Class"); return parseProperty(true); }
if (isKw("function")) { if (inProc) err("a Function cannot be defined inside another procedure"); return parseProc(true, true); }
if (isKw("sub")) { if (inProc) err("a Sub cannot be defined inside another procedure"); return parseProc(false, true); }
err("Default must be followed by Property, Function, or Sub");
}
}
return parseAssignOrCall();
}
StmtP mk(Stmt::K k, int ln) { auto s = std::make_shared<Stmt>(); s->k = k; s->line = ln; return s; }
// ---- Dim ----
StmtP parseDim(bool /*unused*/) {
int ln = cur().line; if (isKw("dim")) adv(); // no keyword when reached via Public/Private
auto s = mk(Stmt::DimS, ln);
while (true) {
std::string nm = ident("variable name");
std::vector<ExprP> dims;
if (is(Tok::LParen)) { adv(); dims = parseArgList(Tok::RParen); }
s->decls.push_back({nm, dims});
if (is(Tok::Comma)) { adv(); continue; }
break;
}
return s;
}
StmtP parseReDim() {
int ln = cur().line; adv();
auto s = mk(Stmt::ReDimS, ln);
if (isKw("preserve")) { adv(); s->preserve = true; }
s->name = ident("array name");
expect(Tok::LParen, "(");
s->dims = parseArgList(Tok::RParen);
return s;
}
StmtP parseSet() {
int ln = cur().line; adv();
auto s = mk(Stmt::SetAssign, ln);
s->target = parsePostfix();
expect(Tok::Eq, "=");
s->value = parseExpr();
return s;
}
StmtP parseConst() {
int ln = cur().line; adv();
auto s = mk(Stmt::ConstS, ln);
while (true) {
std::string nm = ident("const name");
expect(Tok::Eq, "=");
s->consts.push_back({nm, parseExpr()});
if (is(Tok::Comma)) { adv(); continue; }
break;
}
return s;
}
StmtP parseOnError() {
int ln = cur().line; adv(); // On
expectKw("error");
auto s = mk(Stmt::OnErrorS, ln);
if (isKw("resume")) { adv(); expectKw("next"); s->errMode = 1; }
else { expectKw("goto"); if (is(Tok::Number)) adv(); s->errMode = 0; } // GoTo 0
return s;
}