-
Notifications
You must be signed in to change notification settings - Fork 227
/
Interpreter.cpp
3101 lines (3051 loc) · 125 KB
/
Interpreter.cpp
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
/* Interpreter.cpp
*
* Copyright (C) 1993-2021 Paul Boersma
*
* This code 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 2 of the License, or (at
* your option) any later version.
*
* This code 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 work. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Interpreter.h"
#include "praatP.h"
#include "praat_script.h"
#include "Formula.h"
#include "praat_version.h"
#include "../kar/UnicodeData.h"
#include "../fon/Vector.h"
#define Interpreter_WORD 1
#define Interpreter_SENTENCE 2
#define Interpreter_TEXT 3
#define Interpreter_INFILE 4
#define Interpreter_OUTFILE 5
#define Interpreter_FOLDER 6
#define Interpreter_REAL 7
#define Interpreter_POSITIVE 8
#define Interpreter_INTEGER 9
#define Interpreter_NATURAL 10
#define Interpreter_BOOLEAN 11
#define Interpreter_MINIMUM_TYPE_FOR_NUMERIC_VARIABLE Interpreter_REAL
#define Interpreter_MAXIMUM_TYPE_FOR_NUMERIC_VARIABLE Interpreter_BOOLEAN
#define Interpreter_REALVECTOR 12
#define Interpreter_POSITIVEVECTOR 13
#define Interpreter_INTEGERVECTOR 14
#define Interpreter_NATURALVECTOR 15
#define Interpreter_MINIMUM_TYPE_FOR_NUMERIC_VECTOR_VARIABLE Interpreter_REALVECTOR
#define Interpreter_MAXIMUM_TYPE_FOR_NUMERIC_VECTOR_VARIABLE Interpreter_NATURALVECTOR
#define Interpreter_REALMATRIX 16
#define Interpreter_CHOICE 17
#define Interpreter_OPTIONMENU 18
#define Interpreter_MAXIMUM_TYPE_WITH_VARIABLE_NAME Interpreter_OPTIONMENU
#define Interpreter_BUTTON 19
#define Interpreter_OPTION 20
#define Interpreter_COMMENT 21
Thing_implement (InterpreterVariable, SimpleString, 0);
static autoInterpreterVariable InterpreterVariable_create (conststring32 key) {
try {
if (key [0] == U'e' && key [1] == U'\0')
Melder_throw (U"You cannot use 'e' as the name of a variable (e is the constant 2.71...).");
if (key [0] == U'p' && key [1] == U'i' && key [2] == U'\0')
Melder_throw (U"You cannot use 'pi' as the name of a variable (pi is the constant 3.14...).");
if (key [0] == U'u' && key [1] == U'n' && key [2] == U'd' && key [3] == U'e' && key [4] == U'f' && key [5] == U'i' &&
key [6] == U'n' && key [7] == U'e' && key [8] == U'd' && key [9] == U'\0')
Melder_throw (U"You cannot use 'undefined' as the name of a variable.");
autoInterpreterVariable me = Thing_new (InterpreterVariable);
my string = Melder_dup (key);
return me;
} catch (MelderError) {
Melder_throw (U"Interpreter variable not created.");
}
}
conststring32 kInterpreter_ReturnType_errorMessage (kInterpreter_ReturnType returnType, conststring32 command) {
switch (returnType) {
case kInterpreter_ReturnType::VOID_:
return Melder_cat (U"The command \"", command, U"\" does not return anything");
case kInterpreter_ReturnType::OBJECT_:
return Melder_cat (U"The command \"", command, U"\" returns an object");
case kInterpreter_ReturnType::REAL_:
case kInterpreter_ReturnType::INTEGER_:
return Melder_cat (U"The command \"", command, U"\" returns a number or a string");
case kInterpreter_ReturnType::STRING_:
return Melder_cat (U"The command \"", command, U"\" returns a string");
case kInterpreter_ReturnType::REALVECTOR_:
case kInterpreter_ReturnType::INTEGERVECTOR_:
return Melder_cat (U"The command \"", command, U"\" returns a vector");
case kInterpreter_ReturnType::REALMATRIX_:
return Melder_cat (U"The command \"", command, U"\" returns a matrix");
case kInterpreter_ReturnType::STRINGARRAY_:
return Melder_cat (U"The command \"", command, U"\" returns a string array");
default:
return Melder_cat (U"The command \"", command, U"\" has an unknown return type");
}
}
Thing_implement (Interpreter, Thing, 0);
autoInterpreter Interpreter_create (conststring32 environmentName, ClassInfo editorClass) {
try {
autoInterpreter me = Thing_new (Interpreter);
my variablesMap. max_load_factor (0.65f);
my environmentName = Melder_dup (environmentName);
my editorClass = editorClass;
return me;
} catch (MelderError) {
Melder_throw (U"Interpreter not created.");
}
}
autoInterpreter Interpreter_createFromEnvironment (Editor editor) {
if (! editor)
return Interpreter_create (nullptr, nullptr);
return Interpreter_create (editor -> name.get(), editor -> classInfo);
}
void Melder_includeIncludeFiles (autostring32 *inout_text) {
for (int depth = 0; ; depth ++) {
char32 *head = inout_text->get();
integer numberOfIncludes = 0;
if (depth > 10)
Melder_throw (U"Include files nested too deep. Probably cyclic.");
for (;;) {
char32 *includeLocation, *includeFileName, *tail;
integer headLength, includeTextLength, newLength;
/*
Look for an include statement. If not found, we have finished.
*/
includeLocation = ( str32nequ (head, U"include ", 8) ? head : str32str (head, U"\ninclude ") );
if (! includeLocation)
break;
if (includeLocation != head)
includeLocation += 1;
numberOfIncludes += 1;
/*
Separate out the head.
*/
*includeLocation = U'\0';
/*
Separate out the name of the include file.
*/
includeFileName = includeLocation + 8;
while (Melder_isHorizontalSpace (*includeFileName)) includeFileName ++;
tail = includeFileName;
while (Melder_staysWithinLine (*tail)) tail ++;
if (*tail != U'\0') {
*tail = U'\0';
tail += 1;
}
/*
Get the contents of the include file.
*/
structMelderFile includeFile { };
Melder_relativePathToFile (includeFileName, & includeFile);
autostring32 includeText;
try {
includeText = MelderFile_readText (& includeFile);
} catch (MelderError) {
Melder_throw (U"Include file ", & includeFile, U" not read.");
}
/*
Construct the new text.
*/
headLength = (head - inout_text->get()) + str32len (head);
includeTextLength = str32len (includeText.get());
newLength = headLength + includeTextLength + 1 + str32len (tail);
autostring32 newText (newLength);
str32cpy (newText.get(), inout_text->get());
str32cpy (newText.get() + headLength, includeText.get());
str32cpy (newText.get() + headLength + includeTextLength, U"\n");
str32cpy (newText.get() + headLength + includeTextLength + 1, tail);
/*
Replace the old text with the new. This will work even within an autostring.
*/
*inout_text = newText.move();
/*
Cycle.
*/
head = inout_text->get() + headLength + includeTextLength + 1;
}
if (numberOfIncludes == 0) break;
}
}
integer Interpreter_readParameters (Interpreter me, mutablestring32 text) {
char32 *formLocation = nullptr;
integer npar = 0;
my dialogTitle [0] = U'\0';
/*
Look for a "form" line.
*/
{// scope
char32 *p = & text [0];
for (;;) {
/*
Invariant here: we are at the beginning of a line.
*/
Melder_skipHorizontalSpace (& p);
if (str32nequ (p, U"form", 4) && Melder_isEndOfInk (p [4])) {
formLocation = p;
break;
}
Melder_skipToEndOfLine (& p);
if (*p == U'\0')
break;
p ++; // skip newline symbol
}
}
/*
If there is no "form" line, there are no parameters.
*/
if (formLocation) {
char32 *dialogTitle = Melder_findEndOfHorizontalSpace (formLocation + 4);
char32 *endOfLine = Melder_findEndOfLine (dialogTitle);
if (*endOfLine == U'\0')
Melder_throw (U"Unfinished form (only a \"form\" line).");
*endOfLine = U'\0'; // destroy input temporarily in order to limit copying of dialog title
str32ncpy (my dialogTitle, dialogTitle, Interpreter_MAX_DIALOG_TITLE_LENGTH);
*endOfLine = U'\n'; // restore input
my numberOfParameters = 0;
while (true) {
int type = 0;
char32 *startOfLine = Melder_findEndOfHorizontalSpace (endOfLine + 1);
/*
Skip empty lines and lines with comments.
*/
while (*startOfLine == U'#' || *startOfLine == U';' || *startOfLine == U'!' || Melder_isEndOfLine (*startOfLine)) {
endOfLine = Melder_findEndOfLine (startOfLine);
if (Melder_isEndOfText (*endOfLine))
Melder_throw (U"Unfinished form (missing \"endform\").");
startOfLine = Melder_findEndOfHorizontalSpace (endOfLine + 1);
}
if (str32nequ (startOfLine, U"endform", 7) && Melder_isEndOfInk (startOfLine [7]))
break;
char32 *parameterLocation;
if (str32nequ (startOfLine, U"word", 4) && Melder_isEndOfInk (startOfLine [4]))
{ type = Interpreter_WORD; parameterLocation = startOfLine + 4; }
else if (str32nequ (startOfLine, U"sentence", 8) && Melder_isEndOfInk (startOfLine [8]))
{ type = Interpreter_SENTENCE; parameterLocation = startOfLine + 8; }
else if (str32nequ (startOfLine, U"infile", 6) && Melder_isEndOfInk (startOfLine [6]))
{ type = Interpreter_INFILE; parameterLocation = startOfLine + 6; }
else if (str32nequ (startOfLine, U"outfile", 7) && Melder_isEndOfInk (startOfLine [7]))
{ type = Interpreter_OUTFILE; parameterLocation = startOfLine + 7; }
else if (str32nequ (startOfLine, U"folder", 6) && Melder_isEndOfInk (startOfLine [6]))
{ type = Interpreter_FOLDER; parameterLocation = startOfLine + 6; }
else if (str32nequ (startOfLine, U"text", 4) && Melder_isEndOfInk (startOfLine [4]))
{ type = Interpreter_TEXT; parameterLocation = startOfLine + 4; }
else if (str32nequ (startOfLine, U"real", 4) && Melder_isEndOfInk (startOfLine [4]))
{ type = Interpreter_REAL; parameterLocation = startOfLine + 4; }
else if (str32nequ (startOfLine, U"positive", 8) && Melder_isEndOfInk (startOfLine [8]))
{ type = Interpreter_POSITIVE; parameterLocation = startOfLine + 8; }
else if (str32nequ (startOfLine, U"integer", 7) && Melder_isEndOfInk (startOfLine [7]))
{ type = Interpreter_INTEGER; parameterLocation = startOfLine + 7; }
else if (str32nequ (startOfLine, U"natural", 7) && Melder_isEndOfInk (startOfLine [7]))
{ type = Interpreter_NATURAL; parameterLocation = startOfLine + 7; }
else if (str32nequ (startOfLine, U"boolean", 7) && Melder_isEndOfInk (startOfLine [7]))
{ type = Interpreter_BOOLEAN; parameterLocation = startOfLine + 7; }
else if (str32nequ (startOfLine, U"realvector", 10) && Melder_isEndOfInk (startOfLine [10]))
{ type = Interpreter_REALVECTOR; parameterLocation = startOfLine + 10; }
else if (str32nequ (startOfLine, U"positivevector", 14) && Melder_isEndOfInk (startOfLine [14]))
{ type = Interpreter_POSITIVEVECTOR; parameterLocation = startOfLine + 14; }
else if (str32nequ (startOfLine, U"integervector", 13) && Melder_isEndOfInk (startOfLine [13]))
{ type = Interpreter_INTEGERVECTOR; parameterLocation = startOfLine + 13; }
else if (str32nequ (startOfLine, U"naturalvector", 13) && Melder_isEndOfInk (startOfLine [13]))
{ type = Interpreter_NATURALVECTOR; parameterLocation = startOfLine + 13; }
else if (str32nequ (startOfLine, U"realmatrix", 10) && Melder_isEndOfInk (startOfLine [10]))
{ type = Interpreter_REALMATRIX; parameterLocation = startOfLine + 10; }
else if (str32nequ (startOfLine, U"choice", 6) && Melder_isEndOfInk (startOfLine [6]))
{ type = Interpreter_CHOICE; parameterLocation = startOfLine + 6; }
else if (str32nequ (startOfLine, U"optionmenu", 10) && Melder_isEndOfInk (startOfLine [10]))
{ type = Interpreter_OPTIONMENU; parameterLocation = startOfLine + 10; }
else if (str32nequ (startOfLine, U"button", 6) && Melder_isEndOfInk (startOfLine [6]))
{ type = Interpreter_BUTTON; parameterLocation = startOfLine + 6; }
else if (str32nequ (startOfLine, U"option", 6) && Melder_isEndOfInk (startOfLine [6]))
{ type = Interpreter_OPTION; parameterLocation = startOfLine + 6; }
else if (str32nequ (startOfLine, U"comment", 7) && Melder_isEndOfInk (startOfLine [7]))
{ type = Interpreter_COMMENT; parameterLocation = startOfLine + 7; }
else {
endOfLine = Melder_findEndOfLine (startOfLine);
*endOfLine = U'\0'; // destroy input in order to limit printing of parameter type
Melder_throw (U"Unknown parameter type:\n\"", startOfLine, U"\".");
}
/*
Example:
form Something
real Time_(s) 3.14 (= pi)
choice Colour 2
button Red
button Green
button Blue
endform
my parameters [1] := "Time_(s)"
my parameters [2] := "Colour"
my parameters [3] := ""
my parameters [4] := ""
my parameters [5] := ""
my arguments [1] := "3.14 (= pi)"
my arguments [2] := "2"
my arguments [3] := "Red" (funny, but needed in Interpreter_getArgumentsFromString)
my arguments [4] := "Green"
my arguments [5] := "Blue"
*/
if (type <= Interpreter_MAXIMUM_TYPE_WITH_VARIABLE_NAME) {
Melder_skipHorizontalSpace (& parameterLocation);
if (Melder_isEndOfLine (*parameterLocation)) {
*parameterLocation = U'\0'; // destroy input in order to limit printing of line
Melder_throw (U"Missing parameter:\n\"", startOfLine, U"\".");
}
char32 *q = my parameters [++ my numberOfParameters];
while (Melder_staysWithinInk (*parameterLocation))
* (q ++) = * (parameterLocation ++);
*q = U'\0';
npar ++;
} else {
my parameters [++ my numberOfParameters] [0] = U'\0';
}
char32 *argumentLocation;
if (type >= Interpreter_MINIMUM_TYPE_FOR_NUMERIC_VECTOR_VARIABLE && type <= Interpreter_MAXIMUM_TYPE_FOR_NUMERIC_VECTOR_VARIABLE) {
char32 *formatLocation = Melder_findEndOfHorizontalSpace (parameterLocation);
if (Melder_isEndOfLine (*formatLocation)) {
*formatLocation = U'\0'; // destroy input in order to limit printing of line
Melder_throw (U"Missing format:\n\"", startOfLine, U"\".");
}
char32 *q = my formats [my numberOfParameters];
if (*formatLocation != U'(') {
*formatLocation = U'\0'; // destroy input in order to limit printing of line
Melder_throw (U"Missing format (should start with \"(\"):\n\"", startOfLine, U"\".");
}
while (*formatLocation != U')') {
if (Melder_isEndOfLine (*formatLocation)) {
*formatLocation = U'\0'; // destroy input in order to limit printing of line
Melder_throw (U"Incomplete format (should end in \")\"):\n\"", startOfLine, U"\".");
}
* (q ++) = * (formatLocation ++);
}
* (q ++) = * (formatLocation ++); // copy the closing parenthesis
*q = U'\0';
argumentLocation = Melder_findEndOfHorizontalSpace (formatLocation);
} else {
argumentLocation = Melder_findEndOfHorizontalSpace (parameterLocation);
}
endOfLine = Melder_findEndOfLine (argumentLocation);
if (Melder_isEndOfText (*endOfLine))
Melder_throw (U"Unfinished form (missing \"endform\").");
*endOfLine = U'\0'; // destroy input temporarily in order to limit copying of argument
my arguments [my numberOfParameters] = Melder_dup_f (argumentLocation);
*endOfLine = U'\n'; // restore input
my types [my numberOfParameters] = type;
}
} else {
npar = my numberOfParameters = 0;
}
return npar;
}
autoUiForm Interpreter_createForm (Interpreter me, GuiWindow parent, conststring32 path,
void (*okCallback) (UiForm, integer, Stackel, conststring32, Interpreter, conststring32, bool, void *), void *okClosure,
bool selectionOnly)
{
autoUiForm form = UiForm_create (parent,
Melder_cat (selectionOnly ? U"Run script (selection only): " : U"Run script: ", my dialogTitle),
okCallback, okClosure, nullptr, nullptr);
UiField radio = nullptr;
if (path)
form -> scriptFilePath = Melder_dup (path);
for (int ipar = 1; ipar <= my numberOfParameters; ipar ++) {
/*
Convert underscores to spaces.
*/
char32 parameter [100], *p = & parameter [0];
str32cpy (parameter, my parameters [ipar]);
while (*p) {
if (*p == U'_')
*p = U' ';
p ++;
}
switch (my types [ipar]) {
case Interpreter_WORD: {
UiForm_addWord (form.get(), nullptr, nullptr, parameter, my arguments [ipar].get());
} break; case Interpreter_SENTENCE: {
UiForm_addSentence (form.get(), nullptr, nullptr, parameter, my arguments [ipar].get());
} break; case Interpreter_TEXT: {
UiForm_addText (form.get(), nullptr, nullptr, parameter, my arguments [ipar].get());
} break; case Interpreter_INFILE: {
UiForm_addInfile (form.get(), nullptr, nullptr, parameter, my arguments [ipar].get());
} break; case Interpreter_OUTFILE: {
UiForm_addOutfile (form.get(), nullptr, nullptr, parameter, my arguments [ipar].get());
} break; case Interpreter_FOLDER: {
UiForm_addFolder (form.get(), nullptr, nullptr, parameter, my arguments [ipar].get());
} break; case Interpreter_REAL: {
UiForm_addReal (form.get(), nullptr, nullptr, parameter, my arguments [ipar].get()); // TODO: an address of a real variable
} break; case Interpreter_POSITIVE: {
UiForm_addPositive (form.get(), nullptr, nullptr, parameter, my arguments [ipar].get());
} break; case Interpreter_INTEGER: {
UiForm_addInteger (form.get(), nullptr, nullptr, parameter, my arguments [ipar].get());
} break; case Interpreter_NATURAL: {
UiForm_addNatural (form.get(), nullptr, nullptr, parameter, my arguments [ipar].get());
} break; case Interpreter_BOOLEAN: {
UiForm_addBoolean (form.get(), nullptr, nullptr, parameter, my arguments [ipar] [0] == U'1' ||
my arguments [ipar] [0] == U'y' || my arguments [ipar] [0] == U'Y' ||
(my arguments [ipar] [0] == U'o' && my arguments [ipar] [1] == U'n'));
} break; case Interpreter_REALVECTOR: {
kUi_realVectorFormat format = kUi_realVectorFormat_getValue (my formats [ipar]);
if (format == kUi_realVectorFormat::UNDEFINED)
Melder_throw (U"Undefined real vector format \"", my formats [ipar], U"\".");
UiForm_addRealVector (form.get(), nullptr, nullptr, parameter, format, my arguments [ipar].get());
} break; case Interpreter_POSITIVEVECTOR: {
kUi_realVectorFormat format = kUi_realVectorFormat_getValue (my formats [ipar]);
if (format == kUi_realVectorFormat::UNDEFINED)
Melder_throw (U"Undefined positive vector format \"", my formats [ipar], U"\".");
UiForm_addPositiveVector (form.get(), nullptr, nullptr, parameter, format, my arguments [ipar].get());
} break; case Interpreter_INTEGERVECTOR: {
kUi_integerVectorFormat format = kUi_integerVectorFormat_getValue (my formats [ipar]);
if (format == kUi_integerVectorFormat::UNDEFINED)
Melder_throw (U"Undefined integer vector format \"", my formats [ipar], U"\".");
UiForm_addIntegerVector (form.get(), nullptr, nullptr, parameter, format, my arguments [ipar].get());
} break; case Interpreter_NATURALVECTOR: {
kUi_integerVectorFormat format = kUi_integerVectorFormat_getValue (my formats [ipar]);
if (format == kUi_integerVectorFormat::UNDEFINED)
Melder_throw (U"Undefined natural vector format \"", my formats [ipar], U"\".");
UiForm_addNaturalVector (form.get(), nullptr, nullptr, parameter, kUi_integerVectorFormat_getValue (my formats [ipar]), my arguments [ipar].get());
} break; case Interpreter_REALMATRIX: {
Melder_throw (U"Cannot handle matrices in forms yet."); // TODO
// UiForm_addRealMatrix (form.get(), nullptr, nullptr, parameter, my arguments [ipar].get());
} break; case Interpreter_CHOICE: {
radio = UiForm_addRadio (form.get(), nullptr, nullptr, nullptr, parameter, (int) Melder_atoi (my arguments [ipar].get()), 1);
} break; case Interpreter_OPTIONMENU: {
radio = UiForm_addOptionMenu (form.get(), nullptr, nullptr, nullptr, parameter, (int) Melder_atoi (my arguments [ipar].get()), 1);
} break; case Interpreter_BUTTON: {
if (radio)
UiRadio_addButton (radio, my arguments [ipar].get());
} break; case Interpreter_OPTION: {
if (radio)
UiOptionMenu_addButton (radio, my arguments [ipar].get());
} break; case Interpreter_COMMENT: {
UiForm_addLabel (form.get(), nullptr, my arguments [ipar].get());
} break; default: {
UiForm_addWord (form.get(), nullptr, nullptr, parameter, my arguments [ipar].get());
}
}
/*
Strip parentheses and colon off parameter name.
*/
if ((p = str32chr (my parameters [ipar], U'(')) != nullptr) {
*p = U'\0';
if (p - my parameters [ipar] > 0 && p [-1] == U'_')
p [-1] = U'\0';
}
p = my parameters [ipar];
if (*p != U'\0' && p [str32len (p) - 1] == U':')
p [str32len (p) - 1] = U'\0';
}
UiForm_finish (form.get());
return form;
}
void Interpreter_getArgumentsFromDialog (Interpreter me, UiForm dialog) {
for (int ipar = 1; ipar <= my numberOfParameters; ipar ++) {
char32 parameter [100], *p;
/*
Strip parentheses and colon off parameter name.
*/
if ((p = str32chr (my parameters [ipar], U'(')) != nullptr) {
*p = U'\0';
if (p - my parameters [ipar] > 0 && p [-1] == U'_')
p [-1] = U'\0';
}
p = my parameters [ipar];
if (*p != U'\0' && p [str32len (p) - 1] == U':')
p [str32len (p) - 1] = U'\0';
/*
Convert underscores to spaces.
*/
str32cpy (parameter, my parameters [ipar]);
p = & parameter [0];
while (*p) {
if (*p == U'_')
*p = U' ';
p ++;
}
switch (my types [ipar]) {
case Interpreter_WORD: {
case Interpreter_SENTENCE:
case Interpreter_TEXT:
const conststring32 value = UiForm_getString (dialog, parameter);
my arguments [ipar] = Melder_dup_f (value);
break;
}
case Interpreter_INFILE: {
case Interpreter_OUTFILE:
case Interpreter_FOLDER:
const conststring32 value = UiForm_getString (dialog, parameter);
structMelderFile file { };
Melder_relativePathToFile (value, & file); // the working directory should have been set to the script file path
my arguments [ipar] = Melder_dup_f (Melder_fileToPath (& file));
break;
}
case Interpreter_REAL:
case Interpreter_POSITIVE: {
const double value = UiForm_getReal_check (dialog, parameter);
my arguments [ipar] = autostring32 (40, true);
Melder_sprint (my arguments [ipar].get(),40+1, value);
break;
}
case Interpreter_INTEGER:
case Interpreter_NATURAL:
case Interpreter_BOOLEAN: {
const integer value = UiForm_getInteger (dialog, parameter);
my arguments [ipar] = autostring32 (40, true);
Melder_sprint (my arguments [ipar].get(),40+1, value);
break;
}
case Interpreter_REALVECTOR:
case Interpreter_POSITIVEVECTOR:
{
const VEC realVectorValue = UiForm_getRealVector (dialog, parameter);
autoMelderString buffer;
for (integer i = 1; i <= realVectorValue.size; i ++) {
MelderString_append (& buffer, realVectorValue [i]);
if (i < realVectorValue.size)
MelderString_appendCharacter (& buffer, U' ');
}
my arguments [ipar] = Melder_dup (buffer.string);
break;
}
case Interpreter_INTEGERVECTOR:
case Interpreter_NATURALVECTOR:
{
const INTVEC integerVectorValue = UiForm_getIntegerVector (dialog, parameter);
autoMelderString buffer;
for (integer i = 1; i <= integerVectorValue.size; i ++) {
MelderString_append (& buffer, integerVectorValue [i]);
if (i < integerVectorValue.size)
MelderString_appendCharacter (& buffer, U' ');
}
my arguments [ipar] = Melder_dup (buffer.string);
break;
}
case Interpreter_REALMATRIX: {
Melder_throw (U"Cannot handle matrices in forms yet");
break;
}
case Interpreter_CHOICE:
case Interpreter_OPTIONMENU: {
const integer integerValue = UiForm_getInteger (dialog, parameter);
const conststring32 stringValue = UiForm_getString (dialog, parameter);
my arguments [ipar] = autostring32 (40, true);
Melder_sprint (my arguments [ipar].get(),40+1, integerValue);
Melder_sprint (my choiceArguments [ipar],100, stringValue);
break;
}
case Interpreter_BUTTON:
case Interpreter_OPTION:
case Interpreter_COMMENT:
break;
default:
Melder_fatal (U"Unhandled parameter type ", my types [ipar]);
}
}
}
static void tidyUpParameterNames (Interpreter me, integer size) {
for (integer ipar = 1; ipar <= size; ipar ++) {
mutablestring32 p = my parameters [ipar];
/*
Ignore buttons and comments again (after `size` was
made smaller than my numberOfParameters).
*/
if (! *p)
continue;
/*
Strip parentheses and colon off parameter name.
*/
if ((p = str32chr (p, U'(')) != nullptr) {
*p = U'\0';
if (p - my parameters [ipar] > 0 && p [-1] == U'_')
p [-1] = U'\0';
}
p = my parameters [ipar];
if (*p != U'\0' && p [str32len (p) - 1] == U':')
p [str32len (p) - 1] = U'\0';
}
}
static void convertBooleansAndChoicesToNumbersAndRelativeToAbsolutePaths (Interpreter me, integer size) {
for (integer ipar = 1; ipar <= size; ipar ++) {
if (my types [ipar] == Interpreter_INFILE || my types [ipar] == Interpreter_OUTFILE || my types [ipar] == Interpreter_FOLDER) {
structMelderFile file { };
Melder_relativePathToFile (my arguments [ipar].get(), & file);
my arguments [ipar] = Melder_dup_f (Melder_fileToPath (& file));
} else if (my types [ipar] == Interpreter_BOOLEAN) {
mutablestring32 arg = & my arguments [ipar] [0];
if (str32equ (arg, U"1") || str32equ (arg, U"yes") || str32equ (arg, U"on") ||
str32equ (arg, U"Yes") || str32equ (arg, U"On") || str32equ (arg, U"YES") || str32equ (arg, U"ON"))
{
str32cpy (arg, U"1");
} else if (str32equ (arg, U"0") || str32equ (arg, U"no") || str32equ (arg, U"off") ||
str32equ (arg, U"No") || str32equ (arg, U"Off") || str32equ (arg, U"NO") || str32equ (arg, U"OFF"))
{
str32cpy (arg, U"0");
} else {
Melder_throw (U"Unknown value \"", arg, U"\" for boolean \"", my parameters [ipar], U"\".");
}
} else if (my types [ipar] == Interpreter_CHOICE) {
integer jpar;
mutablestring32 arg = & my arguments [ipar] [0];
for (jpar = ipar + 1; jpar <= my numberOfParameters; jpar ++) {
if (my types [jpar] != Interpreter_BUTTON && my types [jpar] != Interpreter_OPTION)
Melder_throw (U"Unknown value \"", arg, U"\" for choice \"", my parameters [ipar], U"\".");
if (str32equ (my arguments [jpar].get(), arg)) { // the button labels are in the arguments; see Interpreter_readParameters
str32cpy (arg, Melder_integer (jpar - ipar));
str32cpy (my choiceArguments [ipar], my arguments [jpar].get());
break;
}
}
if (jpar > my numberOfParameters)
Melder_throw (U"Unknown value \"", arg, U"\" for choice \"", my parameters [ipar], U"\".");
} else if (my types [ipar] == Interpreter_OPTIONMENU) {
integer jpar;
mutablestring32 arg = & my arguments [ipar] [0];
for (jpar = ipar + 1; jpar <= my numberOfParameters; jpar ++) {
if (my types [jpar] != Interpreter_OPTION && my types [jpar] != Interpreter_BUTTON)
Melder_throw (U"Unknown value \"", arg, U"\" for option menu \"", my parameters [ipar], U"\".");
if (str32equ (my arguments [jpar].get(), arg)) {
str32cpy (arg, Melder_integer (jpar - ipar));
str32cpy (my choiceArguments [ipar], my arguments [jpar].get());
break;
}
}
if (jpar > my numberOfParameters)
Melder_throw (U"Unknown value \"", arg, U"\" for option menu \"", my parameters [ipar], U"\".");
}
}
}
void Interpreter_getArgumentsFromString (Interpreter me, conststring32 arguments) {
int size = my numberOfParameters;
integer length = str32len (arguments);
while (size >= 1 && my parameters [size] [0] == U'\0')
size --; /* Ignore fields without a variable name (button, comment). */
tidyUpParameterNames (me, size);
for (int ipar = 1; ipar < size; ipar ++) {
int ichar = 0;
/*
Ignore buttons and comments again. The buttons will keep their labels as "arguments".
*/
if (my parameters [ipar] [0] == U'\0')
continue;
/*
Erase the current values, probably the default values,
and replace with the actual arguments.
*/
my arguments [ipar] = autostring32 (length);
/*
Skip spaces until next argument.
*/
while (Melder_isHorizontalSpace (*arguments))
arguments ++;
/*
The argument is everything up to the next space, or, if it starts with a double quote,
everything between this quote and the matching double quote;
in this case, the argument can represent a double quote by a sequence of two double quotes.
Example: the string
"I said ""hello"""
will be passed to the dialog as a single argument containing the text
I said "hello"
*/
if (*arguments == U'\"') {
arguments ++; // do not include leading double quote
for (;;) {
if (*arguments == U'\0')
Melder_throw (U"Missing matching quote.");
if (*arguments == U'\"' && * ++ arguments != U'\"')
break; // remember second quote
my arguments [ipar] [ichar ++] = *arguments ++;
}
} else {
while (Melder_staysWithinInk (*arguments))
my arguments [ipar] [ichar ++] = *arguments ++;
}
my arguments [ipar] [ichar] = U'\0'; // trailing null byte
}
/*
The last item is handled separately, because it consists of the rest of the line.
Leading spaces are skipped, but trailing spaces are included.
*/
if (size > 0) {
while (Melder_isHorizontalSpace (*arguments))
arguments ++;
my arguments [size] = Melder_dup_f (arguments);
}
convertBooleansAndChoicesToNumbersAndRelativeToAbsolutePaths (me, size);
}
void Interpreter_getArgumentsFromArgs (Interpreter me, integer narg, Stackel args) {
trace (narg, U" arguments");
integer size = my numberOfParameters;
while (size >= 1 && my parameters [size] [0] == U'\0')
size --; // ignore trailing fields without a variable name (button, comment)
tidyUpParameterNames (me, size);
integer iarg = 0;
for (integer ipar = 1; ipar <= size; ipar ++) {
/*
Ignore buttons and comments again. The buttons will keep their labels as "arguments".
*/
if (my parameters [ipar] [0] == U'\0')
continue;
/*
Erase the current values, probably the default values...
*/
my arguments [ipar]. reset(); //
if (iarg == narg)
Melder_throw (U"Found ", narg, U" arguments but expected more.");
Stackel arg = & args [++ iarg];
/*
... and replace with the actual arguments.
*/
my arguments [ipar] =
arg -> which == Stackel_NUMBER ? Melder_dup (Melder_double (arg -> number)) :
arg -> which == Stackel_STRING ? Melder_dup (arg -> getString()) :
arg -> which == Stackel_NUMERIC_VECTOR ? Melder_dup (Melder_VEC (arg -> numericVector)) :
autostring32();
Melder_assert (my arguments [ipar]);
}
if (iarg < narg)
Melder_throw (U"Found ", narg, U" arguments but expected only ", iarg, U".");
convertBooleansAndChoicesToNumbersAndRelativeToAbsolutePaths (me, size);
}
void Interpreter_getArgumentsFromCommandLine (Interpreter me, integer argc, char **argv) {
trace (argc, U" arguments");
integer size = my numberOfParameters;
while (size >= 1 && my parameters [size] [0] == U'\0')
size --; // ignore trailing fields without a variable name (button, comment)
tidyUpParameterNames (me, size);
integer iarg = 0;
for (integer ipar = 1; ipar <= size; ipar ++) {
/*
Ignore buttons and comments again. The buttons will keep their labels as "arguments".
*/
if (my parameters [ipar] [0] == U'\0')
continue;
/*
Erase the current values, probably the default values,
and replace with the actual arguments.
*/
if (iarg == argc)
Melder_throw (U"Found ", argc, U" arguments but expected more.");
my arguments [ipar] = Melder_8to32 (argv [iarg ++]);
Melder_assert (my arguments [ipar]);
}
if (iarg < argc)
Melder_throw (U"Found ", argc, U" arguments but expected only ", iarg, U".");
convertBooleansAndChoicesToNumbersAndRelativeToAbsolutePaths (me, size);
}
static void Interpreter_addNumericVariable (Interpreter me, conststring32 key, double value) {
autoInterpreterVariable variable = InterpreterVariable_create (key);
variable -> numericValue = value;
my variablesMap [key] = variable.move();
variable.releaseToAmbiguousOwner();
}
static void Interpreter_addStringVariable (Interpreter me, conststring32 key, conststring32 value) {
autoInterpreterVariable variable = InterpreterVariable_create (key);
variable -> stringValue = Melder_dup (value);
my variablesMap [key] = variable.move();
variable.releaseToAmbiguousOwner();
}
static void Interpreter_addNumericVectorVariable (Interpreter me, conststring32 key, conststring32 value) {
autoInterpreterVariable variable = InterpreterVariable_create (key);
variable -> numericVectorValue = splitByWhitespace_VEC (value);
my variablesMap [key] = variable.move();
variable.releaseToAmbiguousOwner();
}
InterpreterVariable Interpreter_hasVariable (Interpreter me, conststring32 key) {
Melder_assert (key);
auto it = my variablesMap. find (key [0] == U'.' ? Melder_cat (my procedureNames [my callDepth], key) : key);
if (it != my variablesMap.end())
return it -> second.get();
else
return nullptr;
}
InterpreterVariable Interpreter_lookUpVariable (Interpreter me, conststring32 key) {
Melder_assert (key);
conststring32 variableNameIncludingProcedureName =
key [0] == U'.' ? Melder_cat (my procedureNames [my callDepth], key) : key;
auto it = my variablesMap. find (variableNameIncludingProcedureName);
if (it != my variablesMap.end())
return it -> second.get();
/*
The variable doesn't yet exist: create a new one.
*/
autoInterpreterVariable variable = InterpreterVariable_create (variableNameIncludingProcedureName);
InterpreterVariable variable_ref = variable.get();
my variablesMap [variableNameIncludingProcedureName] = variable.move();
return variable_ref;
}
static integer lookupLabel (Interpreter me, conststring32 labelName) {
for (integer ilabel = 1; ilabel <= my numberOfLabels; ilabel ++)
if (str32equ (labelName, my labelNames [ilabel]))
return ilabel;
Melder_throw (U"Unknown label \"", labelName, U"\".");
}
static bool isCommand (conststring32 string) {
const char32 *p = & string [0];
/*
Things that start with "nowarn", "noprogress", or "nocheck" are commands.
*/
if (p [0] == U'n' && p [1] == U'o' &&
(str32nequ (p + 2, U"warn ", 5) || str32nequ (p + 2, U"progress ", 9) || str32nequ (p + 2, U"check ", 6)))
return true;
if (str32nequ (p, U"demo ", 5))
return true;
/*
Otherwise, things that start with nonupper case are formulas.
*/
if (! Melder_isUpperCaseLetter (*p))
return false;
/*
The remaining possibility is things that start with upper case.
If they contain an underscore, they are object names, hence we must have a formula.
Otherwise, we have a command.
*/
while (Melder_isAlphanumeric (*p))
p ++;
return *p != U'_';
}
static void parameterToVariable (Interpreter me, int type, conststring32 in_parameter, int ipar) {
char32 parameter [200];
Melder_assert (type != 0);
str32cpy (parameter, in_parameter);
if (type >= Interpreter_MINIMUM_TYPE_FOR_NUMERIC_VARIABLE && type <= Interpreter_MAXIMUM_TYPE_FOR_NUMERIC_VARIABLE) {
Interpreter_addNumericVariable (me, parameter, Melder_atof (my arguments [ipar].get()));
} else if (type == Interpreter_CHOICE || type == Interpreter_OPTIONMENU) {
Interpreter_addNumericVariable (me, parameter, Melder_atof (my arguments [ipar].get()));
str32cat (parameter, U"$");
Interpreter_addStringVariable (me, parameter, my choiceArguments [ipar]);
} else if (type == Interpreter_BUTTON || type == Interpreter_OPTION || type == Interpreter_COMMENT) {
; // do not add a variable
} else if (type >= Interpreter_MINIMUM_TYPE_FOR_NUMERIC_VECTOR_VARIABLE && type <= Interpreter_MAXIMUM_TYPE_FOR_NUMERIC_VECTOR_VARIABLE) {
str32cat (parameter, U"#");
Interpreter_addNumericVectorVariable (me, parameter, my arguments [ipar].get());
} else {
str32cat (parameter, U"$");
Interpreter_addStringVariable (me, parameter, my arguments [ipar].get());
}
}
inline static void NumericVectorVariable_move (InterpreterVariable variable, VEC movedVector, bool rightHandSideOwned) {
if (rightHandSideOwned) {
/*
Statement like: a# = b# + c#
*/
variable -> numericVectorValue. adoptFromAmbiguousOwner (movedVector);
} else if (variable -> numericVectorValue.size == movedVector.size) {
if (variable -> numericVectorValue.cells == movedVector.cells) {
/*
Statement like: a# = a#
*/
(void) 0; // assigning a variable to itself: do nothing
} else {
/*
Statement like: a# = b# // with matching sizes
*/
variable -> numericVectorValue.all() <<= movedVector;
}
} else {
/*
Statement like: a# = b# // with non-matching sizes
*/
variable -> numericVectorValue = copy_VEC (movedVector);
}
}
inline static void StringArrayVariable_move (InterpreterVariable variable, STRVEC movedVector, bool rightHandSideOwned) {
if (rightHandSideOwned) {
/*
Statement like: a$# = b$# + c$#
*/
variable -> stringArrayValue. adoptFromAmbiguousOwner (movedVector);
} else if (variable -> stringArrayValue.size == movedVector.size) {
if ((char32 **) variable -> stringArrayValue.elements == movedVector.elements) {
/*
Statement like: a$# = a$#
*/
(void) 0; // assigning a variable to itself: do nothing
} else {
/*
Statement like: a$# = b$# // with matching sizes
*/
variable -> stringArrayValue.all() <<= movedVector;
}
} else {
/*
Statement like: a$# = b$# // with non-matching sizes
*/
variable -> stringArrayValue = copy_STRVEC (movedVector);
}
}
inline static void NumericMatrixVariable_move (InterpreterVariable variable, MAT movedMatrix, bool rightHandSideOwned) {
if (rightHandSideOwned) {
/*
Statement like: a## = b## + c##
*/
variable -> numericMatrixValue. adoptFromAmbiguousOwner (movedMatrix);
} else if (variable -> numericMatrixValue.nrow == movedMatrix.nrow && variable -> numericMatrixValue.ncol == movedMatrix.ncol) {
if (variable -> numericMatrixValue.cells == movedMatrix.cells) {
/*
Statement like: a## = a##
*/
(void) 0; // assigning a variable to itself: do nothing
} else {
/*
Statement like: a## = b## // with matching sizes
*/
variable -> numericMatrixValue.all() <<= movedMatrix;
}
} else {
/*
Statement like: a## = b## // with non-matching sizes
*/
variable -> numericMatrixValue = copy_MAT (movedMatrix);
}
}
inline static void NumericVectorVariable_add (InterpreterVariable variable, double scalar) {
variable -> numericVectorValue.all() += scalar;
}
inline static void NumericVectorVariable_add (InterpreterVariable variable, constVEC vector) {
VEC const& variableVector = variable -> numericVectorValue.get();
Melder_require (vector.size == variableVector.size,
U"You cannot add a vector with size ", vector.size,
U" to a vector with a different size (", variableVector.size, U")."
);
variableVector += vector;
}
inline static void NumericVectorVariable_subtract (InterpreterVariable variable, double scalar) {
variable -> numericVectorValue.all() -= scalar;
}
inline static void NumericVectorVariable_subtract (InterpreterVariable variable, constVEC vector) {
VEC const& variableVector = variable -> numericVectorValue.get();
Melder_require (vector.size == variable -> numericVectorValue.size,
U"You cannot subtract a vector with size ", vector.size,
U" from a vector with a different size (", variableVector.size, U")."
);
variableVector -= vector;
}
inline static void NumericVectorVariable_multiply (InterpreterVariable variable, double scalar) {
variable -> numericVectorValue.all() *= scalar;
}
inline static void NumericVectorVariable_multiply (InterpreterVariable variable, constVEC vector) {
VEC const& variableVector = variable -> numericVectorValue.get();
Melder_require (vector.size != variableVector.size,
U"You cannot multiply a vector with size ", variableVector.size,
U" with a vector with a different size (", vector.size, U")."
);
variableVector *= vector;
}
inline static void NumericVectorVariable_divide (InterpreterVariable variable, double scalar) {
variable -> numericVectorValue.all() /= scalar;
}
inline static void NumericVectorVariable_divide (InterpreterVariable variable, constVEC vector) {
VEC const& variableVector = variable -> numericVectorValue.get();
Melder_require (vector.size != variableVector.size,
U"You cannot divide a vector with size ", variableVector.size,
U" by a vector with a different size (", vector.size, U")."
);
variableVector /= vector;
}
inline static void NumericMatrixVariable_add (InterpreterVariable variable, double scalar) {
MAT variableMatrix = variable -> numericMatrixValue.get();
for (integer irow = 1; irow <= variableMatrix.nrow; irow ++)
for (integer icol = 1; icol <= variableMatrix.ncol; icol ++)
variableMatrix [irow] [icol] += scalar;
}
inline static void NumericMatrixVariable_add (InterpreterVariable variable, constMAT matrix) {
MAT variableMatrix = variable -> numericMatrixValue.get();
if (matrix.nrow != variableMatrix.nrow || matrix.ncol != variableMatrix.ncol)
Melder_throw (U"You cannot add a matrix with size ", matrix.nrow, U"x", matrix.ncol,
U" to a matrix with a different size (", variableMatrix.nrow, U"x", variableMatrix.ncol, U").");
for (integer irow = 1; irow <= variableMatrix.nrow; irow ++)
for (integer icol = 1; icol <= variableMatrix.ncol; icol ++)
variableMatrix [irow] [icol] += matrix [irow] [icol];
}
inline static void NumericMatrixVariable_subtract (InterpreterVariable variable, double scalar) {
MAT variableMatrix = variable -> numericMatrixValue.get();
for (integer irow = 1; irow <= variableMatrix.nrow; irow ++)
for (integer icol = 1; icol <= variableMatrix.ncol; icol ++)