forked from Sidoine/Ovale
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAST.lua
2921 lines (2793 loc) · 86.6 KB
/
AST.lua
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
--[[--------------------------------------------------------------------
Copyright (C) 2014 Johnny C. Lam.
See the file LICENSE.txt for copying permission.
--]]--------------------------------------------------------------------
--[[----------------------------------------------------------------------------
This module implements a parser that generates an abstract syntax tree (AST)
from an Ovale script.
An AST data structure is a table with the following public properties:
ast.annotation
ast.annotation.customFunction
ast.annotation.definition
ast.annotation.functionCall
ast.child
--]]----------------------------------------------------------------------------
local OVALE, Ovale = ...
local OvaleAST = Ovale:NewModule("OvaleAST")
Ovale.OvaleAST = OvaleAST
--<private-static-properties>
local L = Ovale.L
local OvalePool = Ovale.OvalePool
local OvaleProfiler = Ovale.OvaleProfiler
-- Forward declarations for module dependencies.
local OvaleCondition = nil
local OvaleLexer = nil
local OvaleScripts = nil
local OvaleSpellBook = nil
local OvaleStance = nil
local format = string.format
local gsub = string.gsub
local ipairs = ipairs
local next = next
local pairs = pairs
local rawset = rawset
local setmetatable = setmetatable
local strlower = string.lower
local strsub = string.sub
local tconcat = table.concat
local tinsert = table.insert
local tonumber = tonumber
local tostring = tostring
local tsort = table.sort
local type = type
local wipe = wipe
local yield = coroutine.yield
local API_GetItemInfo = GetItemInfo
-- Register for profiling.
OvaleProfiler:RegisterProfiling(OvaleAST)
-- Keywords for the Ovale script language.
local KEYWORD = {
["and"] = true,
["if"] = true,
["not"] = true,
["or"] = true,
["unless"] = true,
}
local DECLARATION_KEYWORD = {
["AddActionIcon"] = true,
["AddCheckBox"] = true,
["AddFunction"] = true,
["AddIcon"] = true,
["AddListItem"] = true,
["Define"] = true,
["Include"] = true,
["ItemInfo"] = true,
["ItemRequire"] = true,
["ItemList"] = true,
["ScoreSpells"] = true,
["SpellInfo"] = true,
["SpellList"] = true,
["SpellRequire"] = true,
}
local PARAMETER_KEYWORD = {
["checkbox"] = true,
["help"] = true,
["if_buff"] = true,
["if_equipped"] = true,
["if_spell"] = true,
["if_stance"] = true,
["if_target_debuff"] = true,
["itemcount"] = true,
["itemset"] = true,
["level"] = true,
["listitem"] = true,
["specialization"] = true,
["talent"] = true,
["text"] = true,
["wait"] = true,
}
local SPELL_AURA_KEYWORD = {
["SpellAddBuff"] = true,
["SpellAddDebuff"] = true,
["SpellAddPetBuff"] = true,
["SpellAddPetDebuff"] = true,
["SpellAddTargetBuff"] = true,
["SpellAddTargetDebuff"] = true,
["SpellDamageBuff"] = true,
["SpellDamageDebuff"] = true,
}
local STANCE_KEYWORD = {
["if_stance"] = true,
["stance"] = true,
["to_stance"] = true,
}
do
-- SpellAuraList keywords are declaration keywords.
for keyword, value in pairs(SPELL_AURA_KEYWORD) do
DECLARATION_KEYWORD[keyword] = value
end
-- All keywords are Ovale script keywords.
for keyword, value in pairs(DECLARATION_KEYWORD) do
KEYWORD[keyword] = value
end
for keyword, value in pairs(PARAMETER_KEYWORD) do
KEYWORD[keyword] = value
end
end
-- Table of pattern/tokenizer pairs for the Ovale script language.
local MATCHES = nil
-- Functions that are actions; ACTION_PARAMETER_COUNT[action] = number of required parameters
local ACTION_PARAMETER_COUNT = {
["item"] = 1,
["macro"] = 1,
["spell"] = 1,
["texture"] = 1,
["setstate"] = 2,
}
-- Actions that are special "state" actions and return no other relevant action information.
local STATE_ACTION = {
["setstate"] = true,
}
-- Functions for accessing string databases.
local STRING_LOOKUP_FUNCTION = {
["ItemName"] = true,
["L"] = true,
["SpellName"] = true,
}
-- Unary and binary operators with precedence.
local UNARY_OPERATOR = {
["not"] = { "logical", 15 },
["-"] = { "arithmetic", 50 },
}
local BINARY_OPERATOR = {
-- logical
["or"] = { "logical", 5, "associative" },
["xor"] = { "logical", 8, "associative" },
["and"] = { "logical", 10, "associative" },
-- comparison
["!="] = { "compare", 20 },
["<"] = { "compare", 20 },
["<="] = { "compare", 20 },
["=="] = { "compare", 20 },
[">"] = { "compare", 20 },
[">="] = { "compare", 20 },
-- addition, subtraction
["+"] = { "arithmetic", 30, "associative" },
["-"] = { "arithmetic", 30 },
-- multiplication, division, modulus
["%"] = { "arithmetic", 40 },
["*"] = { "arithmetic", 40, "associative" },
["/"] = { "arithmetic", 40 },
-- exponentiation
["^"] = { "arithmetic", 100 },
}
-- INDENT[k] is a string of k concatenated tabs.
local INDENT = {}
do
INDENT[0] = ""
local metatable = {
__index = function(tbl, key)
key = tonumber(key)
if key > 0 then
local s = tbl[key - 1] .. "\t"
rawset(tbl, key, s)
return s
end
return INDENT[0]
end,
}
setmetatable(INDENT, metatable)
end
local self_indent = 0
local self_outputPool = OvalePool("OvaleAST_outputPool")
local self_controlPool = OvalePool("OvaleAST_controlPool")
local self_parametersPool = OvalePool("OvaleAST_parametersPool")
local self_childrenPool = OvalePool("OvaleAST_childrenPool")
local self_postOrderPool = OvalePool("OvaleAST_postOrderPool")
local self_pool = OvalePool("OvaleAST_pool")
do
self_pool.Clean = function(self, node)
if node.child then
self_childrenPool:Release(node.child)
node.child = nil
end
if node.postOrder then
self_postOrderPool:Release(node.postOrder)
node.postOrder = nil
end
end
end
--</private-static-properties>
--<public-static-properties>
-- Export list of parameters keywords.
OvaleAST.PARAMETER_KEYWORD = PARAMETER_KEYWORD
--</public-static-properties>
--<private-static-methods>
-- Implementation of PHP-like print_r() taken from http://lua-users.org/wiki/TableSerialization.
-- This is used to print out a table, but has been modified to print out an AST.
local function print_r(node, indent, done, output)
done = done or {}
output = output or {}
indent = indent or ''
for key, value in pairs(node) do
if type(value) == "table" then
if done[value] then
tinsert(output, indent .. "[" .. tostring(key) .. "] => (self_reference)")
else
-- Shortcut conditional allocation
done[value] = true
if value.type then
tinsert(output, indent .. "[" .. tostring(key) .. "] =>")
else
tinsert(output, indent .. "[" .. tostring(key) .. "] => {")
end
print_r(value, indent .. " ", done, output)
if not value.type then
tinsert(output, indent .. "}")
end
end
else
tinsert(output, indent .. "[" .. tostring(key) .. "] => " .. tostring(value))
end
end
return output
end
-- Follow the flyweight pattern for number nodes.
local function GetNumberNode(value, nodeList, annotation)
-- Check for a flyweight node with this exact numerical value.
annotation.numberFlyweight = annotation.numberFlyweight or {}
local node = annotation.numberFlyweight[value]
if not node then
node = OvaleAST:NewNode(nodeList)
node.type = "value"
node.value = value
node.origin = 0
node.rate = 0
-- Store the first node with this exact numerical value in numberFlyweight.
annotation.numberFlyweight[value] = node
end
return node
end
--[[
Fill an array of nodes in order of post-order traversal.
The odd indices hold the nodes in post-order traversal order.
The even indices hold the parents of the node in the preceding indices.
--]]
local function PostOrderTraversal(node, array, visited)
if node.child then
for _, childNode in ipairs(node.child) do
if not visited[childNode] then
PostOrderTraversal(childNode, array, visited)
-- Insert the current node as the parent of the preceding child node.
array[#array + 1] = node
end
end
end
array[#array + 1] = node
visited[node] = true
end
--[[---------------------------------------------
Lexer functions (for use with OvaleLexer)
--]]---------------------------------------------
local function TokenizeComment(token)
return yield("comment", token)
end
local function TokenizeLua(token, options)
-- Strip off leading [[ and trailing ]].
token = strsub(token, 3, -3)
return yield("lua", token)
end
local function TokenizeName(token)
if KEYWORD[token] then
return yield("keyword", token)
else
return yield("name", token)
end
end
local function TokenizeNumber(token, options)
if options and options.number then
token = tonumber(token)
end
return yield("number", token)
end
local function TokenizeString(token, options)
-- Strip leading and trailing quote characters.
if options and options.string then
token = strsub(token, 2, -2)
end
return yield("string", token)
end
local function TokenizeWhitespace(token)
return yield("space", token)
end
local function Tokenize(token)
return yield(token, token)
end
local function NoToken()
return yield(nil)
end
do
MATCHES = {
{ "^%s+", TokenizeWhitespace },
{ "^%d+%.?%d*", TokenizeNumber },
{ "^[%a_][%w_]*", TokenizeName },
{ "^((['\"])%2)", TokenizeString }, -- empty string
{ [[^(['\"]).-\\%1]], TokenizeString },
{ [[^(['\"]).-[^\]%1]], TokenizeString },
{ "^#.-\n", TokenizeComment },
{ "^!=", Tokenize },
{ "^==", Tokenize },
{ "^<=", Tokenize },
{ "^>=", Tokenize },
{ "^.", Tokenize },
{ "^$", NoToken },
}
end
local function GetTokenIterator(s)
local exclude = { space = true, comments = true }
do
-- Fix some API brokenness in the Penlight lexer.
if exclude.space then
exclude[TokenizeWhitespace] = true
end
if exclude.comments then
exclude[TokenizeComment] = true
end
end
return OvaleLexer.scan(s, MATCHES, exclude)
end
-- "Flatten" a parameter value node into a string, or a table of strings if it is a comma-separated value.
local function FlattenParameterValue(parameterValue, annotation)
local value = parameterValue
if type(parameterValue) == "table" then
local node = parameterValue
if node.type == "comma_separated_values" then
value = self_parametersPool:Get()
for k, v in ipairs(node.csv) do
value[k] = FlattenParameterValue(v, annotation)
end
annotation.parametersList = annotation.parametersList or {}
annotation.parametersList[#annotation.parametersList + 1] = value
else
local isBang = false
if node.type == "bang_value" then
isBang = true
node = node.child[1]
end
if node.type == "value" then
value = node.value
elseif node.type == "variable" then
value = node.name
elseif node.type == "string" then
value = node.value
end
if isBang then
value = "!" .. tostring(value)
end
end
end
return value
end
--[[------------------------
"Unparser" functions
--]]------------------------
-- Return the precedence of an operator in the given node.
-- Returns nil if the node is not an expression node.
local function GetPrecedence(node)
local precedence = node.precedence
if not precedence then
local operator = node.operator
if operator then
if node.expressionType == "unary" and UNARY_OPERATOR[operator] then
precedence = UNARY_OPERATOR[operator][2]
elseif node.expressionType == "binary" and BINARY_OPERATOR[operator] then
precedence = BINARY_OPERATOR[operator][2]
end
end
end
return precedence
end
local function HasParameters(node)
return node.rawPositionalParams and next(node.rawPositionalParams) or node.rawNamedParams and next(node.rawNamedParams)
end
-- Forward declarations of functions needed to implement the recursive unparser.
local UNPARSE_VISITOR = nil
local Unparse = nil
local UnparseAddCheckBox = nil
local UnparseAddFunction = nil
local UnparseAddIcon = nil
local UnparseAddListItem = nil
local UnparseBangValue = nil
local UnparseComment = nil
local UnparseCommaSeparatedValues = nil
local UnparseDefine = nil
local UnparseExpression = nil
local UnparseFunction = nil
local UnparseGroup = nil
local UnparseIf = nil
local UnparseItemInfo = nil
local UnparseItemRequire = nil
local UnparseList = nil
local UnparseNumber = nil
local UnparseParameters = nil
local UnparseScoreSpells = nil
local UnparseScript = nil
local UnparseSpellAuraList = nil
local UnparseSpellInfo = nil
local UnparseSpellRequire = nil
local UnparseString = nil
local UnparseUnless = nil
local UnparseVariable = nil
Unparse = function(node)
if node.asString then
-- Return cached string representation if present.
return node.asString
else
local visitor
if node.previousType then
visitor = UNPARSE_VISITOR[node.previousType]
else
visitor = UNPARSE_VISITOR[node.type]
end
if not visitor then
OvaleAST:Error("Unable to unparse node of type '%s'.", node.type)
else
return visitor(node)
end
end
end
UnparseAddCheckBox = function(node)
local s
if node.rawPositionalParams and next(node.rawPositionalParams) or node.rawNamedParams and next(node.rawNamedParams) then
s = format("AddCheckBox(%s %s %s)", node.name, Unparse(node.description), UnparseParameters(node.rawPositionalParams, node.rawNamedParams))
else
s = format("AddCheckBox(%s %s)", node.name, Unparse(node.description))
end
return s
end
UnparseAddFunction = function(node)
local s
if HasParameters(node) then
s = format("AddFunction %s %s%s", node.name, UnparseParameters(node.rawPositionalParams, node.rawNamedParams), UnparseGroup(node.child[1]))
else
s = format("AddFunction %s%s", node.name, UnparseGroup(node.child[1]))
end
return s
end
UnparseAddIcon = function(node)
local s
if HasParameters(node) then
s = format("AddIcon %s%s", UnparseParameters(node.rawPositionalParams, node.rawNamedParams), UnparseGroup(node.child[1]))
else
s = format("AddIcon%s", UnparseGroup(node.child[1]))
end
return s
end
UnparseAddListItem = function(node)
local s
if HasParameters(node) then
s = format("AddListItem(%s %s %s %s)", node.name, node.item, Unparse(node.description), UnparseParameters(node.rawPositionalParams, node.rawNamedParams))
else
s = format("AddListItem(%s %s %s)", node.name, node.item, Unparse(node.description))
end
return s
end
UnparseBangValue = function(node)
return "!" .. Unparse(node.child[1])
end
UnparseComment = function(node)
if not node.comment or node.comment == "" then
return ""
else
return "#" .. node.comment
end
end
UnparseCommaSeparatedValues = function(node)
local output = self_outputPool:Get()
for k, v in ipairs(node.csv) do
output[k] = Unparse(v)
end
local outputString = tconcat(output, ",")
self_outputPool:Release(output)
return outputString
end
UnparseDefine = function(node)
return format("Define(%s %s)", node.name, node.value)
end
UnparseExpression = function(node)
local expression
local precedence = GetPrecedence(node)
if node.expressionType == "unary" then
local rhsExpression
local rhsNode = node.child[1]
local rhsPrecedence = GetPrecedence(rhsNode)
if rhsPrecedence and precedence >= rhsPrecedence then
rhsExpression = "{ " .. Unparse(rhsNode) .. " }"
else
rhsExpression = Unparse(rhsNode)
end
if node.operator == "-" then
expression = "-" .. rhsExpression
else
expression = node.operator .. " " .. rhsExpression
end
elseif node.expressionType == "binary" then
local lhsExpression, rhsExpression
local lhsNode = node.child[1]
local lhsPrecedence = GetPrecedence(lhsNode)
if lhsPrecedence and lhsPrecedence < precedence then
lhsExpression = "{ " .. Unparse(lhsNode) .. " }"
else
lhsExpression = Unparse(lhsNode)
end
local rhsNode = node.child[2]
local rhsPrecedence = GetPrecedence(rhsNode)
if rhsPrecedence and precedence > rhsPrecedence then
rhsExpression = "{ " .. Unparse(rhsNode) .. " }"
elseif rhsPrecedence and precedence == rhsPrecedence then
if BINARY_OPERATOR[node.operator][3] == "associative" and node.operator == rhsNode.operator then
rhsExpression = Unparse(rhsNode)
else
rhsExpression = "{ " .. Unparse(rhsNode) .. " }"
end
else
rhsExpression = Unparse(rhsNode)
end
expression = lhsExpression .. " " .. node.operator .. " " .. rhsExpression
end
return expression
end
UnparseFunction = function(node)
local s
if HasParameters(node) then
local name
local filter = node.rawNamedParams.filter
if filter == "debuff" then
name = gsub(node.name, "^Buff", "Debuff")
else
name = node.name
end
local target = node.rawNamedParams.target
if target then
s = format("%s.%s(%s)", target, name, UnparseParameters(node.rawPositionalParams, node.rawNamedParams))
else
s = format("%s(%s)", name, UnparseParameters(node.rawPositionalParams, node.rawNamedParams))
end
else
s = format("%s()", node.name)
end
return s
end
UnparseGroup = function(node)
local output = self_outputPool:Get()
output[#output + 1] = ""
output[#output + 1] = INDENT[self_indent] .. "{"
self_indent = self_indent + 1
for _, statementNode in ipairs(node.child) do
local s = Unparse(statementNode)
if s == "" then
output[#output + 1] = s
else
output[#output + 1] = INDENT[self_indent] .. s
end
end
self_indent = self_indent - 1
output[#output + 1] = INDENT[self_indent] .. "}"
local outputString = tconcat(output, "\n")
self_outputPool:Release(output)
return outputString
end
UnparseIf = function(node)
if node.child[2].type == "group" then
return format("if %s%s", Unparse(node.child[1]), UnparseGroup(node.child[2]))
else
return format("if %s %s", Unparse(node.child[1]), Unparse(node.child[2]))
end
end
UnparseItemInfo = function(node)
local identifier = node.name and node.name or node.itemId
return format("ItemInfo(%s %s)", identifier, UnparseParameters(node.rawPositionalParams, node.rawNamedParams))
end
UnparseItemRequire = function(node)
local identifier = node.name and node.name or node.itemId
return format("ItemRequire(%s %s %s)", identifier, node.property, UnparseParameters(node.rawPositionalParams, node.rawNamedParams))
end
UnparseList = function(node)
return format("%s(%s %s)", node.keyword, node.name, UnparseParameters(node.rawPositionalParams, node.rawNamedParams))
end
UnparseNumber = function(node)
return tostring(node.value)
end
UnparseParameters = function(positionalParams, namedParams)
local output = self_outputPool:Get()
for k, v in pairs(namedParams) do
if k == "checkbox" then
for _, name in ipairs(v) do
output[#output + 1] = format("checkbox=%s", Unparse(name))
end
elseif k == "listitem" then
for list, item in pairs(v) do
output[#output + 1] = format("listitem=%s:%s", list, Unparse(item))
end
elseif type(v) == "table" then
output[#output + 1] = format("%s=%s", k, Unparse(v))
elseif k == "filter" or k == "target" then
-- Skip output of "filter" or "target".
else
output[#output + 1] = format("%s=%s", k, v)
end
end
tsort(output)
for k = #positionalParams, 1, -1 do
tinsert(output, 1, Unparse(positionalParams[k]))
end
local outputString = tconcat(output, " ")
self_outputPool:Release(output)
return outputString
end
UnparseScoreSpells = function(node)
return format("ScoreSpells(%s)", UnparseParameters(node.rawPositionalParams, node.rawNamedParams))
end
UnparseScript = function(node)
local output = self_outputPool:Get()
local previousDeclarationType
for _, declarationNode in ipairs(node.child) do
if declarationNode.type == "item_info" or declarationNode.type == "spell_aura_list" or declarationNode.type == "spell_info" or declarationNode.type == "spell_require" then
local s = Unparse(declarationNode)
if s == "" then
output[#output + 1] = s
else
output[#output + 1] = INDENT[self_indent + 1] .. s
end
else
local insertBlank = false
-- Add an extra blank line if the type is different from the previous type.
if previousDeclarationType and previousDeclarationType ~= declarationNode.type then
insertBlank = true
end
-- Always an extra blank line preceding "AddFunction" or "AddIcon".
if declarationNode.type == "add_function" or declarationNode.type == "icon" then
insertBlank = true
end
if insertBlank then
output[#output + 1] = ""
end
output[#output + 1] = Unparse(declarationNode)
previousDeclarationType = declarationNode.type
end
end
local outputString = tconcat(output, "\n")
self_outputPool:Release(output)
return outputString
end
UnparseSpellAuraList = function(node)
local identifier = node.name and node.name or node.spellId
return format("%s(%s %s)", node.keyword, identifier, UnparseParameters(node.rawPositionalParams, node.rawNamedParams))
end
UnparseSpellInfo = function(node)
local identifier = node.name and node.name or node.spellId
return format("SpellInfo(%s %s)", identifier, UnparseParameters(node.rawPositionalParams, node.rawNamedParams))
end
UnparseSpellRequire = function(node)
local identifier = node.name and node.name or node.spellId
return format("SpellRequire(%s %s %s)", identifier, node.property, UnparseParameters(node.rawPositionalParams, node.rawNamedParams))
end
UnparseString = function(node)
return '"' .. node.value .. '"'
end
UnparseUnless = function(node)
if node.child[2].type == "group" then
return format("unless %s%s", Unparse(node.child[1]), UnparseGroup(node.child[2]))
else
return format("unless %s %s", Unparse(node.child[1]), Unparse(node.child[2]))
end
end
UnparseVariable = function(node)
return node.name
end
do
UNPARSE_VISITOR = {
["action"] = UnparseFunction,
["add_function"] = UnparseAddFunction,
["arithmetic"] = UnparseExpression,
["bang_value"] = UnparseBangValue,
["checkbox"] = UnparseAddCheckBox,
["compare"] = UnparseExpression,
["comma_separated_values"] = UnparseCommaSeparatedValues,
["comment"] = UnparseComment,
["custom_function"] = UnparseFunction,
["define"] = UnparseDefine,
["function"] = UnparseFunction,
["group"] = UnparseGroup,
["icon"] = UnparseAddIcon,
["if"] = UnparseIf,
["item_info"] = UnparseItemInfo,
["item_require"] = UnparseItemRequire,
["list"] = UnparseList,
["list_item"] = UnparseAddListItem,
["logical"] = UnparseExpression,
["score_spells"] = UnparseScoreSpells,
["script"] = UnparseScript,
["spell_aura_list"] = UnparseSpellAuraList,
["spell_info"] = UnparseSpellInfo,
["spell_require"] = UnparseSpellRequire,
["state"] = UnparseFunction,
["string"] = UnparseString,
["unless"] = UnparseUnless,
["value"] = UnparseNumber,
["variable"] = UnparseVariable,
}
end
--[[--------------------
Parser functions
--]]--------------------
-- Prints the error message and the next 20 tokens from tokenStream.
local function SyntaxError(tokenStream, ...)
OvaleAST:Print(...)
local context = { "Next tokens:" }
for i = 1, 20 do
local tokenType, token = tokenStream:Peek(i)
if tokenType then
context[#context + 1] = token
else
context[#context + 1] = "<EOS>"
break
end
end
OvaleAST:Print(tconcat(context, " "))
end
-- Forward declarations of parser functions needed to implement a recursive descent parser.
local PARSE_VISITOR = nil
local Parse = nil
local ParseAddCheckBox = nil
local ParseAddFunction = nil
local ParseAddIcon = nil
local ParseAddListItem = nil
local ParseDeclaration = nil
local ParseDefine = nil
local ParseExpression = nil
local ParseFunction = nil
local ParseGroup = nil
local ParseIf = nil
local ParseInclude = nil
local ParseItemInfo = nil
local ParseItemRequire = nil
local ParseList = nil
local ParseNumber = nil
local ParseParameterValue = nil
local ParseParameters = nil
local ParseParentheses = nil
local ParseScoreSpells = nil
local ParseScript = nil
local ParseSimpleExpression = nil
local ParseSimpleParameterValue = nil
local ParseSpellAuraList = nil
local ParseSpellInfo = nil
local ParseSpellRequire = nil
local ParseString = nil
local ParseStatement = nil
local ParseUnless = nil
local ParseVariable = nil
Parse = function(nodeType, tokenStream, nodeList, annotation)
local visitor = PARSE_VISITOR[nodeType]
if not visitor then
OvaleAST:Error("Unable to parse node of type '%s'.", nodeType)
else
return visitor(tokenStream, nodeList, annotation)
end
end
ParseAddCheckBox = function(tokenStream, nodeList, annotation)
local ok = true
-- Consume the 'AddCheckBox' token.
do
local tokenType, token = tokenStream:Consume()
if not (tokenType == "keyword" and token == "AddCheckBox") then
SyntaxError(tokenStream, "Syntax error: unexpected token '%s' when parsing ADDCHECKBOX; 'AddCheckBox' expected.", token)
ok = false
end
end
-- Consume the left parenthesis.
if ok then
local tokenType, token = tokenStream:Consume()
if tokenType ~= "(" then
SyntaxError(tokenStream, "Syntax error: unexpected token '%s' when parsing ADDCHECKBOX; '(' expected.", token)
ok = false
end
end
-- Consume the checkbox name.
local name
if ok then
local tokenType, token = tokenStream:Consume()
if tokenType == "name" then
name = token
else
SyntaxError(tokenStream, "Syntax error: unexpected token '%s' when parsing ADDCHECKBOX; name expected.", token)
ok = false
end
end
-- Consume the description string.
local descriptionNode
if ok then
ok, descriptionNode = ParseString(tokenStream, nodeList, annotation)
end
-- Consume any parameters.
local parameters
local positionalParams, namedParams
if ok then
ok, positionalParams, namedParams = ParseParameters(tokenStream, nodeList, annotation)
end
-- Consume the right parenthesis.
if ok then
local tokenType, token = tokenStream:Consume()
if tokenType ~= ")" then
SyntaxError(tokenStream, "Syntax error: unexpected token '%s' when parsing ADDCHECKBOX; ')' expected.", token)
ok = false
end
end
-- Create the AST node.
local node
if ok then
node = OvaleAST:NewNode(nodeList)
node.type = "checkbox"
node.name = name
node.description = descriptionNode
node.rawPositionalParams = positionalParams
node.rawNamedParams = namedParams
annotation.parametersReference = annotation.parametersReference or {}
annotation.parametersReference[#annotation.parametersReference + 1] = node
end
return ok, node
end
ParseAddFunction = function(tokenStream, nodeList, annotation)
local ok = true
-- Consume the 'AddFunction' token.
local tokenType, token = tokenStream:Consume()
if not (tokenType == "keyword" and token == "AddFunction") then
SyntaxError(tokenStream, "Syntax error: unexpected token '%s' when parsing ADDFUNCTION; 'AddFunction' expected.", token)
ok = false
end
-- Consume the function name.
local name
if ok then
local tokenType, token = tokenStream:Consume()
if tokenType == "name" then
name = token
else
SyntaxError(tokenStream, "Syntax error: unexpected token '%s' when parsing ADDFUNCTION; name expected.", token)
ok = false
end
end
-- Consume any parameters.
local positionalParams, namedParams
if ok then
ok, positionalParams, namedParams = ParseParameters(tokenStream, nodeList, annotation)
end
-- Consume the body.
local bodyNode
if ok then
ok, bodyNode = ParseGroup(tokenStream, nodeList, annotation)
end
-- Create the AST node.
local node
if ok then
node = OvaleAST:NewNode(nodeList, true)
node.type = "add_function"
node.name = name
node.child[1] = bodyNode
node.rawPositionalParams = positionalParams
node.rawNamedParams = namedParams
annotation.parametersReference = annotation.parametersReference or {}
annotation.parametersReference[#annotation.parametersReference + 1] = node
-- Add the postOrder list to the body node.
annotation.postOrderReference = annotation.postOrderReference or {}
annotation.postOrderReference[#annotation.postOrderReference + 1] = bodyNode
annotation.customFunction = annotation.customFunction or {}
annotation.customFunction[name] = node
end
return ok, node
end
ParseAddIcon = function(tokenStream, nodeList, annotation)
local ok = true
-- Consume the 'AddIcon' token.
local tokenType, token = tokenStream:Consume()
if not (tokenType == "keyword" and token == "AddIcon") then
SyntaxError(tokenStream, "Syntax error: unexpected token '%s' when parsing ADDICON; 'AddIcon' expected.", token)
ok = false
end
-- Consume any parameters.
local positionalParams, namedParams
if ok then
ok, positionalParams, namedParams = ParseParameters(tokenStream, nodeList, annotation)
end
-- Consume the body.
local bodyNode
if ok then
ok, bodyNode = ParseGroup(tokenStream, nodeList, annotation)
end
-- Create the AST node.
local node
if ok then
node = OvaleAST:NewNode(nodeList, true)
node.type = "icon"
node.child[1] = bodyNode
node.rawPositionalParams = positionalParams
node.rawNamedParams = namedParams
annotation.parametersReference = annotation.parametersReference or {}
annotation.parametersReference[#annotation.parametersReference + 1] = node
-- Add the postOrder list to the body node.
annotation.postOrderReference = annotation.postOrderReference or {}
annotation.postOrderReference[#annotation.postOrderReference + 1] = bodyNode
end
return ok, node
end
ParseAddListItem = function(tokenStream, nodeList, annotation)
local ok = true