-
Notifications
You must be signed in to change notification settings - Fork 61
/
stdLambda.cls
2018 lines (1834 loc) · 82.9 KB
/
stdLambda.cls
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
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "stdLambda"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'Ensure Option-Explicit is disabled!!
'For VB6 compatibility we rely on the auto-definition of Application and ThisWorkbook
'Option Explicit
'Used for enabling some debugging features
#Const devMode = True
'For Mac testing purposes only
'#const Mac = true
'Implement stdICallable interface
Implements stdICallable
'Direct call convention of VBA.CallByName
#If Not Mac Then
#If VBA7 Then
'VBE7 is interchangable with msvbvm60.dll however VBE7.dll appears to always be present where as msvbvm60 is only occasionally present.
Private Declare PtrSafe Function rtcCallByName Lib "VBE7.dll" (ByVal cObj As Object, ByVal sMethod As LongPtr, ByVal eCallType As VbCallType, ByRef pArgs() As Variant, ByVal lcid As Long) As Variant
#Else
Private Declare Function rtcCallByName Lib "msvbvm60" (ByVal cObj As Object, ByVal sMethod As Long, ByVal eCallType As VbCallType, ByRef pArgs() As Variant, ByVal lcid As Long) As Variant
#End If
#End If
'Tokens, token definitions and operations
Private Type TokenDefinition
name As String
Regex As String
RegexObj As Object
End Type
Private Type token
Type As TokenDefinition
value As Variant
BracketDepth As Long
End Type
Private Type Operation
Type As iType
subType As ISubType
value As Variant
End Type
'Evaluation operation types
Private Enum iType
oPush = 1
oPop = 2
oMerge = 3
oAccess = 4
oSet = 5
oArithmetic = 6
oLogic = 7
oFunc = 8
oComparison = 9
oMisc = 10
oJump = 11
oReturn = 12
oObject = 13
End Enum
Private Enum ISubType
'Arithmetic
oAdd = 1
oSub = 2
oMul = 3
oDiv = 4
oPow = 5
oNeg = 6
oMod = 7
'Logic
oAnd = 8
oOr = 9
oNot = 10
oXor = 11
'comparison
oEql = 12
oNeq = 13
oLt = 14
oLte = 15
oGt = 16
oGte = 17
oIs = 18
'misc operators
oCat = 19
oLike = 20
'misc
ifTrue = 21
ifFalse = 22
withValue = 23
argument = 24
'object
oPropGet = 25
oPropLet = 26
oPropSet = 27
oMethodCall = 28
oFieldCall = 29
oEquality = 30 'Yet to be implemented
oIsOperator = 31 'Yet to be implemented
oEnum = 32 'Yet to be implemented
End Enum
Private Enum LambdaType
iStandardLambda = 1
iBoundLambda = 2
End Enum
'Special constant used in parsing:
Private Const UniqueConst As String = "3207af79-30df-4890-ade1-640f9f28f309"
Private Const vbGetOrMethod as Long = VbGet Or VbMethod
Private Const minStackSize as Long = 30 'note that the stack size may become smaller than this
'@TODO: Convert to TThis
Private Type TSingleton
Cache As Object
End Type
Private Type TBoundLambda
Lambda As stdLambda 'was oBound
Args As Variant 'was vBound
End Type
Private Type TThis
Singleton As TSingleton
tokens() As token
iTokenIndex As Long
operations() As Operation
iOperationIndex As Long
stackSize As Long
scopes() As Variant
scopesArgCount() As Variant
scopeCount As Long
funcScope As Long
Equation as string
'Instance var on both class and object
FunctionExtensions As Object
isBoundLambda as Boolean
Bound As TBoundLambda
UsePerformanceCache as Boolean
PerformanceCache as Object
End Type
Private This as TThis
'Create a stdLambda object from a string equation
'@constructor
'@param sEquation - The equation to parse
'@param bUsePerformanceCache - Whether to cache the parsed equation for performance
'@param bSandboxExtras - Whether to allow extra functions to be called
'@returns - A first class object representing the equation. Can be called with `.Run(param1, param2, ...)` or `.RunEx(params)`
'@example ```vb
'Debug.Print stdLambda.Create("1+3*8/2*(2+2+3)").Run()
'With stdLambda.Create("$1+1+3*8/2*(2+2+3)")
' Debug.Print .Run(10)
' Debug.Print .Run(15)
' Debug.Print .Run(20)
'End With
'Debug.Print stdLambda.Create("$1.Range(""A1"")").Run(Sheets(1)).Address(True, True, xlA1, True)
'Debug.Print stdLambda.Create("$1.join("","")").Run(stdArray.Create(1,2))
'```
Public Function Create(ByVal sEquation As String, Optional ByVal bUsePerformanceCache As Boolean = False, Optional ByVal bSandboxExtras As Boolean = False) As stdLambda
'Cache Lambda created
If this.Singleton.Cache Is Nothing Then Set this.Singleton.Cache = CreateObject("Scripting.Dictionary")
Dim sID As String: sID = bUsePerformanceCache & "-" & bSandboxExtras & ")" & sEquation
If Not this.Singleton.Cache.exists(sID) Then
Set this.Singleton.Cache(sID) = New stdLambda
Call this.Singleton.Cache(sID).protInit(LambdaType.iStandardLambda, sEquation, bUsePerformanceCache, bSandboxExtras)
End If
'Return cached lambda
Set Create = this.Singleton.Cache(sID)
End Function
'Create a stdLambda object from an Array of strings
'@constructor
'@param sEquation as Variant<Array<String>> - The equation to parse
'@param bUsePerformanceCache - Whether to cache the parsed equation for performance
'@param bSandboxExtras - Whether to allow extra functions to be called
'@returns - A first class object representing the equation. Can be called with `.Run(param1, param2, ...)` or `.RunEx(params)`
'@example ```vb
'Debug.Print stdLambda.CreateMultiline(Array( _
' "let x = 8/2*(2+2+3)", _
' "1+3*x"
')).Run()
'```
Public Function CreateMultiline(ByRef sEquation As Variant, Optional ByVal bUsePerformanceCache As Boolean = False, Optional ByVal bSandboxExtras As Boolean = False) As stdLambda
Set CreateMultiline = Create(Join(sEquation, " "), bUsePerformanceCache, bSandboxExtras)
End Function
'Initialise the lambda
'@protected
'@param iLambdaType as LambdaType - Type of lambda to initialise
'@param params - Parameters to initialise the lambda with
Public Sub protInit(ByVal iLambdaType As Long, ParamArray params() As Variant)
Select Case iLambdaType
Case LambdaType.iStandardLambda
Dim sEquation As String: sEquation = params(0)
this.Equation = sEquation
this.UsePerformanceCache = params(1)
Dim bSandboxExtras As Boolean: bSandboxExtras = params(2)
'Performance cache
if this.UsePerformanceCache then set this.PerformanceCache = CreateObject("Scripting.Dictionary")
'Function extensions
Set this.FunctionExtensions = stdLambda.oFunctExt
If bSandboxExtras OR this.FunctionExtensions is nothing Then set this.FunctionExtensions = CreateObject("Scripting.Dictionary")
this.isBoundLambda = false
this.tokens = Tokenise(sEquation)
this.iTokenIndex = 1
this.iOperationIndex = 0
this.stackSize = 0
this.scopeCount = 0
this.funcScope = 0
Call parseBlock("eof")
Call finishOperations
Case LambdaType.iBoundLambda
this.isBoundLambda = True
Set this.Bound.Lambda = params(0)
this.Bound.Args = params(1)
this.Equation = "BOUND..."
'Function extensions
Set this.FunctionExtensions = stdLambda.oFunctExt
If bSandboxExtras OR this.FunctionExtensions is nothing Then set this.FunctionExtensions = CreateObject("Scripting.Dictionary")
Case Else
Err.Raise 1, "stdLambda::Init", "No lambda with that type."
End Select
End Sub
'Run the lambda from passed parameters
'@param params as Array<Variant> - Array of parameters to run the lambda with
'@returns - The result of the lambda
Public Function Run(ParamArray params() As Variant) As Variant
Attribute Run.VB_UserMemId = 0
If Not this.isBoundLambda Then
'Execute top-down parser
Call CopyVariant(Run, evaluate(this.operations, params))
Else
Call CopyVariant(Run, this.Bound.Lambda.RunEx(ConcatArrays(this.Bound.Args, params)))
End If
End Function
'Run the lambda from an array of parameters
'@param params as Variant<Array<Variant>> - Array of parameters to run the lambda with
'@returns - The result of the lambda
Public Function RunEx(ByVal params As Variant) As Variant
If Not this.isBoundLambda Then
If Not isArray(params) Then
Err.Raise 1, "params to be supplied as array of arguments", ""
End If
'Execute top-down parser
Call CopyVariant(RunEx, evaluate(this.operations, params))
Else
Call CopyVariant(RunEx, this.Bound.Lambda.RunEx(ConcatArrays(this.Bound.Args, params)))
End If
End Function
'Bind parameters to the function. Arguments will be passed in the order they are supplied, before any arguments supplied to the function.
'@param params as Array<Variant> - Parameters to bind to the lambda.
'@returns - The lambda
Public Function Bind(ParamArray params() As Variant) As stdLambda
Set Bind = BindEx(params)
End Function
'Bind an array of parameters to the function. Arguments will be passed in the order they are supplied, before any arguments supplied to the function.
'@param params as Variant<Array<Variant>> - Array of parameters to bind
'@returns - The lambda existing lambda
Public Function BindEx(ByVal params As Variant) As stdLambda
Set BindEx = New stdLambda
Dim callable As stdICallable: Set callable = Me
Call BindEx.protInit(LambdaType.iBoundLambda, callable, params)
End Function
'Bind a named global variable to the function
'@param sGlobalName - New global name
'@param variable - Data to store in global variable
'@returns - The lambda existing lambda
Public Function BindGlobal(ByVal sGlobalName as string, ByVal variable as Variant) as stdLambda
set BindGlobal = Me
If this.isBoundLambda Then
Call this.Bound.Lambda.BindGlobal(sGlobalName, variable)
Else
If this.FunctionExtensions is nothing then Set this.FunctionExtensions = CreateObject("Scripting.Dictionary")
If IsObject(variable) Then
Set this.FunctionExtensions(sGlobalName) = variable
Else
Let this.FunctionExtensions(sGlobalName) = variable
End If
End If
End Function
'Extend the lambda with new functions and named global variables
'@returns Object<Dictionary<string,stdICallable> | Dictionary<string,variant>> - Dictionary of functions and named global variables
Public Property Get oFunctExt() as Object
set oFunctExt = this.FunctionExtensions
End Property
'Implementation of stdICallable::Run
'@param params as Array<Variant> - Parameters to run the lambda with
'@returns - The result of the lambda
Private Function stdICallable_Run(ParamArray params() As Variant) As Variant
If Not this.isBoundLambda Then
'Execute top-down parser
Call CopyVariant(stdICallable_Run, evaluate(this.operations, params))
Else
Call CopyVariant(stdICallable_Run, this.Bound.Lambda.RunEx(ConcatArrays(this.Bound.Args, params)))
End If
End Function
'Implementation of stdICallable::RunEx
'@param params as Variant<Array<Variant>> - Array of parameters to run the lambda with
'@returns - The result of the lambda
Private Function stdICallable_RunEx(ByVal params As Variant) As Variant
If Not isArray(params) Then
Err.Raise 1, "params to be supplied as array of arguments", ""
End If
If Not this.isBoundLambda Then
'Execute top-down parser
Call CopyVariant(stdICallable_RunEx, evaluate(this.operations, params))
Else
Call CopyVariant(stdICallable_RunEx, this.Bound.Lambda.RunEx(ConcatArrays(this.Bound.Args, params)))
End If
End Function
'Implementation of stdICallable::Bind
'@param params as Array<Variant> - Parameters to bind to the lambda.
'@returns - The bound lambda
Private Function stdICallable_Bind(ParamArray params() As Variant) As stdICallable
Set stdICallable_Bind = BindEx(params)
End Function
'Late-bound, no dependency, function calling
'@param sMessage as "obj"|"className"|"bindGlobal" - Message to send. "obj" returns the object, "className" returns the class name, "bindGlobal" binds a global variable to the lambda.
'@param success - Success of message. If message wasn't processed return false.
'@param params - Parameters to pass along with message
'@returns - Anything returned by the function
Private Function stdICallable_SendMessage(ByVal sMessage as string, ByRef success as boolean, ByVal params as variant) as Variant
select case sMessage
case "obj"
set stdICallable_SendMessage = Me
success = true
case "className"
stdICallable_SendMessage = "stdLambda"
success = true
case "bindGlobal"
'Bind global based whether this is a bound lambda or not
Call BindGlobal(params(0), params(1))
success = true
case else
success = false
end select
End Function
'================
'
' TOKENISATION
'
'================
'Get token definitions, a mapping of token names to regexes. This is used in the tokenisation process.
'@private
'@returns - Array of token definitions
Private Function getTokenDefinitions() As TokenDefinition()
Dim arr() As TokenDefinition
ReDim arr(1 To 99)
Dim i As Long: i = 0
'Whitespace
i = i + 1: arr(i) = getTokenDefinition("space", "\s+") 'String
'Literal
i = i + 1: arr(i) = getTokenDefinition("literalString", """(?:""""|[^""])*""") 'String
i = i + 1: arr(i) = getTokenDefinition("literalNumber", "\d+(?:\.\d+)?") 'Number
i = i + 1: arr(i) = getTokenDefinition("literalBoolean", "True|False", isKeyword:=True)
'Named operators
i = i + 1: arr(i) = getTokenDefinition("is", "is", isKeyword:=True)
i = i + 1: arr(i) = getTokenDefinition("mod", "mod", isKeyword:=True)
i = i + 1: arr(i) = getTokenDefinition("and", "and", isKeyword:=True)
i = i + 1: arr(i) = getTokenDefinition("or", "or", isKeyword:=True)
i = i + 1: arr(i) = getTokenDefinition("xor", "xor", isKeyword:=True)
i = i + 1: arr(i) = getTokenDefinition("not", "not", isKeyword:=True)
i = i + 1: arr(i) = getTokenDefinition("like", "like", isKeyword:=True)
i = i + 1: arr(i) = getTokenDefinition("let", "let", isKeyword:=True)
i = i + 1: arr(i) = getTokenDefinition("set", "set", isKeyword:=True)
'Structural
' Inline if
i = i + 1: arr(i) = getTokenDefinition("if", "if", isKeyword:=True)
i = i + 1: arr(i) = getTokenDefinition("then", "then", isKeyword:=True)
i = i + 1: arr(i) = getTokenDefinition("else", "else", isKeyword:=True)
i = i + 1: arr(i) = getTokenDefinition("end", "end", isKeyword:=True)
' Brackets
i = i + 1: arr(i) = getTokenDefinition("lBracket", "\(")
i = i + 1: arr(i) = getTokenDefinition("rBracket", "\)")
' Functions
i = i + 1: arr(i) = getTokenDefinition("fun", "fun", isKeyword:=True)
i = i + 1: arr(i) = getTokenDefinition("comma", ",") 'params
' Lines
i = i + 1: arr(i) = getTokenDefinition("colon", ":")
'VarName
i = i + 1: arr(i) = getTokenDefinition("arg", "\$\d+")
i = i + 1: arr(i) = getTokenDefinition("var", "[a-zA-Z][a-zA-Z0-9_]*")
'Operators
i = i + 1: arr(i) = getTokenDefinition("propertyAccess", "\.\$")
i = i + 1: arr(i) = getTokenDefinition("methodAccess", "(\.\#)")
i = i + 1: arr(i) = getTokenDefinition("fieldAccess", "\.")
i = i + 1: arr(i) = getTokenDefinition("multiply", "\*")
i = i + 1: arr(i) = getTokenDefinition("divide", "\/")
i = i + 1: arr(i) = getTokenDefinition("power", "\^")
i = i + 1: arr(i) = getTokenDefinition("add", "\+")
i = i + 1: arr(i) = getTokenDefinition("subtract", "\-")
i = i + 1: arr(i) = getTokenDefinition("equal", "\=")
i = i + 1: arr(i) = getTokenDefinition("notEqual", "\<\>")
i = i + 1: arr(i) = getTokenDefinition("greaterThanEqual", "\>\=")
i = i + 1: arr(i) = getTokenDefinition("greaterThan", "\>")
i = i + 1: arr(i) = getTokenDefinition("lessThanEqual", "\<\=")
i = i + 1: arr(i) = getTokenDefinition("lessThan", "\<")
i = i + 1: arr(i) = getTokenDefinition("concatenate", "\&")
ReDim Preserve arr(1 To i)
getTokenDefinitions = arr
End Function
'===========
'
' PARSING
'
'===========
'Continually parse statements until some endToken is reached.
'@private
'@param endToken as Array<String> - Names of tokens which should be checked to stop parsing statements
'@remark - Entry point for parsing
Private Sub parseBlock(ParamArray endToken() As Variant)
Call addScope
Dim size As Integer: size = this.stackSize + 1
' Consume multiple lines
Dim bLoop As Boolean: bLoop = True
Do
While optConsume("colon"): Wend
Call parseStatement
While optConsume("colon"): Wend
For i = LBound(endToken) To UBound(endToken)
If peek(endToken(i)) Then
bLoop = False
End If
Next
Loop While bLoop
' Get rid of all extra expression results and declarations
While this.stackSize > size
Call addOperation(oMerge, , , -1)
Wend
this.scopeCount = this.scopeCount - 1
End Sub
'Increment the number of scopes and initialise them. Scopes are used to store variables, functions and function arg counts.
Private Sub addScope()
this.scopeCount = this.scopeCount + 1
Dim scope As Long: scope = this.scopeCount
ReDim Preserve this.scopes(1 To scope)
ReDim Preserve this.scopesArgCount(1 To scope)
Set this.scopes(scope) = CreateObject("Scripting.Dictionary")
Set this.scopesArgCount(scope) = CreateObject("Scripting.Dictionary")
End Sub
'Parse a statement of code.
'@remark - A statement consists of either a variable assignment, a function declaration or an expression
'(typically this wouldn't classify as a statement, but for the purpose of stdLambda and simplifying parsing it does).
Private Sub parseStatement()
If (peek("set") or peek("let")) and peek("var",2) And peek("equal", 3) Then
Call parseAssignment
ElseIf peek("fun") Then
Call parseFunctionDeclaration
Else
Call parseExpression
End If
End Sub
'Parse expression.
'@remark - Parsing an expression is split into a number of stages, each with a different priority.
'This is to ensure that the correct order of operations is followed. E.G. think about the expression `1+2*3`. We want to ensure
'that the multiplication is performed before the addition. This is done by parsing the expression in a specific order. The order
'is defined by the priority of the operation. The order of operations is as follows:
'1. Logical XOR
'2. Logical OR
'3. Logical AND
'4. Logical NOT
'5. Comparison (=, <>, <, <=, >, >=, is, Like)
'6. Concatenation (&)
'7. Arithmetic (+, -)
'8. Arithmetic (mod)
'9. Arithmetic (*, /)
'10. Arithmetic (Unary +, -) e.g. -1
'11. Arithmetic (^)
'12. Arithmetic (Unary +, -) (for RHS of power operator) e.g. 2^-1
'13. Flow (if then else)
'14. Value (numbers, $vars, strings, booleans, brackets)
'@remark - The order of priority is opposite to the order of evaluation. I.E. Comparrison is evaluated before Logical AND allowing
'expressions such as `1<2 and 2<3` to be evaluated correctly without requiring bracketing. It's important to note however that all
'comparrisons have the same priority. This means that `1<2<3` will be evaluated as `(1<2)<3` which is not the same as `1<(2<3)`.
Private Sub parseExpression()
Call parseLogicPriority1
End Sub
'Parse Logical XOR
Private Sub parseLogicPriority1()
Call parseLogicPriority2
Dim bLoop As Boolean: bLoop = True
Do
If optConsume("xor") Then
Call parseLogicPriority2
Call addOperation(oLogic, oXor, , -1)
Else
bLoop = False
End If
Loop While bLoop
End Sub
'Parse Logical OR
Private Sub parseLogicPriority2()
Call parseLogicPriority3
Dim bLoop As Boolean: bLoop = True
Do
If optConsume("or") Then
Call parseLogicPriority3
Call addOperation(oLogic, oOr, , -1)
Else
bLoop = False
End If
Loop While bLoop
End Sub
'Parse Logical AND
Private Sub parseLogicPriority3()
Call parseLogicPriority4
Dim bLoop As Boolean: bLoop = True
Do
If optConsume("and") Then
Call parseLogicPriority4
Call addOperation(oLogic, oAnd, , -1)
Else
bLoop = False
End If
Loop While bLoop
End Sub
'Parse Logical NOT
Private Sub parseLogicPriority4() 'not
Dim invert As Variant: invert = vbNull
While optConsume("not")
If invert = vbNull Then invert = False
invert = Not invert
Wend
Call parseComparisonPriority1
If invert <> vbNull Then
Call addOperation(oLogic, oNot)
If invert = False Then
Call addOperation(oLogic, oNot)
End If
End If
End Sub
'Parse comparison operators (=, <>, <, <=, >, >=, is, Like)
Private Sub parseComparisonPriority1()
Call parseArithmeticPriority1
Dim bLoop As Boolean: bLoop = True
Do
If optConsume("lessThan") Then
Call parseArithmeticPriority1
Call addOperation(oComparison, oLt, , -1)
ElseIf optConsume("lessThanEqual") Then
Call parseArithmeticPriority1
Call addOperation(oComparison, oLte, , -1)
ElseIf optConsume("greaterThan") Then
Call parseArithmeticPriority1
Call addOperation(oComparison, oGt, , -1)
ElseIf optConsume("greaterThanEqual") Then
Call parseArithmeticPriority1
Call addOperation(oComparison, oGte, , -1)
ElseIf optConsume("equal") Then
Call parseArithmeticPriority1
Call addOperation(oComparison, oEql, , -1)
ElseIf optConsume("notEqual") Then
Call parseArithmeticPriority1
Call addOperation(oComparison, oNeq, , -1)
ElseIf optConsume("is") Then
Call parseArithmeticPriority1
Call addOperation(oComparison, oIs, , -1)
ElseIf optConsume("like") Then
Call parseArithmeticPriority1
Call addOperation(oComparison, oLike, , -1)
Else
bLoop = False
End If
Loop While bLoop
End Sub
'Parse concatenation operator (&)
Private Sub parseArithmeticPriority1() '&
Call parseArithmeticPriority2
Dim bLoop As Boolean: bLoop = True
Do
If optConsume("concatenate") Then
Call parseArithmeticPriority2
Call addOperation(oMisc, oCat, , -1)
Else
bLoop = False
End If
Loop While bLoop
End Sub
'Parse + and - operators
Private Sub parseArithmeticPriority2()
Call parseArithmeticPriority3
Dim bLoop As Boolean: bLoop = True
Do
If optConsume("add") Then
Call parseArithmeticPriority3
Call addOperation(oArithmetic, oAdd, , -1)
ElseIf optConsume("subtract") Then
Call parseArithmeticPriority3
Call addOperation(oArithmetic, oSub, , -1)
Else
bLoop = False
End If
Loop While bLoop
End Sub
'Parse mod operator
Private Sub parseArithmeticPriority3() 'mod
Call parseArithmeticPriority4
Dim bLoop As Boolean: bLoop = True
Do
If optConsume("mod") Then
Call parseArithmeticPriority4
Call addOperation(oArithmetic, oMod, , -1)
Else
bLoop = False
End If
Loop While bLoop
End Sub
'Parse * and / operators
Private Sub parseArithmeticPriority4()
Call parseArithmeticPriority5
Dim bLoop As Boolean: bLoop = True
Do
If optConsume("multiply") Then
Call parseArithmeticPriority5
Call addOperation(oArithmetic, oMul, , -1)
ElseIf optConsume("divide") Then
Call parseArithmeticPriority5
Call addOperation(oArithmetic, oDiv, , -1)
Else
bLoop = False
End If
Loop While bLoop
End Sub
'Parse unary + and - operators (i.e. -1)
Private Sub parseArithmeticPriority5()
If optConsume("subtract") Then
Call parseArithmeticPriority5 'recurse
Call addOperation(oArithmetic, oNeg)
ElseIf optConsume("add") Then
Call parseArithmeticPriority5 'recurse
Else
Call parseArithmeticPriority6
End If
End Sub
'Parse power (^) operator
Private Sub parseArithmeticPriority6() '^
Call parseFlowPriority1
Do
If optConsume("power") Then
Call parseArithmeticPriority6andahalf '- and + are still identity operators
Call addOperation(oArithmetic, oPow, , -1)
Else
bLoop = False
End If
Loop While bLoop
End Sub
'Parse unary + and - operators on the RHS of a power operator (i.e. 2^-1)
Private Sub parseArithmeticPriority6andahalf()
If optConsume("subtract") Then
Call parseArithmeticPriority6andahalf 'recurse
Call addOperation(oArithmetic, oNeg)
ElseIf optConsume("add") Then
Call parseArithmeticPriority6andahalf 'recurse
Else
Call parseFlowPriority1
End If
End Sub
'Parse flow control (if ... then ... else ... end)
Private Sub parseFlowPriority1()
If optConsume("if") Then
Call parseExpression
Dim skipThenJumpIndex As Integer: skipThenJumpIndex = addOperation(oJump, ifFalse, , -1)
Dim size As Integer: size = this.stackSize
Call consume("then")
Call parseBlock("else", "end")
Dim skipElseJumpIndex As Integer: skipElseJumpIndex = addOperation(oJump)
this.operations(skipThenJumpIndex).value = this.iOperationIndex
this.stackSize = size
If optConsume("end") Then
Call addOperation(oPush, , 0, 1) 'Expressions should always return a value
this.operations(skipElseJumpIndex).value = this.iOperationIndex
Else
Call consume("else")
Call parseBlock("eof", "rBracket", "end")
this.operations(skipElseJumpIndex).value = this.iOperationIndex
Call optConsume("end")
End If
Else
Call parseValuePriority1
End If
End Sub
'Parse evaluation of numbers, arguments, strings, booleans, variable names and brackets. Will also parse accessors on these values.
'i.e. `varName.someMethod(1,2,3).someProp`
Private Sub parseValuePriority1()
'Prefix unary operators for set/let
Dim iOperationType as ISubType
iOperationType = iif(optConsume("let"), oPropLet, oFieldCall)
iOperationType = iif(optConsume("set"), oPropSet, iOperationType)
If peek("literalNumber") Then
Call addOperation(oPush, , CDbl(consume("literalNumber")), 1)
ElseIf peek("arg") Then
Call addOperation(oAccess, argument, val(mid(consume("arg"), 2)), 1)
Call parseManyAccessors(iOperationType)
ElseIf peek("literalString") Then
Call parseString
ElseIf peek("literalBoolean") Then
Call addOperation(oPush, , consume("literalBoolean") = "true", 1)
ElseIf peek("var") Then
If Not parseScopeAccess Then
Call parseFunction
End If
Call parseManyAccessors(iOperationType)
Else
Call consume("lBracket")
Call parseExpression
Call consume("rBracket")
Call parseManyAccessors(iOperationType)
End If
End Sub
'Parse a call to a standard in-built function and add it to the stack
'@remark - This is a special case of a function call. It is parsed differently because it is a built-in function and not
'an in-code defined function.
Private Function parseFunction() As Variant
Call addOperation(oPush, , consume("var"), 1)
Dim size As Integer: size = this.stackSize
Call parseOptParameters
Call addOperation(oFunc)
this.stackSize = size
End Function
'Parse object field, property and method accessors. Specifically allows for more than one accessor to be chained together
'i.e. `obj.someMethod(1,"hi").someProp`
Private Sub parseManyAccessors(Optional ByVal ISubType as ISubType = oFieldCall)
Dim bLoop As Boolean: bLoop = True
Do
bLoop = False
if parseOptObjectField(ISubType) then bLoop = True
If parseOptObjectProperty(ISubType) Then bLoop = True
If parseOptObjectMethod() Then bLoop = True
Loop While bLoop
End Sub
'Parse an object's method or property call (i.e. `obj.someMethod` or `obj.someProp`) and add it to the operations stack
'@param ISubType - Whether this is a property get or property let/set
'@returns - Whether a method or property was found
Private Function parseOptObjectField(Optional ByVal ISubType as ISubType = oFieldCall) as Boolean
parseOptObjectField = false
if optConsume("fieldAccess") then
Dim size As Integer: size = this.stackSize
Call addOperation(oPush, , consume("var"), 1)
Call parseOptParameters
'Parse Let/Set ... = ... as a special case
if peek("equal") and ISubType <> oFieldCall then
Call consume("equal")
Call parseExpression
Call addOperation(oObject, ISubType)
else
Call addOperation(oObject, oFieldCall)
end if
this.stackSize = size
parseOptObjectField = True
end if
End Function
'Parse an object's property access (i.e. Obj.someProp) and add it to the operations stack
'@param ISubType - Whether this is a property get or property let/set
'@returns - Whether a property was found
Private Function parseOptObjectProperty(Optional ByVal ISubType as ISubType = oPropGet) As Boolean
parseOptObjectProperty = False
If optConsume("propertyAccess") Then
Dim size As Integer: size = this.stackSize
Call addOperation(oPush, , consume("var"), 1)
Call parseOptParameters
'Parse Let/Set ... = ... as a special case
if peek("equal") and ISubType <> oPropGet then
Call consume("equal")
Call parseExpression
Call addOperation(oObject, ISubType)
else
Call addOperation(oObject, oPropGet)
end if
this.stackSize = size
parseOptObjectProperty = True
End If
End Function
'Parse an object's method call (i.e. Obj.someMethod) and add it to the operations stack
'@returns - Whether a method was found
Private Function parseOptObjectMethod() As Boolean
parseOptObjectMethod = False
If optConsume("methodAccess") Then
Dim size As Integer: size = this.stackSize
Call addOperation(oPush, , consume("var"), 1)
Call parseOptParameters
Call addOperation(oObject, oMethodCall)
this.stackSize = size
parseOptObjectMethod = True
End If
End Function
'Parse a function call's parameters and add them to the operations stack
'@returns - Whether parameters were found
'@remark Parsing parameters is "optional" in the sense that if no parameters are found, the function call will remain parsed.
Private Function parseOptParameters() As Boolean
parseOptParameters = False
If optConsume("lBracket") Then
Dim iArgCount As Integer
While Not peek("rBracket")
If iArgCount > 0 Then
Call consume("comma")
End If
Call parseExpression
iArgCount = iArgCount + 1
Wend
Call consume("rBracket")
If iArgCount > 0 Then
Call addOperation(oPush, , iArgCount, 1)
End If
parseOptParameters = True
End If
End Function
'Parse a string literal and add it to the operations stack
Private Sub parseString()
Dim sRes As String: sRes = consume("literalString")
sRes = Mid(sRes, 2, Len(sRes) - 2)
sRes = Replace(sRes, """""", """")
Call addOperation(oPush, , sRes, 1)
End Sub
'Parse whether a function call or variable access is being made and add it to the operations stack
'@returns - Whether a named variable or function was found in the scope
Private Function parseScopeAccess() As Boolean
If peek("lBracket", 2) Then
parseScopeAccess = parseFunctionAccess()
Else
parseScopeAccess = parseVariableAccess()
End If
End Function
'Parse the access of a named variable's value and add it to the operations stack
'@returns - Whether a variable was found in the scope
Private Function parseVariableAccess() As Boolean
parseVariableAccess = False
Dim varName As String: varName = consume("var")
Dim offset As Long: offset = findVariable(varName)
If offset >= 0 Then
parseVariableAccess = True
Call addOperation(oAccess, , 1 + offset, 1)
Else
this.iTokenIndex = this.iTokenIndex - 1 ' Revert token consumption
End If
End Function
'Parse an assignment and add it to the current scope and operations stack
Private Sub parseAssignment()
'Consume set/let keyword
if not optConsume("let") then Call consume("set")
Dim varName As String: varName = consume("var")
Call consume("equal")
Call parseExpression
Dim offset As Long: offset = findVariable(varName)
If offset >= 0 Then
' If the variable already existed, move the data to that pos on the stack
Call addOperation(oSet, , offset, -1)
Call addOperation(oAccess, , offset, 1) ' To keep a return value
Else
' If the variable didn't exist yet, treat this stack pos as its source
Call this.scopes(this.scopeCount).add(varName, this.stackSize)
End If
End Sub
'Find the position on the Operations stack of a variable by name
'@param varName - Name of variable to find
'@returns - The position of the variable on the Operations stack
Private Function findVariable(varName As String) As Long
Dim scope As Long: scope = this.scopeCount
findVariable = -1
While scope > 0
If this.scopes(scope).exists(varName) Then
If scope < this.funcScope Then
Call Throw("Can't access """ & varName & """, functions can unfortunately not access data outside their block")
ElseIf this.scopesArgCount(scope).exists(varName) Then
Call Throw("Expected a variable, but found a function for name " & varName)
Else
findVariable = this.stackSize - this.scopes(scope).item(varName)
scope = 0
End If
End If
scope = scope - 1
Wend
End Function
'Parse a named scoped in-code defined function call and add it to the current scope and operations stack
'@returns - Whether a function was found
Private Function parseFunctionAccess() As Boolean
parseFunctionAccess = False
Dim funcName As String: funcName = consume("var")
Dim argCount As Long
Dim funcPos As Long: funcPos = findFunction(funcName, argCount)
If funcPos <> -1 Then
parseFunctionAccess = True
Dim returnPosIndex As Integer: returnPosIndex = addOperation(oPush, , , 1)
' Consume the arguments
consume ("lBracket")
Dim iArgCount As Integer
While Not peek("rBracket")
If iArgCount > 0 Then Call consume("comma")
Call parseExpression
iArgCount = iArgCount + 1
Wend
Call consume("rBracket")
If iArgCount <> argCount Then
Call Throw(argCount & " arguments should have been provided to " & funcName & " but only " & iArgCount & " were received")
End If
' Add call and return data
Call addOperation(oJump, , funcPos, -iArgCount) 'only -argCount since pushing Result and popping return pos cancel out
this.operations(returnPosIndex).value = this.iOperationIndex
Else
this.iTokenIndex = this.iTokenIndex - 1 ' Revert token consumption
End If
End Function
'Parse a function declaration and add it to the current scope and operations stack
Private Sub parseFunctionDeclaration()
' Create a dedicated scope for this funcion
Call addScope
Dim prevFuncScope As Long: prevFuncScope = this.funcScope
this.funcScope = this.scopeCount
' Add operation to skip this code in normal operation flow
Dim skipToIndex As Integer: skipToIndex = addOperation(oJump)