-
Notifications
You must be signed in to change notification settings - Fork 0
/
preprocessor.scd
2868 lines (2721 loc) · 78.9 KB
/
preprocessor.scd
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
0+0; // preprocessor chokes on opening paren, avoid it, that is really unfortunate
/**
Chucklib-livecode: A framework for live-coding improvisation of electronic music
Copyright (C) 2018 Henry James Harkins
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
**/
this.preProcessor = { |code|
if("/+(".includes(code.first)) {
try {
\chucklibLiveCode.eval(code)
} { |error|
// Error is not typically used in the SC class library.
// If you get an Error here, it's probably an error parsing a cll statement.
// You don't need the call stack of parser internals.
if(error.class == Error) {
error.errorString.postln;
""
} {
error.throw; // all other errors should halt
}
};
} {
code
}
};
// avoid wslib dependency
{ |str, exclude = " "|
var firstI = str.detectIndex { |ch| exclude.includes(ch).not },
lastI;
if(firstI.isNil) {
String.new
} {
lastI = str.size - 1;
while { lastI >= firstI and: { exclude.includes(str[lastI]) } } {
lastI = lastI - 1;
};
if(lastI >= firstI) {
str[firstI .. lastI]
} {
String.new
}
}
} => Func(\strTrim);
// main preprocessor
{ |code|
if(code.first == $( and: {
code = Func(\strTrim).eval(code, " \t\n");
code.last == $)
}) {
// 'code' has already lost trailing spaces
code = Func(\strTrim).eval(code[1 .. code.size - 2], " \n\t");
};
if("/+".includes(code.first)) {
code = \clParseIntoStatements.eval(code);
code.do { |stmt, i|
// [i, stmt].debug("preprocessor");
case
{ stmt.first == $/ and: { stmt[1] != $/ } } {
code[i] = PR(\chucklibLiveCode)/*.copy?*/.process(stmt.drop(1));
}
{ stmt.first == $+ } {
if(BP.exists(\clRegister).not) {
PR(\clRegister) => BP(\clRegister);
};
code[i] = BP(\clRegister).process(stmt.drop(1));
};
};
code = code.join(";\n");
if(Library.at(\cllDebug) == true) {
code.debug("cll preprocessor result");
};
code
} {
code
}
} => Func(\chucklibLiveCode);
// separate strings
(
{ |code|
var escape = false, betweenStmts = true, // quote = false, squote = false,
ch, ch2, statements = Array(), start, continue;
code = CollStream(code);
while { (ch = code.next).notNil } {
case
{ ch == $; } {
statements = statements.add(code.collection[start .. code.pos - 2]);
start = code.pos;
betweenStmts = true;
}
{ ch == $/ } {
ch2 = code.next;
case
{ ch2 == $/ } {
while { (ch = code.next).notNil and: { ch != $\n } };
// rewind a character, but only if there's still work to do
if(code.peek.notNil) {
code.pos = code.pos - 1;
} {
// the while condition will terminate after this...
// this will prevent adding a spurious line to 'statements'
// note, this is only at end of input
start = code.pos;
};
}
// a separate function allows recursion for nesting
{ ch2 == $* } {
\clParseDelimComment.eval(code);
// skip over comment, but not mid-statement
if(betweenStmts) {
start = code.pos;
};
}
{ ch2.notNil } {
if(betweenStmts) {
// if we are starting a statement
// and the following code matches the set-pattern template,
// parse accordingly
start = code.pos - 2; // for all cl statement types
if("^[A-Za-z0-9_]+(\\.[A-Za-z0-9_]*)*[ ]*=[ ]*[0-9/]*\\\""
.matchRegexp(code.collection, code.pos - 1)
) {
while {
ch = code.next;
ch.notNil and: { ch != $= }
};
while {
ch = code.next;
ch.notNil and: { ch != $" } // this is part of the regexp! must succeed
};
if(ch.isNil) {
Error("Should be impossible: statement matched set-pattern regexp but failed scanning")
.throw;
};
\clParsePatString.eval(code);
} {
betweenStmts = false; // not a set-pattern statement
};
}
};
}
{ betweenStmts } {
if(ch.isSpace.not) {
betweenStmts = false;
code.pos = code.pos - 1; // reread this char on the next iteration
start = code.pos;
}; // else eat whitespace between ; and next non-space
}
{ ch == $\" } {
continue = true;
while { continue and: { (ch = code.next).notNil } } {
switch(ch)
{ $\\ } {
escape = escape.not;
}
{ $\" } {
if(escape) {
escape = false;
} {
continue = false;
}
}
}
}
// because a ; inside grouping delimiters should not end a statement
{ "([{".includes(ch) } {
\clParseBracketed.eval(code, ch, false)
}
};
if(start <= code.pos and: { start < code.collection.size }) {
statements = statements.add(code.collection[start .. code.pos]);
};
statements
} => Func(\clParseIntoStatements);
// assumes "open" already read
{ |code, open, patString(false)|
var brak = "()[]{}", i = brak.indexOf(open), close, wrongClose, ch, ch2;
var savePos = code.pos;
// [open, code.collection[savePos .. savePos + 10]].debug(">> clParseBracketed");
if(i.notNil) {
close = brak[i+1];
wrongClose = brak[1, 3..].reject(_ == close);
while {
ch = code.next;
ch.notNil and: { ch != close }
} {
case
{ ch == $" } {
if(patString) { \clParsePatString.eval(code) } { \clParseQuote.eval(code, ch) }
}
{ ch == $' } {
\clParseQuote.eval(code, ch)
}
{ ch == $/ } {
ch2 = code.next;
case
{ ch2 == $/ } {
while { (ch = code.next).notNil and: { ch != $\n } };
code.pos = code.pos - 1;
}
{ ch2 == $* } { \clParseDelimComment.eval(code) }
{ code.pos = code.pos - 1 };
}
{ ch == $\\ } {
if(patString) { \clParseGenerator.eval(code, true) }
}
{ "([{".includes(ch) } {
\clParseBracketed.eval(code, ch, patString)
}
{ wrongClose.includes(ch) } {
Error("Unmatched " ++ open).throw;
}
// else keep going
};
if(ch != close) {
Error("Unclosed " ++ open).throw
};
} {
if(open.isKindOf(Char)) {
Error("Invalid opening delimiter " ++ open).throw;
} {
Error("Checking a bracketed region, invalid input = '%'".format(open)).throw;
};
};
// [open, code.collection[savePos .. savePos + 10], code.collection[code.pos .. code.pos + 10]].debug("<< clParseBracketed");
ch
} => Func(\clParseBracketed);
{ |code, quote($")|
var escaped = false, ch, pos = code.pos;
var savePos = code.pos;
// [quote, code.collection[savePos .. savePos + 10]].debug(">> clParseQuote");
while {
ch = code.next;
ch.notNil and: { escaped or: { ch != quote } }
} {
if(ch == $\\ and: { escaped.not }) { escaped = true } { escaped = false };
};
if(ch.isNil) { Error("Unclosed quote " ++ quote ++ " : " ++ code.collection[max(0, pos - 20) .. pos + 20]).throw };
// [quote, code.collection[savePos .. savePos + 10], code.collection[code.pos .. code.pos + 10]].debug("<< clParseQuote");
ch
} => Func(\clParseQuote);
{ |code|
var ch;
var savePos = code.pos;
// [code.collection[savePos .. savePos + 10]].debug(">> clParsePatString");
while {
ch = code.next;
ch.notNil and: { ch != $" }
} {
case
{ ch == $\\ } {
\clParseGenerator.eval(code, true);
}
{ ch == $" } {
\clParsePatString.eval(code);
};
};
if(ch.isNil) { Error("Unclosed pattern string quote").throw };
// [code.collection[savePos .. savePos + 10], code.collection[code.pos .. code.pos + 10]].debug("<< clParsePatString");
ch
} => Func(\clParsePatString);
{ |code, allowedBrackets|
var ch;
while {
ch = code.next/*.debug("skip over")*/;
// generators may now have a {} pair before the arg list
// e.g. \ser*{Pwhite(1,4,inf)}(...)
ch.notNil and: { allowedBrackets.includes(ch).not }
};
// ch.debug("clParseGeneratorBrackets got");
\clParseBracketed.eval(code, ch, true); // can only be in a patstring here
ch // return bracket type
} => Func(\clParseGeneratorBrackets);
{ |code, patString(false)|
var ch, openBracket;
var savePos = code.pos;
// [code.collection[savePos .. savePos + 10]].debug(">> clParseGenerator");
// ["[a-zA-Z0-9_]+\\(", code.collection[code.pos ..],
// code.collection.findRegexpAt("[a-zA-Z0-9_]+[!*(]", code.pos)
// ].debug("check gen");
if(code.collection.findRegexpAt("[a-zA-Z0-9_]+[!*(]", code.pos).notNil) {
// somewhat ugly, but... there can be two bracketed groups
// if there are two, they must be {}()
// if only one, it must be ()
openBracket = \clParseGeneratorBrackets.eval(code, "({");
if(openBracket == ${) {
\clParseGeneratorBrackets.eval(code, "(");
};
} {
Error("Backslash in cl pattern string must introduce a generator").throw;
};
// [code.collection[savePos .. savePos + 10], code.collection[code.pos .. code.pos + 10]].debug("<< clParseGenerator");
ch
} => Func(\clParseGenerator);
// 'code' is a CollStream
// assumes we've already read the slash-star
{ |code|
var ch, ch2, continue = true;
var savePos = code.pos;
// [code.collection[savePos .. savePos + 10]].debug(">> clParseDelimComment");
while { (ch = ch2 ?? { code.next }).notNil and: { continue } } {
ch2 = nil;
switch(ch)
{ $/ } {
ch2 = code.next;
if(ch2 == $*) { \clParseDelimComment.eval(code) }; // recursion
}
{ $* } {
ch2 = code.next;
if(ch2 == $/) { continue = false };
}
};
// [code.collection[savePos .. savePos + 10], code.collection[code.pos .. code.pos + 10]].debug("<< clParseDelimComment");
ch
} => Func(\clParseDelimComment);
);
(
Proto {
~process = { |code|
var result;
block { |break|
~statements.do { |assn|
if(~replaceRegexpMacros.(assn.value).matchRegexp(code)) {
if((result = assn.key.envirGet).notNil) {
result = result.value(code);
} {
// result = PR(key).copy.process(code);
// for testing:
~instance = PR(assn.key).copy;
result = ~instance.process(code);
};
break.(result);
};
};
"Code does not match any known cl-livecode statement template. Ignored.".warn;
nil
};
};
~tokens = (
al: "A-Za-z",
dig: "0-9",
id: "[A-Za-z][A-Za-z0-9_]*",
int: "(-[0-9]+|[0-9]+)",
// http://www.regular-expressions.info/floatingpoint.html
float: "[\\-+]?[0-9]*\\.?[0-9]+([eE][\\-+]?[0-9]+)?",
spc: " " // space, tab, return
);
~statements = [
\clMake -> "^ *make\\*?\\(.*\\)",
\clFuncCall -> "^ *`id\\.\\(.*\\)",
\clPassThru -> "^ *([A-Z][A-Za-z0-9_]*\\.)?`id\\(.*\\)",
\clChuck -> "^ *([A-Z][A-Za-z0-9_]*\\.)?`id *=>.*",
\clPatternSet -> "^ *`id(\\.|`id|`id\\*[0-9]+)* = .*",
\clGenerator -> "^ *`id(\\.|`id)* \\*.*",
\clXferPattern -> "^ *`id(\\.`id)?(\\*`int)? ->>", // harder match should come first
\clCopyPattern -> "^ *`id(\\.`id)?(\\*`int)? ->",
\clStartStop -> "^([/`spc]*`id)+[`spc]*[+-]",
\clPatternToDoc -> "^ *`id(\\.|`id)*(\\*[0-9]+)?[`spc]*$"
];
// support functions
// ~replaceRegexpMacros.("`id(.`id)+ = .*");
// ~replaceRegexpMacros.("blah`id");
// ~replaceRegexpMacros.("`id(.`id)+ = .*").matchRegexp("kik.k1 = 'xxxx'");
~replaceRegexpMacros = { |regexp|
var key, matches;
// should replace from right to left -- don't break indices
matches = regexp.findRegexp("`[a-z0-9]+");
if(matches.notEmpty) {
~removeDupIndices.(matches).reverseDo { |found|
// allow escaping "\`"
if(found[0] == 0 or: { regexp[found[0]-1] != $\\ }) {
key = found[1].drop(1).asSymbol;
if(~tokens[key].notNil) {
// replace only one instance: before match ++ replacement ++ after match
regexp = "%%%".format(
if(found[0] > 0) { regexp[.. found[0] - 1] } { "" },
~tokens[key],
if(found[0] + found[1].size < regexp.size) {
regexp[found[0] + found[1].size ..]
} { "" }
);
};
};
};
};
regexp
};
// this assumes duplicates will be adjacent.
// results of findRegexp appear to be sorted from left to right in the source string
// so this is *probably* ok.
~removeRegexpDups = { |regexpResults|
var out = Array(regexpResults.size).add(regexpResults.first);
regexpResults.doAdjacentPairs { |a, b|
if(b != a) { out.add(b) };
};
out
};
~removeDupIndices = { |regexpResults|
var out = Array(regexpResults.size).add(regexpResults.first);
regexpResults.doAdjacentPairs { |a, b|
if(b[0] != a[0]) { out.add(b) };
};
out
};
} => PR(\chucklibLiveCode);
// statement handlers will use instances, so I can set state variables
Proto {
~clClass = BP;
~isMain = false;
~isPitch = false;
~hasGen = false;
// note: ~parm will be set to nil for composite patterns
~process = { |code|
~eqIndex = code.indexOf($=);
if(~eqIndex.isNil) {
Error("patternSet statement has no '=': This should never happen").throw;
};
~parseIDs.(code);
~parsePattern.(code);
// ~buildStatement.();
// code.quote
};
~parseIDs = { |code|
var i, ids, test, temp;
// everything before ~eqIndex should be the ID string
ids = code[.. ~eqIndex - 1].split($.).collect { |str| Func(\strTrim).eval(str) };
ids = Pseq(ids).asStream;
// class (I expect this won't be used often)
test = ids.next;
if(test.first.isUpper) {
~clClass = test.asSymbol.asClass;
test = ids.next;
};
// chucklib object key
~objKey = test.asSymbol; // really? what about array types?
if(~clClass.exists(~objKey).not) {
Error("clPatternSet: %(%) does not exist.".format(~clClass.name, ~objKey.asCompileString)).throw;
};
test = ids.next;
// phrase name
if(test.size == 0) {
~phrase = \main;
} {
i = test.indexOf($*);
if(i.notNil) {
temp = test[i+1 .. ];
if(temp.notEmpty and: temp.every(_.isDecDigit)) {
~numToApply = temp.asInteger;
} {
"%: Invalid apply number".format(test).warn;
};
~phrase = test[ .. i-1].asSymbol;
} {
~phrase = test.asSymbol; // really? what about array types?
};
};
test = ids.next;
// parameter name
if(test.size == 0) {
~parm = ~clClass.new(~objKey)[\defaultParm] ?? { \main };
~isMain = true;
} {
~parm = test.asSymbol;
if(~clClass.new(~objKey)[\parmMap][~parm].isNil) {
Error("BP(%) does not declare parameter %".format(
~objKey.asCompileString, ~parm.asCompileString
)).throw;
};
~isMain = (~parm == ~clClass.new(~objKey)[\defaultParm]);
};
// if the target object doesn't exist, we would already have thrown an error
// so no need to check again
~isPitch = ~clClass.new(~objKey).v.tryPerform(\parmIsPitch, ~parm) ?? { false };
currentEnvironment
};
// cases:
// - composite
// - no |
// - has |
~cases = [
{ |code|
// var i;
// if(code[0] == $") { i = 1 } { i = 0 };
// ".(".includes(code[i]) // want to use '.' as a segment char too
code[0] == $(
} -> \compositePattern,
// { |code| code.includes($|) } -> \patternWithDividers,
true -> \patternString // \patternWithoutDividers
];
~parsePattern = { |code|
var case, rightHand;
// bug here: should not include semicolon
// proper fix: after replacing the parser, find the \clPatStringNode and get its string
~inString = rightHand = Func(\strTrim).eval(code[~eqIndex + 1 ..]);
if(rightHand.last == $;) {
~inString = rightHand = rightHand.drop(-1);
};
// code.asCompileString.debug("code");
// cases
case = ~cases.detect { |case| case.key.(rightHand) };
if(case.isNil) {
Error("clPatternSet: Pattern does not match any known cases. This should never happen").throw;
};
case.value.envirGet.(rightHand, code);
};
~compositePattern = { |code| // compositePattern does not need full statement
var stream, group;
~isMain = false;
~isPitch = false;
~parm = nil;
code = ~unquoteString.(code);
// code = code.drop(1).drop(-1);
if(code.first != $() {
code = code.drop(1) ++ $);
} {
code = code.drop(1);
};
stream = CollStream(code);
~stream = stream;
~group = group = PR(\clCompGrouping).copy.process(stream);
~quant = ~getQuantFrom.(stream);
group.clumpOperators;
if(group.repeats.isNil) { group.repeats = inf };
~inString = "\"\"";
~buildStatement.();
};
~patternString = { |rightHand, code| // ~patternString *does* need the full statement
var parsed = ClPatternSetNode(CollStream(code)),
id, objKey, phrase, parm, bpb, stream, wrapArray = false,
streamOne = { |stream, i|
var phraseSym = if(i.notNil) { (phrase ++ i).asSymbol } { phrase };
stream << "BP(" <<< objKey << ").setPattern(" <<< phraseSym << ", ";
stream <<< parm << ", Pseq(";
if(wrapArray) { stream << "[ " };
parsed.patStringNode.streamCode(stream);
if(wrapArray) { stream << " ]" };
stream << ", 1), " <<< rightHand << ", " << nil << ");\n"; // nil = quant... needed?
stream << "BP(" <<< objKey << ").setPhraseDur("
<<< phraseSym << ", " << bpb << ")";
};
~parsed = parsed;
id = parsed.idNode;
objKey = id.objKey;
phrase = id.phrase;
parm = id.parm;
if(parsed.hasQuant) {
bpb = parsed.quantNode.quant;
};
if(bpb.isNil) {
if(BP.exists(objKey)) {
bpb = (BP(objKey).clock ?? { TempoClock.default }).beatsPerBar;
} {
bpb = 4; // lame default
};
};
if(parsed.patStringNode.isKindOf(ClPatStringNode)) {
// wrap the clPatString in the abstract generator
// this is necessary to massage the event list into a playable stream
parsed.patStringNode = ClGeneratorNode.newEmpty.putAll((
bpKey: objKey,
phrase: phrase,
parm: parm,
isMain: parsed.isMain,
isPitch: parsed.isPitch,
children: [
ClStringNode.newEmpty.string_(""),
parsed.patStringNode // patString is the abstract generator's only argument
],
name: ""
));
// moderate hack: I should wrap the string in a patstring -> divider -> generator
// but I'm lazy
wrapArray = true;
};
parsed.patStringNode.setTime(0, bpb);
// write the code
stream = CollStream.new;
if(parsed.children[0].numToApply.isNil) {
streamOne.(stream);
} {
parsed.children[0].numToApply.do { |i|
if(i > 0) { stream << ";\n" };
streamOne.(stream, i);
};
};
stream.collection;
};
~unquoteString = { |str, pos = 0, delimiter = $", ignoreInParens(false)|
var i = str.indexOf(delimiter), j, escaped = false, parenCount = 0;
if(i.isNil) {
str
} {
j = i;
while {
j = j + 1;
j < str.size and: {
escaped or: { str[j] != delimiter }
}
} {
switch(str[j])
{ $\\ } { escaped = escaped.not }
{ $( } {
if(ignoreInParens) {
parenCount = parenCount + 1;
escaped = true;
} {
escaped = false;
};
}
{ $) } {
if(ignoreInParens) {
parenCount = parenCount - 1;
if(parenCount < 0) {
"unquoteString: paren mismatch in '%'".format(str).warn;
} {
escaped = parenCount > 0;
};
} {
escaped = false;
};
}
{
if(ignoreInParens.not or: { parenCount <= 0 }) {
escaped = false;
};
}
// if(str[j] == $\\) { escaped = escaped.not } { escaped = false };
};
if(j - i <= 1) {
String.new // special case: two adjacent quotes = empty string
} {
str[i + 1 .. j - 1];
};
};
};
~getQuantFrom = { |stream|
var ch, str;
while { (ch = stream.next).notNil and: { ch.isSpace } }; // skip spaces
if(ch == $() {
stream.pos = stream.pos - 1;
str = ~stringInMatchingBrackets.(stream);
str // return value: string, to plug into generated statement
} { nil }
};
~decodePitch = { |pitchStr|
var degree, legato = 0.9, accent = false;
case
{ ~isPitch and: { pitchStr.isString } } {
pitchStr = pitchStr.asString;
case
{ pitchStr[0].isDecDigit } {
degree = (pitchStr[0].ascii - 48).wrap(1, 10) - 1;
pitchStr.drop(1).do { |ch|
switch(ch)
{ $- } { degree = degree - 0.1 }
{ $+ } { degree = degree + 0.1 }
{ $, } { degree = degree - 7 }
{ $' } { degree = degree + 7 }
{ $~ } { legato = inf /*1.01*/ }
{ $_ } { legato = 0.9 }
{ $. } { legato = 0.4 }
{ $> } { accent = true }
};
// degree -> legato // Association identifies pitch above
SequenceNote(degree, nil, legato, if(accent) { \accent })
}
// { "~_.".includes(pitchStr[0]) } { pitchStr[0] } // for articulation pools?
{ "*@!".includes(pitchStr[0]) } { pitchStr[0] } // placeholders for clGens etc.
{ pitchStr[0] != $ } {
// Rest(0) -> legato
// also, now we need to distinguish between rests and replaceable slots
SequenceNote(Rest(pitchStr[0].ascii), nil, legato)
}
{ nil }
}
{ pitchStr == $ } { nil }
{ pitchStr }
};
// pitchNum is a scale degree, assuming 0 as neutral-octave tonic
// accidentals encoded by +/- 0.1
// currently assuming 7 notes per octave -- will have to fix this
~encodePitch = { |seqNote|
var pitchNum = seqNote.asFloat,
natural = pitchNum.round,
octave = natural div: 7,
class = natural - (octave * 7),
octaveChar = if(octave < 0) { $, } { $' },
accidentalChar = if(pitchNum < natural) { $- } { $+ },
str = (class + 1).asString;
(pitchNum absdif: natural * 10).do { str = str ++ accidentalChar };
octave.abs.do { str = str ++ octaveChar };
case
{ seqNote.length <= 0.4 } { str = str ++ "." }
{ seqNote.length > 1 } { str = str ++ "~" };
str
};
// CODE GENERATION
~buildStatement = {
var stmt = CollStream.new;
if(~parm.notNil) {
Error("\clPatternSet: Pattern string should have been handled outside of buildStatement").throw;
} {
"%(%).setPattern(%, %, %, %, %)".format(
~clClass, ~objKey.asCompileString,
~phrase.asCompileString, nil, // we already know ~parm is nil in this branch
~group.asPatString, ~inString.asCompileString, ~quant
);
};
};
}.import((chucklibLiveCode: #[tokens, replaceRegexpMacros, removeRegexpDups, removeDupIndices]), #[tokens]) => PR(\clPatternSet);
// model composite-pattern elements as objects
Proto {
~type = \seq;
~repeats = 1;
~prep = { |items|
~items = items;
currentEnvironment
};
~asPatString = { |stream|
if(stream.isNil) { stream = CollStream.new };
stream << "P" << ~type << "(";
~itemString.(stream);
stream << ", " << (~repeats ? 1) << ")";
stream.collection;
};
~itemString = { |stream|
if(stream.isNil) { stream = CollStream.new };
stream << "[";
~items.do { |item, i|
if(i > 0) { stream << ", " };
if(item.isKindOf(Proto)) {
item.asPatString(stream);
} {
stream <<< item;
};
};
stream << "]";
stream.collection;
};
~clumpOperators = {
~items = ~splitArray.(~items, $.);
~items = ~items.collect { |item|
case
{ item.isString } { ~processRepeats.(item) }
{ item.isKindOf(Array) } {
if(item.size > 1) {
PR(\clCompGrouping).copy.prep(item).clumpOperators;
} {
item = item[0];
if(item.isKindOf(Proto)) {
item.clumpOperators;
} {
if(item.isString) { ~processRepeats.(item) } { item }
}
};
}
{ item.isKindOf(Proto) } {
item.clumpOperators;
}
{ item }
};
currentEnvironment
};
~splitArray = { |array, delimiter|
var result = Array.new, subarray = Array.new;
array.do { |item|
if(item == delimiter) {
result = result.add(subarray);
subarray = Array.new;
} {
subarray = subarray.add(item);
};
};
result.add(subarray)
};
~processRepeats = { |str|
var starI, pctI, rpt;
if(str.first.isDecDigit) {
i = str.indexOf($%);
if(i.notNil) {
"%: Weights are not valid in a sequence; ignoring".format(str).warn;
~processRepeats.(str[i+1..]); // handle '*', or return symbol
} {
i = str.indexOf($*);
if(i.isNil) {
Error("Invalid item: Repeats without item to repeat").throw;
};
rpt = str[..i-1].asInteger;
str = ~processWildcard.(str[i+1..]);
PR(\clCompRpt).copy.prep(str, rpt);
}
} {
~processWildcard.(str) // .asSymbol
};
};
~processWildcard = { |str|
var i;
str = Func(\strTrim).eval(str);
if(str[0] == $') {
i = str.find("'", offset: 1);
if(i.isNil) {
Error("%: No closing quote".format(str)).throw;
};
PR(\clCompWildcardItem).copy.prep(str[1 .. i-1]);
} {
str.asSymbol
};
};
} => PR(\clCompSequence);
Proto {
~type = \rand;
~repeats = 1;
~prep = { |items, hasWeights(false)|
~items = items;
~hasWeights = hasWeights;
if(hasWeights) { ~type = \wrand }; // I think I'm hacking more
currentEnvironment
};
~clumpOperators = { currentEnvironment };
~itemString = { |stream|
var weights;
if(stream.isNil) { stream = CollStream.new };
stream << "[";
~items.do { |item, i|
if(i > 0) { stream << ", " };
if(item.isKindOf(Proto)) {
item.asPatString(stream);
} {
stream <<< item;
};
};
stream << "]";
if(~hasWeights) {
weights = ~items.collect({ |item| item.tryPerform(\weight) ? 1 }).normalizeSum;
stream << ", [";
weights.do { |w, i|
if(i > 0) { stream << ", " };
stream << w;
};
stream << "]"
};
stream.collection;
};
}.import((clCompSequence: #[asPatString/*, itemString*/])) => PR(\clCompRandom);
Proto {
~type = \n;
~repeats = 1;
~prep = { |items, repeats(1), weight|
~items = items;
~repeats = repeats;
~wt = weight;
currentEnvironment
};
~weight = { ~wt }; // avoid notUnderstood error if weight is nil
~clumpOperators = { currentEnvironment };
~asPatString = { |stream|
if(stream.isNil) { stream = CollStream.new };
stream << "Pn(";
if(~items.isKindOf(Proto)) {
~items.asPatString(stream);
} {
stream <<< ~items;
};
stream << ", " << (~repeats ? 1) << ")";
stream.collection;
};
}.import((clCompSequence: #[itemString])) => PR(\clCompRpt);
Proto {
~prep = { |item, weight(1)|
~item = item;
~weight = weight;
currentEnvironment
};
~itemString = { ~item.asCompileString };
~asPatString = { |stream|
if(stream.isNil) { stream = CollStream.new };
stream <<< ~item
};
} => PR(\clCompWeightedItem);
Proto {
~weight = 1;
~prep = { |item/*, weight(1)*/|
~item = item;
// ~weight = weight;
currentEnvironment
};
~itemString = { ~item.asCompileString };
~asPatString = { |stream|
if(stream.isNil) { stream = CollStream.new };
stream << "Pfuncn({ ~phrases.keys.select { |key| %.matchRegexp(key.asString) }.choose }, 1)".format(~item.asCompileString);
};
} => PR(\clCompWildcardItem);
// LATER
// Proto {
// ~clumpOperators = { currentEnvironment };
// } => PR(\clCompWeightedRand);
Proto {
~type = \group;
~hasWeights = false;
// ~repeats = 1;
~process = { |stream, checkDoubleStar = true|
var ch, continue = true, str = String.new, rpt;
if(checkDoubleStar) { ~checkDoubleStar.(stream) };
~items = Array();
while { continue and: { (ch = stream.next).notNil } } {
case
{ ".|".includes(ch) } { // operators, add as chars
if(str.size > 0) { ~items = ~items.add(str) };
~items = ~items.add(ch);
str = String.new;
}
{ ch == $( } {
if(str.size > 0) { ~items = ~items.add(str) };
~items = ~items.add(PR(\clCompGrouping).copy.process(stream, false));
if(~items.last.tryPerform(\weight).notNil) {
~hasWeights = true;
};
str = String.new;
}
{ ch == $) } {
if(str.size > 0) { ~items = ~items.add(str) };
continue = false;
}
{ ch == $' } {
while {
str = str ++ ch;
ch = stream.next;
ch.notNil and: { ch != $' }
};
if(ch.notNil) { str = str ++ ch };
}
{ "*%".includes(ch) } {
rpt = try {
~scanInt.(stream);
} { |exc|
if(exc.what == \nonInt) { nil } { exc.throw }
};
if(rpt.notNil) {
if(ch == $%) { ~hasWeights = true };
str = rpt ++ ch ++ str;
} {
"Composite pattern: Ignored invalid % string %".format(
if(ch == $*) { "repeat" } { "weight" },
rpt
).warn;