-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathpreprocessor_plugins.py
More file actions
1847 lines (1408 loc) · 75.9 KB
/
Copy pathpreprocessor_plugins.py
File metadata and controls
1847 lines (1408 loc) · 75.9 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
# Preprocessor Plugins
#
# This file is part of the SublimeKSP Compiler which is released under GNU General Public License version 3.
# For more information visit https://github.com/nojanath/SublimeKSP.
#
# This file adds a selection of extra syntax, functions and macros that aim to make programming in the
# Kontakt scripting language nicer. These functions are executed very near the beginning of the
# compiling process. They work by scanning through the deque of Line objects, and using regex, the
# line commands are manipulated or added to.
#=================================================================================================
# IDEAS:
# += -= operators
# UI functions to receive arguments in any order: set_bounds(slider, width := 50, x := 20)
# Multidimensional PGS keys
# Single line if statements
# A psuedo callback for UI arrays that automatically creates all the callbacks
import copy
import re
import math
import collections
import utils
from ksp_compiler import ParseException, Line, placeholders
from simple_eval import SimpleEval
from time import strftime, localtime
varPrefixRe = r"[?~%!@$]"
variableNameRe = r'(?P<whole>(?P<prefix>\b|[?~$%!@])(?P<name>[a-zA-Z0-9_][a-zA-Z0-9_\.]*))\b' # A variable name
variableNameUnRe = r'((\b|[?~$%!@])[0-9]*[a-zA-Z0-9_][a-zA-Z0-9_]*(\.[a-zA-Z_0-9]+)*)\b' # Same as above but without names
persistenceRe = r"(?:\b(?P<persistence>pers|instpers|read)\s+)?"
nameInDeclareStmtRe = r"%s\s*(?=[\[\(\:]|$)" % variableNameRe # Match the variable name in a whole declare statement.
stringOrPlaceholderRe = r'({\d+}|\"[^"]*\")'
variableOrInt = r"[^\]]+" # Something that is not a square bracket closing
commasNotInBrackets = re.compile(r",(?![^\(\)\[\]]*[\)\]])") # All commas that are not in parenthesis.
forRe = re.compile(r"^for(?:\(|\s+)")
endForRe = re.compile(r"^end\s+for$")
whileRe = re.compile(r"^while(?:\(|\s+)")
endWhileRe = re.compile(r"^end\s+while$")
ifRe = re.compile(r"^if(?:\s+|\()")
endIfRe = re.compile(r"^end\s+if$")
familyStartRe = r"^family\s+(?P<famname>.+)$"
familyEndRe = r"^end\s+family$"
initRe = r"^on\s+init$"
endOnRe = r"^end\s+on$"
concatSyntax = "concat" # The name of the function to concat arrays.
stringEvaluator = SimpleEval() # Object used to evaluate strings as maths expressions.
#=================================================================================================
def substituteDefines(lines, define_cache = None):
cache = handleDefineConstants(lines, define_cache)
handleDefineLiterals(lines) # Define literals are only avilable for backwards compatibility as regular defines now serve this purpose.
return cache
def pre_macro_functions(lines):
''' This function is called before the macros have been expanded.
Returns the resulting define objects as a cache to be re-used.
lines is a deque of Line objects - see ksp_compiler.py.'''
createBuiltinDefines(lines)
return substituteDefines(lines)
def macro_iter_functions(lines, placeholders=placeholders):
''' Will process macro iteration and return true if any were found '''
return (handleIterateMacro(lines, placeholders) or handleLiterateMacro(lines, placeholders))
def post_macro_iter_functions(lines, placeholders=placeholders):
''' Will process macro iteration and return true if any were found '''
return (handleIteratePostMacro(lines, placeholders)) or (handleLiteratePostMacro(lines, placeholders))
def post_macro_functions(lines):
''' This function is called after the regular macros have been expanded.
lines is a deque of Line objects - see ksp_compiler.py. '''
handleIncrementer(lines)
handleConstBlock(lines)
handleStructs(lines)
handleUIArrays(lines)
handleSameLineDeclaration(lines)
handleMultidimensionalArrays(lines)
handleListBlocks(lines)
handleOpenSizeArrays(lines)
handlePersistence(lines)
handleLists(lines)
handleUIFunctions(lines)
''' continued in ksp_compiler.py, run_post_macro_functions()
because KSPCompiler has to own running of handleStringArrayInitialisation method,
so that string placeholders can be properly used there when compiling from command line
(this fixed the circular import dependancy that was there before, which prevented compiling
from command line properly)'''
#=================================================================================================
def simplifyAdditionString(string):
''' Evaluates a string of add operations, any add pairs that cannot be evalutated are left.
e.g. "2 + 2 + 3 + 4 + x + y + 2" => "11 + x + y + 2 '''
parts = string.split("+")
count = 0
while count < len(parts) - 1:
try:
simplified = int(parts[count]) + int(parts[count+1])
parts[count] = str(simplified)
parts.remove(parts[count + 1])
except:
count += 1
pass
return("+".join(parts))
def tryStringEval(expression, line, name):
''' Evaluates a maths expression in the same way Kontakt would (only integers). '''
try:
final = stringEvaluator.eval(str(expression).strip())
except:
raise ParseException(line,
"Invalid syntax in %s value! This number must able to be evaluated to a single number at compile time. Please use only define constants, numbers or math operations here!\n" % name)
return (final)
def replaceLines(original, new):
original.clear()
original.extend(new)
def countFamily(lineText, famCount):
''' Checks the line for family start or end and returns the current family depth '''
if lineText.startswith("family ") or lineText.startswith("family "):
famCount += 1
elif famCount != 0:
if re.search(familyEndRe, lineText):
famCount -= 1
return(famCount)
def inspectFamilyState(lines, textLineno):
''' If the given line is in at least 1 family, return the family prefixes. '''
currentFamilyNames = []
for i in range(len(lines)):
if i == textLineno:
if currentFamilyNames:
return (".".join(currentFamilyNames) + ".")
else:
return (None)
break
line = lines[i].command.strip()
if "family" in line:
m = re.search(familyStartRe, line)
if m:
currentFamilyNames.append(m.group("famname"))
elif re.search(familyEndRe, line):
currentFamilyNames.pop()
#=================================================================================================
class StructMember(object):
def __init__(self, name, command, prefix):
self.name = name
self.command = command
self.prefix = prefix # The prefix symbol of the member (@!%$)
self.numElements = None
def makeMemberAnArray(self, numElements):
''' Make the command of this member into an array. numElements is a string of any amount of numbers seperated by commas.
Structs exploit the fact the you can put the square brackets of an array after any 'subname' of a dot seperated name. '''
cmd = self.command
if "[" in self.command:
bracketLocation = cmd.find("[")
self.command = cmd[: bracketLocation + 1] + numElements + ", " + cmd[bracketLocation + 1 :]
else:
self.command = re.sub(r"\b%s\b" % self.name, "%s[%s]" % (self.name, numElements), cmd)
if ":=" in self.command:
assignOperatorLocation = self.command.find(":=") + 2
self.command = "%s(%s)" % (self.command[ : assignOperatorLocation], self.command[assignOperatorLocation : ])
if self.prefix == "@":
self.prefix = "!"
elif self.prefix == "~":
self.prefix = "?"
def addNamePrefix(self, namePrefix):
''' Add the prefix to the member with a dot operator. '''
self.command = re.sub(r"\b%s\b" % self.name, "%s%s.%s" % (self.prefix, namePrefix, self.name), self.command)
class Struct(object):
def __init__(self, name):
self.name = name
self.members = []
def addMember(self, memberObj):
self.members.append(memberObj)
def deleteMember(self, index):
del self.members[index]
def insertMember(self, location, memberObj):
self.members.insert(location, memberObj)
def handleStructs(lines):
prefix = r'&'
structs = []
def findStructs():
''' Find all the struct blocks and build struct objects of them. '''
isCurrentlyInAStructBlock = False
for lineIdx in range(len(lines)):
line = lines[lineIdx].command.strip()
# Find the start of a struct block
if line.startswith("struct"):
m = re.search(r"^struct\s+%s$" % variableNameRe, line)
if m:
structObj = Struct(m.group("name"))
if isCurrentlyInAStructBlock:
raise ParseException(lines[lineIdx], "Struct definitions cannot be nested!\n")
isCurrentlyInAStructBlock = True
lines[lineIdx].command = ""
# Find the end of a struct block
elif re.search(r"^end\s+struct$", line):
isCurrentlyInAStructBlock = False
structs.append(structObj)
lines[lineIdx].command = ""
# If in a struct, add each member as an object to the struct
elif isCurrentlyInAStructBlock:
if line:
if not line.startswith("declare ") and not line.startswith("declare "):
raise ParseException(lines[lineIdx], "Structs can only consist of variable declarations!\n")
m = re.search(nameInDeclareStmtRe, line)
if m:
variableName = m.group("whole")
structDeclMatch = re.search(r"\&\s*%s" % variableNameRe, line)
if structDeclMatch:
variableName = "%s%s %s" % ("&", structDeclMatch.group("whole"), variableName)
prefixSymbol = ""
if re.match(varPrefixRe, variableName):
prefixSymbol = variableName[:1]
variableName = variableName[1:]
structObj.addMember(StructMember(variableName, line.replace("%s%s" % (prefixSymbol, variableName), variableName), prefixSymbol))
lines[lineIdx].command = ""
findStructs()
if structs:
# Make the struct names a list so they are easily searchable
structNames = [structs[i].name for i in range(len(structs))]
def resolveStructsWithinStructs():
''' Where structs have been declared as members of another struct, flatten them. '''
for i in range(len(structs)):
j = 0
counter = 0
stillRemainginStructs = False
# Struct member may themselves have struct members, so this is looped until it is fully resolved.
while j < len(structs[i].members) or stillRemainginStructs == True:
m = re.search(r"^([^%s]+\.)?%s\s*%s\s+%s" % (prefix, prefix, variableNameUnRe, variableNameUnRe), structs[i].members[j].name)
if m:
structs[i].deleteMember(j)
structNum = structNames.index(m.group(2))
structVariable = m.group(5).strip()
if m.group(1):
structVariable = m.group(1) + structVariable
if structNum == i:
raise ParseException(lines[0], "Declared struct cannot be the same as struct parent!\n")
insertLocation = j
for memberIdx in range(len(structs[structNum].members)):
structMember = structs[structNum].members[memberIdx]
varName = structVariable + "." + structMember.name
newCommand = re.sub(r"\b%s\b" % structMember.name, varName, structMember.command)
structs[i].insertMember(insertLocation, StructMember(varName, newCommand, structMember.prefix))
insertLocation += 1
# If there are still any struct member declarations, keep looping to resolve them.
for name in structs[i].members[j].name:
mm = re.search(r"^(?:[^%s]+\.)?%s\s*%s\s+%s" % (prefix, prefix, variableNameUnRe, variableNameUnRe), name)
if mm:
stillRemainginStructs = True
j += 1
if j >= len(structs[i].members) and stillRemainginStructs:
stillRemainginStructs = False
j = 0
counter += 1
if counter > 100000:
raise ParseException(lines[0], "Error: too many iterations while building structs!")
break
resolveStructsWithinStructs()
def findAndHandleStructInstanceDeclarations():
''' Find all places where an instance of a struct has been declared and build the lines necesary. '''
newLines = collections.deque()
for i in range(len(lines)):
line = lines[i].command.strip()
m = re.search(r"^declare\s+%s\s*%s\s+%s(?:\[(.*)\])?$" % (prefix, variableNameUnRe, variableNameUnRe), line)
if m:
structName = m.group(1)
declaredName = m.group(4)
try:
structIdx = structNames.index(structName)
except ValueError:
raise ParseException(lines[i], "Undeclared struct %s!\n" % structName)
newMembers = copy.deepcopy(structs[structIdx].members)
# If necessary make the struct members into arrays.
arrayNumElements = m.group(7)
if arrayNumElements:
for j in range(len(newMembers)):
newMembers[j].makeMemberAnArray(arrayNumElements)
if "," in arrayNumElements:
arrayNumElements = utils.split_args(arrayNumElements, lines[i])
for dimIdx in range(len(arrayNumElements)):
newLines.append(lines[i].copy("declare const %s.SIZE_D%d := %s" % (declaredName, dimIdx + 1, arrayNumElements[dimIdx])))
else:
newLines.append(lines[i].copy("declare const %s.SIZE := %s" % (declaredName, arrayNumElements)))
# Add the declared names as a prefix and add the memebers to the newLines deque
for j in range(len(newMembers)):
newMembers[j].addNamePrefix(declaredName)
newLines.append(lines[i].copy(newMembers[j].command))
else:
newLines.append(lines[i])
replaceLines(lines, newLines)
findAndHandleStructInstanceDeclarations()
#=================================================================================================
class Incrementer(object):
def __init__(self, name, start, step, line):
self.name = name
self.iterationVal = start
self.step = step
self.line = line
def increaseVal(self):
self.iterationVal += self.step
def handleIncrementer(lines):
iterObjs = []
found_end = True
for i in range(len(lines)):
line = lines[i].command.strip()
# Check for START_INC and add the object to the array.
if line.startswith("START_INC"):
mm = re.search(r"^%s\s*\(\s*%s\s*\,\s*(.+)s*\,\s*(.+)\s*\)" % ("START_INC", variableNameUnRe), line)
if found_end:
found_end = False
if mm:
lines[i].command = ""
iterObjs.append(Incrementer(mm.group(1), tryStringEval(mm.group(4), lines[i], "start"), tryStringEval(mm.group(5), lines[i], "step"), lines[i]))
else:
raise ParseException(lines[i], "Incorrect parameters for START_INC! Expected: START_INC(<name>, <start-num>, <step-num>)\n")
# If any incremeter has ended, pop the last object off the array.
elif line == "END_INC":
found_end = True
lines[i].command = ""
try:
iterObjs.pop()
except:
raise ParseException(lines[i], "Did not find a corresponding 'START_INC'!")
# If there are any iterators active, scan the line and replace occurances of the name with it's value.
elif iterObjs:
for iterationObj in iterObjs:
mm = re.search(r"\b%s\b" % iterationObj.name, line)
if mm:
lines[i].command = re.sub(r"\b%s\b" % iterationObj.name, str(iterationObj.iterationVal), lines[i].command)
iterationObj.increaseVal()
if iterObjs:
raise ParseException(iterObjs[0].line, "Did not find a corresponding 'END_INC'!")
#=================================================================================================
class ArrayConcat(object):
def __init__(self, arrayToFill, declare, brackets, size, arraysToConcat, line):
self.line = line
self.arrayToFill = arrayToFill
self.declare = declare
self.size = size
self.brackets = brackets
self.arraysToConcat = arraysToConcat.split(",")
def checkArraySize(self, origLineIdx, lines):
''' If the concat function is used on a declared empty size array, the size of the array needs to be calculated. '''
if self.declare:
if not self.brackets:
raise ParseException(self.line, "No array size given. Leave brackets [] empty to have the size auto generated.\n")
elif not self.size:
def findArrays():
''' Scan through the lines up to this point to find all the the arrays that have been chosen to be concatenated,
and from these add their number of elements to determine the total size needed. '''
sizes = []
arrayNameList = list(self.arraysToConcat)
for i in range(origLineIdx):
lineText = lines[i].command.strip()
if lineText.startswith("declare"):
for arr in arrayNameList:
try: # The regex doesn't like it when there are [] or () in the arr list.
mm = re.search(r"^declare\s+%s?%s\s*(\[.*\])" % (varPrefixRe, arr.strip()), lineText)
if mm:
sizes.append(mm.group(1))
arrayNameList.remove(arr)
break
except:
raise ParseException(lines[i], "Syntax error!\n")
if arrayNameList: # If everything was found, then the list will be empty.
raise ParseException(self.line, "Undeclared array(s) in %s function: %s!\n" % (concatSyntax, ', '.join(arrayNameList).strip()))
return(simplifyAdditionString(re.sub(r"[\[\]]", "", '+'.join(sizes))))
self.size = findArrays()
def getRawArrayDeclaration(self):
''' Return the command that should replace line that triggered the concat. '''
return("declare %s[%s]" % (self.arrayToFill, str(self.size)))
def buildLines(self):
''' Return all the lines needed to perfrom the concat. '''
newLines = collections.deque()
numArgs = len(self.arraysToConcat)
offsets = ["0"]
offsets.extend(["num_elements(%s)" % arrName for arrName in self.arraysToConcat])
addOffset = ""
if numArgs != 1:
addOffset = " + concat_offset"
newLines.append(self.line.copy("concat_offset := 0"))
offsetCommand = "concat_offset := concat_offset + #offset#"
templateText = [
"for concat_it := 0 to num_elements(#arg#) - 1",
" #parent#[concat_it%s] := #arg#[concat_it]" % addOffset,
"end for"]
for j in range(numArgs):
if j != 0 and numArgs != 1:
newLines.append(self.line.copy(offsetCommand.replace("#offset#", offsets[j])))
for text in templateText:
newLines.append(self.line.copy(text.replace("#arg#", self.arraysToConcat[j]).replace("#parent#", self.arrayToFill)))
return(newLines)
def handleArrayConcat(lines):
arrayConcatRe = r"(?P<declare>^\s*declare\s+)?%s\s*(?P<brackets>\[(?P<arraysize>.*)\])?\s*:=\s*%s\s*\((?P<arraylist>[^\)]*)" % (variableNameRe, concatSyntax)
newLines = collections.deque()
for lineIdx in range(len(lines)):
line = lines[lineIdx].command.strip()
if "concat" in line:
m = re.search(arrayConcatRe, line)
if m:
concatObj = ArrayConcat(m.group("whole"), m.group("declare"), m.group("brackets"), m.group("arraysize"), m.group("arraylist"), lines[lineIdx])
concatObj.checkArraySize(lineIdx, lines)
if m.group("declare"):
newLines.append(lines[lineIdx].copy(concatObj.getRawArrayDeclaration()))
newLines.extend(concatObj.buildLines())
continue
# The variables needed are declared at the start of the init callback.
elif line.startswith("on"):
if re.search(initRe, line):
newLines.append(lines[lineIdx])
# Only add preprocessor variable if not previously declared
if not (any(l.command == "declare concat_i" for l in newLines) or any(l.command == "declare concat_offset" for l in newLines)):
newLines.append(lines[lineIdx].copy("declare concat_it"))
newLines.append(lines[lineIdx].copy("declare concat_offset"))
continue
newLines.append(lines[lineIdx])
replaceLines(lines, newLines)
#=================================================================================================
class MultiDimensionalArray(object):
def __init__(self, name, prefix, dimensionsString, persistence, assignment, familyPrefix, line):
self.name = name
self.prefix = prefix or ""
self.assignment = assignment or ""
self.dimensions = utils.split_args(dimensionsString, line)
self.persistence = persistence or ""
self.rawArrayName = familyPrefix + "_" + self.name
def getRawArrayDeclaration(self):
newName = self.prefix + "_" + self.name
totalArraySize = "*".join(["(" + dim + ")" for dim in self.dimensions])
return("declare %s %s [%s] %s" % (self.persistence, newName, totalArraySize, self.assignment))
def buildPropertyAndConstants(self, line):
propertyTemplate = [
"property #propName#",
"function get(#dimList#) -> result",
"result := #rawArrayName#[#calculatedDimList#]",
"end function",
"function set(#dimList#, val)",
"#rawArrayName#[#calculatedDimList#] := val",
"end function ",
"end property"]
constTemplate = "declare const #name#.SIZE_D#dimNum# := #val#"
newLines = collections.deque()
# Build the declare const lines and add them to the newLines deque.
for dimNum, dimSize in enumerate(self.dimensions):
declareConstText = constTemplate \
.replace("#name#", self.name) \
.replace("#dimNum#", str(dimNum + 1)) \
.replace("#val#", dimSize)
newLines.append(line.copy(declareConstText))
# Build the list of arguments, eg: "d1, d2, d3"
dimensionArgList = ["d" + str(dimNum + 1) for dimNum in range(len(self.dimensions))]
dimensionArgString = ",".join(dimensionArgList)
# Create the maths for mapping multiple dimensions to a single dimension array, eg: "d1 * (20) + d2"
numDimensions = len(self.dimensions)
calculatedDimList = []
for dimNum in range(numDimensions - 1):
for i in range(numDimensions - 1, dimNum, -1):
calculatedDimList.append("(%s) * " % self.dimensions[i])
calculatedDimList.append(dimensionArgList[dimNum] + " + ")
calculatedDimList.append(dimensionArgList[numDimensions - 1])
calculatedDimensions = "".join(calculatedDimList)
for propLine in propertyTemplate:
propertyText = propLine \
.replace("#propName#", self.name) \
.replace("#dimList#", dimensionArgString) \
.replace("#rawArrayName#", self.rawArrayName) \
.replace("#calculatedDimList#", calculatedDimensions)
newLines.append(line.copy(propertyText))
return(newLines)
# TODO: Check whether making this only init callback is ok.
def handleMultidimensionalArrays(lines):
multipleDimensionsRe = r"\[(?P<dimensions>[^\]]+(?:\,[^\]]+)+)\]" # Match square brackets with 2 or more comma separated dimensions.
multidimensionalArrayRe = r"^declare\s+%s%s\s*%s(?P<assignment>\s*:=.+)?$" % (persistenceRe, variableNameRe, multipleDimensionsRe)
newLines = collections.deque()
famCount = 0
initFlag = False
for lineIdx in range(len(lines)):
line = lines[lineIdx].command.strip()
if not initFlag:
if re.search(initRe, line):
initFlag = True
newLines.append(lines[lineIdx])
else: # Multidimensional arrays are only allowed in the init callback.
if re.search(endOnRe, line):
initFlag = False # In case there are other init CBs (Combine Duplciate Callbacks)
newLines.append(lines[lineIdx])
else:
# If a multidim array is found, if necessary the family prefix is added and the lines needed for the property are added.
famCount = countFamily(line, famCount)
if line.startswith("declare"):
m = re.search(multidimensionalArrayRe, line)
if m:
famPrefix = ""
if famCount != 0:
famPrefix = inspectFamilyState(lines, lineIdx)
name = m.group("name")
multiDim = MultiDimensionalArray(name, \
m.group("prefix"), \
m.group("dimensions"), \
m.group("persistence"), \
m.group("assignment"), \
famPrefix, \
lines[lineIdx])
newLines.append(lines[lineIdx].copy(multiDim.getRawArrayDeclaration()))
newLines.extend(multiDim.buildPropertyAndConstants(lines[lineIdx]))
else:
newLines.append(lines[lineIdx])
else:
newLines.append(lines[lineIdx])
replaceLines(lines, newLines)
#===========================================================================================
class UIPropertyTemplate:
def __init__(self, name, argString):
self.name = name
self.args = argString.replace(" ", "").split(",")
class UIPropertyFunction:
def __init__(self, functionType, args, line):
self.functionType = functionType
self.args = args[1:]
if len(self.args) > len(functionType.args):
raise ParseException(line, "Too many arguments! Maximum is %d, got %d.\n" % (len(functionType.args), len(self.args)))
elif len(self.args) == 0:
raise ParseException(line, "Function requires at least 2 arguments!\n")
self.uiId = args[0]
def buildUiPropertyLines(self, line):
''' Return the set ui property commands, e.g. name -> par := val '''
newLines = collections.deque()
for argNum in range(len(self.args)):
newLines.append(line.copy("%s -> %s := %s" % (self.uiId, self.functionType.args[argNum], self.args[argNum])))
return(newLines)
def handleUIFunctions(lines):
# Templates for the functions. Note the ui-id as the first arg and the functions start
# with'set_' is assumed to be true later on.
uiControlPropertyFunctionTemplates = [
"set_bounds(ui-id, x, y, width, height)",
"set_button_properties(ui-id, text, picture, text_alignment, font_type, textpos_y)",
"set_knob_properties(ui-id, text, default)",
"set_label_properties(ui-id, text, picture, text_alignment, font_type, textpos_y)",
"set_level_meter_properties(ui-id, bg_color, off_color, on_color, overload_color)",
"set_menu_properties(ui-id, picture, font_type, text_alignment, textpos_y)",
"set_slider_properties(ui-id, default, picture, mouse_behaviour)",
"set_switch_properties(ui-id, text, picture, text_alignment, font_type, textpos_y)",
"set_table_properties(ui-id, bar_color, zero_line_color)",
"set_text_edit_properties(ui-id, text, picture, text_alignment, font_type, textpos_y)",
"set_value_edit_properties(ui-id, text, font_type, textpos_y, show_arrows)",
"set_waveform_properties(ui-id, bar_color, zero_line_color, bg_color, bg_alpha, wave_color, wave_cursor_color, slicemarkers_color, wf_vis_mode)",
"set_wavetable2d_properties(ui-id, wt_zone, bg_color, bg_alpha, wave_color, wave_alpha, wave_end_color, wave_end_alpha)",
"set_wavetable3d_properties(ui-id, wt_zone, bg_color, bg_alpha, wavetable_color, wavetable_alpha, wavetable_end_color, wavetable_end_alpha, parallax_x, parallax_y)" ]
# Use the template string above to build a list of UIProperyTemplate objects.
uiFuncs = []
for funcTemplate in uiControlPropertyFunctionTemplates:
m = re.search(r"^(?P<name>[^\(]+)\(ui-id,(?P<args>[^\)]+)", funcTemplate)
uiFuncs.append(UIPropertyTemplate(m.group("name"), m.group("args")))
newLines = collections.deque()
for lineIdx in range(len(lines)):
line = lines[lineIdx].command.strip()
foundProp = False
if line.startswith("set_"):
for func in uiFuncs:
if re.search(r"^%s\b" % func.name, line):
foundProp = True
paramString = line[line.find("(") + 1 : len(line) - 1].strip()
paramList = utils.split_args(paramString, lines[lineIdx])
uiPropertyObj = UIPropertyFunction(func, paramList, lines[lineIdx])
newLines.extend(uiPropertyObj.buildUiPropertyLines(lines[lineIdx]))
break
if not foundProp:
newLines.append(lines[lineIdx])
replaceLines(lines, newLines)
#=================================================================================================
def handleSameLineDeclaration(lines):
''' When a variable is declared and initialised on the same line, check to see if the value needs to be
moved over to the next line. '''
newLines = collections.deque()
famCount = 0
for lineIdx in range(len(lines)):
line = lines[lineIdx].command.strip()
famCount = countFamily(line, famCount)
if line.startswith("declare"):
m = re.search(r"^declare\s+(?:(polyphonic|global|local)\s+)*%s%s\s*:=" % (persistenceRe, variableNameRe), line)
if m and not re.search(r"\b%s\s*\(" % concatSyntax, line):
valueIsConstantInteger = False
value = line[line.find(":=") + 2 :]
if not re.search(stringOrPlaceholderRe, line):
try:
# Ideally this would check to see if the value is a Kontakt constant as those are valid inline as well...
eval(value) # Just used as a test to see if the the value is a constant.
valueIsConstantInteger = True
except:
pass
if not valueIsConstantInteger:
preAssignmentText = line[: line.find(":=")]
variableName = m.group("name")
if famCount != 0:
variableName = inspectFamilyState(lines, lineIdx) + variableName
newLines.append(lines[lineIdx].copy(preAssignmentText))
newLines.append(lines[lineIdx].copy(variableName + " " + line[line.find(":=") :]))
continue
newLines.append(lines[lineIdx])
replaceLines(lines, newLines)
#=================================================================================================
class ConstBlock(object):
def __init__(self, name):
self.name = name
self.memberValues = []
self.memberNames = []
self.previousVal = "-1"
def addMember(self, name, value):
''' Add a constant number '''
self.memberNames.append(name)
newVal = value
if not value:
newVal = self.previousVal + "+1"
newVal = simplifyAdditionString(newVal)
self.memberValues.append(newVal)
self.previousVal = newVal
def buildLines(self, line):
''' Return the the commands for the whole const block. '''
newLines = collections.deque()
newLines.append(line.copy("declare %s[%s] := (%s)" % (self.name, len(self.memberNames), ", ".join(self.memberValues))))
newLines.append(line.copy("declare !%s.str[%s] := (%s)" % (self.name, len(self.memberNames), ", ".join(['"{}"'.format(n.replace('__', ' ',).replace('_', ' ')) for n in self.memberNames]))))
newLines.append(line.copy("declare const %s.SIZE := %s" % (self.name, len(self.memberNames))))
newLines.append(line.copy("declare @%s.title := \"%s\"" % (self.name, self.name.replace('__', ' ',).replace('_', ' '))))
for memNum in range(len(self.memberNames)):
newLines.append(line.copy("declare const %s.%s := %s" % (self.name, self.memberNames[memNum], self.memberValues[memNum])))
newLines.append(line.copy("declare const %s.%s.idx := %s" % (self.name, self.memberNames[memNum], memNum)))
return(newLines)
def handleConstBlock(lines):
constBlockStartRe = r"^const\s+%s$" % variableNameRe
constBlockEndRe = r"^end\s+const$"
constBlockMemberRe = r"^%s(?:$|\s*\:=\s*(?P<value>.+))" % variableNameRe
newLines = collections.deque()
constBlockObj = None
inConstBlock = False
for lineIdx in range(len(lines)):
line = lines[lineIdx].command.strip()
if line.startswith("const"):
m = re.search(constBlockStartRe, line)
if m:
constBlockObj = ConstBlock(m.group("name"))
inConstBlock = True
continue
elif re.search(constBlockEndRe, line):
if constBlockObj.memberValues:
newLines.extend(constBlockObj.buildLines(lines[lineIdx]))
inConstBlock = False
continue
elif inConstBlock:
m = re.search(constBlockMemberRe, line)
if m:
constBlockObj.addMember(m.group("whole"), m.group("value"))
continue
elif not line.strip() == "":
raise ParseException(lines[lineIdx], "Syntax error: in a const block, list constant names and optionally assign them a constant value.")
newLines.append(lines[lineIdx])
replaceLines(lines, newLines)
#=================================================================================================
class ListBlock(object):
def __init__(self, name, size):
self.name = name
self.size = size or ""
self.isMultiDim = False
if size:
self.isMultiDim = "," in size
self.members = []
def addMember(self, command):
self.members.append(command)
def buildLines(self, line):
''' The list block just builds lines ready for the list function later on to interpret them. '''
newLines = collections.deque()
newLines.append(line.copy("declare list %s[%s]" % (self.name, self.size)))
for memNum in range(len(self.members)):
memberName = self.members[memNum]
# If the member is a comma separated list, then we first need to assign the list to an array in kontakt.
if self.isMultiDim:
stringList = utils.split_args(memberName, line)
if len(stringList) != 1:
memberName = self.name + str(memNum)
newLines.append(line.copy("declare %s[] := (%s)" % (memberName, self.members[memNum])))
newLines.append(line.copy("list_add(%s, %s)" % (self.name, memberName)))
return(newLines)
def handleListBlocks(lines):
listBlockStartRe = r"^list\s*%s\s*(?:\[(?P<size>%s)?\])?$" % (variableNameRe, variableOrInt)
listBlockEndRe = r"^end\s+list$"
newLines = collections.deque()
listBlockObj = None
isListBlock = False
for lineIdx in range(len(lines)):
line = lines[lineIdx].command.strip()
m = re.search(listBlockStartRe, line)
if m:
isListBlock = True
listBlockObj = ListBlock(m.group("whole"), m.group("size"))
elif isListBlock and not line == "":
if re.search(listBlockEndRe, line):
isListBlock = False
if listBlockObj.members:
newLines.extend(listBlockObj.buildLines(lines[lineIdx]))
else:
listBlockObj.addMember(line)
else:
newLines.append(lines[lineIdx])
replaceLines(lines, newLines)
#=================================================================================================
class List(object):
def __init__(self, name, prefix, persistence, isMatrix, familyPrefix):
self.name = name
if isMatrix:
self.name = "_%s" % self.name
self.noUnderscoreName = name
self.prefix = prefix or ""
self.persistence = persistence or ""
self.isMatrix = isMatrix
self.familyPrefix = familyPrefix or ""
self.inc = "0"
self.sizeList = [] # If this is a matrix, the sizes of each element are stored.
def getListDeclaration(self, line):
''' This function returns the lines for a list declaration. Because the size of the list caluated based on how
many list_add() functions have been used, this function must be called after all list_add() are resolved. '''
newLines = collections.deque()
if not self.isMatrix:
newLines.append(line.copy("declare %s %s%s[%s]" % (self.persistence, self.prefix, self.name, self.inc)))
newLines.append(line.copy("declare const %s.SIZE := %s" % (self.noUnderscoreName, self.inc)))
else:
listMatrixTemplate = [
"declare #list#.sizes[#size#] := (#sizeList#)",
"declare #list#.pos[#size#] := (#posList#)",
"property #list#",
"function get(d1, d2) -> result",
"result := _#list#[#list#.pos[d1] + d2]",
"end function",
"function set(d1, d2, val)",
"_#list#[#list#.pos[d1] + d2] := val",
"end function",
"end property"]
newLines.append(line.copy("declare %s %s%s[%s]" % (self.persistence, self.prefix, self.name, self.inc)))
newLines.append(line.copy("declare const %s.SIZE := %s" % (self.noUnderscoreName, len(self.sizeList))))
sizeCounter = "0"
posList = ["0"]
for i in range(len(self.sizeList) - 1):
sizeCounter = simplifyAdditionString("%s+%s" % (sizeCounter, self.sizeList[i]))
posList.append(sizeCounter)
for text in listMatrixTemplate:
replacedText = text.replace("#list#", self.noUnderscoreName) \
.replace("#sizeList#", ",".join(self.sizeList)) \
.replace("#posList#", ",".join(posList)) \
.replace("#size#", str(len(self.sizeList)))
newLines.append(line.copy(replacedText))
return(newLines)
def increaseInc(self, value):
self.inc = simplifyAdditionString("%s+%s" % (self.inc, str(value)))
self.sizeList.append(str(value))
def getListAddLine(self, value, line):
''' Return the line for single list add command. '''
string = "%s[%s] := %s" % (self.familyPrefix + self.name, self.inc, value)
self.increaseInc(1)
return(line.copy(string))
def getArrayListAddLines(self, value, line, arrayName, arraySize):
''' This is called when an array is being added to a list with list_add. The lines necessary are returned. '''
newLines = collections.deque()
addArrayToListTemplate = [
"for list_it := 0 to #size# - 1",
"#list#[list_it + #offset#] := #arr#[list_it]",
"end for"]
for templateLine in addArrayToListTemplate:
text = templateLine.replace("#size#", arraySize) \
.replace("#list#", self.familyPrefix + self.name) \
.replace("#offset#", self.inc) \
.replace("#arr#", arrayName)
newLines.append(line.copy(text))
self.increaseInc(arraySize)
return(newLines)
def handleLists(lines):
def findAllArrays(lines):
''' Scan the all the lines and store arrays and their sizes. '''
arrayNames = []
arraySizes = []
initFlag = False
for i in range(len(lines)):
line = lines[i].command.strip()
if initFlag == False:
if line.startswith("on"):
if re.search(initRe, line):
initFlag = True
else:
if line.startswith("end"):