Debian Codegraph @

sys/Formula.cpp

raw
1 /* Formula.cpp
2 *
3 * Copyright (C) 1992-2026 Paul Boersma
4 *
5 * This code is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or (at
8 * your option) any later version.
9 *
10 * This code is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this work. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #if defined (UNIX)
20 #include <sys/stat.h>
21 #endif
22 #include "../dwsys/NUM2.h"
23 #include "Formula.h"
24 #include "Interpreter.h"
25 #include "Ui.h"
26 #include "praatP.h"
27 #include "praat_script.h"
28 #include "../kar/UnicodeData.h"
29 #include "../kar/longchar.h"
30 #include "UiPause.h"
31 #include "GuiTrust.h"
32 #include "Script.h"
33 #include "Notebook.h"
34 #include "DemoEditor.h"
35
36 static Interpreter theInterpreter;
37 static autoInterpreterStack theLocalInterpreterStack;
38 static Daata theSource;
39 static conststring32 theExpression;
40 static int theLevel = 1;
41 #define MAXIMUM_NUMBER_OF_LEVELS 20
42 static int theExpressionType [1 + MAXIMUM_NUMBER_OF_LEVELS];
43 static bool theOptimize;
44
45 typedef struct structFormulaInstruction {
46 integer symbol;
47 integer position;
48 union {
49 double number;
50 integer label;
51 char32 *string;
52 Daata object;
53 InterpreterVariable variable;
54 } content;
55 } *FormulaInstruction;
56
57 static FormulaInstruction lexan, parse;
58 static integer ilabel, ilexan, iparse, numberOfInstructions, numberOfStringConstants;
59
60 enum { NO_SYMBOL_,
61
62 #define DECLARE_WITH_TENSORS(symbol) \
63 symbol, symbol##VEC_, symbol##MAT_,
64
65 /* First, all symbols after which "-" is unary. */
66 /* The list ends with "MINUS_" itself. */
67
68 /* Opening symbols. */
69 IF_, THEN_, ELSE_, OPENING_PARENTHESIS_, OPENING_BRACKET_, OPENING_BRACE_, COMMA_, COLON_, FROM_, TO_,
70 /* Operators with boolean results. */
71 OR_, AND_, NOT_, EQ_, NE_, LE_, LT_, GE_, GT_,
72 /* Operators with results. */
73 ADD_, SUB_, MUL_, RDIV_, IDIV_, MOD_, POWER_, CALL_, MINUS_,
74
75 /* Then, the symbols after which "-" is binary. */
76
77 /* Closing symbols. */
78 ENDIF_, FI_, CLOSING_PARENTHESIS_, CLOSING_BRACKET_, CLOSING_BRACE_,
79 /* Things with a value. */
80 #define LOW_VALUE NUMBER_
81 NUMBER_, NUMBER_PI_, NUMBER_E_, NUMBER_UNDEFINED_,
82 /* Attributes of objects. */
83 #define LOW_ATTRIBUTE XMIN_
84 XMIN_, XMAX_, YMIN_, YMAX_, NX_, NY_, DX_, DY_,
85 ROW_, COL_, NROW_, NCOL_, ROW_STR_, COL_STR_, Y_, X_,
86 #define HIGH_ATTRIBUTE X_
87 #define HIGH_VALUE HIGH_ATTRIBUTE
88
89 SELF_, SELF_STR_, OBJECT_, OBJECT_STR_, MATRIX_, MATRIX_STR_,
90 STOPWATCH_,
91
92 /* The following symbols can be followed by "-" only if they are a variable. */
93
94 /* Functions of 1 variable; if you add, update the #defines. */
95 #define LOW_FUNCTION_1 ABS_
96 DECLARE_WITH_TENSORS (ABS_)
97 DECLARE_WITH_TENSORS (ROUND_) DECLARE_WITH_TENSORS (FLOOR_) DECLARE_WITH_TENSORS (CEILING_)
98 DECLARE_WITH_TENSORS (RECTIFY_)
99 DECLARE_WITH_TENSORS (SQRT_)
100 DECLARE_WITH_TENSORS (SIN_) DECLARE_WITH_TENSORS (COS_) DECLARE_WITH_TENSORS (TAN_)
101 DECLARE_WITH_TENSORS (ARCSIN_) DECLARE_WITH_TENSORS (ARCCOS_) DECLARE_WITH_TENSORS (ARCTAN_)
102 SINC_, SINCPI_,
103 DECLARE_WITH_TENSORS (EXP_)
104 DECLARE_WITH_TENSORS (SINH_) DECLARE_WITH_TENSORS (COSH_) DECLARE_WITH_TENSORS (TANH_)
105 DECLARE_WITH_TENSORS (ARCSINH_) DECLARE_WITH_TENSORS (ARCCOSH_) DECLARE_WITH_TENSORS (ARCTANH_)
106 DECLARE_WITH_TENSORS (SIGMOID_) DECLARE_WITH_TENSORS (INV_SIGMOID_)
107 SOFTMAX_VEC_, SOFTMAX_PER_ROW_MAT_,
108 ERF_, ERFC_, GAUSS_P_, GAUSS_Q_, INV_GAUSS_Q_,
109 RANDOM_BERNOULLI_, RANDOM_BERNOULLI_VEC_,
110 RANDOM_POISSON_, TRANSPOSE_MAT_,
111 ROW_SUMS_VEC_, COLUMN_SUMS_VEC_,
112 DECLARE_WITH_TENSORS (LOG2_) DECLARE_WITH_TENSORS (LN_) DECLARE_WITH_TENSORS (LOG10_)
113 LN_GAMMA_,
114 HERTZ_TO_BARK_, BARK_TO_HERTZ_, PHON_TO_DIFFERENCE_LIMENS_, DIFFERENCE_LIMENS_TO_PHON_,
115 HERTZ_TO_MEL_, MEL_TO_HERTZ_, HERTZ_TO_SEMITONES_, SEMITONES_TO_HERTZ_,
116 ERB_, HERTZ_TO_ERB_, ERB_TO_HERTZ_,
117 SUM_, MEAN_, STDEV_, CENTER_, RANDOM_IMAX_,
118 EVALUATE_, EVALUATE_NOCHECK_, EVALUATE_STR_, EVALUATE_NOCHECK_STR_,
119 STRING_STR_, HORIZONTAL_STR_, VERTICAL_STR_, NUMBERS_VEC_, SLEEP_, UNICODE_, UNICODE_STR_,
120 #define HIGH_FUNCTION_1 UNICODE_STR_
121
122 /* Functions of 2 variables; if you add, update the #defines. */
123 #define LOW_FUNCTION_2 ARCTAN2_
124 ARCTAN2_, RANDOM_UNIFORM_, RANDOM_INTEGER_, RANDOM_GAUSS_, RANDOM_BINOMIAL_,
125 RANDOM_GAMMA_,
126 CHI_SQUARE_P_, CHI_SQUARE_Q_, INCOMPLETE_GAMMAP_,
127 INV_CHI_SQUARE_Q_, STUDENT_P_, STUDENT_Q_, INV_STUDENT_Q_,
128 BETA_, BETA2_, BESSEL_I_, BESSEL_K_, LN_BETA_,
129 SOUND_PRESSURE_TO_PHON_, OBJECTS_ARE_IDENTICAL_,
130 ROW_VEC_, COL_VEC_,
131 INNER_, CORRELATION_, OUTER_MAT_, MUL_VEC_, MUL_MAT_, MUL_FAST_MAT_, MUL_METAL_MAT_,
132 MUL_TN_MAT_, MUL_NT_MAT_, MUL_TT_MAT_, REPEAT_VEC_,
133 ROW_INNERS_VEC_, SOLVE_VEC_, SOLVE_MAT_,
134 #define HIGH_FUNCTION_2 SOLVE_MAT_
135
136 /* Functions of 3 variables; if you add, update the #defines. */
137 #define LOW_FUNCTION_3 FISHER_P_
138 FISHER_P_, FISHER_Q_, INV_FISHER_Q_,
139 BINOMIAL_P_, BINOMIAL_Q_, INCOMPLETE_BETA_, INV_BINOMIAL_P_, INV_BINOMIAL_Q_,
140 #define HIGH_FUNCTION_3 INV_BINOMIAL_Q_
141
142 /* Functions of 4 variables; if you add, update the #defines. */
143 #define LOW_FUNCTION_4 SOLVE_WEAKLYCONSTRAINED_VEC_
144 SOLVE_WEAKLYCONSTRAINED_VEC_,
145 #define HIGH_FUNCTION_4 SOLVE_WEAKLYCONSTRAINED_VEC_
146
147 /* Functions of a variable number of variables; if you add, update the #defines. */
148 #define LOW_FUNCTION_N DO_
149 DO_, DOSTR_,
150 WRITE_INFO_, WRITE_INFO_LINE_, APPEND_INFO_, APPEND_INFO_LINE_,
151 WRITE_FILE_, WRITE_FILE_LINE_, APPEND_FILE_, APPEND_FILE_LINE_,
152 PAUSE_SCRIPT_, EXIT_SCRIPT_, RUN_SCRIPT_, RUN_SCRIPT_WITH_FORM_, RUN_NOTEBOOK_,
153 RUN_SYSTEM_, RUN_SYSTEM_STR_, RUN_SYSTEM_NOCHECK_, RUN_SUBPROCESS_, RUN_SUBPROCESS_STR_,
154 MIN_, MIN_E_, MIN_IGNORE_UNDEFINED_,
155 MAX_, MAX_E_, MAX_IGNORE_UNDEFINED_,
156 IMIN_, IMIN_E_, IMIN_IGNORE_UNDEFINED_,
157 IMAX_, IMAX_E_, IMAX_IGNORE_UNDEFINED_,
158 QUANTILE_,
159 NORM_,
160 LEFT_STR_, RIGHT_STR_, MID_STR_,
161 PAD_LEFT_STR_, PAD_RIGHT_STR_, TRUNCATE_LEFT_STR_, TRUNCATE_RIGHT_STR_, PAD_OR_TRUNCATE_LEFT_STR_, PAD_OR_TRUNCATE_RIGHT_STR_,
162 SELECTED_, SELECTED_STR_, NUMBER_OF_SELECTED_, SELECTED_VEC_, SELECTED_STRVEC_,
163 SELECT_OBJECT_, PLUS_OBJECT_, MINUS_OBJECT_, REMOVE_OBJECT_,
164 ASK_FOR_TRUST_, BEGIN_PAUSE_,
165 REAL_, POSITIVE_, INTEGER_, NATURAL_,
166 WORD_, SENTENCE_, TEXT_, BOOLEAN_,
167 CHOICE_, OPTIONMENU_, OPTION_MENU_, OPTION_,
168 INFILE_, OUTFILE_, FOLDER_,
169 REALVECTOR_, POSITIVEVECTOR_, INTEGERVECTOR_, NATURALVECTOR_,
170 HEADING_, COMMENT_, END_PAUSE_,
171 LOWER_CASE_APP_NAME_STR_, UPPER_CASE_APP_NAME_STR_,
172 CLOCK_,
173 APP_VERSION_, APP_VERSION_STR_, APP_YEAR_, APP_MONTH_, APP_MONTH_STR_, APP_DAY_,
174 CHOOSE_READ_FILE_STR_, CHOOSE_WRITE_FILE_STR_, CHOOSE_FOLDER_STR_, CHOOSE_DIRECTORY_STR_,
175 DEMO_WINDOW_TITLE_, DEMO_SHOW_, DEMO_WAIT_FOR_INPUT_, DEMO_PEEK_INPUT_, DEMO_INPUT_, DEMO_CLICKED_IN_,
176 DEMO_CLICKED_, DEMO_X_, DEMO_Y_, DEMO_KEY_PRESSED_, DEMO_KEY_,
177 DEMO_SHIFT_KEY_PRESSED_, DEMO_COMMAND_KEY_PRESSED_, DEMO_OPTION_KEY_PRESSED_,
178 ZERO_VEC_, ZERO_MAT_,
179 LINEAR_VEC_, LINEAR_MAT_, TO_VEC_, FROM_TO_VEC_, FROM_TO_BY_VEC_, FROM_TO_COUNT_VEC_, BETWEEN_BY_VEC_, BETWEEN_COUNT_VEC_,
180 SORT_VEC_, SORT_REMOVE_UNDEFINED_VEC_, SORT_STRVEC_, SORT_NUMBER_AWARE_STRVEC_, SHUFFLE_VEC_, SHUFFLE_STRVEC_,
181 RANDOM_UNIFORM_VEC_, RANDOM_UNIFORM_MAT_,
182 RANDOM_INTEGER_VEC_, RANDOM_INTEGER_MAT_,
183 RANDOM_GAUSS_VEC_, RANDOM_GAUSS_MAT_,
184 RANDOM_GAMMA_VEC_, RANDOM_GAMMA_MAT_,
185 SOLVE_SPARSE_VEC_, SOLVE_NONNEGATIVE_VEC_,
186 PEAKS_MAT_,
187 SIZE_, NUMBER_OF_ROWS_, NUMBER_OF_COLUMNS_, COMBINE_VEC_, BLAKE3_VEC_, PART_VEC_, PART_MAT_, EDITOR_,
188 RANDOM__INITIALIZE_WITH_SEED_UNSAFELY_BUT_PREDICTABLY_, RANDOM__INITIALIZE_SAFELY_AND_UNPREDICTABLY_,
189 HASH_, HEX_STR_, UNHEX_STR_,
190 EMPTY_STRVEC_, READ_LINES_FROM_FILE_STRVEC_,
191 FILE_NAMES_STRVEC_, FOLDER_NAMES_STRVEC_, FILE_NAMES_CASE_INSENSITIVE_STRVEC_, FOLDER_NAMES_CASE_INSENSITIVE_STRVEC_,
192 SPLIT_BY_WHITESPACE_STRVEC_, SPLIT_BY_STRVEC_,
193 LOWER_CASE_STR_, LOWER_CAMEL_CASE_STR_, LOWER_SNAKE_CASE_STR_,
194 UPPER_CASE_STR_, UPPER_CAMEL_CASE_STR_, UPPER_SNAKE_CASE_STR_,
195 #define HIGH_FUNCTION_N UPPER_SNAKE_CASE_STR_
196
197 /* String functions. */
198 #define LOW_STRING_FUNCTION LOW_FUNCTION_STR1
199 #define LOW_FUNCTION_STR1 LENGTH_
200 LENGTH_, STRING_TO_NUMBER_, FILE_READABLE_, FOLDER_EXISTS_, TRY_TO_WRITE_FILE_, TRY_TO_APPEND_FILE_, DELETE_FILE_,
201 CREATE_FOLDER_, CREATE_DIRECTORY_, SET_WORKING_DIRECTORY_, VARIABLE_EXISTS_,
202 READ_FILE_, READ_FILE_STR_, READ_FILE_VEC_, READ_FILE_MAT_,
203 UNICODE_TO_BACKSLASH_TRIGRAPHS_STR_, BACKSLASH_TRIGRAPHS_TO_UNICODE_STR_, ENVIRONMENT_STR_,
204 BIG_INTEGER_STR_, HALF_STR_, GRAPHICAL_HALF_STR_, SINGLE_STR_, GRAPHICAL_SINGLE_STR_, DOUBLE_STR_, GRAPHICAL_DOUBLE_STR_,
205 NATURAL_LOGARITHM_STR_, GRAPHICAL_NATURAL_LOGARITHM_STR_,
206 #define HIGH_FUNCTION_STR1 GRAPHICAL_NATURAL_LOGARITHM_STR_
207 #define LOW_FUNCTION_STR0 DATE_STR_
208 DATE_STR_, DATE_UTC_STR_, DATE_ISO_STR_, DATE_UTC_ISO_STR_, DATE_VEC_, DATE_UTC_VEC_, INFO_STR_, // TODO: two of those aren't really string functions
209 #define HIGH_FUNCTION_STR0 INFO_STR_
210 #define LOW_FUNCTION_STR2 INDEX_
211 INDEX_, INDEX_CASE_INSENSITIVE_, RINDEX_, RINDEX_CASE_INSENSITIVE_,
212 STARTS_WITH_, STARTS_WITH_CASE_INSENSITIVE_, ENDS_WITH_, ENDS_WITH_CASE_INSENSITIVE_,
213 INDEX_REGEX_, RINDEX_REGEX_, EXTRACT_NUMBER_,
214 MOVE_AND_OR_RENAME_FILE_,
215 FIXED_STR_, PERCENT_STR_, GRAPHICAL_PERCENT_STR_, HEXADECIMAL_STR_,
216 #define HIGH_FUNCTION_STR2 HEXADECIMAL_STR_
217 EXTRACT_WORD_STR_, EXTRACT_LINE_STR_,
218 REPLACE_STR_, REPLACE_REGEX_STR_,
219 #define HIGH_STRING_FUNCTION REPLACE_REGEX_STR_
220
221 /* Range functions. */
222 #define LOW_RANGE_FUNCTION SUM_OVER_
223 SUM_OVER_,
224 #define HIGH_RANGE_FUNCTION SUM_OVER_
225
226 #define LOW_FUNCTION LOW_FUNCTION_1
227 #define HIGH_FUNCTION HIGH_RANGE_FUNCTION
228
229 /* Membership operator. */
230 PERIOD_,
231 #define highestInputSymbol PERIOD_
232
233 /* Symbols introduced by the parser. */
234
235 TRUE_, FALSE_,
236 GOTO_, IFTRUE_, IFFALSE_, INCREMENT_GREATER_GOTO_,
237 LABEL_,
238 DECREMENT_AND_ASSIGN_, ADD_3DOWN_, POP_2_,
239 VEC_CELL_, MAT_CELL_, STRVEC_CELL_, VARIABLE_REFERENCE_,
240 TENSOR_LITERAL_, TENSOR_LITERAL_CELL_,
241 SELF0_, SELFSTR0_, TO_OBJECT_,
242 OBJECT_XMIN_, OBJECT_XMAX_, OBJECT_YMIN_, OBJECT_YMAX_, OBJECT_NX_, OBJECT_NY_,
243 OBJECT_DX_, OBJECT_DY_, OBJECT_NROW_, OBJECT_NCOL_, OBJECT_ROW_STR_, OBJECT_COL_STR_,
244 OBJECTCELL0_, OBJECTCELL0_STR_, OBJECTCELL1_, OBJECTCELL1_STR_, OBJECTCELL2_, OBJECTCELL2_STR_,
245 OBJECTLOCATION0_, OBJECTLOCATION0_STR_, OBJECTLOCATION1_, OBJECTLOCATION1_STR_, OBJECTLOCATION2_, OBJECTLOCATION2_STR_,
246 SELFMATRIX1_, SELFMATRIX1_STR_, SELFMATRIX2_, SELFMATRIX2_STR_,
247 SELFFUNCTION1_, SELFFUNCTION1_STR_, SELFFUNCTION2_, SELFFUNCTION2_STR_,
248 MATRIX0_, MATRIX0_STR_, MATRIX1_, MATRIX1_STR_, MATRIX2_, MATRIX2_STR_,
249 FUNCTION0_, FUNCTION0_STR_, FUNCTION1_, FUNCTION1_STR_, FUNCTION2_, FUNCTION2_STR_,
250 SQR_,
251
252 /* Symbols introduced by lexical analysis. */
253
254 STRING_,
255 NUMERIC_VARIABLE_, NUMERIC_VECTOR_VARIABLE_, NUMERIC_MATRIX_VARIABLE_,
256 STRING_VARIABLE_, STRING_ARRAY_VARIABLE_,
257 VARIABLE_NAME_, INDEXED_NUMERIC_VARIABLE_, INDEXED_STRING_VARIABLE_,
258 END_
259 #define highestSymbol END_
260 };
261
262 /* The names that start with an underscore (_) do not occur in the formula text: */
263 /* they are used in error messages and in debugging (see Formula_print). */
264
265 static const conststring32 Formula_instructionNames [] = { U"",
266 #define NAME_WITH_TENSORS(name) \
267 U"" #name, U"" #name "#", U"" #name "##",
268
269 U"if", U"then", U"else", U"(", U"[", U"{", U",", U":", U"from", U"to",
270 U"or", U"and", U"not", U"=", U"<>", U"<=", U"<", U">=", U">",
271 U"+", U"-", U"*", U"/", U"div", U"mod", U"^", U"_call", U"_neg",
272 U"endif", U"fi", U")", U"]", U"}",
273 U"a number", U"pi", U"e", U"undefined",
274 U"xmin", U"xmax", U"ymin", U"ymax", U"nx", U"ny", U"dx", U"dy",
275 U"row", U"col", U"nrow", U"ncol", U"row$", U"col$", U"y", U"x",
276 U"self", U"self$", U"object", U"object$", U"_matrix", U"_matrix$",
277 U"stopwatch",
278 NAME_WITH_TENSORS (abs)
279 NAME_WITH_TENSORS (round) NAME_WITH_TENSORS (floor) NAME_WITH_TENSORS (ceiling)
280 NAME_WITH_TENSORS (rectify)
281 NAME_WITH_TENSORS (sqrt)
282 NAME_WITH_TENSORS (sin) NAME_WITH_TENSORS (cos) NAME_WITH_TENSORS (tan)
283 NAME_WITH_TENSORS (arcsin) NAME_WITH_TENSORS (arccos) NAME_WITH_TENSORS (arctan)
284 U"sinc", U"sincpi",
285 NAME_WITH_TENSORS (exp)
286 NAME_WITH_TENSORS (sinh) NAME_WITH_TENSORS (cosh) NAME_WITH_TENSORS (tanh)
287 NAME_WITH_TENSORS (arcsinh) NAME_WITH_TENSORS (arccosh) NAME_WITH_TENSORS (arctanh)
288 NAME_WITH_TENSORS (sigmoid) NAME_WITH_TENSORS (invSigmoid)
289 U"softmax#", U"softmaxPerRow##",
290 U"erf", U"erfc", U"gaussP", U"gaussQ", U"invGaussQ",
291 U"randomBernoulli", U"randomBernoulli#",
292 U"randomPoisson", U"transpose##",
293 U"rowSums#", U"columnSums#",
294 NAME_WITH_TENSORS (log2) NAME_WITH_TENSORS (ln) NAME_WITH_TENSORS (log10)
295 U"lnGamma",
296 U"hertzToBark", U"barkToHertz", U"phonToDifferenceLimens", U"differenceLimensToPhon",
297 U"hertzToMel", U"melToHertz", U"hertzToSemitones", U"semitonesToHertz",
298 U"erb", U"hertzToErb", U"erbToHertz",
299 U"sum", U"mean", U"stdev", U"center", U"randomImax",
300 U"evaluate", U"evaluate_nocheck", U"evaluate$", U"evaluate_nocheck$",
301 U"string$", U"horizontal$", U"vertical$", U"numbers#", U"sleep", U"unicode", U"unicode$",
302 U"arctan2", U"randomUniform", U"randomInteger", U"randomGauss", U"randomBinomial",
303 U"randomGamma",
304 U"chiSquareP", U"chiSquareQ", U"incompleteGammaP", U"invChiSquareQ", U"studentP", U"studentQ", U"invStudentQ",
305 U"beta", U"beta2", U"besselI", U"besselK", U"lnBeta",
306 U"soundPressureToPhon", U"objectsAreIdentical",
307 U"row#", U"col#",
308 U"inner", U"correlation", U"outer##", U"mul#", U"mul##", U"mul_fast##", U"mul_metal##",
309 U"mul_tn##", U"mul_nt##", U"mul_tt##", U"repeat#",
310 U"rowInners#", U"solve#", U"solve##",
311 U"fisherP", U"fisherQ", U"invFisherQ",
312 U"binomialP", U"binomialQ", U"incompleteBeta", U"invBinomialP", U"invBinomialQ",
313 U"solveWeaklyConstrained#",
314 U"do", U"do$",
315 U"writeInfo", U"writeInfoLine", U"appendInfo", U"appendInfoLine",
316 U"writeFile", U"writeFileLine", U"appendFile", U"appendFileLine",
317 U"pauseScript", U"exitScript", U"runScript", U"runScriptWithForm", U"runNotebook",
318 U"runSystem", U"runSystem$", U"runSystem_nocheck", U"runSubprocess", U"runSubprocess$",
319 U"min", U"min_e", U"min_removeUndefined",
320 U"max", U"max_e", U"max_removeUndefined",
321 U"imin", U"imin_e", U"imin_removeUndefined",
322 U"imax", U"imax_e", U"imax_removeUndefined",
323 U"quantile",
324 U"norm",
325 U"left$", U"right$", U"mid$",
326 U"padLeft$", U"padRight$", U"truncateLeft$", U"truncateRight$", U"padOrTruncateLeft$", U"padOrTruncateRight$",
327 U"selected", U"selected$", U"numberOfSelected", U"selected#", U"selected$#",
328 U"selectObject", U"plusObject", U"minusObject", U"removeObject",
329 U"askForTrust", U"beginPause",
330 U"real", U"positive", U"integer", U"natural",
331 U"word", U"sentence", U"text", U"boolean",
332 U"choice", U"optionmenu", U"optionMenu", U"option",
333 U"infile", U"outfile", U"folder",
334 U"realvector", U"positivevector", U"integervector", U"naturalvector",
335 U"heading", U"comment", U"endPause",
336 U"lowerCaseAppName$", U"upperCaseAppName$",
337 U"clock",
338 U"appVersion", U"appVersion$", U"appYear", U"appMonth", U"appMonth$", U"appDay",
339 U"chooseReadFile$", U"chooseWriteFile$", U"chooseFolder$", U"chooseDirectory$",
340 U"demoWindowTitle", U"demoShow", U"demoWaitForInput", U"demoPeekInput", U"demoInput", U"demoClickedIn",
341 U"demoClicked", U"demoX", U"demoY", U"demoKeyPressed", U"demoKey$",
342 U"demoShiftKeyPressed", U"demoCommandKeyPressed", U"demoOptionKeyPressed",
343 U"zero#", U"zero##",
344 U"linear#", U"linear##", U"to#", U"from_to#", U"from_to_by#", U"from_to_count#", U"between_by#", U"between_count#",
345 U"sort#", U"sort_removeUndefined#", U"sort$#", U"sort_numberAware$#", U"shuffle#", U"shuffle$#",
346 U"randomUniform#", U"randomUniform##",
347 U"randomInteger#", U"randomInteger##",
348 U"randomGauss#", U"randomGauss##",
349 U"randomGamma#", U"randomGamma##", U"solveSparse#", U"solveNonnegative#",
350 U"peaks##",
351 U"size", U"numberOfRows", U"numberOfColumns", U"combine#", U"blake3#", U"part#", U"part##", U"editor",
352 U"random_initializeWithSeedUnsafelyButPredictably", U"random_initializeSafelyAndUnpredictably",
353 U"hash", U"hex$", U"unhex$",
354 U"empty$#", U"readLinesFromFile$#",
355 U"fileNames$#", U"folderNames$#", U"fileNames_caseInsensitive$#", U"folderNames_caseInsensitive$#",
356 U"splitByWhitespace$#", U"splitBy$#",
357 U"lowerCase$", U"lowerCamelCase$", U"lowerSnakeCase$",
358 U"upperCase$", U"upperCamelCase$", U"upperSnakeCase$",
359
360 // LOW_FUNCTION_STR1
361 U"length", U"number", U"fileReadable", U"folderExists", U"tryToWriteFile", U"tryToAppendFile", U"deleteFile",
362 U"createFolder", U"createDirectory", U"setWorkingDirectory", U"variableExists",
363 U"readFile", U"readFile$", U"readFile#", U"readFile##",
364 U"unicodeToBackslashTrigraphs$", U"backslashTrigraphsToUnicode$", U"environment$",
365 U"bigInteger$", U"half$", U"graphicalHalf$", U"single$", U"graphicalSingle$", U"double$", U"graphicalDouble$",
366 U"naturalLogarithm$", U"graphicalNaturalLogarithm$",
367 // HIGH_FUNCTION_STR1
368 U"date$", U"date_utc$", U"date_iso$", U"date_utc_iso$", U"date#", U"date_utc#", U"info$",
369 // LOW_FUNCTION_STR2
370 U"index", U"index_caseInsensitive", U"rindex", U"rindex_caseInsensitive",
371 U"startsWith", U"startsWith_caseInsensitive", U"endsWith", U"endsWith_caseInsensitive",
372 U"index_regex", U"rindex_regex", U"extractNumber",
373 U"moveAndOrRenameFile",
374 U"fixed$", U"percent$", U"graphicalPercent$", U"hexadecimal$",
375 // HIGH_FUNCTION_STR2
376 U"extractWord$", U"extractLine$",
377 U"replace$", U"replace_regex$",
378 U"sumOver",
379 U".",
380 U"_true", U"_false",
381 U"_goto", U"_iftrue", U"_iffalse", U"_incrementGreaterGoto",
382 U"_label",
383 U"_decrementAndAssign", U"_add3Down", U"_pop2",
384 U"_numericVectorElement", U"_numericMatrixElement", U"_stringVectorElement", U"_variableReference",
385 U"_tensorLiteral", U"_tensorLiteralCell",
386 U"_self0", U"_self0$", U"_toObject",
387 U"_object_xmin", U"_object_xmax", U"_object_ymin", U"_object_ymax", U"_object_nx", U"_object_ny",
388 U"_object_dx", U"_object_dy", U"_object_nrow", U"_object_ncol", U"_object_row$", U"_object_col$",
389 U"_objectcell0", U"_objectcell0$", U"_objectcell1", U"_objectcell1$", U"_objectcell2", U"_objectcell2$",
390 U"_objectlocation0", U"_objectlocation0$", U"_objectlocation1", U"_objectlocation1$", U"_objectlocation2", U"_objectlocation2$",
391 U"_selfmatrix1", U"_selfmatrix1$", U"_selfmatrix2", U"_selfmatrix2$",
392 U"_selffunction1", U"_selffunction1$", U"_selffunction2", U"_selffunction2$",
393 U"_matrix0", U"_matrix0$", U"_matrix1", U"_matrix1$", U"_matrix2", U"_matrix2$",
394 U"_function0", U"_function0$", U"_function1", U"_function1$", U"_function2", U"_function2$",
395 U"_square",
396 U"_string",
397 U"a numeric variable", U"a vector variable", U"a matrix variable",
398 U"a string variable", U"a string array variable",
399 U"a variable name", U"an indexed numeric variable", U"an indexed string variable",
400 U"the end of the formula"
401 };
402 static_assert (sizeof (Formula_instructionNames) == (1 + END_) * sizeof (conststring32));
403
404 #define newlabel (-- ilabel)
405 #define newread (lexan [++ ilexan]. symbol)
406 #define oldread (-- ilexan)
407
408 static void formulaError (conststring32 message, integer position) {
409 static MelderString truncatedExpression;
410 MelderString_ncopy (& truncatedExpression, theExpression, position + 1);
411 Melder_throw (message, U":\n« ", truncatedExpression.string);
412 }
413
414 static integer Formula_hasLanguageName (conststring32 f) {
415 static autoINTVEC index;
416 if (NUMisEmpty (index.get())) {
417 index = to_INTVEC (highestInputSymbol);
418 std::sort (index.begin(), index.end(),
419 [] (integer i, integer j) {
420 return str32cmp (Formula_instructionNames [i], Formula_instructionNames [j]) < 0;
421 }
422 );
423 }
424 constexpr integer sentinel = 0; // has to be different from the numbers 1 .. index.size
425 const integer *const found = std::lower_bound (index.begin(), index.end(), sentinel,
426 [f] (integer i, integer j) {
427 return str32cmp (
428 i == sentinel ? f : Formula_instructionNames [i],
429 j == sentinel ? f : Formula_instructionNames [j]
430 ) < 0;
431 }
432 );
433 if (found != index.end() && Melder_equ (Formula_instructionNames [*found], f))
434 return *found;
435 return 0;
436 }
437
438 static void Formula_lexan () {
439 /*
440 Purpose:
441 translate the formula text into a series of symbols.
442 Postcondition:
443 if not thrown, then the last symbol is END_.
444 Example:
445 the text "x*7" yields 5 symbols:
446 lexan [0] is empty;
447 lexan [1]. symbol = X_;
448 lexan [2]. symbol = MUL_;
449 lexan [3]. symbol = NUMBER_;
450 lexan [3]. number = 7.00000000e+00;
451 lexan [4]. symbol = END_;
452 */
453 char32 kar; // the character most recently read from theExpression
454 integer ikar = -1; // the position of that character in theExpression
455 #define newchar kar = theExpression [++ ikar]
456 #define oldchar -- ikar
457
458 integer itok = 0; // position of most recent symbol in "lexan"
459 #define newtok(s) { lexan [++ itok]. symbol = s; lexan [itok]. position = ikar; }
460 #define toknumber(g) lexan [itok]. content.number = (g)
461 #define tokmatrix(m) lexan [itok]. content.object = (m)
462
463 static MelderString token; // string to collect a symbol name in
464 #define stringtokon MelderString_empty (& token);
465 #define stringtokchar { MelderString_appendCharacter (& token, kar); newchar; }
466 #define stringtokoff (void) 0
467
468 ilexan = iparse = ilabel = numberOfStringConstants = 0;
469 do {
470 newchar;
471 if (Melder_isHorizontalOrVerticalSpace (kar)) {
472 ; // ignore spaces and tabs
473 } else if (kar == U'\0') {
474 newtok (END_)
475 } else if (Melder_isAsciiDecimalNumber (kar)) {
476 char32 saveKar = kar;
477 bool isHexadecimal = false;
478 if (kar == U'0') {
479 newchar;
480 if (kar == U'x') {
481 isHexadecimal = true;
482 newchar;
483 } else {
484 oldchar;
485 }
486 }
487 if (isHexadecimal) {
488 stringtokon;
489 do stringtokchar while (Melder_isHexadecimalDigit (kar));
490 stringtokoff;
491 oldchar;
492 newtok (NUMBER_)
493 toknumber (strtoull (Melder_peek32to8 (token.string), nullptr, 16));
494 } else {
495 kar = saveKar;
496 stringtokon;
497 do stringtokchar while (Melder_isAsciiDecimalNumber (kar));
498 if (kar == U'.')
499 do stringtokchar while (Melder_isAsciiDecimalNumber (kar));
500 if (kar == U'e' || kar == U'E') {
501 kar = U'e';
502 stringtokchar
503 if (kar == U'-')
504 stringtokchar
505 else if (kar == U'+')
506 newchar;
507 if (! Melder_isAsciiDecimalNumber (kar))
508 formulaError (U"Missing exponent", ikar);
509 do stringtokchar while (Melder_isAsciiDecimalNumber (kar));
510 }
511 if (kar == U'%')
512 stringtokchar
513 stringtokoff;
514 oldchar;
515 newtok (NUMBER_)
516 toknumber (Melder_atof (token.string));
517 }
518 } else if (Melder_isLetter (kar) && ! Melder_isUpperCaseLetter (kar) ||
519 (kar == U'.' && Melder_isLetter (theExpression [ikar + 1]) && ! Melder_isUpperCaseLetter (theExpression [ikar + 1])
520 && (itok == 0 || (lexan [itok]. symbol != MATRIX_ && lexan [itok]. symbol != MATRIX_STR_
521 && lexan [itok]. symbol != CLOSING_BRACKET_)))) {
522 integer tok;
523 bool isString = false;
524 int rank = 0;
525 stringtokon;
526 do stringtokchar while (Melder_isWordCharacter (kar) || kar == U'.');
527 if (kar == U'$') {
528 isString = true;
529 stringtokchar
530 if (kar == U'#') {
531 rank += 1;
532 stringtokchar
533 }
534 }
535 if (kar == U'#') {
536 rank += 1;
537 stringtokchar
538 if (kar == U'#') {
539 rank += 1;
540 stringtokchar
541 if (kar == U'#') {
542 rank += 1;
543 stringtokchar
544 if (kar == U'#') {
545 rank += 1;
546 stringtokchar
547 }
548 }
549 }
550 }
551 stringtokoff;
552 oldchar;
553 /*
554 `token` now contains a word, possibly ending in $, #, ## or $#;
555 it could be a variable name, a function name, both, or a procedure name.
556 Try a language or function name first.
557 */
558 tok = Formula_hasLanguageName (token.string);
559 if (tok) {
560 /*
561 We have a language name or a function name. It MIGHT be meant to be a variable name, though,
562 regarding the large and expanding number of language names.
563 */
564 /*
565 First the constants. They are reserved words and can never be variable names.
566 */
567 if (tok == NUMBER_PI_) {
568 newtok (NUMBER_)
569 toknumber (NUMpi);
570 } else if (tok == NUMBER_E_) {
571 newtok (NUMBER_)
572 toknumber (NUMe);
573 } else if (tok == NUMBER_UNDEFINED_) {
574 newtok (NUMBER_)
575 toknumber (undefined);
576 /*
577 One very common language name must be converted to a synonym.
578 */
579 } else if (tok == FI_) {
580 newtok (ENDIF_)
581 /*
582 Is it a function name? These may be ambiguous.
583 */
584 } else if (tok >= LOW_FUNCTION && tok <= HIGH_FUNCTION) {
585 /*
586 Look ahead to find out whether the next token is a left parenthesis (or a colon).
587 */
588 integer jkar;
589 jkar = ikar + 1;
590 while (Melder_isHorizontalSpace (theExpression [jkar]))
591 jkar ++;
592 if (theExpression [jkar] == U'(' || theExpression [jkar] == U':') {
593 newtok (tok) // this must be a function name
594 } else if (theExpression [jkar] == U'[' && rank == 0) {
595 if (isString) {
596 newtok (INDEXED_STRING_VARIABLE_)
597 } else {
598 newtok (INDEXED_NUMERIC_VARIABLE_)
599 }
600 lexan [itok]. content.string = Melder_dup_f (token.string).transfer();
601 numberOfStringConstants ++;
602 } else {
603 /*
604 This could be a variable with the same name as a function.
605 */
606 const InterpreterVariable var = Interpreter_hasVariable (theInterpreter, token.string);
607 if (! var) {
608 newtok (VARIABLE_NAME_)
609 lexan [itok]. content.string = Melder_dup_f (token.string).transfer();
610 numberOfStringConstants ++;
611 } else {
612 if (rank == 0) {
613 if (isString) {
614 newtok (STRING_VARIABLE_)
615 } else {
616 newtok (NUMERIC_VARIABLE_)
617 }
618 } else if (rank == 1) {
619 if (isString) {
620 newtok (STRING_ARRAY_VARIABLE_)
621 } else {
622 newtok (NUMERIC_VECTOR_VARIABLE_)
623 }
624 } else if (rank == 2) {
625 if (isString) {
626 formulaError (U"String matrices not implemented.", ikar);
627 } else {
628 newtok (NUMERIC_MATRIX_VARIABLE_)
629 }
630 } else if (rank == 3) {
631 formulaError (U"Rank-3 tensors not implemented.", ikar);
632 } else {
633 formulaError (U"Rank-4 tensors not implemented.", ikar);
634 }
635 lexan [itok]. content.variable = var;
636 }
637 }
638 /*
639 Not a function name.
640 Must be a language name (if, then, else, endif, or, and, not, div, mod, x, ncol, stopwatch).
641 Some can be used as variable names (x, ncol...).
642 */
643 } else if (tok >= LOW_ATTRIBUTE && tok <= HIGH_ATTRIBUTE) {
644 /*
645 Look back to find out whether this is an attribute.
646 */
647 if (itok > 0 && lexan [itok]. symbol == PERIOD_) {
648 /*
649 This must be an attribute that follows a period.
650 */
651 newtok (tok)
652 } else if (theSource) {
653 /*
654 Look for ambiguity.
655 */
656 if (Interpreter_hasVariable (theInterpreter, token.string))
657 Melder_throw (
658 U"«", token.string,
659 U"» is ambiguous: a variable or an attribute of the current object. "
660 U"Please change variable name.");
661 if (tok == ROW_ || tok == COL_ || tok == X_ || tok == Y_) {
662 newtok (tok)
663 } else {
664 newtok (MATRIX_)
665 tokmatrix (theSource);
666 newtok (PERIOD_)
667 newtok (tok)
668 }
669 } else {
670 /*
671 This must be a variable, since there is no "current object" here.
672 */
673 integer jkar = ikar + 1;
674 while (Melder_isHorizontalSpace (theExpression [jkar])) jkar ++;
675 if (theExpression [jkar] == U'[' && rank == 0) {
676 if (isString) {
677 newtok (INDEXED_STRING_VARIABLE_)
678 } else {
679 newtok (INDEXED_NUMERIC_VARIABLE_)
680 }
681 lexan [itok]. content.string = Melder_dup_f (token.string).transfer();
682 numberOfStringConstants ++;
683 } else {
684 const InterpreterVariable var = Interpreter_hasVariable (theInterpreter, token.string);
685 if (! var) {
686 newtok (VARIABLE_NAME_)
687 lexan [itok]. content.string = Melder_dup_f (token.string).transfer();
688 numberOfStringConstants ++;
689 } else {
690 if (rank == 0) {
691 if (isString) {
692 newtok (STRING_VARIABLE_)
693 } else {
694 newtok (NUMERIC_VARIABLE_)
695 }
696 } else if (rank == 1) {
697 if (isString) {
698 newtok (STRING_ARRAY_VARIABLE_)
699 } else {
700 newtok (NUMERIC_VECTOR_VARIABLE_)
701 }
702 } else if (rank == 2) {
703 if (isString) {
704 formulaError (U"String matrices not implemented.", ikar);
705 } else {
706 newtok (NUMERIC_MATRIX_VARIABLE_)
707 }
708 } else if (rank == 3) {
709 formulaError (U"Rank-3 tensors not implemented.", ikar);
710 } else {
711 formulaError (U"Rank-4 tensors not implemented.", ikar);
712 }
713 lexan [itok]. content.variable = var;
714 }
715 }
716 }
717 } else {
718 newtok (tok) // this must be a language name
719 }
720 } else {
721 /*
722 token.string is not a language name
723 */
724 integer jkar = ikar + 1;
725 while (Melder_isHorizontalSpace (theExpression [jkar]))
726 jkar ++;
727 if (theExpression [jkar] == U'(' || theExpression [jkar] == U':') {
728 Melder_throw (
729 U"Unknown function «", token.string, U"» in formula.");
730 } else if (theExpression [jkar] == '[' && rank == 0) {
731 if (isString) {
732 newtok (INDEXED_STRING_VARIABLE_)
733 } else {
734 newtok (INDEXED_NUMERIC_VARIABLE_)
735 }
736 lexan [itok]. content.string = Melder_dup_f (token.string).transfer();
737 numberOfStringConstants ++;
738 } else {
739 InterpreterVariable var = Interpreter_hasVariable (theInterpreter, token.string);
740 if (! var) {
741 newtok (VARIABLE_NAME_)
742 lexan [itok]. content.string = Melder_dup_f (token.string).transfer();
743 numberOfStringConstants ++;
744 } else {
745 if (rank == 0) {
746 if (isString) {
747 newtok (STRING_VARIABLE_)
748 } else {
749 newtok (NUMERIC_VARIABLE_)
750 }
751 } else if (rank == 1) {
752 if (isString) {
753 newtok (STRING_ARRAY_VARIABLE_)
754 } else {
755 newtok (NUMERIC_VECTOR_VARIABLE_)
756 }
757 } else if (rank == 2) {
758 if (isString) {
759 formulaError (U"String matrices not implemented.", ikar);
760 } else {
761 newtok (NUMERIC_MATRIX_VARIABLE_)
762 }
763 } else if (rank == 3) {
764 formulaError (U"Rank-3 tensors not implemented.", ikar);
765 } else {
766 formulaError (U"Rank-4 tensors not implemented.", ikar);
767 }
768 lexan [itok]. content.variable = var;
769 }
770 }
771 }
772 } else if (kar >= U'A' && kar <= U'Z') {
773 bool endsInDollarSign = false;
774 stringtokon;
775 do stringtokchar while (Melder_isAlphanumeric (kar) || kar == U'_');
776 if (kar == U'$') {
777 stringtokchar
778 endsInDollarSign = true;
779 }
780 stringtokoff;
781 oldchar;
782 /*
783 `token` now contains a word that could be an object name.
784 */
785 char32 *underscore = str32chr (token.string, '_');
786 if (str32equ (token.string, U"Self")) {
787 if (! theSource)
788 formulaError (U"Cannot use “Self” if there is no current object.", ikar);
789 newtok (MATRIX_)
790 tokmatrix (theSource);
791 } else if (str32equ (token.string, U"Self$")) {
792 if (! theSource)
793 formulaError (U"Cannot use “Self$” if there is no current object.", ikar);
794 newtok (MATRIX_STR_)
795 tokmatrix (theSource);
796 } else if (! underscore) {
797 Melder_throw (
798 U"Unknown symbol «", token.string, U"» in formula "
799 U"(variables start with nonupper case; object names contain an underscore).");
800 } else if (str32nequ (token.string, U"Object_", 7)) {
801 const integer uniqueID = Melder_atoi (token.string + 7);
802 integer i = theCurrentPraatObjects -> n;
803 while (i > 0 && uniqueID != theCurrentPraatObjects -> list [i]. id)
804 i --;
805 if (i == 0)
806 formulaError (U"No such object (note: variables start with nonupper case)", ikar);
807 newtok (endsInDollarSign ? MATRIX_STR_ : MATRIX_)
808 tokmatrix ((Daata) theCurrentPraatObjects -> list [i]. object);
809 } else {
810 integer i = theCurrentPraatObjects -> n;
811 *underscore = U' ';
812 if (endsInDollarSign)
813 token.string [-- token.length] = U'\0';
814 while (i > 0 && ! str32equ (token.string, theCurrentPraatObjects -> list [i]. name.get()))
815 i --;
816 if (i == 0)
817 formulaError (U"No such object (note: variables start with nonupper case)", ikar);
818 newtok (endsInDollarSign ? MATRIX_STR_ : MATRIX_)
819 tokmatrix ((Daata) theCurrentPraatObjects -> list [i]. object);
820 }
821 } else if (kar == U'(') {
822 newchar;
823 if (kar == U'=') {
824 newtok (END_) // "(=" = final comment
825 } else {
826 oldchar;
827 newtok (OPENING_PARENTHESIS_)
828 }
829 } else if (kar == U')') {
830 newtok (CLOSING_PARENTHESIS_)
831 } else if (kar == U'+') {
832 newtok (ADD_)
833 } else if (kar == U'-') {
834 if (itok == 0 || lexan [itok]. symbol <= MINUS_) {
835 newtok (MINUS_)
836 } else {
837 newtok (SUB_)
838 }
839 } else if (kar == U'*') {
840 newchar;
841 if (kar == U'*') {
842 newtok (POWER_) // "**" = "^"
843 } else {
844 oldchar;
845 newtok (MUL_)
846 }
847 } else if (kar == U'/') {
848 newchar;
849 if (kar == U'=') {
850 newtok (NE_) // "/=" = "<>"
851 } else {
852 oldchar;
853 newtok (RDIV_)
854 }
855 } else if (kar == U'=') {
856 newtok (EQ_) // "="
857 newchar;
858 if (kar != U'=') {
859 oldchar; // "==" = "="
860 }
861 } else if (kar == U'>') {
862 newchar;
863 if (kar == U'=') {
864 newtok (GE_)
865 } else {
866 oldchar;
867 newtok (GT_)
868 }
869 } else if (kar == U'<') {
870 newchar;
871 if (kar == U'=') {
872 newtok (LE_)
873 } else if (kar == U'>') {
874 newtok (NE_)
875 } else {
876 oldchar;
877 newtok (LT_)
878 }
879 } else if (kar == U'!') {
880 newchar;
881 if (kar == U'=') {
882 newtok (NE_) // "!=" = "<>"
883 } else {
884 oldchar;
885 newtok (NOT_)
886 }
887 } else if (kar == U',') {
888 newtok (COMMA_)
889 } else if (kar == U':') {
890 newtok (COLON_)
891 } else if (kar == U';') {
892 newtok (END_)
893 } else if (kar == U'^') {
894 newtok (POWER_)
895 } else if (kar == U'@') {
896 do {
897 newchar;
898 } while (Melder_isHorizontalSpace (kar));
899 stringtokon;
900 do stringtokchar while (Melder_isWordCharacter (kar) || kar == U'.');
901 stringtokoff;
902 oldchar;
903 newtok (CALL_)
904 lexan [itok]. content.string = Melder_dup_f (token.string).transfer();
905 numberOfStringConstants ++;
906 } else if (kar == U'"') {
907 /*
908 String constant, straight-quote version.
909 */
910 newchar;
911 stringtokon;
912 for (;;) {
913 if (kar == U'\0')
914 formulaError (U"No closing quote in string constant", ikar);
915 if (kar == U'"') {
916 newchar;
917 if (kar == U'"')
918 stringtokchar
919 else break;
920 } else {
921 stringtokchar
922 }
923 }
924 stringtokoff;
925 oldchar;
926 newtok (STRING_)
927 lexan [itok]. content.string = Melder_dup_f (token.string).transfer();
928 numberOfStringConstants ++;
929 } else if (kar == U'“') {
930 /*
931 String constant, curly-quote version.
932 */
933 newchar;
934 stringtokon;
935 for (;;) {
936 if (kar == U'\0')
937 formulaError (U"No closing quote in string constant", ikar);
938 if (kar == U'”')
939 break;
940 stringtokchar
941 }
942 stringtokoff;
943 newtok (STRING_)
944 lexan [itok]. content.string = Melder_dup_f (token.string).transfer();
945 numberOfStringConstants ++;
946 } else if (kar == U'~') {
947 /*
948 The content of the remainder of the line,
949 including any leading and trailing space,
950 will become a string constant (this is good for formulas).
951 */
952 newchar;
953 stringtokon;
954 for (;;) {
955 if (kar == U'\0')
956 break;
957 stringtokchar
958 }
959 stringtokoff;
960 oldchar;
961 newtok (STRING_)
962 lexan [itok]. content.string = Melder_dup_f (token.string).transfer();
963 numberOfStringConstants ++;
964 } else if (kar == U'|') {
965 newtok (OR_) /* "|" = "or" */
966 newchar;
967 if (kar != U'|') {
968 oldchar; /* "||" = "or" */
969 }
970 } else if (kar == U'&') {
971 newtok (AND_) /* "&" = "and" */
972 newchar;
973 if (kar != U'&') {
974 oldchar; /* "&&" = "and" */
975 }
976 } else if (kar == U'[') {
977 newtok (OPENING_BRACKET_)
978 } else if (kar == U']') {
979 newtok (CLOSING_BRACKET_)
980 } else if (kar == U'{') {
981 newtok (OPENING_BRACE_)
982 } else if (kar == U'}') {
983 newtok (CLOSING_BRACE_)
984 } else if (kar == U'.') {
985 newtok (PERIOD_)
986 } else {
987 formulaError (U"Unknown symbol", ikar);
988 }
989 } while (lexan [itok]. symbol != END_);
990 }
991
992 static void fit (integer symbol) {
993 if (symbol == newread) {
994 return; // success
995 } else {
996 const conststring32 symbolName1 = Formula_instructionNames [symbol];
997 const conststring32 symbolName2 = Formula_instructionNames [lexan [ilexan]. symbol];
998 const bool needQuotes1 = ! str32chr (symbolName1, U' ');
999 const bool needQuotes2 = ! str32chr (symbolName2, U' ');
1000 static MelderString message;
1001 MelderString_copy (& message,
1002 U"Expected ", ( needQuotes1 ? U"“" : nullptr ), symbolName1, ( needQuotes1 ? U"”" : nullptr ),
1003 U", but found ", ( needQuotes2 ? U"“" : nullptr ), symbolName2, ( needQuotes2 ? U"”" : nullptr ));
1004 formulaError (message.string, lexan [ilexan]. position);
1005 }
1006 }
1007
1008 static bool fitArguments () {
1009 const integer symbol = newread;
1010 if (symbol == OPENING_PARENTHESIS_)
1011 return true; // success: a function call like: myFunction (...)
1012 if (symbol == COLON_)
1013 return false; // success: a function call like: myFunction: ...
1014 const conststring32 symbolName2 = Formula_instructionNames [lexan [ilexan]. symbol];
1015 const bool needQuotes2 = ! str32chr (symbolName2, U' ');
1016 static MelderString message;
1017 MelderString_copy (& message,
1018 U"Expected “(” or “:”, but found ", ( needQuotes2 ? U"“" : nullptr ), symbolName2, ( needQuotes2 ? U"”" : nullptr ));
1019 formulaError (message.string, lexan [ilexan]. position);
1020 return false; // will never occur
1021 }
1022
1023 #define newparse(s) parse [++ iparse]. symbol = (s)
1024 #define parsenumber(g) parse [iparse]. content.number = (g)
1025 #define parselabel(l) parse [iparse]. content.label = (l)
1026
1027 static void parseExpression ();
1028
1029 static void parsePowerFactor () {
1030 integer symbol = newread;
1031
1032 if (symbol >= LOW_VALUE && symbol <= HIGH_VALUE) {
1033 newparse (symbol);
1034 if (symbol == NUMBER_) parsenumber (lexan [ilexan]. content.number);
1035 return;
1036 }
1037
1038 if (symbol == STRING_) {
1039 newparse (symbol);
1040 parse [iparse]. content.string = lexan [ilexan]. content.string; // reference copy!
1041 return;
1042 }
1043
1044 if (symbol == NUMERIC_VARIABLE_ || symbol == STRING_VARIABLE_) {
1045 newparse (symbol);
1046 parse [iparse]. content.variable = lexan [ilexan]. content.variable;
1047 return;
1048 }
1049
1050 if (symbol == INDEXED_NUMERIC_VARIABLE_ || symbol == INDEXED_STRING_VARIABLE_) {
1051 char32 *var = lexan [ilexan]. content.string; // Save before incrementing ilexan.
1052 if (newread == OPENING_BRACKET_) {
1053 int n = 0;
1054 if (newread != CLOSING_BRACKET_) {
1055 oldread;
1056 parseExpression ();
1057 n ++;
1058 while (newread == COMMA_) {
1059 parseExpression ();
1060 n ++;
1061 }
1062 oldread;
1063 fit (CLOSING_BRACKET_);
1064 }
1065 newparse (NUMBER_); parsenumber (n);
1066 newparse (symbol);
1067 } else {
1068 Melder_crash (U"Formula:parsePowerFactor (indexed variable): No '['; cannot happen.");
1069 }
1070 parse [iparse]. content.string = var;
1071 return;
1072 }
1073
1074 if (symbol == NUMERIC_VECTOR_VARIABLE_) {
1075 const InterpreterVariable var = lexan [ilexan]. content.variable; // save before incrementing ilexan
1076 if (newread == OPENING_BRACKET_) {
1077 parseExpression ();
1078 fit (CLOSING_BRACKET_);
1079 newparse (VEC_CELL_);
1080 } else {
1081 oldread;
1082 newparse (NUMERIC_VECTOR_VARIABLE_);
1083 }
1084 parse [iparse]. content.variable = var;
1085 return;
1086 }
1087
1088 if (symbol == NUMERIC_MATRIX_VARIABLE_) {
1089 const InterpreterVariable var = lexan [ilexan]. content.variable; // save before incrementing ilexan
1090 if (newread == OPENING_BRACKET_) {
1091 parseExpression ();
1092 fit (COMMA_);
1093 parseExpression ();
1094 fit (CLOSING_BRACKET_);
1095 newparse (MAT_CELL_);
1096 } else {
1097 oldread;
1098 newparse (NUMERIC_MATRIX_VARIABLE_);
1099 }
1100 parse [iparse]. content.variable = var;
1101 return;
1102 }
1103
1104 if (symbol == STRING_ARRAY_VARIABLE_) {
1105 const InterpreterVariable var = lexan [ilexan]. content.variable; // save before incrementing ilexan
1106 if (newread == OPENING_BRACKET_) {
1107 parseExpression ();
1108 fit (CLOSING_BRACKET_);
1109 newparse (STRVEC_CELL_);
1110 } else {
1111 oldread;
1112 newparse (STRING_ARRAY_VARIABLE_);
1113 }
1114 parse [iparse]. content.variable = var;
1115 return;
1116 }
1117
1118 if (symbol == VARIABLE_NAME_) {
1119 const InterpreterVariable var = Interpreter_hasVariable (theInterpreter, lexan [ilexan]. content.string);
1120 if (! var)
1121 formulaError (U"Unknown variable", lexan [ilexan]. position);
1122 newparse (NUMERIC_VARIABLE_);
1123 parse [iparse]. content.variable = var;
1124 return;
1125 }
1126
1127 if (symbol == SELF_) {
1128 symbol = newread;
1129 if (symbol == OPENING_BRACKET_) {
1130 parseExpression ();
1131 if (newread == COMMA_) {
1132 parseExpression ();
1133 newparse (SELFMATRIX2_);
1134 fit (CLOSING_BRACKET_);
1135 return;
1136 }
1137 oldread;
1138 newparse (SELFMATRIX1_);
1139 fit (CLOSING_BRACKET_);
1140 return;
1141 }
1142 if (symbol == OPENING_PARENTHESIS_) {
1143 parseExpression ();
1144 if (newread == COMMA_) {
1145 parseExpression ();
1146 newparse (SELFFUNCTION2_);
1147 fit (CLOSING_PARENTHESIS_);
1148 return;
1149 }
1150 oldread;
1151 newparse (SELFFUNCTION1_);
1152 fit (CLOSING_PARENTHESIS_);
1153 return;
1154 }
1155 oldread;
1156 newparse (SELF0_);
1157 return;
1158 }
1159
1160 if (symbol == SELF_STR_) {
1161 symbol = newread;
1162 if (symbol == OPENING_BRACKET_) {
1163 parseExpression ();
1164 if (newread == COMMA_) {
1165 parseExpression ();
1166 newparse (SELFMATRIX2_STR_);
1167 fit (CLOSING_BRACKET_);
1168 return;
1169 }
1170 oldread;
1171 newparse (SELFMATRIX1_STR_);
1172 fit (CLOSING_BRACKET_);
1173 return;
1174 }
1175 if (symbol == OPENING_PARENTHESIS_) {
1176 parseExpression ();
1177 if (newread == COMMA_) {
1178 parseExpression ();
1179 newparse (SELFFUNCTION2_STR_);
1180 fit (CLOSING_PARENTHESIS_);
1181 return;
1182 }
1183 oldread;
1184 newparse (SELFFUNCTION1_STR_);
1185 fit (CLOSING_PARENTHESIS_);
1186 return;
1187 }
1188 oldread;
1189 newparse (SELFSTR0_);
1190 return;
1191 }
1192
1193 if (symbol == OBJECT_) {
1194 symbol = newread;
1195 if (symbol == OPENING_BRACKET_) {
1196 parseExpression (); // the object's name or ID
1197 newparse (TO_OBJECT_);
1198 if (newread == CLOSING_BRACKET_) {
1199 symbol = newread;
1200 if (symbol == PERIOD_) {
1201 switch (newread) {
1202 case XMIN_:
1203 newparse (OBJECT_XMIN_);
1204 return;
1205 case XMAX_:
1206 newparse (OBJECT_XMAX_);
1207 return;
1208 case YMIN_:
1209 newparse (OBJECT_YMIN_);
1210 return;
1211 case YMAX_:
1212 newparse (OBJECT_YMAX_);
1213 return;
1214 case NX_:
1215 newparse (OBJECT_NX_);
1216 return;
1217 case NY_:
1218 newparse (OBJECT_NY_);
1219 return;
1220 case DX_:
1221 newparse (OBJECT_DX_);
1222 return;
1223 case DY_:
1224 newparse (OBJECT_DY_);
1225 return;
1226 case NROW_:
1227 newparse (OBJECT_NROW_);
1228 return;
1229 case NCOL_:
1230 newparse (OBJECT_NCOL_);
1231 return;
1232 case ROW_STR_:
1233 fit (OPENING_BRACKET_);
1234 parseExpression ();
1235 newparse (OBJECT_ROW_STR_);
1236 fit (CLOSING_BRACKET_);
1237 return;
1238 case COL_STR_:
1239 fit (OPENING_BRACKET_);
1240 parseExpression ();
1241 newparse (OBJECT_COL_STR_);
1242 fit (CLOSING_BRACKET_);
1243 return;
1244 default:
1245 formulaError (U"After “object [number].” there should be “xmin”, “xmax”, “ymin”, "
1246 "“ymax”, “nx”, “ny”, “dx”, “dy”, “nrow” or “ncol”", lexan [ilexan]. position);
1247 }
1248 } else if (symbol == OPENING_BRACKET_) {
1249 parseExpression ();
1250 if (newread == COMMA_) {
1251 parseExpression ();
1252 newparse (OBJECTCELL2_);
1253 fit (CLOSING_BRACKET_);
1254 } else {
1255 oldread;
1256 newparse (OBJECTCELL1_);
1257 fit (CLOSING_BRACKET_);
1258 }
1259 } else {
1260 oldread;
1261 newparse (OBJECTCELL0_);
1262 }
1263 } else {
1264 oldread;
1265 fit (COMMA_);
1266 parseExpression ();
1267 if (newread == COMMA_) {
1268 parseExpression ();
1269 newparse (OBJECTCELL2_);
1270 fit (CLOSING_BRACKET_);
1271 } else {
1272 oldread;
1273 newparse (OBJECTCELL1_);
1274 fit (CLOSING_BRACKET_);
1275 }
1276 }
1277 } else if (symbol == OPENING_PARENTHESIS_) {
1278 parseExpression (); // the object's name or ID
1279 newparse (TO_OBJECT_);
1280 if (newread == CLOSING_PARENTHESIS_) {
1281 newparse (OBJECTLOCATION0_);
1282 } else {
1283 oldread;
1284 fit (COMMA_);
1285 parseExpression ();
1286 if (newread == COMMA_) {
1287 parseExpression ();
1288 newparse (OBJECTLOCATION2_);
1289 fit (CLOSING_PARENTHESIS_);
1290 } else {
1291 oldread;
1292 newparse (OBJECTLOCATION1_);
1293 fit (CLOSING_PARENTHESIS_);
1294 }
1295 }
1296 } else {
1297 formulaError (U"After “object” there should be “(” or “[”", lexan [ilexan]. position);
1298 }
1299 return;
1300 }
1301
1302 if (symbol == OBJECT_STR_) {
1303 symbol = newread;
1304 if (symbol == OPENING_BRACKET_) {
1305 parseExpression (); // the object's name or ID
1306 newparse (TO_OBJECT_);
1307 if (newread == CLOSING_BRACKET_) {
1308 newparse (OBJECTCELL0_STR_);
1309 } else {
1310 oldread;
1311 fit (COMMA_);
1312 parseExpression ();
1313 if (newread == COMMA_) {
1314 parseExpression ();
1315 newparse (OBJECTCELL2_STR_);
1316 fit (CLOSING_BRACKET_);
1317 } else {
1318 oldread;
1319 newparse (OBJECTCELL1_STR_);
1320 fit (CLOSING_BRACKET_);
1321 }
1322 }
1323 } else if (symbol == OPENING_PARENTHESIS_) {
1324 parseExpression (); // the object's name or ID
1325 newparse (TO_OBJECT_);
1326 if (newread == CLOSING_PARENTHESIS_) {
1327 newparse (OBJECTLOCATION0_STR_);
1328 } else {
1329 oldread;
1330 fit (COMMA_);
1331 parseExpression ();
1332 if (newread == COMMA_) {
1333 parseExpression ();
1334 newparse (OBJECTLOCATION2_STR_);
1335 fit (CLOSING_PARENTHESIS_);
1336 } else {
1337 oldread;
1338 newparse (OBJECTLOCATION1_STR_);
1339 fit (CLOSING_PARENTHESIS_);
1340 }
1341 }
1342 } else {
1343 formulaError (U"After “object$” there should be “(” or “[”", lexan [ilexan]. position);
1344 }
1345 return;
1346 }
1347
1348 if (symbol == OPENING_PARENTHESIS_) {
1349 parseExpression ();
1350 fit (CLOSING_PARENTHESIS_);
1351 return;
1352 }
1353
1354 if (symbol == IF_) {
1355 const integer elseLabel = newlabel; // has to be local,
1356 const integer endifLabel = newlabel; // because of recursion
1357 parseExpression ();
1358 newparse (IFFALSE_);
1359 parselabel (elseLabel);
1360 fit (THEN_);
1361 parseExpression ();
1362 newparse (GOTO_);
1363 parselabel (endifLabel);
1364 fit (ELSE_);
1365 newparse (LABEL_);
1366 parselabel (elseLabel);
1367 parseExpression ();
1368 fit (ENDIF_);
1369 newparse (LABEL_);
1370 parselabel (endifLabel);
1371 return;
1372 }
1373
1374 if (symbol == MATRIX_) {
1375 const Daata thee = lexan [ilexan]. content.object;
1376 Melder_assert (thee != nullptr);
1377 symbol = newread;
1378 if (symbol == OPENING_BRACKET_) {
1379 if (newread == CLOSING_BRACKET_) {
1380 newparse (MATRIX0_);
1381 parse [iparse]. content.object = thee;
1382 } else {
1383 oldread;
1384 parseExpression ();
1385 if (newread == COMMA_) {
1386 parseExpression ();
1387 newparse (MATRIX2_);
1388 parse [iparse]. content.object = thee;
1389 fit (CLOSING_BRACKET_);
1390 } else {
1391 oldread;
1392 newparse (MATRIX1_);
1393 parse [iparse]. content.object = thee;
1394 fit (CLOSING_BRACKET_);
1395 }
1396 }
1397 } else if (symbol == OPENING_PARENTHESIS_) {
1398 if (newread == CLOSING_PARENTHESIS_) {
1399 newparse (FUNCTION0_);
1400 parse [iparse]. content.object = thee;
1401 } else {
1402 oldread;
1403 parseExpression ();
1404 if (newread == COMMA_) {
1405 parseExpression ();
1406 newparse (FUNCTION2_);
1407 parse [iparse]. content.object = thee;
1408 fit (CLOSING_PARENTHESIS_);
1409 } else {
1410 oldread;
1411 newparse (FUNCTION1_);
1412 parse [iparse]. content.object = thee;
1413 fit (CLOSING_PARENTHESIS_);
1414 }
1415 }
1416 } else if (symbol == PERIOD_) {
1417 switch (newread) {
1418 case XMIN_:
1419 if (! thy v_hasGetXmin ()) {
1420 formulaError (U"Attribute “xmin” not defined for this object", lexan [ilexan]. position);
1421 } else {
1422 newparse (NUMBER_);
1423 parsenumber (thy v_getXmin ());
1424 return;
1425 }
1426 case XMAX_:
1427 if (! thy v_hasGetXmax ()) {
1428 formulaError (U"Attribute “xmax” not defined for this object", lexan [ilexan]. position);
1429 } else {
1430 newparse (NUMBER_);
1431 parsenumber (thy v_getXmax ());
1432 return;
1433 }
1434 case YMIN_:
1435 if (! thy v_hasGetYmin ()) {
1436 formulaError (U"Attribute “ymin” not defined for this object", lexan [ilexan]. position);
1437 } else {
1438 newparse (NUMBER_);
1439 parsenumber (thy v_getYmin ());
1440 return;
1441 }
1442 case YMAX_:
1443 if (! thy v_hasGetYmax ()) {
1444 formulaError (U"Attribute “ymax” not defined for this object", lexan [ilexan]. position);
1445 } else {
1446 newparse (NUMBER_);
1447 parsenumber (thy v_getYmax ());
1448 return;
1449 }
1450 case NX_:
1451 if (! thy v_hasGetNx ()) {
1452 formulaError (U"Attribute “nx” not defined for this object", lexan [ilexan]. position);
1453 } else {
1454 newparse (NUMBER_);
1455 parsenumber (thy v_getNx ());
1456 return;
1457 }
1458 case NY_:
1459 if (! thy v_hasGetNy ()) {
1460 formulaError (U"Attribute “ny” not defined for this object", lexan [ilexan]. position);
1461 } else {
1462 newparse (NUMBER_);
1463 parsenumber (thy v_getNy ());
1464 return;
1465 }
1466 case DX_:
1467 if (! thy v_hasGetDx ()) {
1468 formulaError (U"Attribute “dx” not defined for this object", lexan [ilexan]. position);
1469 } else {
1470 newparse (NUMBER_);
1471 parsenumber (thy v_getDx ());
1472 return;
1473 }
1474 case DY_:
1475 if (! thy v_hasGetDy ()) {
1476 formulaError (U"Attribute “dy” not defined for this object", lexan [ilexan]. position);
1477 } else {
1478 newparse (NUMBER_);
1479 parsenumber (thy v_getDy ());
1480 return;
1481 }
1482 case NCOL_:
1483 if (! thy v_hasGetNcol ()) {
1484 formulaError (U"Attribute “ncol” not defined for this object", lexan [ilexan]. position);
1485 } else {
1486 newparse (NUMBER_);
1487 parsenumber (thy v_getNcol ());
1488 return;
1489 }
1490 case NROW_:
1491 if (! thy v_hasGetNrow ()) {
1492 formulaError (U"Attribute “nrow” not defined for this object", lexan [ilexan]. position);
1493 } else {
1494 newparse (NUMBER_);
1495 parsenumber (thy v_getNrow ());
1496 return;
1497 }
1498 case ROW_STR_:
1499 if (! thy v_hasGetRowStr ()) {
1500 formulaError (U"Attribute “row$” not defined for this object", lexan [ilexan]. position);
1501 } else {
1502 fit (OPENING_BRACKET_);
1503 parseExpression ();
1504 newparse (ROW_STR_);
1505 parse [iparse]. content.object = thee;
1506 fit (CLOSING_BRACKET_);
1507 return;
1508 }
1509 case COL_STR_:
1510 if (! thy v_hasGetColStr ()) {
1511 formulaError (U"Attribute “col$” not defined for this object", lexan [ilexan]. position);
1512 } else {
1513 fit (OPENING_BRACKET_);
1514 parseExpression ();
1515 newparse (COL_STR_);
1516 parse [iparse]. content.object = thee;
1517 fit (CLOSING_BRACKET_);
1518 return;
1519 }
1520 default: formulaError (U"Unknown attribute.", lexan [ilexan]. position);
1521 }
1522 } else {
1523 formulaError (U"After a name of a matrix there should be “(”, “[”, or “.”", lexan [ilexan]. position);
1524 }
1525 return;
1526 }
1527
1528 if (symbol == MATRIX_STR_) {
1529 const Daata thee = lexan [ilexan]. content.object;
1530 Melder_assert (thee != nullptr);
1531 symbol = newread;
1532 if (symbol == OPENING_BRACKET_) {
1533 if (newread == CLOSING_BRACKET_) {
1534 newparse (MATRIX0_STR_);
1535 parse [iparse]. content.object = thee;
1536 } else {
1537 oldread;
1538 parseExpression ();
1539 if (newread == COMMA_) {
1540 parseExpression ();
1541 newparse (MATRIX2_STR_);
1542 parse [iparse]. content.object = thee;
1543 fit (CLOSING_BRACKET_);
1544 } else {
1545 oldread;
1546 newparse (MATRIX1_STR_);
1547 parse [iparse]. content.object = thee;
1548 fit (CLOSING_BRACKET_);
1549 }
1550 }
1551 } else {
1552 formulaError (U"After a name of a matrix$ there should be “[”", lexan [ilexan]. position);
1553 }
1554 return;
1555 }
1556
1557 if (symbol >= LOW_FUNCTION_1 && symbol <= HIGH_FUNCTION_1) {
1558 const bool isParenthesis = fitArguments ();
1559 parseExpression ();
1560 if (isParenthesis)
1561 fit (CLOSING_PARENTHESIS_);
1562 newparse (symbol);
1563 return;
1564 }
1565
1566 if (symbol >= LOW_FUNCTION_2 && symbol <= HIGH_FUNCTION_2) {
1567 const bool isParenthesis = fitArguments ();
1568 parseExpression ();
1569 fit (COMMA_);
1570 parseExpression ();
1571 if (isParenthesis)
1572 fit (CLOSING_PARENTHESIS_);
1573 newparse (symbol);
1574 return;
1575 }
1576
1577 if (symbol >= LOW_FUNCTION_3 && symbol <= HIGH_FUNCTION_3) {
1578 const bool isParenthesis = fitArguments ();
1579 parseExpression ();
1580 fit (COMMA_);
1581 parseExpression ();
1582 fit (COMMA_);
1583 parseExpression ();
1584 if (isParenthesis)
1585 fit (CLOSING_PARENTHESIS_);
1586 newparse (symbol);
1587 return;
1588 }
1589
1590 if (symbol >= LOW_FUNCTION_4 && symbol <= HIGH_FUNCTION_4) {
1591 const bool isParenthesis = fitArguments ();
1592 parseExpression ();
1593 fit (COMMA_);
1594 parseExpression ();
1595 fit (COMMA_);
1596 parseExpression ();
1597 fit (COMMA_);
1598 parseExpression ();
1599 if (isParenthesis)
1600 fit (CLOSING_PARENTHESIS_);
1601 newparse (symbol);
1602 return;
1603 }
1604
1605 if (symbol >= LOW_FUNCTION_N && symbol <= HIGH_FUNCTION_N) {
1606 int n = 0;
1607 const bool isParenthesis = fitArguments ();
1608 if (newread != CLOSING_PARENTHESIS_) {
1609 oldread;
1610 parseExpression ();
1611 n ++;
1612 while (newread == COMMA_) {
1613 parseExpression ();
1614 n ++;
1615 }
1616 oldread;
1617 if (isParenthesis)
1618 fit (CLOSING_PARENTHESIS_);
1619 }
1620 newparse (NUMBER_); parsenumber (n);
1621 newparse (symbol);
1622 return;
1623 }
1624
1625 if (symbol == OPENING_BRACE_) {
1626 if (newread == CLOSING_BRACE_) {
1627 newparse (NUMBER_);
1628 parsenumber (0);
1629 newparse (TENSOR_LITERAL_);
1630 return;
1631 }
1632 oldread;
1633 parseExpression ();
1634 int n = 1;
1635 while (newread == COMMA_) {
1636 parseExpression ();
1637 n ++;
1638 }
1639 oldread;
1640 fit (CLOSING_BRACE_);
1641 newparse (NUMBER_);
1642 parsenumber (n);
1643 if (newread == OPENING_BRACKET_) {
1644 parseExpression ();
1645 //fit (COMMA_); // this would be for matrices
1646 //parseExpression ();
1647 fit (CLOSING_BRACKET_);
1648 newparse (TENSOR_LITERAL_CELL_);
1649 } else {
1650 oldread;
1651 newparse (TENSOR_LITERAL_);
1652 }
1653 return;
1654 }
1655
1656 if (symbol == CALL_) {
1657 char32 *procedureName = lexan [ilexan]. content.string; // reference copy!
1658 int n = 0;
1659 const bool isParenthesis = fitArguments ();
1660 if (newread != CLOSING_PARENTHESIS_) {
1661 oldread;
1662 parseExpression ();
1663 n ++;
1664 while (newread == COMMA_) {
1665 parseExpression ();
1666 n ++;
1667 }
1668 oldread;
1669 if (isParenthesis)
1670 fit (CLOSING_PARENTHESIS_);
1671 }
1672 newparse (NUMBER_); parsenumber (n);
1673 newparse (CALL_);
1674 parse [iparse]. content.string = procedureName;
1675 return;
1676 }
1677
1678 if (symbol >= LOW_STRING_FUNCTION && symbol <= HIGH_STRING_FUNCTION) {
1679 if (symbol >= LOW_FUNCTION_STR1 && symbol <= HIGH_FUNCTION_STR1) {
1680 const bool isParenthesis = fitArguments ();
1681 parseExpression ();
1682 if (isParenthesis)
1683 fit (CLOSING_PARENTHESIS_);
1684 } else if (symbol >= LOW_FUNCTION_STR2 && symbol <= HIGH_FUNCTION_STR2) {
1685 const bool isParenthesis = fitArguments ();
1686 parseExpression ();
1687 fit (COMMA_);
1688 parseExpression ();
1689 if (isParenthesis)
1690 fit (CLOSING_PARENTHESIS_);
1691 } else if (symbol >= LOW_FUNCTION_STR0 && symbol <= HIGH_FUNCTION_STR0) {
1692 fit (OPENING_PARENTHESIS_);
1693 fit (CLOSING_PARENTHESIS_);
1694 } else if (symbol == EXTRACT_WORD_STR_ || symbol == EXTRACT_LINE_STR_) {
1695 const bool isParenthesis = fitArguments ();
1696 parseExpression ();
1697 fit (COMMA_);
1698 parseExpression ();
1699 if (isParenthesis)
1700 fit (CLOSING_PARENTHESIS_);
1701 } else if (symbol == REPLACE_STR_ || symbol == REPLACE_REGEX_STR_) {
1702 const bool isParenthesis = fitArguments ();
1703 parseExpression ();
1704 fit (COMMA_);
1705 parseExpression ();
1706 fit (COMMA_);
1707 parseExpression ();
1708 fit (COMMA_);
1709 parseExpression ();
1710 if (isParenthesis)
1711 fit (CLOSING_PARENTHESIS_);
1712 } else {
1713 oldread; // needed for retry if we are going to be in a string comparison?
1714 formulaError (U"Function expected", lexan [ilexan + 1]. position);
1715 }
1716 newparse (symbol);
1717 return;
1718 }
1719
1720 if (symbol >= LOW_RANGE_FUNCTION && symbol <= HIGH_RANGE_FUNCTION) {
1721 if (symbol == SUM_OVER_) {
1722 //theOptimize = 1;
1723 newparse (NUMBER_);
1724 parsenumber (0.0); // initialize the sum
1725 const bool isParenthesis = fitArguments ();
1726 const integer symbol2 = newread;
1727 if (symbol2 == NUMERIC_VARIABLE_) { // an existing variable
1728 newparse (VARIABLE_REFERENCE_);
1729 InterpreterVariable loopVariable = lexan [ilexan]. content.variable;
1730 parse [iparse]. content.variable = loopVariable;
1731 } else if (symbol2 == VARIABLE_NAME_) { // a new variable
1732 InterpreterVariable loopVariable = Interpreter_lookUpVariable (theInterpreter, lexan [ilexan]. content.string);
1733 newparse (VARIABLE_REFERENCE_);
1734 parse [iparse]. content.variable = loopVariable;
1735 } else {
1736 formulaError (U"Numeric variable expected", lexan [ilexan]. position);
1737 }
1738 // now on stack: sum, loop variable
1739 if (newread == FROM_) {
1740 parseExpression ();
1741 } else {
1742 oldread;
1743 newparse (NUMBER_);
1744 parsenumber (1.0);
1745 }
1746 newparse (DECREMENT_AND_ASSIGN_); // this pushes the variable back on the stack
1747 // now on stack: sum, loop variable
1748 fit (TO_);
1749 parseExpression ();
1750 // now on stack: sum, loop variable, end value
1751 const integer startLabel = newlabel;
1752 const integer endLabel = newlabel;
1753 newparse (LABEL_);
1754 parselabel (startLabel);
1755 newparse (INCREMENT_GREATER_GOTO_);
1756 parselabel (endLabel);
1757 fit (COMMA_);
1758 parseExpression ();
1759 if (isParenthesis)
1760 fit (CLOSING_PARENTHESIS_);
1761 // now on stack: sum, loop variable, end value, value to add
1762 newparse (ADD_3DOWN_);
1763 // now on stack: sum, loop variable, end value
1764 newparse (GOTO_);
1765 parselabel (startLabel);
1766 newparse (LABEL_);
1767 parselabel (endLabel);
1768 newparse (POP_2_);
1769 // now on stack: sum
1770 return;
1771 }
1772 }
1773
1774 if (symbol == STOPWATCH_) {
1775 newparse (symbol);
1776 return;
1777 }
1778
1779 oldread; // needed for retry if we are going to be in a string comparison
1780 formulaError (U"Symbol misplaced", lexan [ilexan + 1]. position);
1781 }
1782
1783 static void parseFactor ();
1784
1785 static void parsePowerFactors () {
1786 if (newread == POWER_) {
1787 if (ilexan > 2 && lexan [ilexan - 2]. symbol == MINUS_ && lexan [ilexan - 1]. symbol == NUMBER_) {
1788 oldread;
1789 formulaError (U"Expressions like -3^4 are ambiguous; use (-3)^4 or -(3^4) or -(3)^4", lexan [ilexan + 1]. position);
1790 }
1791 parseFactor (); // like a^-b
1792 newparse (POWER_);
1793 }
1794 else
1795 oldread;
1796 }
1797
1798 static void parseMinus () {
1799 parsePowerFactor ();
1800 parsePowerFactors ();
1801 }
1802
1803 static void parseFactor () {
1804 if (newread == MINUS_) {
1805 parseFactor (); // there can be multiple consecutive minuses
1806 newparse (MINUS_);
1807 return;
1808 }
1809 oldread;
1810 parseMinus (); // like -a^b
1811 }
1812
1813 static void parseFactors () {
1814 const integer symbol = newread; // has to be local, because of recursion
1815 if (symbol == MUL_ || symbol == RDIV_ || symbol == IDIV_ || symbol == MOD_) {
1816 parseFactor ();
1817 newparse (symbol);
1818 parseFactors ();
1819 }
1820 else oldread;
1821 }
1822
1823 static void parseTerm () {
1824 parseFactor ();
1825 parseFactors ();
1826 }
1827
1828 static void parseTerms () {
1829 const integer symbol = newread;
1830 if (symbol == ADD_ || symbol == SUB_) {
1831 parseTerm ();
1832 newparse (symbol);
1833 parseTerms ();
1834 }
1835 else oldread;
1836 }
1837
1838 static void parseNot () {
1839 parseTerm ();
1840 parseTerms ();
1841 integer symbol = newread;
1842 if (symbol >= EQ_ && symbol <= GT_) {
1843 parseTerm ();
1844 parseTerms ();
1845 newparse (symbol);
1846 }
1847 else oldread;
1848 }
1849
1850 static void parseAnd () {
1851 if (newread == NOT_) {
1852 parseAnd (); // like not not not
1853 newparse (NOT_);
1854 return;
1855 }
1856 oldread;
1857 parseNot ();
1858 }
1859
1860 static void parseOr () {
1861 parseAnd ();
1862 if (newread == AND_) {
1863 integer falseLabel = newlabel;
1864 integer andLabel = newlabel;
1865 do {
1866 newparse (IFFALSE_); parselabel (falseLabel);
1867 parseAnd ();
1868 } while (newread == AND_);
1869 newparse (IFFALSE_); parselabel (falseLabel);
1870 newparse (TRUE_);
1871 newparse (GOTO_); parselabel (andLabel);
1872 newparse (LABEL_); parselabel (falseLabel);
1873 newparse (FALSE_);
1874 newparse (LABEL_); parselabel (andLabel);
1875 }
1876 oldread;
1877 }
1878
1879 static void parseExpression () {
1880 parseOr ();
1881 if (newread == OR_) {
1882 integer trueLabel = newlabel;
1883 integer orLabel = newlabel;
1884 do {
1885 newparse (IFTRUE_); parselabel (trueLabel);
1886 parseOr ();
1887 } while (newread == OR_);
1888 newparse (IFTRUE_); parselabel (trueLabel);
1889 newparse (FALSE_);
1890 newparse (GOTO_); parselabel (orLabel);
1891 newparse (LABEL_); parselabel (trueLabel);
1892 newparse (TRUE_);
1893 newparse (LABEL_); parselabel (orLabel);
1894 }
1895 oldread;
1896 }
1897
1898 /*
1899 Translate the infix expression "my lexan" into the postfix expression "my parse":
1900 remove parentheses and brackets, commas, colons, FROM_, TO_,
1901 IF_ THEN_ ELSE_ ENDIF_ OR_ AND_;
1902 introduce LABEL_ GOTO_ IFTRUE_ IFFALSE_ TRUE_ FALSE_
1903 SELF0_ SELF1_ SELF2_ MATRIX0_ MATRIX1_ MATRIX2_
1904 Return:
1905 0 if error, otherwise 1.
1906 Precondition:
1907 "my lexan" contains an END_ symbol.
1908 Postconditions:
1909 *my lexan not changed.
1910 result == 0 || my parse [my numberOfInstructions]. symbol == END_
1911 */
1912
1913 static void Formula_parseExpression () {
1914 ilabel = ilexan = iparse = 0;
1915 if (lexan [1]. symbol == END_)
1916 Melder_throw (U"Empty formula.");
1917 parseExpression ();
1918 fit (END_);
1919 newparse (END_);
1920 numberOfInstructions = iparse;
1921 }
1922
1923 static void shift (integer begin, integer distance) {
1924 numberOfInstructions -= distance;
1925 for (integer j = begin; j <= numberOfInstructions; j ++)
1926 parse [j] = parse [j + distance];
1927 }
1928
1929 static integer findLabel (integer label) {
1930 integer result = numberOfInstructions;
1931 while (parse [result]. symbol != LABEL_ ||
1932 parse [result]. content.label != label)
1933 result --;
1934 return result;
1935 }
1936
1937 static void Formula_optimizeFlow ()
1938 /* Vereenvoudig boolse uitdrukkingen. */
1939 /* Nadien: */
1940 /* de stroom volgt het kortste pad; */
1941 /* als de rekenkundige waarden van boolse uitdrukkingen */
1942 /* in de formule niet voorkomen, zijn alle TRUE_s en FALSE_s weg; */
1943 /* als in de formule geen NOT_s voorkwamen op rekenkundige */
1944 /* uitdrukkingen, zijn alle NOT_s weg; */
1945 /* onbereikbare kode is weg; */
1946 {
1947 integer i, j, volg;
1948 for (;;) {
1949 bool improved = false;
1950 for (i = 1; i <= numberOfInstructions; i ++)
1951 {
1952
1953 /* Optimalisatie 1: */
1954 /* true goto x -> goto y / __ ... label x iftrue y */
1955 /* false goto x -> goto y / __ ... label x iffalse y */
1956
1957 if ((parse [i]. symbol == TRUE_ &&
1958 parse [i + 1]. symbol == GOTO_ &&
1959 parse [volg = findLabel (parse [i + 1]. content.label) + 1]
1960 . symbol == IFTRUE_)
1961 ||
1962 (parse [i]. symbol == FALSE_ &&
1963 parse [i + 1]. symbol == GOTO_ &&
1964 parse [volg = findLabel (parse [i + 1]. content.label) + 1]
1965 . symbol == IFFALSE_))
1966 {
1967 improved = true;
1968 parse [i]. symbol = GOTO_;
1969 parse [i]. content.label = parse [volg]. content.label;
1970 shift (i + 1, 1);
1971 }
1972
1973 /* Optimalisatie 2: */
1974 /* true goto x ... label x iffalse y -> */
1975 /* goto z ... label x iffalse y label z */
1976 /* en analoog met false en iftrue. */
1977
1978 if ((parse [i]. symbol == TRUE_ &&
1979 parse [i + 1]. symbol == GOTO_ &&
1980 parse [volg = findLabel (parse [i + 1]. content.label) + 1]
1981 . symbol == IFFALSE_)
1982 ||
1983 (parse [i]. symbol == FALSE_ &&
1984 parse [i + 1]. symbol == GOTO_ &&
1985 parse [volg = findLabel (parse [i + 1]. content.label) + 1]
1986 . symbol == IFTRUE_))
1987 {
1988 improved = true;
1989 parse [i]. symbol = GOTO_;
1990 parse [i]. content.label = newlabel;
1991 for (j = i + 1; j < volg; j ++)
1992 parse [j] = parse [j + 1];
1993 parse [volg]. symbol = LABEL_;
1994 parse [volg]. content.label = ilabel;
1995 }
1996
1997 /* Optimalisatie 3a: */
1998 /* iftrue x goto y label x -> iffalse y label x */
1999
2000 if (parse [i]. symbol == IFTRUE_ &&
2001 parse [i + 1]. symbol == GOTO_ &&
2002 parse [i + 2]. symbol == LABEL_ &&
2003 parse [i]. content.label == parse [i + 2]. content.label)
2004 {
2005 improved = true;
2006 parse [i]. symbol = IFFALSE_;
2007 parse [i]. content.label = parse [i + 1]. content.label;
2008 shift (i + 1, 1);
2009 }
2010
2011 /* Optimalisatie 3b: */
2012 /* iffalse x goto y label x -> iftrue y label x */
2013
2014 if (parse [i]. symbol == IFFALSE_ &&
2015 parse [i + 1]. symbol == GOTO_ &&
2016 parse [i + 2]. symbol == LABEL_ &&
2017 parse [i]. content.label == parse [i + 2]. content.label)
2018 {
2019 improved = true;
2020 parse [i]. symbol = IFTRUE_;
2021 parse [i]. content.label = parse [i + 1]. content.label;
2022 shift (i + 1, 1);
2023 }
2024
2025 /* Optimalisatie 4: */
2026 /* verwijder onbereikbare kode: na een GOTO_ hoort een LABEL_. */
2027
2028 if (parse [i]. symbol == GOTO_ &&
2029 parse [i + 1]. symbol != LABEL_)
2030 {
2031 improved = true;
2032 j = i + 2;
2033 while (parse [j]. symbol != LABEL_) j ++;
2034 shift (i + 1, j - i - 1);
2035 }
2036
2037 /* Optimalisatie 5: */
2038 /* goto x -> 0 / __ label x */
2039
2040 if (parse [i]. symbol == GOTO_ &&
2041 parse [i]. symbol == LABEL_ &&
2042 parse [i]. content.label == parse [i + 1]. content.label)
2043 {
2044 improved = true;
2045 shift (i, 1);
2046 }
2047
2048 /* Optimalisatie 6: */
2049 /* true iffalse x -> 0 */
2050 /* false iftrue x -> 0 */
2051
2052 if ((parse [i]. symbol == TRUE_ && parse [i + 1]. symbol == IFFALSE_)
2053 || (parse [i]. symbol == FALSE_ && parse [i + 1]. symbol == IFTRUE_))
2054 {
2055 improved = true;
2056 shift (i, 2);
2057 }
2058
2059 /* Optimalisatie 7: */
2060 /* true iftrue x -> goto x */
2061 /* false iffalse x -> goto x */
2062
2063 if ((parse [i]. symbol == TRUE_ && parse [i + 1]. symbol == IFTRUE_)
2064 || (parse [i]. symbol == FALSE_ && parse [i + 1]. symbol == IFFALSE_))
2065 {
2066 improved = true;
2067 parse [i]. symbol = GOTO_;
2068 parse [i]. content.label = parse [i + 1]. content.label;
2069 shift (i + 1, 1);
2070 }
2071
2072 /* Optimalisatie 8: */
2073 /* iftrue x -> iftrue y / __ ... label x goto y */
2074 /* iffalse x -> iffalse y / __ ... label x goto y */
2075
2076 if ((parse [i]. symbol == IFTRUE_ || parse [i]. symbol == IFFALSE_)
2077 && parse [volg = findLabel (parse [i]. content.label) + 1]. symbol == GOTO_)
2078 {
2079 improved = true;
2080 parse [i]. content.label = parse [volg]. content.label;
2081 }
2082
2083 /* Optimalisatie 9a: */
2084 /* not iftrue x -> iffalse x */
2085
2086 if (parse [i]. symbol == NOT_ && parse [i + 1]. symbol == IFTRUE_)
2087 {
2088 improved = true;
2089 parse [i]. symbol = IFFALSE_;
2090 parse [i]. content.label = parse [i + 1]. content.label;
2091 shift (i + 1, 1);
2092 }
2093
2094 /* Optimalisatie 9b: */
2095 /* not iffalse x -> iftrue x */
2096
2097 if (parse [i]. symbol == NOT_ && parse [i + 1]. symbol == IFFALSE_)
2098 {
2099 improved = true;
2100 parse [i]. symbol = IFTRUE_;
2101 parse [i]. content.label = parse [i + 1]. content.label;
2102 shift (i + 1, 1);
2103 }
2104
2105 /* De volgende optimalisaties ontbreken want zijn hier overbodig: */
2106 /* goto x -> goto y / __ ... label x goto y */
2107 /* trek twee opeenvolgende labels samen */
2108
2109 } /* for i */
2110
2111 /* Verwijder labels waar niet naar verwezen wordt. */
2112
2113 for (i = 1; i <= numberOfInstructions; i ++)
2114 if (parse [i]. symbol == LABEL_)
2115 {
2116 bool found = false;
2117 for (j = 1; j <= numberOfInstructions; j ++)
2118 if ((parse [j]. symbol == GOTO_ || parse [j]. symbol == IFFALSE_ || parse [j]. symbol == IFTRUE_
2119 || parse [j]. symbol == INCREMENT_GREATER_GOTO_)
2120 && parse [i]. content.label == parse [j]. content.label)
2121 found = true;
2122 if (! found)
2123 {
2124 improved = true;
2125 shift (i, 1);
2126 }
2127 }
2128 if (! improved)
2129 break;
2130 }
2131 }
2132
2133 static integer praat_findObjectById (integer id) {
2134 integer IOBJECT;
2135 WHERE_DOWN (ID == id)
2136 return IOBJECT;
2137 Melder_throw (U"No object with number ", id, U".");
2138 }
2139
2140 static integer praat_findObjectByName (conststring32 name) {
2141 integer IOBJECT;
2142 if (*name >= U'A' && *name <= U'Z') {
2143 static MelderString buffer;
2144 MelderString_copy (& buffer, name);
2145 char32 *spaceLocation = str32chr (buffer.string, U' ');
2146 if (! spaceLocation)
2147 Melder_throw (U"Missing space in object name “", name, U"”.");
2148 *spaceLocation = U'\0';
2149 conststring32 className = & buffer.string [0], givenName = spaceLocation + 1;
2150 WHERE_DOWN (1) {
2151 Daata object = OBJECT;
2152 if (str32equ (className, Thing_className (OBJECT)) && str32equ (givenName, object -> name.get()))
2153 return IOBJECT;
2154 }
2155 ClassInfo klas = Thing_classFromClassName (className, nullptr);
2156 WHERE_DOWN (1) {
2157 Daata object = OBJECT;
2158 if (str32equ (klas -> className, Thing_className (OBJECT)) && str32equ (givenName, object -> name.get()))
2159 return IOBJECT;
2160 }
2161 }
2162 Melder_throw (U"No object with name “", name, U"”.");
2163 }
2164
2165 static void Formula_evaluateConstants () {
2166 for (;;) {
2167 bool improved = false;
2168 for (integer i = 1; i <= numberOfInstructions; i ++) {
2169 integer gain = 0;
2170 if (parse [i]. symbol == NUMBER_) {
2171 if (parse [i]. content.number == 2.0 && parse [i + 1]. symbol == POWER_)
2172 { gain = 1; parse [i]. symbol = SQR_; }
2173 else if (parse [i + 1]. symbol == MINUS_)
2174 { gain = 1; parse [i]. content.number = - parse [i]. content.number; }
2175 else if (parse [i + 1]. symbol == SQR_)
2176 { gain = 1; parse [i]. content.number *= parse [i]. content.number; }
2177 else if (parse [i + 1]. symbol == NUMBER_) {
2178 if (parse [i + 2]. symbol == ADD_)
2179 { gain = 2; parse [i]. content.number += parse [i + 1]. content.number; }
2180 else if (parse [i + 2]. symbol == SUB_)
2181 { gain = 2; parse [i]. content.number -= parse [i + 1]. content.number; }
2182 else if (parse [i + 2]. symbol == MUL_)
2183 { gain = 2; parse [i]. content.number *= parse [i + 1]. content.number; }
2184 else if (parse [i + 2]. symbol == RDIV_)
2185 { gain = 2; parse [i]. content.number /= parse [i + 1]. content.number; }
2186 } else if (parse [i + 1]. symbol == TO_OBJECT_) {
2187 parse [i]. symbol = OBJECT_;
2188 integer IOBJECT = praat_findObjectById (Melder_iround (parse [i]. content.number));
2189 parse [i]. content.object = OBJECT;
2190 gain = 1;
2191 }
2192 } else if (parse [i]. symbol == STRING_) {
2193 if (parse [i + 1]. symbol == TO_OBJECT_) {
2194 parse [i]. symbol = OBJECT_;
2195 const integer IOBJECT = praat_findObjectByName (parse [i]. content.string);
2196 parse [i]. content.object = OBJECT;
2197 gain = 1;
2198 }
2199 } else if (parse [i]. symbol == NUMERIC_VARIABLE_) {
2200 parse [i]. symbol = NUMBER_;
2201 parse [i]. content.number = parse [i]. content.variable -> numericValue;
2202 gain = 0;
2203 improved = true;
2204 } else if (parse [i]. symbol == STRING_VARIABLE_) {
2205 parse [i]. symbol = STRING_;
2206 parse [i]. content.string = parse [i]. content.variable -> stringValue.get(); // again a reference copy (lexan is still the owner)
2207 gain = 0;
2208 improved = true;
2209 #if 0
2210 } else if (parse [i]. symbol == ROW_) {
2211 if (parse [i + 1]. symbol == COL_ && parse [i + 2]. symbol == SELFMATRIX2_)
2212 { gain = 2; parse [i]. symbol = SELF0_; } // TODO: SELF0_ may not have the same restrictions as SELFMATRIX2_
2213 } else if (parse [i]. symbol == COL_) {
2214 if (parse [i + 1]. symbol == SELFMATRIX1_)
2215 { gain = 1; parse [i]. symbol = SELF0_; }
2216 #endif
2217 }
2218 if (gain > 0) {
2219 improved = true;
2220 shift (i + 1, gain);
2221 }
2222 }
2223 if (! improved)
2224 break;
2225 }
2226 }
2227
2228 static void Formula_removeLabels () {
2229 /*
2230 First translate symbolic labels (< 0) into instructions locations (> 0).
2231 */
2232 for (integer i = 1; i <= numberOfInstructions; i ++) {
2233 const integer symboli = parse [i]. symbol;
2234 if (symboli == GOTO_ || symboli == IFTRUE_ || symboli == IFFALSE_ || symboli == INCREMENT_GREATER_GOTO_) {
2235 integer label = parse [i]. content.label;
2236 for (int j = 1; j <= numberOfInstructions; j ++) {
2237 if (parse [j]. symbol == LABEL_ && parse [j]. content.label == label) {
2238 parse [i]. content.label = j;
2239 }
2240 }
2241 }
2242 }
2243 /*
2244 Then remove the labels,
2245 which have become superfluous.
2246 */
2247 if (theOptimize) {
2248 integer i = 1;
2249 while (i <= numberOfInstructions) {
2250 const integer symboli = parse [i]. symbol;
2251 if (symboli == LABEL_) {
2252 shift (i, 1); // remove one label
2253 for (int j = 1; j <= numberOfInstructions; j ++) {
2254 const integer symbolj = parse [j]. symbol;
2255 if ((symbolj == GOTO_ || symbolj == IFTRUE_ || symbolj == IFFALSE_ || symbolj == INCREMENT_GREATER_GOTO_) && parse [j]. content.label > i)
2256 parse [j]. content.label --; /* Pas een label aan. */
2257 }
2258 i --; // voorkom ophogen i (overbodig?)
2259 }
2260 i ++;
2261 }
2262 }
2263 numberOfInstructions --; /* Het END_-symbol hoeft niet geinterpreteerd. */
2264 }
2265
2266 #include <inttypes.h>
2267
2268 /*
2269 For debugging.
2270 */
2271 static void Formula_print (FormulaInstruction f) {
2272 integer i = 0, symbol;
2273 do {
2274 conststring32 instructionName;
2275 symbol = f [++ i]. symbol;
2276 instructionName = Formula_instructionNames [symbol];
2277 if (symbol == NUMBER_)
2278 Melder_casual (i, U" ", instructionName, U" ", f [i]. content.number);
2279 else if (symbol == GOTO_ || symbol == IFFALSE_ || symbol == IFTRUE_ || symbol == LABEL_ || symbol == INCREMENT_GREATER_GOTO_)
2280 Melder_casual (i, U" ", instructionName, U" ", f [i]. content.label);
2281 else if (symbol == NUMERIC_VARIABLE_)
2282 Melder_casual (i, U" ", instructionName, U" ", f [i]. content.variable -> string.get(), U" ", f [i]. content.variable -> numericValue);
2283 else if (symbol == STRING_VARIABLE_)
2284 Melder_casual (i, U" ", instructionName, U" ", f [i]. content.variable -> string.get(), U" ", f [i]. content.variable -> stringValue.get());
2285 else if (symbol == STRING_ || symbol == VARIABLE_NAME_ || symbol == INDEXED_NUMERIC_VARIABLE_ || symbol == INDEXED_STRING_VARIABLE_)
2286 Melder_casual (i, U" ", instructionName, U" ", f [i]. content.string);
2287 else if (symbol == MATRIX_ || symbol == MATRIX_STR_ || symbol == MATRIX1_ || symbol == MATRIX1_STR_ ||
2288 symbol == MATRIX2_ || symbol == MATRIX2_STR_ || symbol == ROW_STR_ || symbol == COL_STR_)
2289 {
2290 Thing object = f [i]. content.object;
2291 if (object) {
2292 Melder_casual (i, U" ", instructionName, U" ", Thing_className (object), U" ", object -> name.get());
2293 } else {
2294 Melder_casual (i, U" ", instructionName);
2295 }
2296 }
2297 else if (symbol == CALL_)
2298 Melder_casual (i, U" ", instructionName, U" ", f [i]. content.string);
2299 else
2300 Melder_casual (i, U" ", instructionName);
2301 } while (symbol != END_);
2302 }
2303
2304 void Formula_compile (Interpreter interpreter, Daata data, conststring32 expression, int expressionType, bool optimize) {
2305 if (interpreter)
2306 Melder_assert (interpreter -> owningInterpreterStack);
2307 theInterpreter = interpreter;
2308 if (! theInterpreter) {
2309 if (! theLocalInterpreterStack) {
2310 theLocalInterpreterStack = InterpreterStack_create (nullptr);
2311 theLocalInterpreterStack -> interpreters [1] = Interpreter_createFromEnvironment (
2312 theLocalInterpreterStack.get(),
2313 Editor (nullptr),
2314 MelderFile (nullptr)
2315 );
2316 }
2317 theInterpreter = theLocalInterpreterStack -> interpreters [1].get();
2318 theInterpreter -> owningInterpreterStack = theLocalInterpreterStack.get();
2319 theInterpreter -> variablesMap. clear ();
2320 }
2321 theSource = data;
2322 theExpression = expression;
2323 theExpressionType [theLevel] = expressionType;
2324 theOptimize = optimize;
2325 if (! lexan) {
2326 lexan = Melder_calloc_f (structFormulaInstruction, Formula_MAXIMUM_STACK_SIZE);
2327 lexan [Formula_MAXIMUM_STACK_SIZE - 1]. symbol = END_; // make sure that cleaning up always terminates
2328 }
2329 if (! parse)
2330 parse = Melder_calloc_f (structFormulaInstruction, Formula_MAXIMUM_STACK_SIZE);
2331
2332 /*
2333 Clean up strings from the previous call.
2334 These strings are in a union, that's why this cannot be done later, when a new string is created.
2335 */
2336 if (numberOfStringConstants) {
2337 ilexan = 1;
2338 for (;;) {
2339 integer symbol = lexan [ilexan]. symbol;
2340 if (symbol == STRING_ ||
2341 symbol == VARIABLE_NAME_ ||
2342 symbol == INDEXED_NUMERIC_VARIABLE_ ||
2343 symbol == INDEXED_STRING_VARIABLE_ ||
2344 symbol == CALL_
2345 ) {
2346 Melder_free (lexan [ilexan]. content.string);
2347 }
2348 else if (symbol == END_) break; // either the end of a formula, or the end of lexan
2349 ilexan ++;
2350 }
2351 numberOfStringConstants = 0;
2352 }
2353
2354 Formula_lexan ();
2355 if (Melder_debug == 17) Formula_print (lexan);
2356 Formula_parseExpression ();
2357 if (Melder_debug == 17) Formula_print (parse);
2358 if (theOptimize) {
2359 Formula_optimizeFlow ();
2360 if (Melder_debug == 17) Formula_print (parse);
2361 Formula_evaluateConstants ();
2362 if (Melder_debug == 17) Formula_print (parse);
2363 }
2364 Formula_removeLabels ();
2365 if (Melder_debug == 17) Formula_print (parse);
2366 }
2367
2368 /*
2369 Running.
2370 */
2371
2372 conststring32 structStackel :: whichText () {
2373 return
2374 our which == Stackel_NUMBER ? U"a number" :
2375 our which == Stackel_NUMERIC_VECTOR ? U"a numeric vector" :
2376 our which == Stackel_NUMERIC_MATRIX ? U"a numeric matrix" :
2377 our which == Stackel_STRING ? U"a string" :
2378 our which == Stackel_STRING_ARRAY ? U"a string vector" :
2379 our which == Stackel_OBJECT ? U"an object" :
2380 U"???";
2381 }
2382
2383 static integer programPointer;
2384
2385 static Stackel theStack;
2386 static integer stackPointer, stackPointerMax;
2387 #define pop & theStack [stackPointer --]
2388 #define topOfStack & theStack [stackPointer]
2389 inline static void pushNumber (const double x) {
2390 /* inline runs 10 to 20 percent faster; here's the test script:
2391 stopwatch
2392 Create Sound from formula: "test", 1, 0.0, 1000.0, 44100, ~ x + 1 + 2 + 3 + 4 + 5 + 6
2393 writeInfoLine: stopwatch
2394 Remove
2395 * Mac: 3.76 -> 3.20 seconds
2396 */
2397 if (++ stackPointer > stackPointerMax)
2398 if (++ stackPointerMax > Formula_MAXIMUM_STACK_SIZE)
2399 Melder_throw (U"Formula: stack overflow. Please simplify your formulas.");
2400 const Stackel stackel = & theStack [stackPointer];
2401 stackel -> reset();
2402 stackel -> which = Stackel_NUMBER;
2403 stackel -> number = ( isdefined (x) ? x : undefined );
2404 //stackel -> number = x; // this one would be 2 percent faster
2405 //stackel -> owned = true; // superfluous, because never checked (2020-12-20)
2406 }
2407 static void pushNumericVector (autoVEC x) {
2408 if (++ stackPointer > stackPointerMax)
2409 if (++ stackPointerMax > Formula_MAXIMUM_STACK_SIZE)
2410 Melder_throw (U"Formula: stack overflow. Please simplify your formulas.");
2411 const Stackel stackel = & theStack [stackPointer];
2412 stackel -> reset();
2413 stackel -> which = Stackel_NUMERIC_VECTOR;
2414 stackel -> numericVector = x.releaseToAmbiguousOwner();
2415 stackel -> owned = true;
2416 }
2417 static void pushNumericVectorReference (VEC x) {
2418 if (++ stackPointer > stackPointerMax)
2419 if (++ stackPointerMax > Formula_MAXIMUM_STACK_SIZE)
2420 Melder_throw (U"Formula: stack overflow. Please simplify your formulas.");
2421 const Stackel stackel = & theStack [stackPointer];
2422 stackel -> reset();
2423 stackel -> which = Stackel_NUMERIC_VECTOR;
2424 stackel -> numericVector = x;
2425 stackel -> owned = false;
2426 }
2427 static void pushNumericMatrix (autoMAT x) {
2428 if (++ stackPointer > stackPointerMax)
2429 if (++ stackPointerMax > Formula_MAXIMUM_STACK_SIZE)
2430 Melder_throw (U"Formula: stack overflow. Please simplify your formulas.");
2431 const Stackel stackel = & theStack [stackPointer];
2432 stackel -> reset();
2433 stackel -> which = Stackel_NUMERIC_MATRIX;
2434 stackel -> numericMatrix = x.releaseToAmbiguousOwner();
2435 stackel -> owned = true;
2436 }
2437 static void pushNumericMatrixReference (MAT x) {
2438 if (++ stackPointer > stackPointerMax)
2439 if (++ stackPointerMax > Formula_MAXIMUM_STACK_SIZE)
2440 Melder_throw (U"Formula: stack overflow. Please simplify your formulas.");
2441 const Stackel stackel = & theStack [stackPointer];
2442 stackel -> reset();
2443 stackel -> which = Stackel_NUMERIC_MATRIX;
2444 stackel -> numericMatrix = x;
2445 stackel -> owned = false;
2446 }
2447 static void pushString (autostring32 x) {
2448 if (++ stackPointer > stackPointerMax)
2449 if (++ stackPointerMax > Formula_MAXIMUM_STACK_SIZE)
2450 Melder_throw (U"Formula: stack overflow. Please simplify your formulas.");
2451 const Stackel stackel = & theStack [stackPointer];
2452 //stackel -> reset(); // incorporated in next statement
2453 stackel -> setString (x.move());
2454 //stackel -> owned = true; // superfluous, because never checked (2020-12-20)
2455 }
2456 static void pushStringVector (autoSTRVEC x) {
2457 if (++ stackPointer > stackPointerMax)
2458 if (++ stackPointerMax > Formula_MAXIMUM_STACK_SIZE)
2459 Melder_throw (U"Formula: stack overflow. Please simplify your formulas.");
2460 const Stackel stackel = & theStack [stackPointer];
2461 stackel -> reset();
2462 stackel -> which = Stackel_STRING_ARRAY;
2463 stackel -> stringArray = x.releaseToAmbiguousOwner();
2464 stackel -> owned = true;
2465 }
2466 static void pushStringVectorReference (STRVEC x) {
2467 if (++ stackPointer > stackPointerMax)
2468 if (++ stackPointerMax > Formula_MAXIMUM_STACK_SIZE)
2469 Melder_throw (U"Formula: stack overflow. Please simplify your formulas.");
2470 const Stackel stackel = & theStack [stackPointer];
2471 stackel -> reset();
2472 stackel -> which = Stackel_STRING_ARRAY;
2473 stackel -> stringArray = x;
2474 stackel -> owned = false;
2475 }
2476 static void pushObject (Daata object) {
2477 if (++ stackPointer > stackPointerMax)
2478 if (++ stackPointerMax > Formula_MAXIMUM_STACK_SIZE)
2479 Melder_throw (U"Formula: stack overflow. Please simplify your formulas.");
2480 const Stackel stackel = & theStack [stackPointer];
2481 stackel -> reset();
2482 stackel -> which = Stackel_OBJECT;
2483 stackel -> object = object;
2484 //stackel -> owned = false; // superfluous, because never checked (2020-12-20)
2485 }
2486 static void pushVariable (InterpreterVariable var) {
2487 if (++ stackPointer > stackPointerMax)
2488 if (++ stackPointerMax > Formula_MAXIMUM_STACK_SIZE)
2489 Melder_throw (U"Formula: stack overflow. Please simplify your formulas.");
2490 const Stackel stackel = & theStack [stackPointer];
2491 stackel -> reset();
2492 stackel -> which = Stackel_VARIABLE;
2493 stackel -> variable = var;
2494 //stackel -> owned = false; // superfluous, because never checked (2020-12-20)
2495 }
2496
2497 static void do_not () {
2498 const Stackel x = pop;
2499 if (x->which == Stackel_NUMBER) {
2500 pushNumber (isundef (x->number) ? undefined : x->number == 0.0 ? 1.0 : 0.0);
2501 } else {
2502 Melder_throw (U"Cannot negate (“not”) ", x->whichText(), U".");
2503 }
2504 }
2505 static void do_eq () {
2506 const Stackel y = pop, x = pop;
2507 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
2508 /*
2509 It is possible that we are comparing a value against --undefined--.
2510 Any defined value is unequal to --undefined--,
2511 but any undefined value (inf or NaN) *is* equal to --undefined--.
2512 Note that this is different from how "==" works in C.
2513 */
2514 pushNumber (NUMequal (x->number, y->number) ? 1.0 : 0.0);
2515 } else if (x->which == Stackel_STRING && y->which == Stackel_STRING) {
2516 pushNumber (str32equ (x->getString(), y->getString()) ? 1.0 : 0.0);
2517 } else if (x->which == Stackel_NUMERIC_VECTOR && y->which == Stackel_NUMERIC_VECTOR) {
2518 pushNumber (NUMequal (x->numericVector, y->numericVector) ? 1.0 : 0.0);
2519 } else if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
2520 pushNumber (NUMequal (x->numericMatrix, y->numericMatrix) ? 1.0 : 0.0);
2521 } else if (x->which == Stackel_STRING_ARRAY && y->which == Stackel_STRING_ARRAY) {
2522 pushNumber (NUMequal (x->stringArray, y->stringArray) ? 1.0 : 0.0);
2523 } else {
2524 Melder_throw (U"Cannot compare (=) ", x->whichText(), U" to ", y->whichText(), U".");
2525 }
2526 }
2527 static void do_ne () {
2528 const Stackel y = pop, x = pop;
2529 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
2530 /*
2531 Unequal is defined as the opposite of equal.
2532 */
2533 pushNumber (NUMequal (x->number, y->number) ? 0.0 : 1.0);
2534 } else if (x->which == Stackel_STRING && y->which == Stackel_STRING) {
2535 pushNumber (str32equ (x->getString(), y->getString()) ? 0.0 : 1.0);
2536 } else if (x->which == Stackel_NUMERIC_VECTOR && y->which == Stackel_NUMERIC_VECTOR) {
2537 pushNumber (NUMequal (x->numericVector, y->numericVector) ? 0.0 : 1.0);
2538 } else if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
2539 pushNumber (NUMequal (x->numericMatrix, y->numericMatrix) ? 0.0 : 1.0);
2540 } else if (x->which == Stackel_STRING_ARRAY && y->which == Stackel_STRING_ARRAY) {
2541 pushNumber (NUMequal (x->stringArray, y->stringArray) ? 0.0 : 1.0);
2542 } else {
2543 Melder_throw (U"Cannot compare (<>) ", x->whichText(), U" to ", y->whichText(), U".");
2544 }
2545 }
2546 static void do_le () {
2547 const Stackel y = pop, x = pop;
2548 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
2549 double xvalue = x->number, yvalue = y->number;
2550 if (isdefined (xvalue)) {
2551 if (isdefined (yvalue)) {
2552 pushNumber (x->number <= y->number ? 1.0 : 0.0);
2553 } else {
2554 pushNumber (0.0); // defined is not equal to, nor less than, undefined
2555 }
2556 } else {
2557 if (isdefined (yvalue)) {
2558 pushNumber (0.0); // undefined is not equal to, nor less than, defined
2559 } else {
2560 pushNumber (1.0); // undefined is equal to undefined
2561 }
2562 }
2563 } else if (x->which == Stackel_STRING && y->which == Stackel_STRING) {
2564 const double result = str32cmp (x->getString(), y->getString()) <= 0 ? 1.0 : 0.0;
2565 pushNumber (result);
2566 } else {
2567 Melder_throw (U"Cannot compare (<=) ", x->whichText(), U" to ", y->whichText(), U".");
2568 }
2569 }
2570 static void do_lt () {
2571 const Stackel y = pop, x = pop;
2572 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
2573 double xvalue = x->number, yvalue = y->number;
2574 if (isdefined (xvalue)) {
2575 if (isdefined (yvalue)) {
2576 pushNumber (x->number < y->number ? 1.0 : 0.0);
2577 } else {
2578 pushNumber (0.0); // defined is not less than undefined
2579 }
2580 } else {
2581 if (isdefined (yvalue)) {
2582 pushNumber (0.0); // undefined is not less than defined
2583 } else {
2584 pushNumber (0.0); // undefined is not less than undefined
2585 }
2586 }
2587 } else if (x->which == Stackel_STRING && y->which == Stackel_STRING) {
2588 const double result = str32cmp (x->getString(), y->getString()) < 0 ? 1.0 : 0.0;
2589 pushNumber (result);
2590 } else {
2591 Melder_throw (U"Cannot compare (<) ", x->whichText(), U" to ", y->whichText(), U".");
2592 }
2593 }
2594 static void do_ge () {
2595 const Stackel y = pop, x = pop;
2596 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
2597 const double xvalue = x->number, yvalue = y->number;
2598 if (isdefined (xvalue)) {
2599 if (isdefined (yvalue)) {
2600 pushNumber (x->number >= y->number ? 1.0 : 0.0);
2601 } else {
2602 pushNumber (0.0); // defined is not equal to, nor greater than, undefined
2603 }
2604 } else {
2605 if (isdefined (yvalue)) {
2606 pushNumber (0.0); // undefined is not equal to, nor greater than, defined
2607 } else {
2608 pushNumber (1.0); // undefined is equal to undefined
2609 }
2610 }
2611 } else if (x->which == Stackel_STRING && y->which == Stackel_STRING) {
2612 const double result = str32cmp (x->getString(), y->getString()) >= 0 ? 1.0 : 0.0;
2613 pushNumber (result);
2614 } else {
2615 Melder_throw (U"Cannot compare (>=) ", x->whichText(), U" to ", y->whichText(), U".");
2616 }
2617 }
2618 static void do_gt () {
2619 const Stackel y = pop, x = pop;
2620 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
2621 const double xvalue = x->number, yvalue = y->number;
2622 if (isdefined (xvalue)) {
2623 if (isdefined (yvalue)) {
2624 pushNumber (x->number > y->number ? 1.0 : 0.0);
2625 } else {
2626 pushNumber (0.0); // defined is not greater than undefined
2627 }
2628 } else {
2629 if (isdefined (yvalue)) {
2630 pushNumber (0.0); // undefined is not greater than defined
2631 } else {
2632 pushNumber (0.0); // undefined is not greater than undefined
2633 }
2634 }
2635 } else if (x->which == Stackel_STRING && y->which == Stackel_STRING) {
2636 const double result = str32cmp (x->getString(), y->getString()) > 0 ? 1.0 : 0.0;
2637 pushNumber (result);
2638 } else {
2639 Melder_throw (U"Cannot compare (>) ", x->whichText(), U" to ", y->whichText(), U".");
2640 }
2641 }
2642 inline static void moveNumericVector (Stackel from, Stackel to) {
2643 //Melder_assert (from -> owned);
2644 //Melder_assert (to -> which == Stackel_NUMERIC_VECTOR);
2645 from -> owned = false;
2646 to -> numericVector = from -> numericVector;
2647 to -> owned = true;
2648 }
2649 inline static void moveNumericMatrix (Stackel from, Stackel to) {
2650 //Melder_assert (from -> owned);
2651 //Melder_assert (to -> which == Stackel_NUMERIC_MATRIX);
2652 from -> owned = false;
2653 to -> numericMatrix = from -> numericMatrix;
2654 to -> owned = true;
2655 }
2656
2657 static void do_add () {
2658 /*
2659 result.. = x.. + y..
2660 */
2661 const Stackel y = pop, x = topOfStack;
2662 if (x->which == Stackel_NUMBER) {
2663 if (y->which == Stackel_NUMBER) {
2664 /*@praat
2665 #
2666 # result = x + y
2667 #
2668 x = 5
2669 y = 6
2670 result = x + y
2671 assert result = 11
2672 @*/
2673 x->number += y->number;
2674 //x->which = Stackel_NUMBER; // superfluous, as is cleaning up
2675 return;
2676 }
2677 if (y->which == Stackel_NUMERIC_VECTOR) {
2678 /*
2679 result# = x + y#
2680 */
2681 if (y->owned) {
2682 /*@praat
2683 #
2684 # result# = x + owned y#
2685 #
2686 result# = 5 + { 11, 13, 31 } ; numeric vector literals are owned
2687 assert result# = { 16, 18, 36 }
2688 @*/
2689 y->numericVector += x->number;
2690 // x does not have to be cleaned up, because it was a number
2691 moveNumericVector (y, x);
2692 } else {
2693 /*@praat
2694 #
2695 # result# = x + unowned y#
2696 #
2697 y# = { 17, -11, 29 }
2698 result# = 30 + y# ; numeric vector variables are not owned
2699 assert result# = { 47, 19, 59 }
2700 @*/
2701 // x does not have to be cleaned up, because it was a number
2702 x->numericVector = add_VEC (y->numericVector, x->number). releaseToAmbiguousOwner();
2703 x->owned = true;
2704 }
2705 x->which = Stackel_NUMERIC_VECTOR;
2706 return;
2707 }
2708 if (y->which == Stackel_NUMERIC_MATRIX) {
2709 /*
2710 result## = x + y##
2711 */
2712 if (y->owned) {
2713 y->numericMatrix += x->number;
2714 // x does not have to be cleaned up, because it was a number
2715 moveNumericMatrix (y, x);
2716 } else {
2717 // x does not have to be cleaned up, because it was a number
2718 x->numericMatrix = add_MAT (y->numericMatrix, x->number). releaseToAmbiguousOwner();
2719 x->owned = true;
2720 }
2721 x->which = Stackel_NUMERIC_MATRIX;
2722 return;
2723 }
2724 }
2725 if (x->which == Stackel_NUMERIC_VECTOR) {
2726 if (y->which == Stackel_NUMERIC_VECTOR) {
2727 /*
2728 result# = x# + y#
2729 i.e.
2730 result# [i] = x# [i] + y# [i]
2731 */
2732 const integer nx = x->numericVector.size, ny = y->numericVector.size;
2733 if (nx != ny) {
2734 /*@praat
2735 #
2736 # Error: unequal sizes.
2737 #
2738 x# = { 11, 13, 17 }
2739 y# = { 8, 90 }
2740 asserterror When adding vectors, their numbers of elements should be equal, instead of 3 and 2.
2741 result# = x# + y#
2742 @*/
2743 Melder_throw (U"When adding vectors, their numbers of elements should be equal, instead of ", nx, U" and ", ny, U".");
2744 }
2745 if (x -> owned) {
2746 /*@praat
2747 #
2748 # result# = owned x# + y#
2749 #
2750 result# = { 11, 13, 17 } + { 44, 56, 67 } ; owned + owned
2751 assert result# = { 55, 69, 84 }
2752 y# = { 3, 2, 89.5 }
2753 result# = { 11, 13, 17 } + y# ; owned + unowned
2754 assert result# = { 14, 15, 106.5 }
2755 @*/
2756 x->numericVector += y->numericVector;
2757 } else if (y -> owned) {
2758 /*@praat
2759 #
2760 # result# = unowned x# + owned y#
2761 #
2762 x# = { 14, -3, 6.25 }
2763 result# = x# + { 55, 1, -89 }
2764 assert result# = { 69, -2, -82.75 }
2765 @*/
2766 y->numericVector += x->numericVector;
2767 // x does not have to be cleaned up, because it was not owned
2768 moveNumericVector (y, x);
2769 } else {
2770 /*@praat
2771 #
2772 # result# = unowned x# + unowned y#
2773 #
2774 x# = { 14, -33, 6.25 }
2775 y# = { -33, 17, 9 }
2776 result# = x# + y#
2777 assert result# = { -19, -16, 15.25 }
2778 @*/
2779 // x does not have to be cleaned up, because it was not owned
2780 x->numericVector = add_VEC (x->numericVector, y->numericVector). releaseToAmbiguousOwner();
2781 x->owned = true;
2782 }
2783 //x->which = Stackel_NUMERIC_VECTOR; // superfluous
2784 return;
2785 }
2786 if (y->which == Stackel_NUMERIC_MATRIX) {
2787 /*
2788 result## = x# + y##
2789 i.e.
2790 result## [i, j] = x# [i] + y## [i, j]
2791 */
2792 const integer xsize = x->numericVector.size;
2793 const integer ynrow = y->numericMatrix.nrow;
2794 Melder_require (ynrow == xsize,
2795 U"When adding a matrix to a vector, the matrix’s number of rows should be equal to the vector’s size, "
2796 "instead of ", ynrow, U" and ", xsize, U"."
2797 );
2798 if (x->owned) {
2799 /*@praat
2800 assert { 1, 2, 3 } + { { 1, 2 }, { 3, 4 }, { 5, 6 } } = { { 2, 3 }, { 5, 6 }, { 8, 9 } }
2801 @*/
2802 autoMAT newMatrix = add_MAT (x->numericVector, y->numericMatrix);
2803 x->reset();
2804 x->numericMatrix = newMatrix. releaseToAmbiguousOwner();
2805 } else {
2806 /*@praat
2807 a# = { 1, 2, 3 }
2808 assert a# + { { 1, 2 }, { 3, 4 }, { 5, 6 } } = { { 2, 3 }, { 5, 6 }, { 8, 9 } }
2809 @*/
2810 // x does not have to be cleaned up, because it was not owned
2811 x->numericMatrix = add_MAT (x->numericVector, y->numericMatrix). releaseToAmbiguousOwner();
2812 x->owned = true;
2813 }
2814 x->which = Stackel_NUMERIC_MATRIX;
2815 return;
2816 }
2817 if (y->which == Stackel_NUMBER) {
2818 /*
2819 result# = x# + y
2820 i.e.
2821 result# [i] = x# [i] + y
2822 */
2823 if (x->owned) {
2824 x->numericVector += y->number;
2825 } else {
2826 // x does not have to be cleaned up, because it was not owned
2827 x->numericVector = add_VEC (x->numericVector, y->number). releaseToAmbiguousOwner();
2828 x->owned = true;
2829 }
2830 //x->which = Stackel_NUMERIC_VECTOR; // superfluous
2831 return;
2832 }
2833 }
2834 if (x->which == Stackel_NUMERIC_MATRIX) {
2835 if (y->which == Stackel_NUMERIC_MATRIX) {
2836 /*
2837 result## = x## + y##
2838 i.e.
2839 result## [i, j] = x## [i, j] + y## [i, j]
2840 */
2841 const integer xnrow = x->numericMatrix.nrow, xncol = x->numericMatrix.ncol;
2842 const integer ynrow = y->numericMatrix.nrow, yncol = y->numericMatrix.ncol;
2843 if (xnrow != ynrow)
2844 Melder_throw (U"When adding matrices, their numbers of rows should be equal, instead of ", xnrow, U" and ", ynrow, U".");
2845 if (xncol != yncol)
2846 Melder_throw (U"When adding matrices, their numbers of columns should be equal, instead of ", xncol, U" and ", yncol, U".");
2847 if (x->owned) {
2848 x->numericMatrix += y->numericMatrix;
2849 } else if (y->owned) {
2850 y->numericMatrix += x->numericMatrix;
2851 // x does not have to be cleaned up, because it was not owned
2852 moveNumericMatrix (y, x);
2853 } else {
2854 // x does not have to be cleaned up, because it was not owned and has the right shape
2855 x->numericMatrix = add_MAT (x->numericMatrix, y->numericMatrix). releaseToAmbiguousOwner();
2856 x->owned = true;
2857 }
2858 //x->which = Stackel_NUMERIC_MATRIX;
2859 return;
2860 }
2861 if (y->which == Stackel_NUMERIC_VECTOR) {
2862 /*
2863 result## = x## + y#
2864 i.e.
2865 result## [i, j] = x## [i, j] + y# [j]
2866 */
2867 Melder_require (y->numericVector.size == x->numericMatrix.ncol,
2868 U"Cannot add a vector with ", y->numericVector.size, U" elements "
2869 "to a matrix with ", x->numericMatrix.ncol, U" columns. "
2870 "These numbers should be equal."
2871 );
2872 if (x->owned) {
2873 /*@praat
2874 #
2875 # result## = owned x## + y#
2876 #
2877 y# = { -5, 6, -19 }
2878 result## = { { 14, -33, 6.25 }, { -33, 17, 9 } } + y#
2879 assert result## = { { 9, -27, -12.75 }, { -38, 23, -10 } }
2880 @*/
2881 x->numericMatrix += y->numericVector;
2882 } else {
2883 /*@praat
2884 #
2885 # result## = unowned x## + y#
2886 #
2887 x## = { { 14, -33, 6.25 }, { -33, 17, 9 } }
2888 y# = { -5, 6, -19 }
2889 result## = x## + y#
2890 assert result## = { { 9, -27, -12.75 }, { -38, 23, -10 } }
2891 @*/
2892 // x does not have to be cleaned up, because it was not owned
2893 x->numericMatrix = add_MAT (x->numericMatrix, y->numericVector). releaseToAmbiguousOwner();
2894 x->owned = true;
2895 }
2896 //x->which = Stackel_NUMERIC_MATRIX;
2897 return;
2898 }
2899 if (y->which == Stackel_NUMBER) {
2900 /*
2901 result## = x## + y
2902 i.e.
2903 result## [i, j] = x## [i, j] + y
2904 */
2905 if (x->owned) {
2906 x->numericMatrix += y->number;
2907 } else {
2908 // x does not have to be cleaned up, because it was not owned
2909 x->numericMatrix = add_MAT (x->numericMatrix, y->number). releaseToAmbiguousOwner();
2910 x->owned = true;
2911 }
2912 //x->which = Stackel_NUMERIC_MATRIX; // superfluous
2913 return;
2914 }
2915 }
2916 if (x->which == Stackel_STRING && y->which == Stackel_STRING) {
2917 /*
2918 result$ = x$ + y$
2919 */
2920 const integer length1 = Melder_length (x->getString()), length2 = Melder_length (y->getString());
2921 autostring32 result (length1 + length2);
2922 str32cpy (result.get(), x->getString());
2923 str32cpy (result.get() + length1, y->getString());
2924 x->setString (result.move());
2925 return;
2926 }
2927 Melder_throw (U"Cannot add ", y->whichText(), U" to ", x->whichText(), U".");
2928 }
2929 static void do_sub () {
2930 /*
2931 result.. = x.. - y..
2932 */
2933 const Stackel y = pop, x = topOfStack;
2934 if (x->which == Stackel_NUMBER) {
2935 if (y->which == Stackel_NUMBER) {
2936 /*@praat
2937 #
2938 # result = x - y
2939 #
2940 x = 5
2941 y = 6
2942 result = x - y
2943 assert result = -1
2944 @*/
2945 x->number -= y->number;
2946 //x->which = Stackel_NUMBER; // superfluous, as is cleaning up
2947 return;
2948 }
2949 if (y->which == Stackel_NUMERIC_VECTOR) {
2950 /*
2951 result# = x - y#
2952 */
2953 if (y->owned) {
2954 /*@praat
2955 #
2956 # result# = x - owned y#
2957 #
2958 result# = 5 - { 11, 13, 31 } ; numeric vector literals are owned
2959 assert result# = { -6, -8, -26 }
2960 @*/
2961 y->numericVector <<= x->number - y->numericVector;
2962 // x does not have to be cleaned up, because it was a number
2963 moveNumericVector (y, x);
2964 } else {
2965 /*@praat
2966 #
2967 # result# = x - unowned y#
2968 #
2969 y# = { 17, -11, 29 }
2970 result# = 30 - y# ; numeric vector variables are not owned
2971 assert result# = { 13, 41, 1 }
2972 @*/
2973 // x does not have to be cleaned up, because it was a number
2974 x->numericVector = subtract_VEC (x->number, y->numericVector). releaseToAmbiguousOwner();
2975 x->owned = true;
2976 }
2977 x->which = Stackel_NUMERIC_VECTOR;
2978 return;
2979 }
2980 if (y->which == Stackel_NUMERIC_MATRIX) {
2981 /*
2982 result## = x - y##
2983 */
2984 if (y->owned) {
2985 subtractReversed_MAT_inout (y->numericMatrix, x->number);
2986 // x does not have to be cleaned up, because it was a number
2987 moveNumericMatrix (y, x);
2988 } else {
2989 // x does not have to be cleaned up, because it was a number
2990 x->numericMatrix = subtract_MAT (x->number, y->numericMatrix). releaseToAmbiguousOwner();
2991 x->owned = true;
2992 }
2993 x->which = Stackel_NUMERIC_MATRIX;
2994 return;
2995 }
2996 }
2997 if (x->which == Stackel_NUMERIC_VECTOR) {
2998 if (y->which == Stackel_NUMERIC_VECTOR) {
2999 /*
3000 result# = x# - y#
3001 i.e.
3002 result# [i] = x# [i] - y# [i]
3003 */
3004 const integer nx = x->numericVector.size, ny = y->numericVector.size;
3005 if (nx != ny) {
3006 /*@praat
3007 #
3008 # Error: unequal sizes.
3009 #
3010 x# = { 11, 13, 17 }
3011 y# = { 8, 90 }
3012 asserterror When subtracting vectors, their numbers of elements should be equal, instead of 3 and 2.
3013 result# = x# - y#
3014 @*/
3015 Melder_throw (U"When subtracting vectors, their numbers of elements should be equal, instead of ", nx, U" and ", ny, U".");
3016 }
3017 if (x -> owned) {
3018 /*@praat
3019 #
3020 # result# = owned x# - y#
3021 #
3022 result# = { 11, 13, 17 } - { 44, 56, 67 } ; owned + owned
3023 assert result# = { -33, -43, -50 }
3024 y# = { 3, 2, 89.5 }
3025 result# = { 11, 13, 17 } - y# ; owned + unowned
3026 assert result# = { 8, 11, -72.5 }
3027 @*/
3028 x->numericVector -= y->numericVector;
3029 } else if (y -> owned) {
3030 /*@praat
3031 #
3032 # result# = unowned x# + owned y#
3033 #
3034 x# = { 14, -3, 6.25 }
3035 result# = x# + { 55, 1, -89 }
3036 assert result# = { 69, -2, -82.75 }
3037 @*/
3038 y->numericVector <<= x->numericVector - y->numericVector;
3039 // x does not have to be cleaned up, because it was not owned
3040 moveNumericVector (y, x);
3041 } else {
3042 /*@praat
3043 #
3044 # result# = unowned x# + unowned y#
3045 #
3046 x# = { 14, -33, 6.25 }
3047 y# = { -33, 17, 9 }
3048 result# = x# - y#
3049 assert result# = { 47, -50, -2.75 }
3050 @*/
3051 // no clean-up of x required, because x is not owned and has the right type
3052 x->numericVector = subtract_VEC (x->numericVector, y->numericVector). releaseToAmbiguousOwner();
3053 x->owned = true;
3054 }
3055 //x->which = Stackel_NUMERIC_VECTOR; // superfluous
3056 return;
3057 }
3058 if (y->which == Stackel_NUMERIC_MATRIX) {
3059 /*
3060 result## = x# - y##
3061 i.e.
3062 result## [i, j] = x# [i] - y## [i, j]
3063 */
3064 const integer xsize = x->numericVector.size;
3065 const integer ynrow = y->numericMatrix.nrow;
3066 Melder_require (ynrow == xsize,
3067 U"When subtracting a matrix from a vector, the matrix’s number of rows should be equal to the vector’s size, "
3068 "instead of ", ynrow, U" and ", xsize, U"."
3069 );
3070 if (x->owned) {
3071 /*@praat
3072 assert { 1, 2, 3 } - { { 1, 2 }, { 3, 4 }, { 5, 6 } } = { { 0, -1 }, { -1, -2 }, { -2, -3 } }
3073 @*/
3074 autoMAT newMatrix = subtract_MAT (x->numericVector, y->numericMatrix);
3075 x->reset();
3076 x->numericMatrix = newMatrix. releaseToAmbiguousOwner();
3077 } else {
3078 /*@praat
3079 a# = { 1, 2, 3 }
3080 assert a# - { { 1, 2 }, { 3, 4 }, { 5, 6 } } = { { 0, -1 }, { -1, -2 }, { -2, -3 } }
3081 @*/
3082 // x does not have to be cleaned up, because it was not owned
3083 x->numericMatrix = subtract_MAT (x->numericVector, y->numericMatrix). releaseToAmbiguousOwner();
3084 x->owned = true;
3085 }
3086 x->which = Stackel_NUMERIC_MATRIX;
3087 return;
3088 }
3089 if (y->which == Stackel_NUMBER) {
3090 /*
3091 result# = x# - y
3092 i.e.
3093 result# [i] = x# [i] - y
3094 */
3095 if (x->owned) {
3096 x->numericVector -= y->number;
3097 } else {
3098 // x does not have to be cleaned up, because it was not owned
3099 x->numericVector = subtract_VEC (x->numericVector, y->number). releaseToAmbiguousOwner();
3100 x->owned = true;
3101 }
3102 //x->which = Stackel_NUMERIC_VECTOR; // superfluous
3103 return;
3104 }
3105 }
3106 if (x->which == Stackel_NUMERIC_MATRIX) {
3107 if (y->which == Stackel_NUMERIC_MATRIX) {
3108 const integer xnrow = x->numericMatrix.nrow, xncol = x->numericMatrix.ncol;
3109 const integer ynrow = y->numericMatrix.nrow, yncol = y->numericMatrix.ncol;
3110 if (xnrow != ynrow)
3111 Melder_throw (U"When subtracting matrices, their numbers of rows should be equal, instead of ", xnrow, U" and ", ynrow, U".");
3112 if (xncol != yncol)
3113 Melder_throw (U"When subtracting matrices, their numbers of columns should be equal, instead of ", xncol, U" and ", yncol, U".");
3114 if (x->owned) {
3115 x->numericMatrix -= y->numericMatrix;
3116 } else if (y->owned) {
3117 subtractReversed_MAT_inout (y->numericMatrix, x->numericMatrix);
3118 // x does not have to be cleaned up, because it was not owned
3119 moveNumericMatrix (y, x);
3120 } else {
3121 // x does not have to be cleaned up, because it was not owned and has the right shape
3122 x->numericMatrix = subtract_MAT (x->numericMatrix, y->numericMatrix). releaseToAmbiguousOwner();
3123 x->owned = true;
3124 }
3125 //x->which = Stackel_NUMERIC_MATRIX; // superfluous
3126 return;
3127 }
3128 if (y->which == Stackel_NUMERIC_VECTOR) {
3129 /*
3130 result## = x## - y#
3131 i.e.
3132 result## [i, j] = x## [i, j] - y# [j]
3133 */
3134 Melder_require (y->numericVector.size == x->numericMatrix.ncol,
3135 U"Cannot subtract a vector with ", y->numericVector.size, U" elements "
3136 "from a matrix with ", x->numericMatrix.ncol, U" columns. "
3137 "These numbers should be equal."
3138 );
3139 if (x->owned) {
3140 /*@praat
3141 #
3142 # result## = owned x## - y#
3143 #
3144 y# = { -5, 6, -19 }
3145 result## = { { 14, -33, 6.25 }, { -33, 17, 9 } } - y#
3146 assert result## = { { 19, -39, 25.25 }, { -28, 11, 28 } }
3147 @*/
3148 x->numericMatrix -= y->numericVector;
3149 } else {
3150 /*@praat
3151 #
3152 # result## = unowned x## - y#
3153 #
3154 x## = { { 14, -33, 6.25 }, { -33, 17, 9 } }
3155 y# = { -5, 6, -19 }
3156 result## = x## - y#
3157 assert result## = { { 19, -39, 25.25 }, { -28, 11, 28 } }
3158 @*/
3159 // x does not have to be cleaned up, because it was not owned
3160 x->numericMatrix = subtract_MAT (x->numericMatrix, y->numericVector). releaseToAmbiguousOwner();
3161 x->owned = true;
3162 }
3163 //x->which = Stackel_NUMERIC_MATRIX;
3164 return;
3165 }
3166 if (y->which == Stackel_NUMBER) {
3167 /*
3168 result## = x## - y
3169 i.e.
3170 result## [i, j] = x## [i, j] - y
3171 */
3172 if (x->owned) {
3173 x->numericMatrix -= y->number;
3174 } else {
3175 // x does not have to be cleaned up, because it was not owned
3176 x->numericMatrix = subtract_MAT (x->numericMatrix, y->number). releaseToAmbiguousOwner();
3177 x->owned = true;
3178 }
3179 //x->which = Stackel_NUMERIC_MATRIX; // superfluous
3180 return;
3181 }
3182 }
3183 if (x->which == Stackel_STRING && y->which == Stackel_STRING) {
3184 const integer length1 = Melder_length (x->getString());
3185 const integer length2 = Melder_length (y->getString());
3186 const integer newlength = length1 - length2;
3187 autostring32 result;
3188 if (newlength >= 0 && str32nequ (x->getString() + newlength, y->getString(), length2)) {
3189 result = autostring32 (newlength);
3190 str32ncpy (result.get(), x->getString(), newlength);
3191 } else {
3192 result = Melder_dup (x->getString());
3193 }
3194 x->setString (result.move());
3195 return;
3196 }
3197 Melder_throw (U"Cannot subtract (-) ", y->whichText(), U" from ", x->whichText(), U".");
3198 }
3199 static void do_mul () {
3200 /*
3201 result.. = x.. * y..
3202 */
3203 const Stackel y = pop, x = topOfStack;
3204 if (x->which == Stackel_NUMBER) {
3205 if (y->which == Stackel_NUMBER) {
3206 /*@praat
3207 #
3208 # result = x * y
3209 #
3210 x = 5
3211 y = 6
3212 result = x * y
3213 assert result = 30
3214 @*/
3215 x->number *= y->number;
3216 //x->which = Stackel_NUMBER; // superfluous, as is cleaning up
3217 return;
3218 }
3219 if (y->which == Stackel_NUMERIC_VECTOR) {
3220 /*
3221 result# = x * y#
3222 */
3223 if (y->owned) {
3224 /*@praat
3225 #
3226 # result# = x * owned y#
3227 #
3228 result# = 5 * { 11, 13, 31 } ; numeric vector literals are owned
3229 assert result# = { 55, 65, 155 }
3230 @*/
3231 y->numericVector *= x->number;
3232 // x does not have to be cleaned up, because it was a number
3233 moveNumericVector (y, x);
3234 } else {
3235 /*@praat
3236 #
3237 # result# = x * unowned y#
3238 #
3239 y# = { 17, -11, 29 }
3240 result# = 30 * y# ; numeric vector variables are not owned
3241 assert result# = { 510, -330, 870 }
3242 @*/
3243 // x does not have to be cleaned up, because it was a number
3244 x->numericVector = multiply_VEC (y->numericVector, x->number). releaseToAmbiguousOwner();
3245 x->owned = true;
3246 }
3247 x->which = Stackel_NUMERIC_VECTOR;
3248 return;
3249 }
3250 if (y->which == Stackel_NUMERIC_MATRIX) {
3251 /*
3252 result## = x * y##
3253 */
3254 if (y->owned) {
3255 y->numericMatrix *= x->number;
3256 // x does not have to be cleaned up, because it was a number
3257 moveNumericMatrix (y, x);
3258 } else {
3259 // x does not have to be cleaned up, because it was a number
3260 x->numericMatrix = multiply_MAT (y->numericMatrix, x->number). releaseToAmbiguousOwner();
3261 x->owned = true;
3262 }
3263 x->which = Stackel_NUMERIC_MATRIX;
3264 return;
3265 }
3266 }
3267 if (x->which == Stackel_NUMERIC_VECTOR) {
3268 if (y->which == Stackel_NUMERIC_VECTOR) {
3269 /*
3270 result# = x# * y#
3271 i.e.
3272 result# [i] = x# [i] * y# [i]
3273 */
3274 const integer nx = x->numericVector.size, ny = y->numericVector.size;
3275 if (nx != ny) {
3276 /*@praat
3277 #
3278 # Error: unequal sizes.
3279 #
3280 x# = { 11, 13, 17 }
3281 y# = { 8, 90 }
3282 asserterror When multiplying vectors, their numbers of elements should be equal, instead of 3 and 2.
3283 result# = x# * y#
3284 @*/
3285 Melder_throw (U"When multiplying vectors, their numbers of elements should be equal, instead of ", nx, U" and ", ny, U".");
3286 }
3287 if (x -> owned) {
3288 /*@praat
3289 #
3290 # result# = owned x# * y#
3291 #
3292 result# = { 11, 13, 17 } * { 44, 56, 67 } ; owned * owned
3293 assert result# = { 484, 728, 1139 }
3294 y# = { 3, 2, 89.5 }
3295 result# = { 11, 13, 17 } * y# ; owned * unowned
3296 assert result# = { 33, 26, 1521.5 }
3297 @*/
3298 x->numericVector *= y->numericVector;
3299 } else if (y -> owned) {
3300 /*@praat
3301 #
3302 # result# = unowned x# * owned y#
3303 #
3304 x# = { 14, -3, 6.25 }
3305 result# = x# * { 55, 1, -89 }
3306 assert result# = { 770, -3, -556.25 }
3307 @*/
3308 y->numericVector *= x->numericVector;
3309 // x does not have to be cleaned up, because it was not owned
3310 moveNumericVector (y, x);
3311 } else {
3312 /*@praat
3313 #
3314 # result# = unowned x# * unowned y#
3315 #
3316 x# = { 14, -33, 6.25 }
3317 y# = { -33, 17, 9 }
3318 result# = x# * y#
3319 assert result# = { -462, -561, 56.25 }
3320 @*/
3321 // x does not have to be cleaned up, because it was not owned
3322 x->numericVector = multiply_VEC (x->numericVector, y->numericVector). releaseToAmbiguousOwner();
3323 x->owned = true;
3324 }
3325 //x->which = Stackel_NUMERIC_VECTOR; // superfluous
3326 return;
3327 }
3328 if (y->which == Stackel_NUMERIC_MATRIX) {
3329 /*
3330 result## = x# * y##
3331 i.e.
3332 result## [i, j] = x# [i] * y## [i, j]
3333 */
3334 const integer xsize = x->numericVector.size;
3335 const integer ynrow = y->numericMatrix.nrow;
3336 Melder_require (ynrow == xsize,
3337 U"When multiplying a vector with a matrix, the matrix’s number of rows should be equal to the vector’s size, "
3338 "instead of ", ynrow, U" and ", xsize, U"."
3339 );
3340 if (x->owned) {
3341 /*@praat
3342 assert { 1, 2, 3 } * { { 1, 2 }, { 3, 4 }, { 5, 6 } } = { { 1, 2 }, { 6, 8 }, { 15, 18 } }
3343 @*/
3344 autoMAT newMatrix = multiply_MAT (x->numericVector, y->numericMatrix);
3345 x->reset();
3346 x->numericMatrix = newMatrix. releaseToAmbiguousOwner();
3347 } else {
3348 /*@praat
3349 a# = { 1, 2, 3 }
3350 assert a# * { { 1, 2 }, { 3, 4 }, { 5, 6 } } = { { 1, 2 }, { 6, 8 }, { 15, 18 } }
3351 @*/
3352 // x does not have to be cleaned up, because it was not owned
3353 x->numericMatrix = multiply_MAT (x->numericVector, y->numericMatrix). releaseToAmbiguousOwner();
3354 x->owned = true;
3355 }
3356 x->which = Stackel_NUMERIC_MATRIX;
3357 return;
3358 }
3359 if (y->which == Stackel_NUMBER) {
3360 /*
3361 result# = x# * y
3362 i.e.
3363 result# [i] = x# [i] * y
3364 */
3365 if (x->owned) {
3366 x->numericVector *= y->number;
3367 } else {
3368 // x does not have to be cleaned up, because it was not owned
3369 x->numericVector = multiply_VEC (x->numericVector, y->number). releaseToAmbiguousOwner();
3370 x->owned = true;
3371 }
3372 //x->which = Stackel_NUMERIC_VECTOR; // superfluous
3373 return;
3374 }
3375 }
3376 if (x->which == Stackel_NUMERIC_MATRIX) {
3377 if (y->which == Stackel_NUMERIC_MATRIX) {
3378 /*
3379 result## = x## * y##
3380 i.e.
3381 result## [i, j] = x## [i, j] * y## [i, j]
3382 */
3383 const integer xnrow = x->numericMatrix.nrow, xncol = x->numericMatrix.ncol;
3384 const integer ynrow = y->numericMatrix.nrow, yncol = y->numericMatrix.ncol;
3385 if (xnrow != ynrow)
3386 Melder_throw (U"When multiplying matrices, their numbers of rows should be equal, instead of ", xnrow, U" and ", ynrow, U".");
3387 if (xncol != yncol)
3388 Melder_throw (U"When multiplying matrices, their numbers of columns should be equal, instead of ", xncol, U" and ", yncol, U".");
3389 if (x->owned) {
3390 x->numericMatrix *= y->numericMatrix;
3391 } else if (y->owned) {
3392 y->numericMatrix *= x->numericMatrix;
3393 // x does not have to be cleaned up, because it was not owned
3394 moveNumericMatrix (y, x);
3395 } else {
3396 // x does not have to be cleaned up, because it was not owned
3397 x->numericMatrix = multiply_MAT (x->numericMatrix, y->numericMatrix). releaseToAmbiguousOwner();
3398 x->owned = true;
3399 }
3400 //x->which = Stackel_NUMERIC_MATRIX;
3401 return;
3402 }
3403 if (y->which == Stackel_NUMERIC_VECTOR) {
3404 /*
3405 result## = x## * y#
3406 i.e.
3407 result## [i, j] = x## [i, j] * y# [j]
3408 */
3409 const integer xncol = x->numericMatrix.ncol;
3410 const integer ysize = y->numericVector.size;
3411 Melder_require (xncol == ysize,
3412 U"When multiplying a matrix with a vector, the vector’s size should be equal to the matrix’s number of columns, "
3413 "instead of ", ysize, U" and ", xncol, U"."
3414 );
3415 if (x->owned) {
3416 x->numericMatrix *= y->numericVector;
3417 } else {
3418 // x does not have to be cleaned up, because it was not owned
3419 x->numericMatrix = multiply_MAT (x->numericMatrix, y->numericVector). releaseToAmbiguousOwner();
3420 x->owned = true;
3421 }
3422 //x->which = Stackel_NUMERIC_MATRIX;
3423 return;
3424 }
3425 if (y->which == Stackel_NUMBER) {
3426 /*
3427 result## = x## * y
3428 i.e.
3429 result## [i, j] = x## [i, j] * y
3430 */
3431 if (x->owned) {
3432 x->numericMatrix *= y->number;
3433 } else {
3434 // x does not have to be cleaned up, because it was not owned
3435 x->numericMatrix = multiply_MAT (x->numericMatrix, y->number). releaseToAmbiguousOwner();
3436 x->owned = true;
3437 }
3438 //x->which = Stackel_NUMERIC_MATRIX; // superfluous
3439 return;
3440 }
3441 }
3442 Melder_throw (U"Cannot multiply (*) ", x->whichText(), U" by ", y->whichText(), U".");
3443 }
3444 static void do_rdiv () {
3445 const Stackel y = pop, x = pop;
3446 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
3447 pushNumber (x->number / y->number); // result could be inf (1/0) or NaN (0/0), which is OK
3448 return;
3449 }
3450 if (x->which == Stackel_NUMERIC_VECTOR) {
3451 if (y->which == Stackel_NUMERIC_VECTOR) {
3452 const integer nelem1 = x->numericVector.size, nelem2 = y->numericVector.size;
3453 if (nelem1 != nelem2)
3454 Melder_throw (U"When dividing vectors, their numbers of elements should be equal, instead of ", nelem1, U" and ", nelem2, U".");
3455 autoVEC result = raw_VEC (nelem1);
3456 for (integer ielem = 1; ielem <= nelem1; ielem ++)
3457 result [ielem] = x->numericVector [ielem] / y->numericVector [ielem];
3458 pushNumericVector (result.move());
3459 return;
3460 }
3461 if (y->which == Stackel_NUMBER) {
3462 /*
3463 result# = x# / y
3464 */
3465 const integer xn = x->numericVector.size;
3466 autoVEC result = raw_VEC (xn);
3467 const double yvalue = y->number;
3468 if (yvalue == 0.0) {
3469 Melder_throw (U"Cannot divide (/) ", x->whichText(), U" by zero.");
3470 } else {
3471 for (integer i = 1; i <= xn; i ++) {
3472 const double xvalue = x->numericVector [i];
3473 result [i] = xvalue / yvalue;
3474 }
3475 }
3476 pushNumericVector (result.move());
3477 return;
3478 }
3479 }
3480 Melder_throw (U"Cannot divide (/) ", x->whichText(), U" by ", y->whichText(), U".");
3481 }
3482 static void do_idiv () {
3483 const Stackel y = pop, x = pop;
3484 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
3485 pushNumber (floor (x->number / y->number));
3486 return;
3487 }
3488 Melder_throw (U"Cannot divide (“div”) ", x->whichText(), U" by ", y->whichText(), U".");
3489 }
3490 static void do_mod () {
3491 const Stackel y = pop, x = pop;
3492 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
3493 pushNumber (x->number - floor (x->number / y->number) * y->number);
3494 return;
3495 }
3496 Melder_throw (U"Cannot divide (“mod”) ", x->whichText(), U" by ", y->whichText(), U".");
3497 }
3498 static void do_minus () {
3499 const Stackel x = topOfStack;
3500 if (x->which == Stackel_NUMBER) {
3501 x->number = - x->number;
3502 } else if (x->which == Stackel_NUMERIC_VECTOR) {
3503 if (x->owned) {
3504 neg_VEC_inout (x->numericVector);
3505 } else {
3506 autoVEC result = neg_VEC (x->numericVector);
3507 x->numericVector = result. releaseToAmbiguousOwner();
3508 x->owned = true;
3509 }
3510 } else if (x->which == Stackel_NUMERIC_MATRIX) {
3511 if (x->owned) {
3512 neg_MAT_inout (x->numericMatrix);
3513 } else {
3514 autoMAT result = neg_MAT (x->numericMatrix);
3515 x->numericMatrix = result. releaseToAmbiguousOwner();
3516 x->owned = true;
3517 }
3518 } else {
3519 Melder_throw (U"Cannot take the opposite (-) of ", x->whichText(), U".");
3520 }
3521 }
3522 static void do_power () {
3523 const Stackel y = pop, x = pop;
3524 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
3525 pushNumber (isundef (x->number) || isundef (y->number) ? undefined : pow (x->number, y->number));
3526 } else if (x->which == Stackel_NUMERIC_VECTOR && y->which == Stackel_NUMBER) {
3527 /*@praat
3528 assert { 3, 4 } ^ 3 = { 27, 64 }
3529 assert { 3, -4 } ^ 3 = { 27, -64 }
3530 assert { -4 } ^ 2.3 = { undefined }
3531 @*/
3532 pushNumericVector (power_VEC (x->numericVector, y->number));
3533 } else if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMBER) {
3534 pushNumericMatrix (power_MAT (x->numericMatrix, y->number));
3535 } else {
3536 Melder_throw (U"Cannot exponentiate (^) ", x->whichText(), U" to ", y->whichText(), U".");
3537 }
3538 }
3539 static void do_sqr () {
3540 const Stackel x = pop;
3541 if (x->which == Stackel_NUMBER) {
3542 pushNumber (isundef (x->number) ? undefined : x->number * x->number);
3543 } else if (x->which == Stackel_NUMERIC_VECTOR) {
3544 /*@praat
3545 a# = zero# (10)
3546 a# ~ sum ({ 3, 4 } ^ 2)
3547 assert sum (a#) = 250
3548 a# ~ sum ({ col } ^ 2)
3549 assert sum (a#) = 385
3550 @*/
3551 pushNumericVector (power_VEC (x->numericVector, 2.0));
3552 } else if (x->which == Stackel_NUMERIC_MATRIX) {
3553 pushNumericMatrix (power_MAT (x->numericMatrix, 2.0));
3554 } else {
3555 Melder_throw (U"Cannot take the square (^ 2) of ", x->whichText(), U".");
3556 }
3557 }
3558 static void do_function_n_n (double (*f) (double)) {
3559 const Stackel x = pop;
3560 if (x->which == Stackel_NUMBER) {
3561 pushNumber (isundef (x->number) ? undefined : f (x->number));
3562 } else {
3563 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
3564 U" requires a numeric argument, not ", x->whichText(), U".");
3565 }
3566 }
3567 static void do_functionvec_n_n (double (*f) (double)) {
3568 const Stackel x = topOfStack;
3569 if (x->which == Stackel_NUMERIC_VECTOR) {
3570 const integer n = x->numericVector.size;
3571 const VEC at = x->numericVector;
3572 if (x->owned) {
3573 for (integer i = 1; i <= n; i ++)
3574 at [i] = f (at [i]);
3575 } else {
3576 autoVEC result = raw_VEC (n);
3577 for (integer i = 1; i <= n; i ++)
3578 result [i] = f (at [i]);
3579 x->numericVector = result. releaseToAmbiguousOwner();
3580 x->owned = true;
3581 }
3582 } else {
3583 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
3584 U" requires a numeric vector argument, not ", x->whichText(), U".");
3585 }
3586 }
3587 static void do_softmax_VEC () {
3588 const Stackel x = topOfStack;
3589 if (x->which == Stackel_NUMERIC_VECTOR) {
3590 if (! x->owned) {
3591 x->numericVector = copy_VEC (x->numericVector). releaseToAmbiguousOwner(); // TODO: no need to copy
3592 x->owned = true;
3593 }
3594 const integer numberOfElements = x->numericVector.size;
3595 double maximum = -1e308;
3596 for (integer i = 1; i <= numberOfElements; i ++) {
3597 if (x->numericVector [i] > maximum)
3598 maximum = x->numericVector [i];
3599 }
3600 for (integer i = 1; i <= numberOfElements; i ++)
3601 x->numericVector [i] -= maximum;
3602 longdouble sum = 0.0;
3603 for (integer i = 1; i <= numberOfElements; i ++) {
3604 x->numericVector [i] = exp (x->numericVector [i]);
3605 sum += x->numericVector [i];
3606 }
3607 for (integer i = 1; i <= numberOfElements; i ++)
3608 x->numericVector [i] /= (double) sum;
3609 } else {
3610 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
3611 U" requires a numeric vector argument, not ", x->whichText(), U".");
3612 }
3613 }
3614 static void do_softmaxPerRow_MAT () {
3615 const Stackel x = topOfStack;
3616 if (x->which == Stackel_NUMERIC_MATRIX) {
3617 if (! x->owned) {
3618 x->numericMatrix = copy_MAT (x->numericMatrix). releaseToAmbiguousOwner(); // TODO: no need to copy
3619 x->owned = true;
3620 }
3621 const integer nrow = x->numericMatrix.nrow, ncol = x->numericMatrix.ncol;
3622 for (integer irow = 1; irow <= nrow; irow ++) {
3623 double maximum = -1e308;
3624 for (integer icol = 1; icol <= ncol; icol ++) {
3625 if (x->numericMatrix [irow] [icol] > maximum)
3626 maximum = x->numericMatrix [irow] [icol];
3627 }
3628 for (integer icol = 1; icol <= ncol; icol ++)
3629 x->numericMatrix [irow] [icol] -= maximum;
3630 longdouble sum = 0.0;
3631 for (integer icol = 1; icol <= ncol; icol ++) {
3632 x->numericMatrix [irow] [icol] = exp (x->numericMatrix [irow] [icol]);
3633 sum += x->numericMatrix [irow] [icol];
3634 }
3635 for (integer icol = 1; icol <= ncol; icol ++)
3636 x->numericMatrix [irow] [icol] /= (double) sum;
3637 }
3638 } else {
3639 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
3640 U" requires a numeric matrix argument, not ", x->whichText(), U".");
3641 }
3642 }
3643
3644 #define DO_NUM_WITH_TENSORS(function, formula, message) \
3645 static void do_##function () { \
3646 const Stackel x = pop; \
3647 if (x->which == Stackel_NUMBER) { \
3648 const double xvalue = x->number; \
3649 pushNumber (formula); \
3650 } else if (x->which == Stackel_NUMERIC_VECTOR) { \
3651 Melder_throw (U"The function " #function " requires a numeric argument, " \
3652 "not a vector. Did you mean to use " #function "# instead?"); \
3653 } else if (x->which == Stackel_NUMERIC_MATRIX) { \
3654 Melder_throw (U"The function " #function " requires a numeric argument, " \
3655 "not a matrix. Did you mean to use " #function "## instead?"); \
3656 } else { \
3657 Melder_throw (message, x->whichText(), \
3658 U". The function " #function " requires a numeric argument."); \
3659 } \
3660 } \
3661 static void do_##function##_VEC () { \
3662 const Stackel x = topOfStack; \
3663 if (x->which == Stackel_NUMERIC_VECTOR) { \
3664 if (x->owned) { \
3665 const integer numberOfElements = x->numericVector.size; \
3666 for (integer i = 1; i <= numberOfElements; i ++) { \
3667 const double xvalue = x->numericVector [i]; \
3668 x->numericVector [i] = isundef (xvalue) ? undefined : formula; \
3669 } \
3670 } else { \
3671 (void) pop; \
3672 const integer numberOfElements = x->numericVector.size; \
3673 autoVEC result = raw_VEC (numberOfElements); \
3674 for (integer i = 1; i <= numberOfElements; i ++) { \
3675 const double xvalue = x->numericVector [i]; \
3676 result [i] = isundef (xvalue) ? undefined : formula; \
3677 } \
3678 pushNumericVector (result.move()); \
3679 } \
3680 } else { \
3681 Melder_throw (U"The function " #function "# requires a vector argument, not ", \
3682 x->whichText(), U"."); \
3683 } \
3684 } \
3685 static void do_##function##_MAT () { \
3686 const Stackel x = topOfStack; \
3687 if (x->which == Stackel_NUMERIC_MATRIX) { \
3688 if (x->owned) { \
3689 const integer nrow = x->numericMatrix.nrow, ncol = x->numericMatrix.ncol; \
3690 for (integer irow = 1; irow <= nrow; irow ++) { \
3691 for (integer icol = 1; icol <= ncol; icol ++) { \
3692 const double xvalue = x->numericMatrix [irow] [icol]; \
3693 x->numericMatrix [irow] [icol] = isundef (xvalue) ? undefined : formula; \
3694 } \
3695 } \
3696 } else { \
3697 (void) pop; \
3698 const integer nrow = x->numericMatrix.nrow, ncol = x->numericMatrix.ncol; \
3699 autoMAT result = raw_MAT (nrow, ncol); \
3700 for (integer irow = 1; irow <= nrow; irow ++) { \
3701 for (integer icol = 1; icol <= ncol; icol ++) { \
3702 const double xvalue = x->numericMatrix [irow] [icol]; \
3703 result [irow] [icol] = isundef (xvalue) ? undefined : formula; \
3704 } \
3705 } \
3706 pushNumericMatrix (result.move()); \
3707 } \
3708 } else { \
3709 Melder_throw (U"The function " #function "## requires a matrix argument, not ", \
3710 x->whichText(), U"."); \
3711 } \
3712 }
3713 DO_NUM_WITH_TENSORS (abs, fabs (xvalue), U"Cannot take the absolute value (abs) of ")
3714 DO_NUM_WITH_TENSORS (round, floor (xvalue + 0.5), U"Cannot round ")
3715 DO_NUM_WITH_TENSORS (floor, Melder_roundDown (xvalue), U"Cannot round down (floor) ")
3716 DO_NUM_WITH_TENSORS (ceiling, Melder_roundUp (xvalue), U"Cannot round up (ceiling) ")
3717 DO_NUM_WITH_TENSORS (rectify, xvalue < 0.0 ? 0.0 : xvalue, U"Cannot rectify ") // NaN-safe
3718 /*@praat
3719 assert rectify (-1.0) = 0.0
3720 assert rectify (0.0) = 0.0
3721 assert rectify (1.0) = 1.0
3722 assert rectify (undefined) = undefined
3723 assert rectify# ({ 1.2, -2.3, 4.5, 0, undefined, -44 }) = { 1.2, 0, 4.5, 0, undefined, 0 }
3724 @*/
3725 DO_NUM_WITH_TENSORS (sqrt, sqrt (xvalue), U"Cannot take the square root (sqrt) of ")
3726 /*@praat
3727 assert sqrt (-1.0) = undefined
3728 assert sqrt (0.0) = 0.0
3729 assert sqrt (1.0) = 1.0
3730 assert sqrt (4.0) = 2.0
3731 assert sqrt (undefined) = undefined
3732 assert sqrt# ({ -1.0, 0.0, 1.0, 4.0, undefined }) = { undefined, 0.0, 1.0, 2.0, undefined }
3733 @*/
3734 DO_NUM_WITH_TENSORS (sin, sin (xvalue), U"Cannot take the sine (sin) of ")
3735 DO_NUM_WITH_TENSORS (cos, cos (xvalue), U"Cannot take the cosine (cos) of ")
3736 DO_NUM_WITH_TENSORS (tan, tan (xvalue), U"Cannot take the tangent (tan) of ")
3737 DO_NUM_WITH_TENSORS (arcsin, asin (xvalue), U"Cannot take the arcsine (arcsin) of ")
3738 /*@praat
3739 assert arcsin (-1.1) = undefined
3740 assert abs (arcsin (-1.0) - -pi/2) < 1e-17
3741 assert arcsin (0.0) = 0
3742 assert abs (arcsin (1.0) - pi/2) < 1e-17
3743 assert arcsin (1.1) = undefined
3744 assert arcsin (undefined) = undefined
3745 @*/
3746 DO_NUM_WITH_TENSORS (arccos, acos (xvalue), U"Cannot take the arccosine (arccos) of ")
3747 /*@praat
3748 assert arccos (-1.1) = undefined
3749 assert abs (arccos (-1.0) - pi) < 1e-17
3750 assert abs (arccos (0.0) - pi/2) < 1e-17
3751 assert arccos (1.0) = 0
3752 assert arccos (1.1) = undefined
3753 assert arccos (undefined) = undefined
3754 @*/
3755 DO_NUM_WITH_TENSORS (arctan, atan (xvalue), U"Cannot take the arctangent (arctan) of ")
3756 DO_NUM_WITH_TENSORS (exp, exp (xvalue), U"Cannot exponentiate (exp) ")
3757 DO_NUM_WITH_TENSORS (sinh, sinh (xvalue), U"Cannot take the hyperbolic sine (sinh) of ")
3758 DO_NUM_WITH_TENSORS (cosh, cosh (xvalue), U"Cannot take the hyperbolic cosine (cosh) of ")
3759 DO_NUM_WITH_TENSORS (tanh, tanh (xvalue), U"Cannot take the hyperbolic tangent (tanh) of ")
3760 DO_NUM_WITH_TENSORS (arcsinh, asinh (xvalue), U"Cannot take the hyperbolic arcsine (arcsinh) of ")
3761 /*@praat
3762 assert arcsinh (-1.0) < 0
3763 assert arcsinh (0.0) = 0
3764 assert arcsinh (1.0) > 0
3765 assert arcsinh (undefined) = undefined
3766 @*/
3767 DO_NUM_WITH_TENSORS (arccosh, acosh (xvalue), U"Cannot take the hyperbolic arccosine (arccosh) of ")
3768 /*@praat
3769 assert arccosh (1.0) = 0
3770 assert arccosh (0.9) = undefined
3771 assert arccosh (0.0) = undefined
3772 assert arccosh (-10.0) = undefined
3773 assert arccosh (undefined) = undefined
3774 @*/
3775 DO_NUM_WITH_TENSORS (arctanh, atanh (xvalue), U"Cannot take the hyperbolic arctangent (arctanh) of ")
3776 /*@praat
3777 assert arctanh (-1.0) = undefined
3778 assert arctanh (0.0) = 0
3779 assert arctanh (1.0) = undefined
3780 assert arctanh (undefined) = undefined
3781 @*/
3782 DO_NUM_WITH_TENSORS (log2, log (xvalue) * NUMlog2e, U"Cannot take the base-2 logarithm (log2) of ")
3783 /*@praat
3784 assert log2 (-1.0) = undefined
3785 assert log2 (0.0) = undefined
3786 assert log2 (1.0) = 0.0
3787 assert log2 (2.0) = 1.0
3788 assert log2 (10.0) > 3.0
3789 assert log2 (undefined) = undefined
3790 @*/
3791 DO_NUM_WITH_TENSORS (ln, log (xvalue), U"Cannot take the natural logarithm (ln) of ")
3792 /*@praat
3793 assert ln (-1.0) = undefined
3794 assert ln (0.0) = undefined
3795 assert ln (1.0) = 0.0
3796 assert abs (ln (2.0) - 0.693) < 0.001
3797 assert ln (3.0) > 1.0
3798 assert ln (undefined) = undefined
3799 @*/
3800 DO_NUM_WITH_TENSORS (log10, log10 (xvalue), U"Cannot take the base-10 logarithm (log10) of ")
3801 /*@praat
3802 assert log10 (-1.0) = undefined
3803 assert log10 (0.0) = undefined
3804 assert log10 (1.0) = 0.0
3805 assert abs (log10 (2.0) - 0.301) < 0.001
3806 assert log10 (10.0) = 1.0
3807 assert log10 (11.0) > 1.0
3808 assert log10 (undefined) = undefined
3809 @*/
3810 DO_NUM_WITH_TENSORS (sigmoid, NUMsigmoid (xvalue), U"Cannot take the sigmoid of ")
3811 /*@praat
3812 assert sigmoid (0.0) = 0.5
3813 assert sigmoid (-1000) = 0
3814 assert arctanh (1000) = undefined
3815 @*/
3816 DO_NUM_WITH_TENSORS (invSigmoid, NUMinvSigmoid (xvalue), U"Cannot take the inverse sigmoid of ")
3817 /*@praat
3818 assert invSigmoid (0.5) = 0.0
3819 assert invSigmoid (-1.0) = undefined ; not a number
3820 assert invSigmoid (0.0) = undefined ; minus infinity
3821 assert invSigmoid (1.0) = undefined ; plus infinity
3822 assert invSigmoid (2.0) = undefined ; not a number
3823 @*/
3824
3825 static void do_sum () {
3826 const Stackel x = pop;
3827 if (x->which == Stackel_NUMERIC_VECTOR) {
3828 pushNumber (NUMsum (x->numericVector));
3829 } else if (x->which == Stackel_NUMERIC_MATRIX) {
3830 pushNumber (NUMsum (x->numericMatrix));
3831 } else {
3832 Melder_throw (U"Cannot compute the sum of ", x->whichText(), U".");
3833 }
3834 }
3835 static void do_mean () {
3836 const Stackel x = pop;
3837 if (x->which == Stackel_NUMERIC_VECTOR) {
3838 pushNumber (NUMmean (x->numericVector));
3839 } else if (x->which == Stackel_NUMERIC_MATRIX) {
3840 pushNumber (NUMmean (x->numericMatrix));
3841 } else {
3842 Melder_throw (U"Cannot compute the mean of ", x->whichText(), U".");
3843 }
3844 }
3845 static void do_stdev () {
3846 const Stackel x = pop;
3847 if (x->which == Stackel_NUMERIC_VECTOR) {
3848 pushNumber (NUMstdev (x->numericVector));
3849 } else if (x->which == Stackel_NUMERIC_MATRIX) {
3850 pushNumber (NUMstdev (x->numericMatrix));
3851 } else {
3852 Melder_throw (U"Cannot compute the standard deviation of ", x->whichText(), U".");
3853 }
3854 }
3855 static void do_center () {
3856 const Stackel x = pop;
3857 if (x->which == Stackel_NUMERIC_VECTOR) {
3858 pushNumber (NUMcenterOfGravity (x->numericVector));
3859 } else {
3860 Melder_throw (U"Cannot compute the center of ", x->whichText(), U".");
3861 }
3862 }
3863 static void do_randomImax () {
3864 const Stackel x = pop;
3865 if (x->which == Stackel_NUMERIC_VECTOR) {
3866 pushNumber (NUMrandomImax (x->numericVector));
3867 } else {
3868 Melder_throw (U"Cannot compute a random imax of ", x->whichText(), U".");
3869 }
3870 }
3871 static void do_function_dd_d (double (*f) (double, double)) {
3872 const Stackel y = pop, x = pop;
3873 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
3874 pushNumber (isundef (x->number) || isundef (y->number) ? undefined : f (x->number, y->number));
3875 } else {
3876 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
3877 U" requires two numeric arguments, not ",
3878 x->whichText(), U" and ", y->whichText(), U".");
3879 }
3880 }
3881 static void do_function_VECdd_d (double (*f) (double, double)) {
3882 const Stackel narg = pop;
3883 Melder_assert (narg->which == Stackel_NUMBER);
3884 Melder_require (narg->number == 3,
3885 U"The function ", Formula_instructionNames [parse [programPointer]. symbol], U" requires three arguments.");
3886 const Stackel y = pop, x = pop, a = pop;
3887 if ((a->which == Stackel_NUMERIC_VECTOR || a->which == Stackel_NUMBER) && x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
3888 const integer numberOfElements = ( a->which == Stackel_NUMBER ? Melder_iround (a->number) : a->numericVector.size );
3889 autoVEC newData = raw_VEC (numberOfElements);
3890 for (integer ielem = 1; ielem <= numberOfElements; ielem ++)
3891 newData [ielem] = f (x->number, y->number);
3892 pushNumericVector (newData.move());
3893 } else {
3894 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
3895 U" requires either three numeric arguments, or one vector argument and two numeric arguments, not ",
3896 a->whichText(), U", ", x->whichText(), U" and ", y->whichText(), U".");
3897 }
3898 }
3899 static void do_function_MATdd_d (double (*f) (double, double)) {
3900 const Stackel narg = pop;
3901 Melder_assert (narg->which == Stackel_NUMBER);
3902 if (narg->number == 3) {
3903 const Stackel y = pop, x = pop, model = pop;
3904 if (model->which == Stackel_NUMERIC_MATRIX && x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
3905 const integer numberOfRows = model->numericMatrix.nrow;
3906 const integer numberOfColumns = model->numericMatrix.ncol;
3907 autoMAT newData = raw_MAT (numberOfRows, numberOfColumns);
3908 for (integer irow = 1; irow <= numberOfRows; irow ++)
3909 for (integer icol = 1; icol <= numberOfColumns; icol ++)
3910 newData [irow] [icol] = f (x->number, y->number);
3911 pushNumericMatrix (newData.move());
3912 } else {
3913 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
3914 U" requires one matrix argument and two numeric arguments, not ",
3915 model->whichText(), U", ", x->whichText(), U" and ", y->whichText(), U".");
3916 }
3917 } else if (narg->number == 4) {
3918 const Stackel y = pop, x = pop, ncol = pop, nrow = pop;
3919 if (nrow->which == Stackel_NUMBER && ncol->which == Stackel_NUMBER && x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
3920 const integer numberOfRows = Melder_iround (nrow->number);
3921 const integer numberOfColumns = Melder_iround (ncol->number);
3922 autoMAT newData = raw_MAT (numberOfRows, numberOfColumns);
3923 for (integer irow = 1; irow <= numberOfRows; irow ++)
3924 for (integer icol = 1; icol <= numberOfColumns; icol ++)
3925 newData [irow] [icol] = f (x->number, y->number);
3926 pushNumericMatrix (newData.move());
3927 } else {
3928 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
3929 U" requires four numeric arguments, not ",
3930 nrow->whichText(), U", ", ncol->whichText(), U", ", x->whichText(), U" and ", y->whichText(), U".");
3931 }
3932 } else
3933 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol], U" requires three or four arguments.");
3934 }
3935
3936 static void do_function_VECll_l (integer (*f) (integer, integer)) {
3937 const Stackel narg = pop;
3938 Melder_assert (narg->which == Stackel_NUMBER);
3939 Melder_require (narg-> number == 3,
3940 U"The function ", Formula_instructionNames [parse [programPointer]. symbol], U" requires three arguments.");
3941 const Stackel y = pop, x = pop, a = pop;
3942 if ((a->which == Stackel_NUMERIC_VECTOR || a->which == Stackel_NUMBER) && x->which == Stackel_NUMBER) {
3943 const integer numberOfElements = ( a->which == Stackel_NUMBER ? Melder_iround (a->number) : a->numericVector.size );
3944 autoVEC newData = raw_VEC (numberOfElements);
3945 for (integer ielem = 1; ielem <= numberOfElements; ielem ++)
3946 newData [ielem] = f (Melder_iround (x->number), Melder_iround (y->number));
3947 pushNumericVector (newData.move());
3948 } else {
3949 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
3950 U" requires either three numeric arguments, or one vector argument and two numeric arguments, not ",
3951 a->whichText(), U", ", x->whichText(), U" and ", y->whichText(), U".");
3952 }
3953 }
3954 static void do_function_MATll_l (integer (*f) (integer, integer)) {
3955 const Stackel narg = pop;
3956 Melder_assert (narg->which == Stackel_NUMBER);
3957 Melder_require (narg->number == 3,
3958 U"The function ", Formula_instructionNames [parse [programPointer]. symbol], U" requires three arguments.");
3959 const Stackel y = pop, x = pop, a = pop;
3960 if (a->which == Stackel_NUMERIC_MATRIX && x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
3961 const integer numberOfRows = a->numericMatrix.nrow;
3962 const integer numberOfColumns = a->numericMatrix.ncol;
3963 autoMAT newData = raw_MAT (numberOfRows, numberOfColumns);
3964 for (integer irow = 1; irow <= numberOfRows; irow ++)
3965 for (integer icol = 1; icol <= numberOfColumns; icol ++)
3966 newData [irow] [icol] = f (Melder_iround (x->number), Melder_iround (y->number));
3967 pushNumericMatrix (newData.move());
3968 } else {
3969 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
3970 U" requires one matrix argument and two numeric arguments, not ",
3971 a->whichText(), U", ", x->whichText(), U" and ", y->whichText(), U".");
3972 }
3973 }
3974 static void do_function_dl_d (double (*f) (double, integer)) {
3975 const Stackel y = pop, x = pop;
3976 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
3977 pushNumber (isundef (x->number) || isundef (y->number) ? undefined :
3978 f (x->number, Melder_iround (y->number)));
3979 } else {
3980 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
3981 U" requires two numeric arguments, not ",
3982 x->whichText(), U" and ", y->whichText(), U".");
3983 }
3984 }
3985 static void do_function_ld_d (double (*f) (integer, double)) {
3986 const Stackel y = pop, x = pop;
3987 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
3988 pushNumber (isundef (x->number) || isundef (y->number) ? undefined :
3989 f (Melder_iround (x->number), y->number));
3990 } else {
3991 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
3992 U" requires two numeric arguments, not ",
3993 x->whichText(), U" and ", y->whichText(), U".");
3994 }
3995 }
3996 static void do_function_ll_l (integer (*f) (integer, integer)) {
3997 const Stackel y = pop, x = pop;
3998 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
3999 pushNumber (isundef (x->number) || isundef (y->number) ? undefined :
4000 f (Melder_iround (x->number), Melder_iround (y->number)));
4001 } else {
4002 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
4003 U" requires two numeric arguments, not ",
4004 x->whichText(), U" and ", y->whichText(), U".");
4005 }
4006 }
4007 static void do_objects_are_identical () {
4008 const Stackel y = pop, x = pop;
4009 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
4010 const integer id1 = Melder_iround (x->number), id2 = Melder_iround (y->number);
4011 integer i = theCurrentPraatObjects -> n;
4012 while (i > 0 && id1 != theCurrentPraatObjects -> list [i]. id)
4013 i --;
4014 if (i == 0)
4015 Melder_throw (U"Object #", id1, U" does not exist in function objectsAreIdentical.");
4016 const Daata object1 = (Daata) theCurrentPraatObjects -> list [i]. object;
4017 i = theCurrentPraatObjects -> n;
4018 while (i > 0 && id2 != theCurrentPraatObjects -> list [i]. id)
4019 i --;
4020 if (i == 0)
4021 Melder_throw (U"Object #", id2, U" does not exist in function objectsAreIdentical.");
4022 const Daata object2 = (Daata) theCurrentPraatObjects -> list [i]. object;
4023 pushNumber (isundef (x->number) || isundef (y->number) ? undefined : Data_equal (object1, object2));
4024 } else {
4025 Melder_throw (U"The function objectsAreIdentical requires two numeric arguments (object IDs), not ",
4026 x->whichText(), U" and ", y->whichText(), U".");
4027 }
4028 }
4029 static void do_function_ddd_d (double (*f) (double, double, double)) {
4030 const Stackel z = pop, y = pop, x = pop;
4031 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER && z->which == Stackel_NUMBER) {
4032 pushNumber (isundef (x->number) || isundef (y->number) || isundef (z->number) ? undefined :
4033 f (x->number, y->number, z->number));
4034 } else {
4035 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
4036 U" requires three numeric arguments, not ", x->whichText(), U", ",
4037 y->whichText(), U", and ", z->whichText(), U".");
4038 }
4039 }
4040 static void do_do () {
4041 const Stackel narg = pop;
4042 Melder_assert (narg->which == Stackel_NUMBER);
4043 if (narg->number < 1)
4044 Melder_throw (U"The function “do” requires at least one argument, namely a menu command.");
4045 const integer numberOfArguments = Melder_iround (narg->number) - 1;
4046 #define MAXNUM_FIELDS 40
4047 structStackel stack [1+MAXNUM_FIELDS];
4048 for (integer iarg = numberOfArguments; iarg >= 0; iarg --) {
4049 const Stackel arg = pop;
4050 stack [iarg] = std::move (*arg);
4051 }
4052 if (stack [0]. which != Stackel_STRING)
4053 Melder_throw (U"The first argument of the function “do” should be a string, namely a menu command, and not ", stack [0]. whichText(), U".");
4054 conststring32 command = stack [0]. getString();
4055 if (theCurrentPraatObjects == & theForegroundPraatObjects && theInterpreter -> hasDynamicEnvironmentEditor()) {
4056 autoMelderString valueString;
4057 MelderString_appendCharacter (& valueString, 1); // TODO: check whether this is needed at all, or is just MelderString_empty enough?
4058 autoMelderDivertInfo divert (& valueString);
4059 autostring32 command2 = Melder_dup (command); // allow the menu command to reuse the stack (?)
4060 Editor_doMenuCommand (theInterpreter -> optionalDynamicEnvironmentEditor(), command2.get(), numberOfArguments, & stack [0], nullptr, theInterpreter);
4061 pushNumber (Melder_atof (valueString.string));
4062 return;
4063 } else if (! praat_commandsWithExternalSideEffectsAreAllowed () &&
4064 (str32nequ (command, U"Save ", 5) || str32nequ (command, U"Write ", 6) || str32nequ (command, U"Append to ", 10) || str32nequ (command, U"Quit", 4)))
4065 {
4066 Melder_throw (U"Commands that write files (including Quit) are not available inside manuals.");
4067 } else {
4068 autoMelderString valueString;
4069 MelderString_appendCharacter (& valueString, 1); // a semaphor to check whether praat_doAction or praat_doMenuCommand wrote anything with MelderInfo
4070 autoMelderDivertInfo divert (& valueString);
4071 autostring32 command2 = Melder_dup (command); // allow the menu command to reuse the stack (?)
4072 if (! praat_doAction (command2.get(), numberOfArguments, & stack [0], theInterpreter) &&
4073 ! praat_doMenuCommand (command2.get(), numberOfArguments, & stack [0], theInterpreter))
4074 {
4075 Melder_throw (U"Command “", command, U"” not available for current selection.");
4076 }
4077 //praat_updateSelection ();
4078 double value = undefined;
4079 if (valueString.string [0] == 1) { // nothing written with MelderInfo by praat_doAction or praat_doMenuCommand? then the return value is the ID of the selected object
4080 integer IOBJECT, result = 0, found = 0;
4081 WHERE (SELECTED) {
4082 result = IOBJECT;
4083 found += 1;
4084 }
4085 if (found == 1)
4086 value = theCurrentPraatObjects -> list [result]. id;
4087 } else {
4088 value = Melder_atof (valueString.string); // including --undefined--
4089 }
4090 pushNumber (value);
4091 return;
4092 }
4093 praat_updateSelection (); // BUG: superfluous? flickering?
4094 pushNumber (1);
4095 }
4096 static void do_evaluate () {
4097 const Stackel expression = pop;
4098 if (expression->which == Stackel_STRING) {
4099 double result;
4100 Interpreter_numericExpression (theInterpreter, expression->getString(), & result);
4101 pushNumber (result);
4102 } else Melder_throw (U"The argument of the function “evaluate” should be a string with a numeric expression, not ", expression->whichText());
4103 }
4104 static void do_evaluate_nocheck () {
4105 const Stackel expression = pop;
4106 if (expression->which == Stackel_STRING) {
4107 try {
4108 double result;
4109 Interpreter_numericExpression (theInterpreter, expression->getString(), & result);
4110 pushNumber (result);
4111 } catch (MelderError) {
4112 Melder_clearError ();
4113 pushNumber (undefined);
4114 }
4115 } else Melder_throw (U"The argument of the function “evaluate_nocheck” should be a string with a numeric expression, not ", expression->whichText());
4116 }
4117 static void do_evaluate_STR () {
4118 const Stackel expression = pop;
4119 if (expression->which == Stackel_STRING) {
4120 autostring32 result = Interpreter_stringExpression (theInterpreter, expression->getString());
4121 pushString (result.move());
4122 } else Melder_throw (U"The argument of the function “evaluate$” should be a string with a string expression, not ", expression->whichText());
4123 }
4124 static void do_evaluate_nocheck_STR () {
4125 const Stackel expression = pop;
4126 if (expression->which == Stackel_STRING) {
4127 try {
4128 autostring32 result = Interpreter_stringExpression (theInterpreter, expression->getString());
4129 pushString (result.move());
4130 } catch (MelderError) {
4131 Melder_clearError ();
4132 pushString (Melder_dup (U""));
4133 }
4134 } else Melder_throw (U"The argument of the function “evaluate_nocheck$” should be a string with a string expression, not ", expression->whichText());
4135 }
4136 static void do_do_STR () {
4137 const Stackel narg = pop;
4138 Melder_assert (narg->which == Stackel_NUMBER);
4139 if (narg->number < 1)
4140 Melder_throw (U"The function “do$” requires at least one argument, namely a menu command.");
4141 const integer numberOfArguments = Melder_iround (narg->number) - 1;
4142 #define MAXNUM_FIELDS 40
4143 structStackel stack [1+MAXNUM_FIELDS];
4144 for (integer iarg = numberOfArguments; iarg >= 0; iarg --) {
4145 const Stackel arg = pop;
4146 stack [iarg] = std::move (*arg);
4147 }
4148 if (stack [0]. which != Stackel_STRING)
4149 Melder_throw (U"The first argument of the function “do$” should be a string, namely a menu command, and not ", stack [0]. whichText(), U".");
4150 conststring32 command = stack [0]. getString();
4151 if (theCurrentPraatObjects == & theForegroundPraatObjects && theInterpreter -> hasDynamicEnvironmentEditor()) {
4152 static MelderString info;
4153 MelderString_empty (& info);
4154 autoMelderDivertInfo divert (& info);
4155 autostring32 command2 = Melder_dup (command);
4156 Editor_doMenuCommand (theInterpreter -> optionalDynamicEnvironmentEditor(), command2.get(), numberOfArguments, & stack [0], nullptr, theInterpreter);
4157 pushString (Melder_dup (info.string));
4158 return;
4159 } else if (! praat_commandsWithExternalSideEffectsAreAllowed () &&
4160 (str32nequ (command, U"Save ", 5) || str32nequ (command, U"Write ", 6) || str32nequ (command, U"Append to ", 10) || str32nequ (command, U"Quit", 4)))
4161 {
4162 Melder_throw (U"Commands that write files (including Quit) are not available inside manuals.");
4163 } else {
4164 static MelderString info;
4165 MelderString_empty (& info);
4166 autoMelderDivertInfo divert (& info);
4167 autostring32 command2 = Melder_dup (command);
4168 if (! praat_doAction (command2.get(), numberOfArguments, & stack [0], theInterpreter) &&
4169 ! praat_doMenuCommand (command2.get(), numberOfArguments, & stack [0], theInterpreter))
4170 {
4171 Melder_throw (U"Command “", command, U"” not available for current selection.");
4172 }
4173 praat_updateSelection ();
4174 pushString (Melder_dup (info.string));
4175 return;
4176 }
4177 praat_updateSelection (); // BUG: superfluous? flickering?
4178 pushString (Melder_dup (U""));
4179 }
4180 static void shared_do_writeInfo (integer numberOfArguments) {
4181 for (integer iarg = 1; iarg <= numberOfArguments; iarg ++) {
4182 const Stackel arg = & theStack [stackPointer + iarg];
4183 if (arg->which == Stackel_NUMBER) {
4184 MelderInfo_write (arg->number);
4185 } else if (arg->which == Stackel_STRING) {
4186 MelderInfo_write (arg->getString());
4187 } else if (arg->which == Stackel_NUMERIC_VECTOR) {
4188 for (integer i = 1; i <= arg->numericVector.size; i ++)
4189 MelderInfo_write (arg->numericVector [i],
4190 i == arg->numericVector.size ? U"" : U" ");
4191 } else if (arg->which == Stackel_NUMERIC_MATRIX) {
4192 for (integer irow = 1; irow <= arg->numericMatrix.nrow; irow ++) {
4193 for (integer icol = 1; icol <= arg->numericMatrix.ncol; icol ++)
4194 MelderInfo_write (arg->numericMatrix [irow] [icol],
4195 icol == arg->numericMatrix.ncol ? U"" : U" ");
4196 MelderInfo_write (irow == arg->numericMatrix.nrow ? U"" : U"\n");
4197 }
4198 } else if (arg->which == Stackel_STRING_ARRAY) {
4199 for (integer i = 1; i <= arg->stringArray.size; i ++)
4200 MelderInfo_write (arg->stringArray [i],
4201 i == arg->stringArray.size ? U"" : U" ");
4202 }
4203 }
4204 }
4205 static void do_writeInfo () {
4206 const Stackel narg = pop;
4207 Melder_assert (narg->which == Stackel_NUMBER);
4208 const integer numberOfArguments = Melder_iround (narg->number);
4209 stackPointer -= numberOfArguments;
4210 MelderInfo_open ();
4211 shared_do_writeInfo (numberOfArguments);
4212 MelderInfo_drain ();
4213 pushNumber (1);
4214 }
4215 static void do_writeInfoLine () {
4216 const Stackel narg = pop;
4217 Melder_assert (narg->which == Stackel_NUMBER);
4218 const integer numberOfArguments = Melder_iround (narg->number);
4219 stackPointer -= numberOfArguments;
4220 MelderInfo_open ();
4221 shared_do_writeInfo (numberOfArguments);
4222 MelderInfo_write (U"\n");
4223 MelderInfo_drain ();
4224 pushNumber (1);
4225 }
4226
4227 static void do_appendInfo () {
4228 MELDER_ASSERT_NONREENTRANT
4229 const Stackel narg = pop;
4230 Melder_assert (narg->which == Stackel_NUMBER);
4231 const integer numberOfArguments = Melder_iround (narg->number);
4232 stackPointer -= numberOfArguments;
4233 shared_do_writeInfo (numberOfArguments);
4234 MelderInfo_drain ();
4235 pushNumber (1);
4236 }
4237 static void do_appendInfoLine () {
4238 MELDER_ASSERT_NONREENTRANT
4239 const Stackel narg = pop;
4240 Melder_assert (narg->which == Stackel_NUMBER);
4241 const integer numberOfArguments = Melder_iround (narg->number);
4242 stackPointer -= numberOfArguments;
4243 shared_do_writeInfo (numberOfArguments);
4244 MelderInfo_write (U"\n");
4245 MelderInfo_drain ();
4246 pushNumber (1);
4247 }
4248 static void shared_do_writeFile (autoMelderString *text, integer numberOfArguments) {
4249 for (int iarg = 2; iarg <= numberOfArguments; iarg ++) {
4250 const Stackel arg = & theStack [stackPointer + iarg];
4251 if (arg->which == Stackel_NUMBER) {
4252 MelderString_append (text, arg->number);
4253 } else if (arg->which == Stackel_STRING) {
4254 MelderString_append (text, arg->getString());
4255 } else if (arg->which == Stackel_NUMERIC_VECTOR) {
4256 for (integer i = 1; i <= arg->numericVector.size; i ++)
4257 MelderString_append (text, arg->numericVector [i],
4258 i == arg->numericVector.size ? U"" : U" ");
4259 } else if (arg->which == Stackel_NUMERIC_MATRIX) {
4260 for (integer irow = 1; irow <= arg->numericMatrix.nrow; irow ++) {
4261 for (integer icol = 1; icol <= arg->numericMatrix.ncol; icol ++)
4262 MelderString_append (text, arg->numericMatrix [irow] [icol],
4263 icol == arg->numericMatrix.ncol ? U"" : U" ");
4264 MelderString_append (text, irow == arg->numericMatrix.nrow ? U"" : U"\n");
4265 }
4266 } else if (arg->which == Stackel_STRING_ARRAY) {
4267 for (integer i = 1; i <= arg->stringArray.size; i ++)
4268 MelderString_append (text, arg->stringArray [i],
4269 i == arg->stringArray.size ? U"" : U" ");
4270 }
4271 }
4272 }
4273 static void do_writeFile () {
4274 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
4275 U"The function “writeFile” is not available inside manuals.");
4276 const Stackel narg = pop;
4277 Melder_assert (narg->which == Stackel_NUMBER);
4278 const integer numberOfArguments = Melder_iround (narg->number);
4279 stackPointer -= numberOfArguments;
4280 const Stackel fileName = & theStack [stackPointer + 1];
4281 Melder_require (fileName->which == Stackel_STRING,
4282 U"The first argument of “writeFile” should be a string (a file name), not ", fileName->whichText(), U".");
4283 autoMelderString text;
4284 shared_do_writeFile (& text, numberOfArguments);
4285 structMelderFile file { };
4286 Melder_relativePathToFile (fileName->getString(), & file);
4287 Melder_checkTrust (theInterpreter, U"save some text to the file\n", & file);
4288 MelderFile_writeText_e (& file, text.string, Melder_getOutputEncoding ());
4289 pushNumber (1);
4290 }
4291 static void do_writeFileLine () {
4292 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
4293 U"The function “writeFileLine” is not available inside manuals.");
4294 const Stackel narg = pop;
4295 Melder_assert (narg->which == Stackel_NUMBER);
4296 const integer numberOfArguments = Melder_iround (narg->number);
4297 stackPointer -= numberOfArguments;
4298 const Stackel fileName = & theStack [stackPointer + 1];
4299 Melder_require (fileName->which == Stackel_STRING,
4300 U"The first argument of “writeFileLine” should be a string (a file name), not ", fileName->whichText(), U".");
4301 autoMelderString text;
4302 shared_do_writeFile (& text, numberOfArguments);
4303 MelderString_appendCharacter (& text, U'\n');
4304 structMelderFile file { };
4305 Melder_relativePathToFile (fileName->getString(), & file);
4306 Melder_checkTrust (theInterpreter, U"save a line of text to the file\n", & file);
4307 MelderFile_writeText_e (& file, text.string, Melder_getOutputEncoding ());
4308 pushNumber (1);
4309 }
4310 static void do_appendFile () {
4311 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
4312 U"The function “appendFile” is not available inside manuals.");
4313 const Stackel elNumberOfArguments = pop;
4314 Melder_assert (elNumberOfArguments->which == Stackel_NUMBER);
4315 const integer numberOfArguments = Melder_iround (elNumberOfArguments->number);
4316 stackPointer -= numberOfArguments;
4317 const Stackel elFileName = & theStack [stackPointer + 1];
4318 Melder_require (elFileName->which == Stackel_STRING,
4319 U"The first argument of “appendFile” should be a string (a file name), not ", elFileName->whichText(), U".");
4320 autoMelderString text;
4321 shared_do_writeFile (& text, numberOfArguments);
4322 structMelderFile file { };
4323 Melder_relativePathToFile (elFileName->getString(), & file);
4324 Melder_checkTrust (theInterpreter, U"append some text to the file\n", & file);
4325 MelderFile_appendText_e (& file, text.string);
4326 pushNumber (1);
4327 }
4328 static void do_appendFileLine () {
4329 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
4330 U"The function “appendFileLine” is not available inside manuals.");
4331 const Stackel narg = pop;
4332 Melder_assert (narg->which == Stackel_NUMBER);
4333 const integer numberOfArguments = Melder_iround (narg->number);
4334 stackPointer -= numberOfArguments;
4335 const Stackel fileName = & theStack [stackPointer + 1];
4336 Melder_require (fileName->which == Stackel_STRING,
4337 U"The first argument of “appendFileLine” should be a string (a file name), not ", fileName->whichText(), U".");
4338 autoMelderString text;
4339 shared_do_writeFile (& text, numberOfArguments);
4340 MelderString_appendCharacter (& text, '\n');
4341 structMelderFile file { };
4342 Melder_relativePathToFile (fileName->getString(), & file);
4343 Melder_checkTrust (theInterpreter, U"append a line of text to the file\n", & file);
4344 MelderFile_appendText_e (& file, text.string);
4345 pushNumber (1);
4346 }
4347 static void do_pauseScript () {
4348 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
4349 U"The function “pauseScript” is not available inside manuals.");
4350 const Stackel narg = pop;
4351 Melder_assert (narg->which == Stackel_NUMBER);
4352 const integer numberOfArguments = Melder_iround (narg->number);
4353 stackPointer -= numberOfArguments;
4354 if (! theCurrentPraatApplication -> batch) { // in batch we ignore pause statements
4355 autoMelderString buffer;
4356 for (int iarg = 1; iarg <= numberOfArguments; iarg ++) {
4357 const Stackel arg = & theStack [stackPointer + iarg];
4358 if (arg->which == Stackel_NUMBER) {
4359 MelderString_append (& buffer, arg->number);
4360 } else if (arg->which == Stackel_STRING) {
4361 MelderString_append (& buffer, arg->getString());
4362 } else if (arg->which == Stackel_NUMERIC_VECTOR) {
4363 for (integer i = 1; i <= arg->numericVector.size; i ++)
4364 MelderString_append (& buffer, arg->numericVector [i],
4365 i == arg->numericVector.size ? U"" : U" ");
4366 } else if (arg->which == Stackel_NUMERIC_MATRIX) {
4367 for (integer irow = 1; irow <= arg->numericMatrix.nrow; irow ++) {
4368 for (integer icol = 1; icol <= arg->numericMatrix.ncol; icol ++)
4369 MelderString_append (& buffer, arg->numericMatrix [irow] [icol],
4370 icol == arg->numericMatrix.ncol ? U"" : U" ");
4371 MelderString_append (& buffer, irow == arg->numericMatrix.nrow ? U"" : U"\n");
4372 }
4373 } else if (arg->which == Stackel_STRING_ARRAY) {
4374 for (integer i = 1; i <= arg->stringArray.size; i ++)
4375 MelderString_append (& buffer, arg->stringArray [i],
4376 i == arg->stringArray.size ? U"" : U" ");
4377 }
4378 }
4379 const Editor optionalPauseWindowOwningEditor = theInterpreter -> optionalDynamicEnvironmentEditor();
4380 const GuiWindow parentShell = ( optionalPauseWindowOwningEditor ? optionalPauseWindowOwningEditor -> windowForm : theCurrentPraatApplication -> topShell );
4381 UiPause_pauseScript (parentShell, optionalPauseWindowOwningEditor, theInterpreter, numberOfArguments == 0 ? U"..." : buffer.string);
4382 }
4383 pushNumber (1);
4384 }
4385 static void do_exitScript () {
4386 const Stackel narg = pop;
4387 Melder_assert (narg->which == Stackel_NUMBER);
4388 const integer numberOfArguments = Melder_iround (narg->number);
4389 stackPointer -= numberOfArguments;
4390 for (int iarg = 1; iarg <= numberOfArguments; iarg ++) {
4391 const Stackel arg = & theStack [stackPointer + iarg];
4392 if (arg->which == Stackel_NUMBER) {
4393 Melder_appendError_noLine (arg->number);
4394 } else if (arg->which == Stackel_STRING) {
4395 Melder_appendError_noLine (arg->getString());
4396 } else if (arg->which == Stackel_NUMERIC_VECTOR) {
4397 for (integer i = 1; i <= arg->numericVector.size; i ++) {
4398 Melder_appendError_noLine (arg->numericVector [i]);
4399 Melder_appendError_noLine (i == arg->numericVector.size ? U"" : U" ");
4400 }
4401 } else if (arg->which == Stackel_NUMERIC_MATRIX) {
4402 for (integer irow = 1; irow <= arg->numericMatrix.nrow; irow ++) {
4403 for (integer icol = 1; icol <= arg->numericMatrix.ncol; icol ++) {
4404 Melder_appendError_noLine (arg->numericMatrix [irow] [icol]);
4405 Melder_appendError_noLine (icol == arg->numericMatrix.ncol ? U"" : U" ");
4406 }
4407 Melder_appendError_noLine (irow == arg->numericMatrix.nrow ? U"" : U"\n");
4408 }
4409 } else if (arg->which == Stackel_STRING_ARRAY) {
4410 for (integer i = 1; i <= arg->stringArray.size; i ++) {
4411 Melder_appendError_noLine (arg->stringArray [i]);
4412 Melder_appendError_noLine (i == arg->stringArray.size ? U"" : U" ");
4413 }
4414 }
4415 }
4416 Melder_throw (U"\nScript exited.");
4417 pushNumber (1);
4418 }
4419 static void do_runScript () {
4420 const Stackel narg = pop;
4421 Melder_assert (narg->which == Stackel_NUMBER);
4422 const integer numberOfArguments = Melder_iround (narg->number);
4423 if (numberOfArguments < 1)
4424 Melder_throw (U"The function “runScript” requires at least one argument, namely the file name.");
4425 stackPointer -= numberOfArguments;
4426 const Stackel fileName = & theStack [stackPointer + 1];
4427 Melder_require (fileName->which == Stackel_STRING,
4428 U"The first argument to “runScript” should be a string (the file name), not ", fileName->whichText());
4429 theLevel += 1;
4430 if (theLevel > MAXIMUM_NUMBER_OF_LEVELS) { // TODO: remove
4431 theLevel -= 1;
4432 //Melder_throw (U"Cannot call runScript() more than ", MAXIMUM_NUMBER_OF_LEVELS, U" levels deep.");
4433 }
4434 try {
4435 const Editor optionalNewInterpreterOwningWindow = theInterpreter -> optionalDynamicEnvironmentEditor();
4436 Melder_assert (theInterpreter -> owningInterpreterStack);
4437 Melder_assert (theInterpreter -> owningInterpreterStack -> current_a() == theInterpreter); // the parent interpreter
4438 praat_runScript (theInterpreter -> owningInterpreterStack, fileName->getString(), numberOfArguments - 1, & theStack [stackPointer + 1], optionalNewInterpreterOwningWindow);
4439 theLevel -= 1;
4440 } catch (MelderError) {
4441 theLevel -= 1;
4442 throw;
4443 }
4444 pushNumber (1);
4445 }
4446 static void do_runScriptWithForm () {
4447 const Stackel narg = pop;
4448 Melder_assert (narg->which == Stackel_NUMBER);
4449 const integer numberOfArguments = Melder_iround (narg->number);
4450 if (numberOfArguments != 1)
4451 Melder_throw (U"The function “runScriptWithForm” requires precisely one argument, namely the file name.");
4452 stackPointer -= numberOfArguments;
4453 const Stackel fileName = & theStack [stackPointer + 1];
4454 Melder_require (fileName->which == Stackel_STRING,
4455 U"The first argument to “runScript” should be a string (the file name), not ", fileName->whichText());
4456 theLevel += 1;
4457 if (theLevel > MAXIMUM_NUMBER_OF_LEVELS) {
4458 theLevel -= 1;
4459 Melder_throw (U"Cannot call runScriptWithForm() more than ", MAXIMUM_NUMBER_OF_LEVELS, U" levels deep.");
4460 }
4461 try {
4462 praat_runScriptWithForm (fileName->getString(), false); // TODO: inherit trust
4463 theLevel -= 1;
4464 } catch (MelderError) {
4465 theLevel -= 1;
4466 throw;
4467 }
4468 pushNumber (1);
4469 }
4470 static void do_runNotebook () {
4471 const Stackel narg = pop;
4472 Melder_assert (narg->which == Stackel_NUMBER);
4473 const integer numberOfArguments = Melder_iround (narg->number);
4474 if (numberOfArguments < 1)
4475 Melder_throw (U"The function “runNotebook” requires at least one argument, namely the file name.");
4476 stackPointer -= numberOfArguments;
4477 const Stackel fileName = & theStack [stackPointer + 1];
4478 Melder_require (fileName->which == Stackel_STRING,
4479 U"The first argument to “runNotebook” should be a string (the file name), not ", fileName->whichText());
4480 theLevel += 1;
4481 if (theLevel > MAXIMUM_NUMBER_OF_LEVELS) {
4482 theLevel -= 1;
4483 Melder_throw (U"Cannot call runNotebook() more than ", MAXIMUM_NUMBER_OF_LEVELS, U" levels deep.");
4484 }
4485 try {
4486 const Editor optionalNewInterpreterOwningWindow = theInterpreter -> optionalDynamicEnvironmentEditor();
4487 Melder_assert (theInterpreter -> owningInterpreterStack);
4488 praat_runNotebook (theInterpreter -> owningInterpreterStack, fileName->getString(), numberOfArguments - 1, & theStack [stackPointer + 1], optionalNewInterpreterOwningWindow);
4489 theLevel -= 1;
4490 } catch (MelderError) {
4491 theLevel -= 1;
4492 throw;
4493 }
4494 pushNumber (1);
4495 }
4496 static void do_runSystem () {
4497 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
4498 U"The function “runSystem” is not available inside manuals.");
4499 const Stackel narg = pop;
4500 Melder_assert (narg->which == Stackel_NUMBER);
4501 const integer numberOfArguments = Melder_iround (narg->number);
4502 stackPointer -= numberOfArguments;
4503 autoMelderString text;
4504 for (integer iarg = 1; iarg <= numberOfArguments; iarg ++) {
4505 const Stackel arg = & theStack [stackPointer + iarg];
4506 if (arg->which == Stackel_NUMBER)
4507 MelderString_append (& text, arg->number);
4508 else if (arg->which == Stackel_STRING)
4509 MelderString_append (& text, arg->getString());
4510 }
4511 Melder_checkTrust (theInterpreter, U"run the system command:\n“", text.string, U"”");
4512 try {
4513 Melder_runSystem (text.string);
4514 } catch (MelderError) {
4515 Melder_throw (U"System command <<", text.string, U">> returned error status;\n"
4516 U"if you want to ignore this, use `runSystem_nocheck` instead of `runSystem`.");
4517 }
4518 pushNumber (1);
4519 }
4520 static void do_runSystem_STR () {
4521 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
4522 U"The function “runSystem$” is not available inside manuals.");
4523 const Stackel narg = pop;
4524 Melder_assert (narg->which == Stackel_NUMBER);
4525 const integer numberOfArguments = Melder_iround (narg->number);
4526 stackPointer -= numberOfArguments;
4527 autoMelderString text;
4528 for (integer iarg = 1; iarg <= numberOfArguments; iarg ++) {
4529 const Stackel arg = & theStack [stackPointer + iarg];
4530 if (arg->which == Stackel_NUMBER)
4531 MelderString_append (& text, arg->number);
4532 else if (arg->which == Stackel_STRING)
4533 MelderString_append (& text, arg->getString());
4534 }
4535 Melder_checkTrust (theInterpreter, U"run the system command:\n“", text.string, U"”");
4536 autostring32 result;
4537 try {
4538 result = runSystem_STR (text.string);
4539 } catch (MelderError) {
4540 Melder_throw (U"System command <<", text.string, U">> returned error status;\n"
4541 U"if you want to ignore this, use `runSystem_nocheck$` instead of `runSystem$`.");
4542 }
4543 pushString (result.move());
4544 }
4545 static void do_runSystem_nocheck () {
4546 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
4547 U"The function “runSystem” is not available inside manuals.");
4548 const Stackel narg = pop;
4549 Melder_assert (narg->which == Stackel_NUMBER);
4550 const integer numberOfArguments = Melder_iround (narg->number);
4551 stackPointer -= numberOfArguments;
4552 autoMelderString text;
4553 for (int iarg = 1; iarg <= numberOfArguments; iarg ++) {
4554 const Stackel arg = & theStack [stackPointer + iarg];
4555 if (arg->which == Stackel_NUMBER)
4556 MelderString_append (& text, arg->number);
4557 else if (arg->which == Stackel_STRING)
4558 MelderString_append (& text, arg->getString());
4559 }
4560 Melder_checkTrust (theInterpreter, U"run the system command:\n“", text.string, U"”");
4561 try {
4562 Melder_runSystem (text.string);
4563 } catch (MelderError) {
4564 Melder_clearError ();
4565 }
4566 pushNumber (1);
4567 }
4568 static void do_runSubprocess () {
4569 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
4570 U"The function “runSubprocess” is not available inside manuals.");
4571 const Stackel narg = pop;
4572 Melder_assert (narg->which == Stackel_NUMBER);
4573 const integer numberOfArguments = Melder_iround (narg->number);
4574 stackPointer -= numberOfArguments;
4575 const Stackel commandFile = & theStack [stackPointer + 1];
4576 Melder_require (commandFile->which == Stackel_STRING,
4577 U"The first argument to “runSubprocess” should be a command name.");
4578 autoSTRVEC arguments (numberOfArguments - 1);
4579 for (int iarg = 1; iarg < numberOfArguments; iarg ++) {
4580 const Stackel arg = & theStack [stackPointer + 1 + iarg];
4581 if (arg->which == Stackel_NUMBER)
4582 arguments [iarg] = Melder_dup (Melder_double (arg->number));
4583 else if (arg->which == Stackel_STRING)
4584 arguments [iarg] = Melder_dup (arg->getString());
4585 }
4586 Melder_checkTrust (theInterpreter, U"run the subprocess command:\n“", commandFile->getString(), U" ", flatten_STR (arguments.get(), U"˰").get(), U"”");
4587 try {
4588 Melder_runSubprocess (commandFile->getString(), numberOfArguments - 1, arguments.peek2());
4589 } catch (MelderError) {
4590 Melder_throw (U"Command “", commandFile->getString(), U"” returned error status.");
4591 }
4592 pushNumber (1);
4593 }
4594 static void do_runSubprocess_STR () {
4595 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
4596 U"The function “runSubprocess$” is not available inside manuals.");
4597 const Stackel narg = pop;
4598 Melder_assert (narg->which == Stackel_NUMBER);
4599 const integer numberOfArguments = Melder_iround (narg->number);
4600 stackPointer -= numberOfArguments;
4601 const Stackel commandFile = & theStack [stackPointer + 1];
4602 Melder_require (commandFile->which == Stackel_STRING,
4603 U"The first argument to “runSubprocess$” should be a command name.");
4604 autoSTRVEC arguments (numberOfArguments - 1);
4605 for (int iarg = 1; iarg < numberOfArguments; iarg ++) {
4606 const Stackel arg = & theStack [stackPointer + 1 + iarg];
4607 if (arg->which == Stackel_NUMBER)
4608 arguments [iarg] = Melder_dup (Melder_double (arg->number));
4609 else if (arg->which == Stackel_STRING)
4610 arguments [iarg] = Melder_dup (arg->getString());
4611 }
4612 Melder_checkTrust (theInterpreter, U"run the subprocess command:\n“", commandFile->getString(), U" ", flatten_STR (arguments.get(), U"˰").get(), U"”");
4613 autostring32 result;
4614 try {
4615 result = runSubprocess_STR (commandFile->getString(), numberOfArguments - 1, arguments.peek2());
4616 } catch (MelderError) {
4617 Melder_throw (U"Command “", commandFile->getString(), U"” returned error status.");
4618 }
4619 pushString (result.move());
4620 }
4621 static void do_min () {
4622 const Stackel n = pop;
4623 Melder_assert (n->which == Stackel_NUMBER);
4624 Melder_require (n->number >= 1,
4625 U"The function “min” requires at least one argument.");
4626 const Stackel last = pop;
4627 if (last->which == Stackel_NUMBER) {
4628 /*@praat
4629 assert min (5, 6, 1, 7) = 1
4630 assert min (undefined, 6, 1, 7) = undefined
4631 assert min (5, undefined, 1, 7) = undefined
4632 assert min (5, 6, undefined, 7) = undefined
4633 assert min (5, 6, 1, undefined) = undefined
4634 assert min (undefined, undefined) = undefined
4635 assert min (undefined) = undefined
4636 assert min (5) = 5
4637 @*/
4638 integer size = Melder_iround (n->number);
4639 autoVEC numericVector = raw_VEC (size);
4640 numericVector [size] = last->number;
4641 for (integer i = size - 1; i > 0; i --) {
4642 const Stackel element = pop;
4643 Melder_require (element->which == Stackel_NUMBER,
4644 U"The function “min” cannot mix a numeric argument with ", element->whichText(), U".");
4645 numericVector [i] = element->number;
4646 }
4647 pushNumber (NUMmin_u (numericVector.get()));
4648 } else if (last->which == Stackel_NUMERIC_VECTOR) {
4649 /*@praat
4650 assert min ({ 5, 6, 1, 7 }) = 1
4651 assert min ({ undefined, 6, 1, 7 }) = undefined
4652 assert min ({ 5, undefined, 1, 7 }) = undefined
4653 assert min ({ 5, 6, undefined, 7 }) = undefined
4654 assert min ({ 5, 6, 1, undefined }) = undefined
4655 assert min ({ undefined, undefined }) = undefined
4656 assert min ({ undefined }) = undefined
4657 assert min (zero# (0)) = undefined
4658 assert min ({ }) = undefined
4659 @*/
4660 Melder_require (n->number == 1,
4661 U"The function “min” requires exactly one vector argument.");
4662 pushNumber (NUMmin_u (last->numericVector));
4663 } else {
4664 Melder_throw (U"Cannot compute the minimum of ", last->whichText(), U".");
4665 }
4666 }
4667 static void do_min_e () {
4668 const Stackel n = pop;
4669 Melder_assert (n->which == Stackel_NUMBER);
4670 Melder_require (n->number >= 1,
4671 U"The function “min_e” requires at least one argument.");
4672 const Stackel last = pop;
4673 if (last->which == Stackel_NUMBER) {
4674 /*@praat
4675 assert min_e (5, 6, 1, 7) = 1
4676 asserterror cannot determine the minimum of a vector: element 1 is undefined.
4677 pos = min_e (undefined, 6, 1, 7)
4678 asserterror cannot determine the minimum of a vector: element 2 is undefined.
4679 pos = min_e (5, undefined, 1, 7)
4680 asserterror cannot determine the minimum of a vector: element 3 is undefined.
4681 pos = min_e (5, 6, undefined, 7)
4682 asserterror cannot determine the minimum of a vector: element 4 is undefined.
4683 pos = min_e (5, 6, 1, undefined)
4684 asserterror cannot determine the minimum of a vector: element 1 is undefined.
4685 pos = min_e (undefined, undefined)
4686 asserterror cannot determine the minimum of a vector: element 1 is undefined.
4687 pos = min_e (undefined)
4688 assert min_e (5) = 5
4689 @*/
4690 integer size = Melder_iround (n->number);
4691 autoVEC numericVector = raw_VEC (size);
4692 numericVector [size] = last->number;
4693 for (integer i = size - 1; i > 0; i --) {
4694 const Stackel element = pop;
4695 Melder_require (element->which == Stackel_NUMBER,
4696 U"The function “min_e” cannot mix a numeric argument with ", element->whichText(), U".");
4697 numericVector [i] = element->number;
4698 }
4699 pushNumber (NUMmin_e (numericVector.get()));
4700 } else if (last->which == Stackel_NUMERIC_VECTOR) {
4701 /*@praat
4702 assert min_e ({ 5, 6, 1, 7 }) = 1
4703 asserterror cannot determine the minimum of a vector: element 1 is undefined.
4704 pos = min_e ({ undefined, 6, 1, 7 })
4705 asserterror cannot determine the minimum of a vector: element 2 is undefined.
4706 pos = min_e ({ 5, undefined, 1, 7 })
4707 asserterror cannot determine the minimum of a vector: element 3 is undefined.
4708 pos = min_e ({ 5, 6, undefined, 7 })
4709 asserterror cannot determine the minimum of a vector: element 4 is undefined.
4710 pos = min_e ({ 5, 6, 1, undefined })
4711 asserterror cannot determine the minimum of a vector: element 1 is undefined.
4712 pos = min_e ({ undefined, undefined })
4713 asserterror cannot determine the minimum of a vector: element 1 is undefined.
4714 pos = min_e ({ undefined })
4715 asserterror cannot determine the minimum of an empty vector.
4716 pos = min_e (zero# (0))
4717 asserterror cannot determine the minimum of an empty vector.
4718 pos = min_e ({})
4719 @*/
4720 Melder_require (n->number == 1,
4721 U"The function “min_e” requires exactly one vector argument.");
4722 pushNumber (NUMmin_e (last->numericVector));
4723 } else {
4724 Melder_throw (U"Cannot compute the minimum of ", last->whichText(), U".");
4725 }
4726 }
4727 static void do_min_removeUndefined () {
4728 const Stackel n = pop;
4729 Melder_assert (n->which == Stackel_NUMBER);
4730 Melder_require (n->number >= 1,
4731 U"The function “min_removeUndefined” requires at least one argument.");
4732 const Stackel last = pop;
4733 if (last->which == Stackel_NUMBER) {
4734 /*@praat
4735 assert min_removeUndefined (5, 6, 1, 7) = 1
4736 assert min_removeUndefined (undefined, 6, 1, 7) = 1
4737 assert min_removeUndefined (5, undefined, 1, 7) = 1
4738 assert min_removeUndefined (5, 6, undefined, 7) = 5
4739 assert min_removeUndefined (5, 6, 1, undefined) = 1
4740 assert min_removeUndefined (undefined, undefined) = undefined
4741 assert min_removeUndefined (undefined) = undefined
4742 assert min_removeUndefined (5) = 5
4743 @*/
4744 integer size = Melder_iround (n->number);
4745 autoVEC numericVector = raw_VEC (size);
4746 numericVector [size] = last->number;
4747 for (integer i = size - 1; i > 0; i --) {
4748 const Stackel element = pop;
4749 Melder_require (element->which == Stackel_NUMBER,
4750 U"The function “min_removeUndefined” cannot mix a numeric argument with ", element->whichText(), U".");
4751 numericVector [i] = element->number;
4752 }
4753 pushNumber (NUMmin_removeUndefined_u (numericVector.get()));
4754 } else if (last->which == Stackel_NUMERIC_VECTOR) {
4755 /*@praat
4756 assert min_removeUndefined ({ 5, 6, 1, 7 }) = 1
4757 assert min_removeUndefined ({ undefined, 6, 1, 7 }) = 1
4758 assert min_removeUndefined ({ 5, undefined, 1, 7 }) = 1
4759 assert min_removeUndefined ({ 5, 6, undefined, 7 }) = 5
4760 assert min_removeUndefined ({ 5, 6, 1, undefined }) = 1
4761 assert min_removeUndefined ({ undefined, undefined }) = undefined
4762 assert min_removeUndefined ({ undefined }) = undefined
4763 assert min_removeUndefined (zero# (0)) = undefined
4764 assert min_removeUndefined ({ }) = undefined
4765 @*/
4766 Melder_require (n->number == 1,
4767 U"The function “min_removeUndefined” requires exactly one vector argument.");
4768 pushNumber (NUMmin_removeUndefined_u (last->numericVector));
4769 } else {
4770 Melder_throw (U"Cannot compute the minimum of ", last->whichText(), U".");
4771 }
4772 }
4773 static void do_max () {
4774 const Stackel n = pop;
4775 Melder_assert (n->which == Stackel_NUMBER);
4776 Melder_require (n->number >= 1,
4777 U"The function “max” requires at least one argument.");
4778 const Stackel last = pop;
4779 if (last->which == Stackel_NUMBER) {
4780 integer size = Melder_iround (n->number);
4781 autoVEC numericVector = raw_VEC (size);
4782 numericVector [size] = last->number;
4783 for (integer i = size - 1; i > 0; i --) {
4784 const Stackel element = pop;
4785 Melder_require (element->which == Stackel_NUMBER,
4786 U"The function “max_removeUndefined” cannot mix a numeric argument with ", element->whichText(), U".");
4787 numericVector [i] = element->number;
4788 }
4789 pushNumber (NUMmax_u (numericVector.get()));
4790 } else if (last->which == Stackel_NUMERIC_VECTOR) {
4791 Melder_require (n->number == 1,
4792 U"The function “max” requires exactly one vector argument.");
4793 pushNumber (NUMmax_u (last->numericVector));
4794 } else {
4795 Melder_throw (U"Cannot compute the maximum of ", last->whichText(), U".");
4796 }
4797 }
4798 static void do_max_e () {
4799 const Stackel n = pop;
4800 Melder_assert (n->which == Stackel_NUMBER);
4801 Melder_require (n->number >= 1,
4802 U"The function “max_e” requires at least one argument.");
4803 const Stackel last = pop;
4804 if (last->which == Stackel_NUMBER) {
4805 integer size = Melder_iround (n->number);
4806 autoVEC numericVector = raw_VEC (size);
4807 numericVector [size] = last->number;
4808 for (integer i = size - 1; i > 0; i --) {
4809 const Stackel element = pop;
4810 Melder_require (element->which == Stackel_NUMBER,
4811 U"The function “max_e” cannot mix a numeric argument with ", element->whichText(), U".");
4812 numericVector [i] = element->number;
4813 }
4814 pushNumber (NUMmax_e (numericVector.get()));
4815 } else if (last->which == Stackel_NUMERIC_VECTOR) {
4816 Melder_require (n->number == 1,
4817 U"The function “max_e” requires exactly one vector argument.");
4818 pushNumber (NUMmax_e (last->numericVector));
4819 } else {
4820 Melder_throw (U"Cannot compute the maximum of ", last->whichText(), U".");
4821 }
4822 }
4823 static void do_max_removeUndefined () {
4824 const Stackel n = pop;
4825 Melder_assert (n->which == Stackel_NUMBER);
4826 Melder_require (n->number >= 1,
4827 U"The function “max_removeUndefined” requires at least one argument.");
4828 const Stackel last = pop;
4829 if (last->which == Stackel_NUMBER) {
4830 integer size = Melder_iround (n->number);
4831 autoVEC numericVector = raw_VEC (size);
4832 numericVector [size] = last->number;
4833 for (integer i = size - 1; i > 0; i --) {
4834 const Stackel element = pop;
4835 Melder_require (element->which == Stackel_NUMBER,
4836 U"The function “max_removeUndefined” cannot mix a numeric argument with ", element->whichText(), U".");
4837 numericVector [i] = element->number;
4838 }
4839 pushNumber (NUMmax_removeUndefined_u (numericVector.get()));
4840 } else if (last->which == Stackel_NUMERIC_VECTOR) {
4841 Melder_require (n->number == 1,
4842 U"The function “max_removeUndefined” requires exactly one vector argument.");
4843 pushNumber (NUMmax_removeUndefined_u (last->numericVector));
4844 } else {
4845 Melder_throw (U"Cannot compute the maximum of ", last->whichText(), U".");
4846 }
4847 }
4848 static void do_imin () {
4849 const Stackel n = pop;
4850 Melder_assert (n->which == Stackel_NUMBER);
4851 Melder_require (n->number >= 1,
4852 U"The function “imin” requires at least one argument.");
4853 const Stackel last = pop;
4854 if (last->which == Stackel_NUMBER) {
4855 double minimum = last->number;
4856 double result = n->number;
4857 for (integer j = Melder_iround (n->number) - 1; j > 0; j --) {
4858 Stackel previous = pop;
4859 Melder_require (previous->which == Stackel_NUMBER,
4860 U"The function “imin” cannot mix a numeric argument with ", previous->whichText(), U".");
4861 if (isundef (minimum) || isundef (previous->number)) {
4862 minimum = undefined;
4863 result = undefined;
4864 } else if (previous->number < minimum) {
4865 minimum = previous->number;
4866 result = j;
4867 }
4868 }
4869 pushNumber (result);
4870 } else if (last->which == Stackel_NUMERIC_VECTOR) {
4871 Melder_require (n->number == 1,
4872 U"The function “imin” requires exactly one vector argument.");
4873 const integer numberOfElements = last->numericVector.size;
4874 integer result = 1;
4875 double minimum = last->numericVector [1];
4876 for (integer i = 2; i <= numberOfElements; i ++) {
4877 if (last->numericVector [i] < minimum) {
4878 result = i;
4879 minimum = last->numericVector [i];
4880 }
4881 }
4882 pushNumber (result);
4883 } else {
4884 Melder_throw (U"Cannot compute the imin of ", last->whichText(), U".");
4885 }
4886 }
4887 static void do_imin_e () {
4888 const Stackel n = pop;
4889 Melder_assert (n->which == Stackel_NUMBER);
4890 Melder_require (n->number >= 1,
4891 U"The function “imin_e” requires at least one argument.");
4892 const Stackel last = pop;
4893 if (last->which == Stackel_NUMBER) {
4894 double minimum = last->number;
4895 double result = n->number;
4896 for (integer j = Melder_iround (n->number) - 1; j > 0; j --) {
4897 Stackel previous = pop;
4898 Melder_require (previous->which == Stackel_NUMBER,
4899 U"The function “imin_e” cannot mix a numeric argument with ", previous->whichText(), U".");
4900 if (isundef (minimum) || isundef (previous->number)) {
4901 minimum = undefined;
4902 result = undefined;
4903 } else if (previous->number < minimum) {
4904 minimum = previous->number;
4905 result = j;
4906 }
4907 }
4908 pushNumber (result);
4909 } else if (last->which == Stackel_NUMERIC_VECTOR) {
4910 Melder_require (n->number == 1,
4911 U"The function “imin_e” requires exactly one vector argument.");
4912 const integer numberOfElements = last->numericVector.size;
4913 integer result = 1;
4914 double minimum = last->numericVector [1];
4915 for (integer i = 2; i <= numberOfElements; i ++) {
4916 if (last->numericVector [i] < minimum) {
4917 result = i;
4918 minimum = last->numericVector [i];
4919 }
4920 }
4921 pushNumber (result);
4922 } else {
4923 Melder_throw (U"Cannot compute the imin of ", last->whichText(), U".");
4924 }
4925 }
4926 static void do_imin_removeUndefined () {
4927 const Stackel n = pop;
4928 Melder_assert (n->which == Stackel_NUMBER);
4929 Melder_require (n->number >= 1,
4930 U"The function “imin_removeUndefined” requires at least one argument.");
4931 const Stackel last = pop;
4932 if (last->which == Stackel_NUMBER) {
4933 double minimum = last->number;
4934 double result = n->number;
4935 for (integer j = Melder_iround (n->number) - 1; j > 0; j --) {
4936 Stackel previous = pop;
4937 Melder_require (previous->which == Stackel_NUMBER,
4938 U"The function “imin_removeUndefined” cannot mix a numeric argument with ", previous->whichText(), U".");
4939 if (isundef (minimum) || isundef (previous->number)) {
4940 minimum = undefined;
4941 result = undefined;
4942 } else if (previous->number < minimum) {
4943 minimum = previous->number;
4944 result = j;
4945 }
4946 }
4947 pushNumber (result);
4948 } else if (last->which == Stackel_NUMERIC_VECTOR) {
4949 Melder_require (n->number == 1,
4950 U"The function “imin_removeUndefined” requires exactly one vector argument.");
4951 const integer numberOfElements = last->numericVector.size;
4952 integer result = 1;
4953 double minimum = last->numericVector [1];
4954 for (integer i = 2; i <= numberOfElements; i ++) {
4955 if (last->numericVector [i] < minimum) {
4956 result = i;
4957 minimum = last->numericVector [i];
4958 }
4959 }
4960 pushNumber (result);
4961 } else {
4962 Melder_throw (U"Cannot compute the imin of ", last->whichText(), U".");
4963 }
4964 }
4965 static void do_imax () {
4966 const Stackel n = pop;
4967 Melder_assert (n->which == Stackel_NUMBER);
4968 Melder_require (n->number >= 1,
4969 U"The function “imax” requires at least one argument.");
4970 const Stackel last = pop;
4971 if (last->which == Stackel_NUMBER) {
4972 double maximum = last->number;
4973 double result = n->number;
4974 for (integer j = Melder_iround (n->number) - 1; j > 0; j --) {
4975 const Stackel previous = pop;
4976 Melder_require (previous->which == Stackel_NUMBER,
4977 U"The function “imax” cannot mix a numeric argument with ", previous->whichText(), U".");
4978 if (isundef (maximum) || isundef (previous->number)) {
4979 maximum = undefined;
4980 result = undefined;
4981 } else if (previous->number > maximum) {
4982 maximum = previous->number;
4983 result = j;
4984 }
4985 }
4986 pushNumber (result);
4987 } else if (last->which == Stackel_NUMERIC_VECTOR) {
4988 Melder_require (n->number == 1,
4989 U"The function “imax” requires exactly one vector argument.");
4990 const integer numberOfElements = last->numericVector.size;
4991 integer result = 1;
4992 double maximum = last->numericVector [1];
4993 for (integer i = 2; i <= numberOfElements; i ++) {
4994 if (last->numericVector [i] > maximum) {
4995 result = i;
4996 maximum = last->numericVector [i];
4997 }
4998 }
4999 pushNumber (result);
5000 } else {
5001 Melder_throw (U"Cannot compute the imax of ", last->whichText(), U".");
5002 }
5003 }
5004 static void do_imax_e () {
5005 const Stackel n = pop;
5006 Melder_assert (n->which == Stackel_NUMBER);
5007 Melder_require (n->number >= 1,
5008 U"The function “imax_e” requires at least one argument.");
5009 const Stackel last = pop;
5010 if (last->which == Stackel_NUMBER) {
5011 double maximum = last->number;
5012 double result = n->number;
5013 for (integer j = Melder_iround (n->number) - 1; j > 0; j --) {
5014 const Stackel previous = pop;
5015 Melder_require (previous->which == Stackel_NUMBER,
5016 U"The function “imax_e” cannot mix a numeric argument with ", previous->whichText(), U".");
5017 if (isundef (maximum) || isundef (previous->number)) {
5018 maximum = undefined;
5019 result = undefined;
5020 } else if (previous->number > maximum) {
5021 maximum = previous->number;
5022 result = j;
5023 }
5024 }
5025 pushNumber (result);
5026 } else if (last->which == Stackel_NUMERIC_VECTOR) {
5027 Melder_require (n->number == 1,
5028 U"The function “imax_e” requires exactly one vector argument.");
5029 const integer numberOfElements = last->numericVector.size;
5030 integer result = 1;
5031 double maximum = last->numericVector [1];
5032 for (integer i = 2; i <= numberOfElements; i ++) {
5033 if (last->numericVector [i] > maximum) {
5034 result = i;
5035 maximum = last->numericVector [i];
5036 }
5037 }
5038 pushNumber (result);
5039 } else {
5040 Melder_throw (U"Cannot compute the imax of ", last->whichText(), U".");
5041 }
5042 }
5043 static void do_imax_removeUndefined () {
5044 const Stackel n = pop;
5045 Melder_assert (n->which == Stackel_NUMBER);
5046 Melder_require (n->number >= 1,
5047 U"The function “imax_removeUndefined” requires at least one argument.");
5048 const Stackel last = pop;
5049 if (last->which == Stackel_NUMBER) {
5050 double maximum = last->number;
5051 double result = n->number;
5052 for (integer j = Melder_iround (n->number) - 1; j > 0; j --) {
5053 const Stackel previous = pop;
5054 Melder_require (previous->which == Stackel_NUMBER,
5055 U"The function “imax_removeUndefined” cannot mix a numeric argument with ", previous->whichText(), U".");
5056 if (isundef (maximum) || isundef (previous->number)) {
5057 maximum = undefined;
5058 result = undefined;
5059 } else if (previous->number > maximum) {
5060 maximum = previous->number;
5061 result = j;
5062 }
5063 }
5064 pushNumber (result);
5065 } else if (last->which == Stackel_NUMERIC_VECTOR) {
5066 Melder_require (n->number == 1,
5067 U"The function “imax_removeUndefined” requires exactly one vector argument.");
5068 const integer numberOfElements = last->numericVector.size;
5069 integer result = 1;
5070 double maximum = last->numericVector [1];
5071 for (integer i = 2; i <= numberOfElements; i ++) {
5072 if (last->numericVector [i] > maximum) {
5073 result = i;
5074 maximum = last->numericVector [i];
5075 }
5076 }
5077 pushNumber (result);
5078 } else {
5079 Melder_throw (U"Cannot compute the imax of ", last->whichText(), U".");
5080 }
5081 }
5082 static void do_quantile () {
5083 const Stackel n = pop;
5084 Melder_assert (n->which == Stackel_NUMBER);
5085 Melder_require (n->number == 2,
5086 U"The function “quantile” requires two arguments, not ", n->number, U".");
5087 const Stackel quantile = pop;
5088 Melder_require (quantile->which == Stackel_NUMBER,
5089 U"The second argument to “quantile” should be a number, not ", quantile->which, U".");
5090 const Stackel vec = pop;
5091 Melder_require (vec->which == Stackel_NUMERIC_VECTOR,
5092 U"The first argument to “quantile” should be a numeric vector, not ", vec->which, U".");
5093 pushNumber (NUMquantile (vec->numericVector, quantile->number));
5094 }
5095 static void do_norm () {
5096 const Stackel n = pop;
5097 Melder_assert (n->which == Stackel_NUMBER);
5098 Melder_require (n->number == 1 || n->number == 2,
5099 U"The function “norm” requires one or two arguments.");
5100 double powerNumber = 2.0;
5101 if (n->number == 2) {
5102 const Stackel power = pop;
5103 if (power->which != Stackel_NUMBER)
5104 Melder_throw (U"The second argument to “norm” should be a number, not ", power->whichText(), U".");
5105 powerNumber = power->number;
5106 }
5107 const Stackel x = pop;
5108 if (x->which == Stackel_NUMERIC_VECTOR) {
5109 pushNumber (NUMnorm (x->numericVector, powerNumber));
5110 } else if (x->which == Stackel_NUMERIC_MATRIX) {
5111 pushNumber (NUMnorm (x->numericMatrix, powerNumber));
5112 } else {
5113 Melder_throw (U"Cannot compute the norm of ", x->whichText(), U".");
5114 }
5115 }
5116 static void do_zero_VEC () {
5117 const Stackel narg = pop;
5118 Melder_assert (narg->which == Stackel_NUMBER);
5119 const integer rank = Melder_iround (narg->number);
5120 Melder_require (rank >= 1,
5121 U"The function “zero#” requires an argument.");
5122 Melder_require (rank <= 1,
5123 U"The function “zero#” cannot have more than one argument (consider using zero##).");
5124 const Stackel nelem = pop;
5125 Melder_require (nelem->which == Stackel_NUMBER,
5126 U"In the function “zero#”, the number of elements should be a number, not ", nelem->whichText(), U".");
5127 const double numberOfElements = nelem->number;
5128 Melder_require (isdefined (numberOfElements),
5129 U"In the function “zero#”, the number of elements is undefined.");
5130 Melder_require (numberOfElements >= 0.0,
5131 U"In the function “zero#”, the number of elements should not be negative.");
5132 pushNumericVector (zero_VEC (Melder_iround (numberOfElements)));
5133 }
5134 static void do_zero_MAT () {
5135 const Stackel narg = pop;
5136 Melder_assert (narg->which == Stackel_NUMBER);
5137 const integer rank = Melder_iround (narg->number);
5138 Melder_require (rank == 2,
5139 U"The function “zero##” requires two arguments.");
5140 const Stackel ncol = pop;
5141 Melder_require (ncol->which == Stackel_NUMBER,
5142 U"In the function “zero##”, the number of columns should be a number, not ", ncol->whichText(), U".");
5143 const double numberOfColumns = ncol->number;
5144 const Stackel nrow = pop;
5145 Melder_require (nrow->which == Stackel_NUMBER,
5146 U"In the function “zero##”, the number of rows should be a number, not ", nrow->whichText(), U".");
5147 const double numberOfRows = nrow->number;
5148 Melder_require (isdefined (numberOfRows),
5149 U"In the function “zero##”, the number of rows is undefined.");
5150 Melder_require (isdefined (numberOfColumns),
5151 U"In the function “zero##”, the number of columns is undefined.");
5152 Melder_require (numberOfRows >= 0.0,
5153 U"In the function “zero##”, the number of rows should not be negative.");
5154 Melder_require (numberOfColumns >= 0.0,
5155 U"In the function “zero##”, the number of columns should not be negative.");
5156 autoMAT result = zero_MAT (Melder_iround (numberOfRows), Melder_iround (numberOfColumns));
5157 pushNumericMatrix (result.move());
5158 }
5159 static void do_linear_VEC () {
5160 const Stackel stackel_narg = pop;
5161 Melder_assert (stackel_narg->which == Stackel_NUMBER);
5162 const integer narg = Melder_iround (stackel_narg->number);
5163 Melder_require (narg == 3 || narg == 4,
5164 U"The function “linear#” requires three or four arguments.");
5165 bool excludeEdges = false; // default
5166 if (narg == 4) {
5167 Stackel stack_excludeEdges = pop;
5168 if (stack_excludeEdges->which != Stackel_NUMBER)
5169 Melder_throw (U"In the function “linear#”, the edge exclusion flag (fourth argument) should be a number, not ", stack_excludeEdges->whichText(), U".");
5170 excludeEdges = Melder_iround (stack_excludeEdges->number);
5171 }
5172 const Stackel stack_numberOfSteps = pop, stack_maximum = pop, stack_minimum = pop;
5173 Melder_require (stack_minimum -> which == Stackel_NUMBER,
5174 U"In the function “linear#”, the minimum (first argument) should be a number, not ", stack_minimum->whichText(), U".");
5175 const double minimum = stack_minimum->number;
5176 Melder_require (isdefined (minimum),
5177 U"Undefined minimum in the function “linear#” (first argument).");
5178 Melder_require (stack_maximum->which == Stackel_NUMBER,
5179 U"In the function “linear#”, the maximum (second argument) should be a number, not ", stack_maximum->whichText(), U".");
5180 const double maximum = stack_maximum->number;
5181 Melder_require (isdefined (maximum),
5182 U"Undefined maximum in the function “linear#” (second argument).");
5183 Melder_require (maximum >= minimum,
5184 U"Maximum (", maximum, U") smaller than minimum (", minimum, U") in function “linear#”.");
5185 Melder_require (stack_numberOfSteps -> which == Stackel_NUMBER,
5186 U"In the function “linear#”, the number of steps (third argument) should be a number, not ", stack_numberOfSteps->whichText(), U".");
5187 Melder_require (isdefined (stack_numberOfSteps->number),
5188 U"Undefined number of steps in the function “linear#” (third argument).");
5189 const integer numberOfSteps = Melder_iround (stack_numberOfSteps->number);
5190 Melder_require (numberOfSteps > 0,
5191 U"In the function “linear#”, the number of steps (third argument) should be positive, not ", numberOfSteps, U".");
5192 autoVEC result = raw_VEC (numberOfSteps);
5193 for (integer ielem = 1; ielem <= numberOfSteps; ielem ++) {
5194 result [ielem] = excludeEdges ?
5195 minimum + (ielem - 0.5) * (maximum - minimum) / numberOfSteps :
5196 minimum + (ielem - 1) * (maximum - minimum) / (numberOfSteps - 1);
5197 }
5198 if (! excludeEdges)
5199 result [numberOfSteps] = maximum; // remove rounding problems
5200 pushNumericVector (result.move());
5201 }
5202 static void do_to_VEC () {
5203 const Stackel narg = pop;
5204 Melder_assert (narg->which == Stackel_NUMBER);
5205 Melder_require (narg->number == 1,
5206 U"The function to#() requires one argument.");
5207 const Stackel to = pop;
5208 Melder_require (to->which == Stackel_NUMBER,
5209 U"In the function “to#”, the argument should be a number, not ", to->whichText(), U".");
5210 autoVEC result = to_VEC (to->number);
5211 pushNumericVector (result.move());
5212 }
5213 static void do_from_to_VEC () {
5214 const Stackel narg = pop;
5215 Melder_assert (narg->which == Stackel_NUMBER);
5216 Melder_require (narg->number == 2,
5217 U"The function “from_to#” requires two arguments.");
5218 const Stackel to = pop, from = pop;
5219 Melder_require (from->which == Stackel_NUMBER,
5220 U"In the function “from_to#”, the first argument should be a number, not ", from->whichText(), U".");
5221 Melder_require (to->which == Stackel_NUMBER,
5222 U"In the function “from_to#”, the second argument should be a number, not ", to->whichText(), U".");
5223 autoVEC result = from_to_VEC (from->number, to->number);
5224 pushNumericVector (result.move());
5225 }
5226 static void do_from_to_by_VEC () {
5227 const Stackel narg = pop;
5228 Melder_assert (narg->which == Stackel_NUMBER);
5229 Melder_require (narg->number == 3,
5230 U"The function “from_to_by#” requires three arguments.");
5231 const Stackel by = pop, to = pop, from = pop;
5232 Melder_require (from->which == Stackel_NUMBER,
5233 U"In the function “from_to_by#”, the first argument should be a number, not ", from->whichText(), U".");
5234 Melder_require (to->which == Stackel_NUMBER,
5235 U"In the function “from_to_by#”, the second argument should be a number, not ", to->whichText(), U".");
5236 Melder_require (by->which == Stackel_NUMBER,
5237 U"In the function “from_to_by#”, the third argument should be a number (the step), not ", by->whichText(), U".");
5238 autoVEC result = from_to_by_VEC (from->number, to->number, by->number);
5239 pushNumericVector (result.move());
5240 }
5241 static void do_from_to_count_VEC () {
5242 const Stackel narg = pop;
5243 Melder_assert (narg->which == Stackel_NUMBER);
5244 Melder_require (narg->number == 3,
5245 U"The function “from_to_count#” requires three arguments.");
5246 const Stackel count = pop, to = pop, from = pop;
5247 Melder_require (from->which == Stackel_NUMBER,
5248 U"In the function “from_to_count#”, the first argument should be a number, not ", from->whichText(), U".");
5249 Melder_require (to->which == Stackel_NUMBER,
5250 U"In the function “from_to_count#”, the second argument should be a number, not ", to->whichText(), U".");
5251 Melder_require (count->which == Stackel_NUMBER,
5252 U"In the function “from_to_count#”, the third argument should be a number (the count), not ", count->whichText(), U".");
5253 autoVEC result = from_to_count_VEC (from->number, to->number, Melder_iround (count->number));
5254 pushNumericVector (result.move());
5255 }
5256 static void do_between_by_VEC () {
5257 const Stackel narg = pop;
5258 Melder_assert (narg->which == Stackel_NUMBER);
5259 Melder_require (narg->number == 3,
5260 U"The function “between_by#” requires three arguments.");
5261 const Stackel by = pop, to = pop, from = pop;
5262 Melder_require (from->which == Stackel_NUMBER,
5263 U"In the function “between_by#”, the first argument should be a number, not ", from->whichText(), U".");
5264 Melder_require (to->which == Stackel_NUMBER,
5265 U"In the function “between_by#”, the second argument should be a number, not ", to->whichText(), U".");
5266 Melder_require (by->which == Stackel_NUMBER,
5267 U"In the function “between_by#”, the third argument should be a number (the step), not ", by->whichText(), U".");
5268 autoVEC result = between_by_VEC (from->number, to->number, by->number);
5269 pushNumericVector (result.move());
5270 }
5271 static void do_between_count_VEC () {
5272 const Stackel narg = pop;
5273 Melder_assert (narg->which == Stackel_NUMBER);
5274 Melder_require (narg->number == 3,
5275 U"The function “between_count#” requires three arguments.");
5276 const Stackel count = pop, to = pop, from = pop;
5277 Melder_require (from->which == Stackel_NUMBER,
5278 U"In the function “between_count#”, the first argument should be a number, not ", from->whichText(), U".");
5279 Melder_require (to->which == Stackel_NUMBER,
5280 U"In the function “between_count#”, the second argument should be a number, not ", to->whichText(), U".");
5281 Melder_require (count->which == Stackel_NUMBER,
5282 U"In the function “between_count#”, the third argument should be a number (the count), not ", count->whichText(), U".");
5283 autoVEC result = between_count_VEC (from->number, to->number, Melder_iround (count->number));
5284 pushNumericVector (result.move());
5285 }
5286 static void do_sort_VEC () {
5287 const Stackel narg = pop;
5288 Melder_assert (narg->which == Stackel_NUMBER);
5289 Melder_require (narg->number == 1,
5290 U"The function “sort#” requires one argument, namely a vector.");
5291 const Stackel vec = pop;
5292 Melder_require (vec->which == Stackel_NUMERIC_VECTOR,
5293 U"The argument of the function “sort#” should be a numeric vector, not ", vec->whichText(), U".");
5294 autoVEC result = sort_e_VEC (vec->numericVector);
5295 pushNumericVector (result.move());
5296 }
5297 static void do_sort_removeUndefined_VEC () {
5298 const Stackel narg = pop;
5299 Melder_assert (narg->which == Stackel_NUMBER);
5300 Melder_require (narg->number == 1,
5301 U"The function “sort_removeUndefined#” requires one argument, namely a vector.");
5302 const Stackel vec = pop;
5303 Melder_require (vec->which == Stackel_NUMERIC_VECTOR,
5304 U"The argument of the function “sort_removeUndefined#” should be a numeric vector, not ", vec->whichText(), U".");
5305 autoVEC result = sort_removeUndefined_VEC (vec->numericVector);
5306 pushNumericVector (result.move());
5307 }
5308 static void do_sort_STRVEC () {
5309 const Stackel narg = pop;
5310 Melder_assert (narg->which == Stackel_NUMBER);
5311 Melder_require (narg->number == 1,
5312 U"The function “sort$#” requires one argument, namely a string array.");
5313 const Stackel strvec = pop;
5314 Melder_require (strvec->which == Stackel_STRING_ARRAY,
5315 U"The argument of the function “sort$#” should be a string array, not ", strvec->whichText(), U".");
5316 autoSTRVEC result = sort_STRVEC (strvec->stringArray);
5317 pushStringVector (result.move());
5318 }
5319 static void do_sort_numberAware_STRVEC () {
5320 const Stackel narg = pop;
5321 Melder_assert (narg->which == Stackel_NUMBER);
5322 Melder_require (narg->number == 1,
5323 U"The function “sort_numberAware$#” requires one argument, namely a string array.");
5324 const Stackel strvec = pop;
5325 Melder_require (strvec->which == Stackel_STRING_ARRAY,
5326 U"The argument of the function “sort_numberAware$#” should be a string array, not ", strvec->whichText(), U".");
5327 autoSTRVEC result = sort_numberAware_STRVEC (strvec->stringArray);
5328 pushStringVector (result.move());
5329 }
5330 static void do_shuffle_VEC () {
5331 const Stackel narg = pop;
5332 Melder_assert (narg->which == Stackel_NUMBER);
5333 Melder_require (narg->number == 1,
5334 U"The function “shuffle#” requires one argument, namely a vector.");
5335 const Stackel vec = pop;
5336 Melder_require (vec->which == Stackel_NUMERIC_VECTOR,
5337 U"The argument of the function “shuffle#” should be a numeric vector, not ", vec->whichText(), U".");
5338 autoVEC result = shuffle_VEC (vec->numericVector);
5339 pushNumericVector (result.move());
5340 }
5341 static void do_shuffle_STRVEC () {
5342 const Stackel narg = pop;
5343 Melder_assert (narg->which == Stackel_NUMBER);
5344 Melder_require (narg->number == 1,
5345 U"The function “shuffle$#” requires one argument, namely a string array.");
5346 const Stackel strvec = pop;
5347 Melder_require (strvec->which == Stackel_STRING_ARRAY,
5348 U"The argument of the function “shuffle$#” should be a string array, not ", strvec->whichText(), U".");
5349 autoSTRVEC result = shuffle_STRVEC (strvec->stringArray);
5350 pushStringVector (result.move());
5351 }
5352 static void do_peaks_MAT () {
5353 const Stackel narg = pop;
5354 Melder_assert (narg->which == Stackel_NUMBER);
5355 Melder_require (narg->number == 4,
5356 U"The function peaks## requires four arguments (vector, edges, interpolation, sortByHeight).");
5357 const Stackel s = pop;
5358 if (s->which != Stackel_NUMBER)
5359 Melder_throw (U"The fourth argument to peaks## should be a number, not ", s->whichText(), U".");
5360 bool sortByHeight = s->number != 0.0;
5361 const Stackel i = pop;
5362 if (i->which != Stackel_NUMBER)
5363 Melder_throw (U"The third argument to peaks## should be a number, not ", i->whichText(), U".");
5364 integer interpolation = Melder_iround (i->number);
5365 const Stackel e = pop;
5366 if (e->which != Stackel_NUMBER)
5367 Melder_throw (U"The second argument to peaks## should be a number, not ", e->whichText(), U".");
5368 bool includeEdges = e->number != 0.0;
5369 const Stackel vec = pop;
5370 if (vec->which != Stackel_NUMERIC_VECTOR)
5371 Melder_throw (U"The first argument to peaks## should be a numeric vector, not ", vec->whichText(), U".");
5372 autoMAT result = peaks_MAT (vec->numericVector, includeEdges, interpolation, sortByHeight);
5373 pushNumericMatrix (result.move());
5374 }
5375 static void do_size () {
5376 const Stackel narg = pop;
5377 Melder_assert (narg->which == Stackel_NUMBER);
5378 Melder_require (narg->number == 1,
5379 U"The function “size” requires one (vector) argument.");
5380 const Stackel array = pop;
5381 if (array->which == Stackel_NUMERIC_VECTOR) {
5382 pushNumber (array->numericVector.size);
5383 } else if (array->which == Stackel_STRING_ARRAY) {
5384 pushNumber (array->stringArray.size);
5385 } else {
5386 Melder_throw (U"The function size requires a vector argument, not ", array->whichText(), U".");
5387 }
5388 }
5389 static void do_numberOfRows () {
5390 const Stackel narg = pop;
5391 Melder_assert (narg->which == Stackel_NUMBER);
5392 Melder_require (narg->number == 1,
5393 U"The function “numberOfRows” requires one argument, namely a matrix.");
5394 const Stackel array = pop;
5395 if (array->which == Stackel_NUMERIC_MATRIX) {
5396 pushNumber (array->numericMatrix.nrow);
5397 } else {
5398 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
5399 U" requires a matrix argument, not ", array->whichText(), U".");
5400 }
5401 }
5402 static void do_numberOfColumns () {
5403 const Stackel narg = pop;
5404 Melder_assert (narg->which == Stackel_NUMBER);
5405 Melder_require (narg->number == 1,
5406 U"The function “numberOfColumns” requires one argument, namely a matrix.");
5407 const Stackel array = pop;
5408 if (array->which == Stackel_NUMERIC_MATRIX) {
5409 pushNumber (array->numericMatrix.ncol);
5410 } else {
5411 Melder_throw (U"The function ", Formula_instructionNames [parse [programPointer]. symbol],
5412 U" requires a matrix argument, not ", array->whichText(), U".");
5413 }
5414 }
5415 static void do_combine_VEC () {
5416 const Stackel narg = pop;
5417 Melder_assert (narg->which == Stackel_NUMBER);
5418 const integer numberOfArguments = Melder_iround (narg->number);
5419 stackPointer -= numberOfArguments;
5420 integer elementCounter = 0;
5421 for (integer iarg = 1; iarg <= numberOfArguments; iarg ++) {
5422 const Stackel arg = & theStack [stackPointer + iarg];
5423 if (arg->which == Stackel_NUMBER) {
5424 elementCounter += 1;
5425 } else if (arg->which == Stackel_NUMERIC_VECTOR) {
5426 elementCounter += arg->numericVector.size;
5427 } else if (arg->which == Stackel_NUMERIC_MATRIX) {
5428 elementCounter += arg->numericMatrix.nrow * arg->numericMatrix.ncol;
5429 } else {
5430 Melder_throw (U"The function “combine#” only takes numbers, vectors and matrices,"
5431 " not ", arg->whichText(), U".");
5432 }
5433 }
5434 autoVEC result = raw_VEC (elementCounter);
5435 integer elementIterator = 0;
5436 for (integer iarg = 1; iarg <= numberOfArguments; iarg ++) {
5437 const Stackel arg = & theStack [stackPointer + iarg];
5438 if (arg->which == Stackel_NUMBER) {
5439 result [++ elementIterator] = arg->number;
5440 } else if (arg->which == Stackel_NUMERIC_VECTOR) {
5441 for (integer i = 1; i <= arg->numericVector.size; i ++)
5442 result [++ elementIterator] = arg->numericVector [i];
5443 } else if (arg->which == Stackel_NUMERIC_MATRIX) {
5444 for (integer irow = 1; irow <= arg->numericMatrix.nrow; irow ++)
5445 for (integer icol = 1; icol <= arg->numericMatrix.ncol; icol ++)
5446 result [++ elementIterator] = arg->numericMatrix [irow] [icol];
5447 } else {
5448 Melder_crash (U"do_combine_VEC should never arrive here.");
5449 }
5450 }
5451 pushNumericVector (result.move());
5452 }
5453 static void do_blake3_VEC () {
5454 const Stackel narg = pop;
5455 Melder_assert (narg->which == Stackel_NUMBER);
5456 Melder_require (narg->number == 1,
5457 U"The function “blake3#” requires exactly one argument (namely a vector, matrix or string), not the ", narg->number, U" given.");
5458 const Stackel arg = pop;
5459 if (arg->which == Stackel_NUMERIC_VECTOR)
5460 pushNumericVector (blake3_VEC (arg->numericVector));
5461 else if (arg->which == Stackel_NUMERIC_MATRIX)
5462 pushNumericVector (blake3_VEC (arg->numericMatrix));
5463 else if (arg->which == Stackel_STRING)
5464 pushNumericVector (blake3_VEC (arg->getString()));
5465 else
5466 Melder_throw (U"The argument of the function “blake3#” should be a vector, a matrix or a string, not ", arg->whichText(), U".");
5467 }
5468 static void do_part_VEC () {
5469 /*
5470 Check the number of arguments: always 3.
5471 */
5472 const Stackel s_narg = pop;
5473 Melder_assert (s_narg->which == Stackel_NUMBER);
5474 const integer narg = s_narg->number;
5475 Melder_require (narg == 3,
5476 U"The function “part#” requires exactly three arguments (namely a vector, a starting index, and an end index), not the ", narg, U" given.");
5477 /*
5478 Check the types of the arguments: always vector, number, number.
5479 */
5480 const Stackel s_last = pop, s_first = pop, s_vec = pop;
5481 Melder_require (s_vec->which == Stackel_NUMERIC_VECTOR,
5482 U"The first argument of the function “part#” should be a numeric vector, not ", s_vec->whichText(), U".");
5483 Melder_require (s_first->which == Stackel_NUMBER,
5484 U"The second argument of the function “part#” should be a number (the starting index), not ", s_first->whichText(), U".");
5485 Melder_require (s_last->which == Stackel_NUMBER,
5486 U"The third argument of the function “part#” should be a number (the end index), not ", s_last->whichText(), U".");
5487 /*
5488 Check the preconditions of the arguments.
5489 */
5490 const constVEC vec = s_vec->numericVector;
5491 const integer numberOfElements = vec.size;
5492 const integer first = Melder_iround (s_first->number);
5493 Melder_require (first > 0,
5494 U"The second argument of the function “part#” (the starting index) should (after rounding) be a positive whole number, not ", first, U".");
5495 Melder_require (first <= numberOfElements,
5496 U"The second argument of the function “part#” (the starting index) should (after rounding) be at most the number of elements (",
5497 numberOfElements, U"), not ", first, U"."
5498 );
5499 const integer last = Melder_iround (s_last->number);
5500 Melder_require (last > 0,
5501 U"The third argument of the function “part#” (the end index) should (after rounding) be a positive whole number, not ", last, U".");
5502 Melder_require (last <= numberOfElements,
5503 U"The third argument of the function “part#” (the end index) should (after rounding) be at most the number of elements (",
5504 numberOfElements, U"), not ", last, U"."
5505 );
5506
5507 const integer newSize = last - (first - 1);
5508 if (newSize > 0)
5509 pushNumericVector (copy_VEC (vec.part (first, last)));
5510 else
5511 pushNumericVector (autoVEC ());
5512 }
5513 static void do_part_MAT () {
5514 /*
5515 Check the number of arguments: always 5.
5516 */
5517 const Stackel s_narg = pop;
5518 Melder_assert (s_narg->which == Stackel_NUMBER);
5519 const integer narg = s_narg->number;
5520 Melder_require (narg == 5,
5521 U"The function “part##” requires exactly five arguments (namely a matrix, a starting row, an end row, a starting column, and an end column), not the ", narg, U" given..");
5522 /*
5523 Check the types of the arguments: always matrix, number, number, number, number.
5524 */
5525 const Stackel s_endColumn = pop, s_startingColumn = pop, s_endRow = pop, s_startingRow = pop, s_mat = pop;
5526 Melder_require (s_mat->which == Stackel_NUMERIC_MATRIX,
5527 U"The first argument of the function “part##” should be a numeric matrix, not ", s_mat->whichText(), U".");
5528 Melder_require (s_startingRow->which == Stackel_NUMBER,
5529 U"The second argument of the function “part##” should be a number (the starting row), not ", s_startingRow->whichText(), U".");
5530 Melder_require (s_endRow->which == Stackel_NUMBER,
5531 U"The third argument of the function “part##” should be a number (the end row), not ", s_endRow->whichText(), U".");
5532 Melder_require (s_startingColumn->which == Stackel_NUMBER,
5533 U"The fourth argument of the function “part##” should be a number (the starting column), not ", s_startingColumn->whichText(), U".");
5534 Melder_require (s_endColumn->which == Stackel_NUMBER,
5535 U"The fifth argument of the function “part##” should be a number (the end column), not ", s_endColumn->whichText(), U".");
5536 /*
5537 Check the preconditions of the arguments.
5538 */
5539 const constMAT mat = s_mat->numericMatrix;
5540 const integer numberOfRows = mat.nrow, numberOfColumns = mat.ncol;
5541 const integer startingRow = Melder_iround (s_startingRow->number);
5542 Melder_require (startingRow > 0,
5543 U"The second argument of the function “part##” (the starting row) should (after rounding) be a positive whole number, not ", startingRow, U".");
5544 Melder_require (startingRow <= numberOfRows,
5545 U"The second argument of the function “part##” (the starting row) should (after rounding) be at most the number of rows (",
5546 numberOfRows, U"), not ", startingRow, U"."
5547 );
5548 const integer endRow = Melder_iround (s_endRow->number);
5549 Melder_require (endRow > 0,
5550 U"The third argument of the function “part##” (the end row) should (after rounding) be a positive whole number, not ", endRow, U".");
5551 Melder_require (endRow <= numberOfRows,
5552 U"The third argument of the function “part##” (the end row) should (after rounding) be at most the number of rows (",
5553 numberOfRows, U"), not ", endRow, U"."
5554 );
5555 const integer startingColumn = Melder_iround (s_startingColumn->number);
5556 Melder_require (startingColumn > 0,
5557 U"The fourth argument of the function “part##” (the starting column) should (after rounding) be a positive whole number, not ", startingColumn, U".");
5558 Melder_require (startingColumn <= numberOfColumns,
5559 U"The fourth argument of the function “part##” (the starting column) should (after rounding) be at most the number of columns (",
5560 numberOfColumns, U"), not ", startingColumn, U"."
5561 );
5562 const integer endColumn = Melder_iround (s_endColumn->number);
5563 Melder_require (endColumn > 0,
5564 U"The fifth argument of the function “part##” (the end column) should (after rounding) be a positive whole number, not ", endColumn, U".");
5565 Melder_require (endColumn <= numberOfColumns,
5566 U"The fifth argument of the function “part##” (the end column) should (after rounding) be at most the number of columns (",
5567 numberOfColumns, U"), not ", endColumn, U"."
5568 );
5569 pushNumericMatrix (copy_MAT (mat.part (startingRow, endRow, startingColumn, endColumn)));
5570 }
5571 static void do_editor () {
5572 const Stackel narg = pop;
5573 Melder_assert (narg->which == Stackel_NUMBER);
5574 if (narg->number == 0) {
5575 /*
5576 No editor mentioned, so switch back to the already existing editor.
5577 */
5578 if (theInterpreter && theInterpreter -> wasStartedFromEditorEnvironment())
5579 theInterpreter -> setDynamicFromOwningEditorEnvironment ();
5580 else
5581 Melder_throw (U"The function “editor” requires an argument when called from outside an editor.");
5582 } else if (narg->number == 1) {
5583 const Stackel editor = pop;
5584 if (editor->which == Stackel_STRING) {
5585 theInterpreter -> setDynamicEditorEnvironmentFromEditor (praat_findEditorFromString (editor->getString()));
5586 } else if (editor->which == Stackel_NUMBER) {
5587 theInterpreter -> setDynamicEditorEnvironmentFromEditor (praat_findEditorById (Melder_iround (editor->number)));
5588 } else {
5589 Melder_throw (U"The function “editor” requires a numeric or string argument, not ", editor->whichText(), U".");
5590 }
5591 } else {
5592 Melder_throw (U"The function “editor” requires 0 or 1 arguments, not ", narg->number, U".");
5593 }
5594 pushNumber (1);
5595 }
5596 static void do_random_initializeWithSeedUnsafelyButPredictably () {
5597 /*@praat
5598 #
5599 # A published test: the 10,000th element of the default 64-bit Mersenne Twister random sequence
5600 # should be 9'981'545'732'273'789'042.
5601 #
5602 random_initializeWithSeedUnsafelyButPredictably (5489)
5603 for i to 10000
5604 a = randomUniform (0, 1)
5605 endfor
5606 random_initializeSafelyAndUnpredictably ()
5607 a *= 2 ^ 64
5608 roundingError = a - 9981545732273789042
5609 writeInfoLine: fixed$ (a, 0), " ", roundingError
5610 assert roundingError <= 2048 ; actually usually zero
5611 @*/
5612 const Stackel narg = pop;
5613 if (narg->number == 1) {
5614 const Stackel s = pop;
5615 if (s->which == Stackel_NUMBER) {
5616 const double seed = s->number;
5617 if (seed < 0.0 || seed > double (INT54_MAX))
5618 Melder_throw (U"For the function “random_initializeWithSeedUnsafelyButPredictably”, "
5619 "the seed should be between 0 and ", double (INT54_MAX), U".");
5620 NUMrandom_initializeWithSeedUnsafelyButPredictably (uint64 (round (seed)));
5621 } else {
5622 Melder_throw (U"The function “hash” requires a string, not ", s->whichText(), U".");
5623 }
5624 } else {
5625 Melder_throw (U"The function “random_initializeWithSeedUnsafelyButPredictably” requires 1 argument (the seed), not ", narg->number, U".");
5626 }
5627 pushNumber (1);
5628 }
5629 static void do_random_initializeSafelyAndUnpredictably () {
5630 const Stackel narg = pop;
5631 Melder_require (narg->number == 0,
5632 U"The function “random_initializeSafelyAndUnpredictably” requires 0 arguments, not ", narg->number, U".");
5633 NUMrandom_initializeSafelyAndUnpredictably ();
5634 pushNumber (1);
5635 }
5636 static void do_hash () {
5637 const Stackel narg = pop;
5638 Melder_assert (narg->which == Stackel_NUMBER);
5639 if (narg->number == 1) {
5640 const Stackel s = pop;
5641 if (s->which == Stackel_STRING) {
5642 const double result = NUMhashString (s->getString());
5643 pushNumber (result);
5644 } else {
5645 Melder_throw (U"The function “hash” requires a string, not ", s->whichText(), U".");
5646 }
5647 } else {
5648 Melder_throw (U"The function “hash” requires 1 argument, not ", narg->number, U".");
5649 }
5650 }
5651 static void do_hex_STR () {
5652 const Stackel narg = pop;
5653 Melder_assert (narg->which == Stackel_NUMBER);
5654 if (narg->number == 1) {
5655 const Stackel s = pop;
5656 if (s->which == Stackel_STRING) {
5657 autostring32 result = hex_STR (s->getString());
5658 pushString (result.move());
5659 } else {
5660 Melder_throw (U"The function “hex$” requires a string, not ", s->whichText(), U".");
5661 }
5662 } else if (narg->number == 2) {
5663 const Stackel k = pop, s = pop;
5664 if (s->which == Stackel_STRING && k->which == Stackel_NUMBER) {
5665 autostring32 result = hex_STR (s->getString(), uint64 (round (k->number)));
5666 pushString (result.move());
5667 } else {
5668 Melder_throw (U"The function “hex$” requires a string and a number, not ", s->whichText(), U".");
5669 }
5670 } else {
5671 Melder_throw (U"The function “hex$” requires 1 or 2 arguments, not ", narg->number, U".");
5672 }
5673 }
5674 static void do_unhex_STR () {
5675 const Stackel narg = pop;
5676 Melder_assert (narg->which == Stackel_NUMBER);
5677 if (narg->number == 1) {
5678 const Stackel s = pop;
5679 if (s->which == Stackel_STRING) {
5680 autostring32 result = unhex_STR (s->getString());
5681 pushString (result.move());
5682 } else {
5683 Melder_throw (U"The function “unhex$” requires a string, not ", s->whichText(), U".");
5684 }
5685 } else if (narg->number == 2) {
5686 const Stackel k = pop, s = pop;
5687 if (s->which == Stackel_STRING && k->which == Stackel_NUMBER) {
5688 autostring32 result = unhex_STR (s->getString(), uint64 (round (k->number)));
5689 pushString (result.move());
5690 } else {
5691 Melder_throw (U"The function “unhex$” requires a string and a number, not ", s->whichText(), U".");
5692 }
5693 } else {
5694 Melder_throw (U"The function “unhex$” requires 1 or 2 arguments, not ", narg->number, U".");
5695 }
5696 }
5697 static void do_empty_STRVEC () {
5698 const Stackel narg = pop;
5699 Melder_assert (narg->which == Stackel_NUMBER);
5700 Melder_require (narg->number == 1,
5701 U"The function “empty$#” requires one argument, namely the number of elements.");
5702 const Stackel numberOfElements = pop;
5703 Melder_require (numberOfElements->which == Stackel_NUMBER,
5704 U"The argument of the function “empty$#” should be a number (namely the number of elements), not ", numberOfElements->whichText(), U".");
5705 autoSTRVEC result { Melder_iround (numberOfElements->number) };
5706 pushStringVector (result.move());
5707 }
5708 static void do_readLinesFromFile_STRVEC () {
5709 const Stackel narg = pop;
5710 Melder_assert (narg->which == Stackel_NUMBER);
5711 Melder_require (narg->number == 1,
5712 U"The function “readLinesFromFile$#” requires one argument, namely the file pattern.");
5713 const Stackel fileName = pop;
5714 if (fileName->which != Stackel_STRING)
5715 Melder_throw (U"The argument of the function “readLinesFromFile$#” should be a string (namely the file pattern), not ", fileName->whichText(), U".");
5716 structMelderFile file { };
5717 Melder_relativePathToFile (fileName->getString(), & file);
5718 autoSTRVEC result = readLinesFromFile_STRVEC (& file);
5719 pushStringVector (result.move());
5720 }
5721 static void do_fileNames_STRVEC () {
5722 const Stackel narg = pop;
5723 Melder_assert (narg->which == Stackel_NUMBER);
5724 Melder_require (narg->number == 1,
5725 U"The function “fileNames$#” requires one argument, namely the file pattern.");
5726 const Stackel filePattern = pop;
5727 if (filePattern->which != Stackel_STRING)
5728 Melder_throw (U"The argument of the function “fileNames$#” should be a string (namely the file path and pattern), not ", filePattern->whichText(), U".");
5729 autoSTRVEC result = fileNames_STRVEC (filePattern->getString());
5730 pushStringVector (result.move());
5731 }
5732 static void do_folderNames_STRVEC () {
5733 const Stackel narg = pop;
5734 Melder_assert (narg->which == Stackel_NUMBER);
5735 Melder_require (narg->number == 1,
5736 U"The function “folderNames$#” requires one argument, namely the file pattern.");
5737 const Stackel folderPattern = pop;
5738 Melder_require (folderPattern->which == Stackel_STRING,
5739 U"The argument of the function “folderNames$#” should be a string (namely the folder path), not ", folderPattern->whichText(), U".");
5740 autoSTRVEC result = folderNames_STRVEC (folderPattern->getString());
5741 pushStringVector (result.move());
5742 }
5743 static void do_fileNames_caseInsensitive_STRVEC () {
5744 const Stackel narg = pop;
5745 Melder_assert (narg->which == Stackel_NUMBER);
5746 Melder_require (narg->number == 1,
5747 U"The function “fileNames_caseInsensitive$#” requires one argument, namely the file pattern.");
5748 const Stackel filePattern = pop;
5749 if (filePattern->which != Stackel_STRING)
5750 Melder_throw (U"The argument of the function “fileNames_caseInsensitive$#” should be a string (namely the file path and pattern), not ", filePattern->whichText(), U".");
5751 autoSTRVEC result = fileNames_caseInsensitive_STRVEC (filePattern->getString());
5752 pushStringVector (result.move());
5753 }
5754 static void do_folderNames_caseInsensitive_STRVEC () {
5755 const Stackel narg = pop;
5756 Melder_assert (narg->which == Stackel_NUMBER);
5757 Melder_require (narg->number == 1,
5758 U"The function “folderNames_caseInsensitive$#” requires one argument, namely the file pattern.");
5759 const Stackel folderPattern = pop;
5760 Melder_require (folderPattern->which == Stackel_STRING,
5761 U"The argument of the function “folderNames_caseInsensitive$#” should be a string (namely the folder path), not ", folderPattern->whichText(), U".");
5762 autoSTRVEC result = folderNames_caseInsensitive_STRVEC (folderPattern->getString());
5763 pushStringVector (result.move());
5764 }
5765 static void do_splitByWhitespace_STRVEC () {
5766 const Stackel narg = pop;
5767 Melder_assert (narg -> which == Stackel_NUMBER);
5768 Melder_require (narg->number == 1,
5769 U"The function “splitByWhitespace$#” requires one argument, namely the string to split.");
5770 const Stackel string = pop;
5771 Melder_require (string->which == Stackel_STRING,
5772 U"The argument of the function “splitByWhitespace$#” should be a string, not ", string->whichText(), U".");
5773 autoSTRVEC result = splitByWhitespace_STRVEC (string->getString());
5774 pushStringVector (result.move());
5775 }
5776 static void do_splitBy_STRVEC () {
5777 const Stackel narg = pop;
5778 Melder_assert (narg -> which == Stackel_NUMBER);
5779 Melder_require (narg->number == 2,
5780 U"The function “splitBy$#” requires two arguments, namely the string to split and the separator.");
5781 const Stackel separator = pop, string = pop;
5782 Melder_require (string->which == Stackel_STRING,
5783 U"The first argument of the function “splitBy$#” should be a string, not ", string->whichText(), U".");
5784 Melder_require (separator->which == Stackel_STRING,
5785 U"The second argument of the function “splitBy$#” (the separator) should be a string, not ", string->whichText(), U".");
5786 autoSTRVEC result = splitBy_STRVEC (string->getString(), separator->getString());
5787 pushStringVector (result.move());
5788 }
5789 static void do_lowerCase_STR () {
5790 const Stackel narg = pop;
5791 Melder_assert (narg->which == Stackel_NUMBER);
5792 if (narg->number == 1) {
5793 const Stackel s = pop;
5794 if (s->which == Stackel_STRING) {
5795 autostring32 result = lowerCase_STR (s->getString());
5796 pushString (result.move());
5797 } else {
5798 Melder_throw (U"The function “lowerCase$” requires a string, not ", s->whichText(), U".");
5799 }
5800 } else {
5801 Melder_throw (U"The function “lowerCase$” requires 1 argument, not ", narg->number, U".");
5802 }
5803 }
5804 static void do_lowerCamelCase_STR () {
5805 const Stackel narg = pop;
5806 Melder_assert (narg->which == Stackel_NUMBER);
5807 if (narg->number == 1) {
5808 const Stackel s = pop;
5809 if (s->which == Stackel_STRING) {
5810 autostring32 result = lowerCamelCase_STR (s->getString());
5811 pushString (result.move());
5812 } else {
5813 Melder_throw (U"The function “lowerCamelCase$” requires a string, not ", s->whichText(), U".");
5814 }
5815 } else {
5816 Melder_throw (U"The function “lowerCamelCase$” requires 1 argument, not ", narg->number, U".");
5817 }
5818 }
5819 static void do_lowerSnakeCase_STR () {
5820 const Stackel narg = pop;
5821 Melder_assert (narg->which == Stackel_NUMBER);
5822 if (narg->number == 1) {
5823 const Stackel s = pop;
5824 if (s->which == Stackel_STRING) {
5825 autostring32 result = lowerSnakeCase_STR (s->getString());
5826 pushString (result.move());
5827 } else {
5828 Melder_throw (U"The function “lowerSnakeCase$” requires a string, not ", s->whichText(), U".");
5829 }
5830 } else {
5831 Melder_throw (U"The function “lowerSnakeCase$” requires 1 argument, not ", narg->number, U".");
5832 }
5833 }
5834 static void do_upperCase_STR () {
5835 const Stackel narg = pop;
5836 Melder_assert (narg->which == Stackel_NUMBER);
5837 if (narg->number == 1) {
5838 const Stackel s = pop;
5839 if (s->which == Stackel_STRING) {
5840 autostring32 result = upperCase_STR (s->getString());
5841 pushString (result.move());
5842 } else {
5843 Melder_throw (U"The function “upperCase$” requires a string, not ", s->whichText(), U".");
5844 }
5845 } else {
5846 Melder_throw (U"The function “upperCase$” requires 1 argument, not ", narg->number, U".");
5847 }
5848 }
5849 static void do_upperCamelCase_STR () {
5850 const Stackel narg = pop;
5851 Melder_assert (narg->which == Stackel_NUMBER);
5852 if (narg->number == 1) {
5853 const Stackel s = pop;
5854 if (s->which == Stackel_STRING) {
5855 autostring32 result = upperCamelCase_STR (s->getString());
5856 pushString (result.move());
5857 } else {
5858 Melder_throw (U"The function “upperCamelCase$” requires a string, not ", s->whichText(), U".");
5859 }
5860 } else {
5861 Melder_throw (U"The function “upperCamelCase$” requires 1 argument, not ", narg->number, U".");
5862 }
5863 }
5864 static void do_upperSnakeCase_STR () {
5865 const Stackel narg = pop;
5866 Melder_assert (narg->which == Stackel_NUMBER);
5867 if (narg->number == 1) {
5868 const Stackel s = pop;
5869 if (s->which == Stackel_STRING) {
5870 autostring32 result = upperSnakeCase_STR (s->getString());
5871 pushString (result.move());
5872 } else {
5873 Melder_throw (U"The function “upperSnakeCase$” requires a string, not ", s->whichText(), U".");
5874 }
5875 } else {
5876 Melder_throw (U"The function “upperSnakeCase$” requires 1 argument, not ", narg->number, U".");
5877 }
5878 }
5879 static void do_numericVectorElement () {
5880 InterpreterVariable vector = parse [programPointer]. content.variable;
5881 const Stackel element = pop;
5882 Melder_require (element->which == Stackel_NUMBER,
5883 U"In vector indexing, the index should be a number, not ", element->whichText(), U".");
5884 Melder_require (isdefined (element->number),
5885 U"The element index is undefined.");
5886 const integer ielement = Melder_iround (element->number);
5887 Melder_require (ielement > 0,
5888 U"In vector indexing, the element index should be positive.");
5889 Melder_require (ielement <= vector->numericVectorValue.size,
5890 U"Element index out of bounds. Looking for element ", ielement,
5891 U", but there are only ", vector->numericVectorValue.size, U" elements."
5892 );
5893 pushNumber (vector->numericVectorValue [ielement]);
5894 }
5895 static void do_numericMatrixElement () {
5896 InterpreterVariable matrix = parse [programPointer]. content.variable;
5897 const Stackel column = pop;
5898 Melder_require (column->which == Stackel_NUMBER,
5899 U"In matrix indexing, the column index should be a number, not ", column->whichText(), U".");
5900 Melder_require (isdefined (column->number),
5901 U"The column index is undefined.");
5902 const integer icolumn = Melder_iround (column->number);
5903 Melder_require (icolumn > 0,
5904 U"In matrix indexing, the column index should be positive.");
5905 Melder_require (icolumn <= matrix->numericMatrixValue. ncol,
5906 U"Column index out of bounds. Looking for column ", icolumn,
5907 U", but there are only ", matrix->numericMatrixValue. ncol, U" columns."
5908 );
5909 const Stackel row = pop;
5910 Melder_require (row->which == Stackel_NUMBER,
5911 U"In matrix indexing, the row index should be a number, not ", row->whichText(), U".");
5912 Melder_require (isdefined (row->number),
5913 U"The row index is undefined.");
5914 const integer irow = Melder_iround (row->number);
5915 Melder_require (irow > 0,
5916 U"In matrix indexing, the row index should be positive.");
5917 Melder_require (irow <= matrix->numericMatrixValue. nrow,
5918 U"Row index out of bounds. Looking for row ", irow,
5919 U", but there are only ", matrix->numericMatrixValue. nrow, U" rows."
5920 );
5921 pushNumber (matrix->numericMatrixValue [irow] [icolumn]);
5922 }
5923 static void do_stringVectorElement () {
5924 InterpreterVariable vector = parse [programPointer]. content.variable;
5925 const Stackel element = pop;
5926 Melder_require (element->which == Stackel_NUMBER,
5927 U"In vector indexing, the index should be a number, not ", element->whichText(), U".");
5928 Melder_require (isdefined (element->number),
5929 U"The element index is undefined.");
5930 const integer ielement = Melder_iround (element->number);
5931 Melder_require (ielement > 0,
5932 U"In vector indexing, the element index should be positive.");
5933 Melder_require (ielement <= vector->stringArrayValue.size,
5934 U"Element index out of bounds. Looking for element ", ielement,
5935 U", but there are only ", vector->stringArrayValue.size, U" elements."
5936 );
5937 pushString (Melder_dup (vector->stringArrayValue [ielement].get()));
5938 }
5939 static void do_indexedNumericVariable () {
5940 const Stackel narg = pop;
5941 Melder_assert (narg->which == Stackel_NUMBER);
5942 const integer nindex = Melder_iround (narg->number);
5943 Melder_require (nindex >= 1,
5944 U"Indexed variables require at least one index.");
5945 char32 *indexedVariableName = parse [programPointer]. content.string;
5946 static MelderString totalVariableName;
5947 MelderString_copy (& totalVariableName, indexedVariableName, U"[");
5948 stackPointer -= nindex;
5949 for (int iindex = 1; iindex <= nindex; iindex ++) {
5950 const Stackel index = & theStack [stackPointer + iindex];
5951 if (index->which == Stackel_NUMBER) {
5952 MelderString_append (& totalVariableName, index->number, iindex == nindex ? U"]" : U",");
5953 } else if (index -> which == Stackel_STRING) {
5954 MelderString_append (& totalVariableName, U"\"", index->getString(), U"\"", iindex == nindex ? U"]" : U",");
5955 } else {
5956 Melder_throw (U"In indexed variables, the index should be a number or a string, not ", index->whichText(), U".");
5957 }
5958 }
5959 InterpreterVariable var = Interpreter_hasVariable (theInterpreter, totalVariableName.string);
5960 Melder_require (!! var,
5961 U"Undefined indexed variable «", totalVariableName.string, U"».");
5962 pushNumber (var -> numericValue);
5963 }
5964 static void do_indexedStringVariable () {
5965 const Stackel narg = pop;
5966 Melder_assert (narg->which == Stackel_NUMBER);
5967 const integer nindex = Melder_iround (narg->number);
5968 Melder_require (nindex >= 1,
5969 U"Indexed variables require at least one index.");
5970 char32 *indexedVariableName = parse [programPointer]. content.string;
5971 static MelderString totalVariableName;
5972 MelderString_copy (& totalVariableName, indexedVariableName, U"[");
5973 stackPointer -= nindex;
5974 for (int iindex = 1; iindex <= nindex; iindex ++) {
5975 const Stackel index = & theStack [stackPointer + iindex];
5976 if (index->which == Stackel_NUMBER) {
5977 MelderString_append (& totalVariableName, index -> number, iindex == nindex ? U"]" : U",");
5978 } else if (index -> which == Stackel_STRING) {
5979 MelderString_append (& totalVariableName, U"\"", index -> getString(), U"\"", iindex == nindex ? U"]" : U",");
5980 } else {
5981 Melder_throw (U"In indexed variables, the index should be a number or a string, not ", index->whichText(), U".");
5982 }
5983 }
5984 InterpreterVariable var = Interpreter_hasVariable (theInterpreter, totalVariableName.string);
5985 Melder_require (!! var,
5986 U"Undefined indexed variable «", totalVariableName.string, U"».");
5987 autostring32 result = Melder_dup (var -> stringValue.get());
5988 pushString (result.move());
5989 }
5990 static void do_length () {
5991 const Stackel s = pop;
5992 if (s->which == Stackel_STRING) {
5993 const double result = NUMlength (s->getString());
5994 pushNumber (result);
5995 } else {
5996 Melder_throw (U"The function “length” requires a string, not ", s->whichText(), U".");
5997 }
5998 }
5999 static void do_number () {
6000 const Stackel s = pop;
6001 if (s->which == Stackel_STRING) {
6002 double result = Melder_atof (s->getString());
6003 pushNumber (result);
6004 } else {
6005 Melder_throw (U"The function “number” requires a string, not ", s->whichText(), U".");
6006 }
6007 }
6008 static void do_fileReadable () {
6009 const Stackel s = pop;
6010 if (s->which == Stackel_STRING) {
6011 structMelderFile file { };
6012 Melder_relativePathToFile (s->getString(), & file);
6013 pushNumber (MelderFile_readable (& file));
6014 } else {
6015 Melder_throw (U"The function “fileReadable” requires a string, not ", s->whichText(), U".");
6016 }
6017 }
6018 static void do_folderExists () {
6019 const Stackel s = pop;
6020 if (s->which == Stackel_STRING) {
6021 structMelderFolder folder { };
6022 Melder_relativePathToFolder (s->getString(), & folder);
6023 pushNumber (MelderFolder_exists (& folder));
6024 } else {
6025 Melder_throw (U"The function “folderExists” requires a string, not ", s->whichText(), U".");
6026 }
6027 }
6028 static void do_tryToWriteFile () {
6029 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
6030 U"The function “tryToWriteFile” is not available inside manuals.");
6031 const Stackel s = pop;
6032 if (s->which == Stackel_STRING) {
6033 structMelderFile file { };
6034 Melder_relativePathToFile (s->getString(), & file);
6035 Melder_checkTrust (theInterpreter, U"try to write to the file\n", & file);
6036 pushNumber (Melder_tryToWriteFile (& file));
6037 } else {
6038 Melder_throw (U"The function “tryToWriteFile” requires a string, not ", s->whichText(), U".");
6039 }
6040 }
6041 static void do_tryToAppendFile () {
6042 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
6043 U"The function “tryToAppendFile” is not available inside manuals.");
6044 const Stackel s = pop;
6045 if (s->which == Stackel_STRING) {
6046 structMelderFile file { };
6047 Melder_relativePathToFile (s->getString(), & file);
6048 Melder_checkTrust (theInterpreter, U"try to append to the file\n", & file);
6049 pushNumber (Melder_tryToAppendFile (& file));
6050 } else {
6051 Melder_throw (U"The function “tryToAppendFile” requires a string, not ", s->whichText(), U".");
6052 }
6053 }
6054 static void do_date_STR () {
6055 pushString (date_STR ());
6056 }
6057 static void do_date_utc_STR () {
6058 pushString (date_utc_STR ());
6059 }
6060 static void do_date_iso_STR () {
6061 pushString (date_iso_STR ());
6062 }
6063 static void do_date_utc_iso_STR () {
6064 pushString (date_utc_iso_STR ());
6065 }
6066 static void do_date_VEC () {
6067 pushNumericVector (date_VEC ());
6068 }
6069 static void do_date_utc_VEC () {
6070 pushNumericVector (date_utc_VEC ());
6071 }
6072 static void do_info_STR () {
6073 autostring32 info = Melder_dup (Melder_getInfo ());
6074 pushString (info.move());
6075 }
6076 static void do_left_STR () {
6077 const Stackel narg = pop;
6078 if (narg->number == 1) {
6079 const Stackel s = pop;
6080 if (s->which == Stackel_STRING) {
6081 pushString (left_STR (s->getString()));
6082 } else {
6083 Melder_throw (U"The function “left$” requires a string (or a string and a number).");
6084 }
6085 } else if (narg->number == 2) {
6086 const Stackel n = pop, s = pop;
6087 if (s->which == Stackel_STRING && n->which == Stackel_NUMBER) {
6088 pushString (left_STR (s->getString(), Melder_iround (n->number)));
6089 } else {
6090 Melder_throw (U"The function “left$” requires a string and a number (or a string only).");
6091 }
6092 } else {
6093 Melder_throw (U"The function “left$” requires one or two arguments: a string and optionally a number.");
6094 }
6095 trace (U"exit");
6096 }
6097 static void do_right_STR () {
6098 const Stackel narg = pop;
6099 if (narg->number == 1) {
6100 const Stackel s = pop;
6101 if (s->which == Stackel_STRING) {
6102 pushString (right_STR (s->getString()));
6103 } else {
6104 Melder_throw (U"The function “right$” requires a string (or a string and a number).");
6105 }
6106 } else if (narg->number == 2) {
6107 const Stackel n = pop, s = pop;
6108 if (s->which == Stackel_STRING && n->which == Stackel_NUMBER) {
6109 pushString (right_STR (s->getString(), Melder_iround (n->number)));
6110 } else {
6111 Melder_throw (U"The function “right$” requires a string and a number (or a string only).");
6112 }
6113 } else {
6114 Melder_throw (U"The function “right$” requires one or two arguments: a string and optionally a number.");
6115 }
6116 }
6117 static void do_mid_STR () {
6118 const Stackel narg = pop;
6119 if (narg->number == 2) {
6120 const Stackel position = pop, str = pop;
6121 if (str->which == Stackel_STRING && position->which == Stackel_NUMBER) {
6122 pushString (mid_STR (str->getString(), Melder_iround (position->number)));
6123 } else {
6124 Melder_throw (U"The function “mid$” requires a string and a number (or two).");
6125 }
6126 } else if (narg->number == 3) {
6127 const Stackel numberOfCharacters = pop, startingPosition = pop, str = pop;
6128 if (str->which == Stackel_STRING && startingPosition->which == Stackel_NUMBER && numberOfCharacters->which == Stackel_NUMBER) {
6129 pushString (mid_STR (str->getString(), Melder_iround (startingPosition->number), Melder_iround (numberOfCharacters->number)));
6130 } else {
6131 Melder_throw (U"The function “mid$” requires a string and two numbers (or one).");
6132 }
6133 } else {
6134 Melder_throw (U"The function “mid$” requires two or three arguments.");
6135 }
6136 }
6137 static void do_padLeft_STR () {
6138 const Stackel narg = pop;
6139 if (narg->number == 2) {
6140 const Stackel width = pop, str = pop;
6141 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER)
6142 pushString (padLeft_STR (str->getString(), Melder_iround (width->number)));
6143 else
6144 Melder_throw (U"The two arguments to “padLeft$” should be a string and a number (the desired width), not ",
6145 str->whichText(), U" and ", width->whichText(), U".");
6146 } else if (narg->number == 3) {
6147 const Stackel pad = pop, width = pop, str = pop;
6148 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER && pad->which == Stackel_STRING)
6149 pushString (padLeft_STR (str->getString(), Melder_iround (width->number), pad->getString()));
6150 else
6151 Melder_throw (U"The three arguments to “padLeft$” should be a string, a number (the desired width),"
6152 U" and a string (the pad), not ", str->whichText(), U", ", width->whichText(),
6153 U" and ", pad->whichText(), U"."
6154 );
6155 } else
6156 Melder_throw (U"The function “padLeft$” requires two or three arguments (a string, a number, and an optional pad string).");
6157 }
6158 static void do_padRight_STR () {
6159 const Stackel narg = pop;
6160 if (narg->number == 2) {
6161 const Stackel width = pop, str = pop;
6162 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER)
6163 pushString (padRight_STR (str->getString(), Melder_iround (width->number)));
6164 else
6165 Melder_throw (U"The two arguments to “padRight$” should be a string and a number (the desired width), not ",
6166 str->whichText(), U" and ", width->whichText(), U".");
6167 } else if (narg->number == 3) {
6168 const Stackel pad = pop, width = pop, str = pop;
6169 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER && pad->which == Stackel_STRING)
6170 pushString (padRight_STR (str->getString(), Melder_iround (width->number), pad->getString()));
6171 else
6172 Melder_throw (U"The three arguments to “padRight$” should be a string, a number (the desired width),"
6173 U" and a string (the pad), not ", str->whichText(), U", ", width->whichText(),
6174 U" and ", pad->whichText(), U"."
6175 );
6176 } else
6177 Melder_throw (U"The function “padRight$” requires two or three arguments (a string, a number, and an optional pad string).");
6178 }
6179 static void do_truncateLeft_STR () {
6180 const Stackel narg = pop;
6181 if (narg->number == 2) {
6182 const Stackel width = pop, str = pop;
6183 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER)
6184 pushString (truncateLeft_STR (str->getString(), Melder_iround (width->number)));
6185 else
6186 Melder_throw (U"The two arguments to “truncateLeft$” should be a string and a number (the desired width), not ",
6187 str->whichText(), U" and ", width->whichText(), U".");
6188 } else
6189 Melder_throw (U"The function “truncateLeft$” requires two arguments: a string and a number (the desired width).");
6190 }
6191 static void do_truncateRight_STR () {
6192 const Stackel narg = pop;
6193 if (narg->number == 2) {
6194 const Stackel width = pop, str = pop;
6195 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER)
6196 pushString (truncateRight_STR (str->getString(), Melder_iround (width->number)));
6197 else
6198 Melder_throw (U"The two arguments to “truncateRight$” should be a string and a number (the desired width), not ",
6199 str->whichText(), U" and ", width->whichText(), U".");
6200 } else
6201 Melder_throw (U"The function “truncateRight$” requires two arguments: a string and a number (the desired width).");
6202 }
6203 static void do_padOrTruncateLeft_STR () {
6204 const Stackel narg = pop;
6205 if (narg->number == 2) {
6206 const Stackel width = pop, str = pop;
6207 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER)
6208 pushString (padOrTruncateLeft_STR (str->getString(), Melder_iround (width->number)));
6209 else
6210 Melder_throw (U"The two arguments to “padOrTruncateLeft$” should be a string and a number (the desired width), not ",
6211 str->whichText(), U" and ", width->whichText(), U".");
6212 } else if (narg->number == 3) {
6213 const Stackel pad = pop, width = pop, str = pop;
6214 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER && pad->which == Stackel_STRING)
6215 pushString (padOrTruncateLeft_STR (str->getString(), Melder_iround (width->number), pad->getString()));
6216 else
6217 Melder_throw (U"The three arguments to “padOrTruncateLeft$” should be a string, a number (the desired width),"
6218 U" and a string (the pad), not ", str->whichText(), U", ", width->whichText(),
6219 U" and ", pad->whichText(), U"."
6220 );
6221 } else
6222 Melder_throw (U"The function “padOrTruncateLeft$” requires two or three arguments (a string, a number, and an optional pad string).");
6223 }
6224 static void do_padOrTruncateRight_STR () {
6225 const Stackel narg = pop;
6226 if (narg->number == 2) {
6227 const Stackel width = pop, str = pop;
6228 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER)
6229 pushString (padOrTruncateRight_STR (str->getString(), Melder_iround (width->number)));
6230 else
6231 Melder_throw (U"The two arguments to “padOrTruncateRight$” should be a string and a number (the desired width), not ",
6232 str->whichText(), U" and ", width->whichText(), U".");
6233 } else if (narg->number == 3) {
6234 const Stackel pad = pop, width = pop, str = pop;
6235 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER && pad->which == Stackel_STRING)
6236 pushString (padOrTruncateRight_STR (str->getString(), Melder_iround (width->number), pad->getString()));
6237 else
6238 Melder_throw (U"The three arguments to “padOrTruncateRight$” should be a string, a number (the desired width),"
6239 U" and a string (the pad), not ", str->whichText(), U", ", width->whichText(),
6240 U" and ", pad->whichText(), U"."
6241 );
6242 } else
6243 Melder_throw (U"The function “padOrTruncateRight$” requires two or three arguments (a string, a number, and an optional pad string).");
6244 }
6245 static void do_unicodeToBackslashTrigraphs_STR () {
6246 const Stackel s = pop;
6247 if (s->which == Stackel_STRING) {
6248 const integer length = Melder_length (s->getString());
6249 autostring32 trigraphs (3 * length);
6250 Longchar_genericize (s->getString(), trigraphs.get());
6251 pushString (trigraphs.move());
6252 } else {
6253 Melder_throw (U"The function “unicodeToBackslashTrigraphs$” requires a string, not ", s->whichText(), U".");
6254 }
6255 }
6256 static void do_backslashTrigraphsToUnicode_STR () {
6257 const Stackel s = pop;
6258 if (s->which == Stackel_STRING) {
6259 const integer length = Melder_length (s->getString());
6260 autostring32 unicode (length);
6261 Longchar_nativize (s->getString(), unicode.get(), false); // noexcept
6262 pushString (unicode.move());
6263 } else {
6264 Melder_throw (U"The function “unicodeToBackslashTrigraphs$” requires a string, not ", s->whichText(), U".");
6265 }
6266 }
6267 static void do_environment_STR () {
6268 const Stackel s = pop;
6269 if (s->which == Stackel_STRING) {
6270 const conststring32 value = Melder_getenv (s->getString());
6271 autostring32 result = Melder_dup (value ? value : U"");
6272 pushString (result.move());
6273 } else {
6274 Melder_throw (U"The function “environment$” requires a string, not ", s->whichText(), U".");
6275 }
6276 }
6277 static void do_index () {
6278 const Stackel t = pop, s = pop;
6279 if (s->which == Stackel_STRING && t->which == Stackel_STRING) {
6280 char32 *substring = str32str (s->getString(), t->getString());
6281 const integer result = ( substring ? substring - s->getString() + 1 : 0 ); // 0 is the special case, meaning "not found"
6282 pushNumber (result);
6283 } else if (s->which == Stackel_STRING_ARRAY && t->which == Stackel_STRING) {
6284 pushNumber (NUMfindFirst (s->stringArray, t->getString()));
6285 } else {
6286 Melder_throw (U"The function “index” requires two strings, not ",
6287 s->whichText(), U" and ", t->whichText(), U".");
6288 }
6289 }
6290 static void do_index_caseInsensitive () {
6291 const Stackel t = pop, s = pop;
6292 if (s->which == Stackel_STRING && t->which == Stackel_STRING) {
6293 char32 *substring = str32str_caseInsensitive (s->getString(), t->getString());
6294 const integer result = ( substring ? substring - s->getString() + 1 : 0 ); // 0 is the special case, meaning "not found"
6295 pushNumber (result);
6296 } else if (s->which == Stackel_STRING_ARRAY && t->which == Stackel_STRING) {
6297 pushNumber (NUMfindFirst_caseInsensitive (s->stringArray, t->getString()));
6298 } else {
6299 Melder_throw (U"The function “index_caseInsensitive” requires two strings, not ",
6300 s->whichText(), U" and ", t->whichText(), U".");
6301 }
6302 }
6303 static void do_rindex () {
6304 const Stackel part = pop, whole = pop;
6305 if (whole->which == Stackel_STRING && part->which == Stackel_STRING) {
6306 char32 *lastSubstring = str32str (whole->getString(), part->getString());
6307 if (part->getString() [0] == U'\0') {
6308 const integer result = Melder_length (whole->getString());
6309 pushNumber (result);
6310 } else if (lastSubstring) {
6311 for (;;) {
6312 char32 *substring = str32str (lastSubstring + 1, part->getString());
6313 if (! substring)
6314 break;
6315 lastSubstring = substring;
6316 }
6317 pushNumber (lastSubstring - whole->getString() + 1);
6318 } else {
6319 pushNumber (0); // 0 is the special case, meaning "not found"
6320 }
6321 } else if (whole->which == Stackel_STRING_ARRAY && part->which == Stackel_STRING) {
6322 pushNumber (NUMfindLast (whole->stringArray, part->getString()));
6323 } else {
6324 Melder_throw (U"The function “rindex” requires two strings, not ",
6325 whole->whichText(), U" and ", part->whichText(), U".");
6326 }
6327 }
6328 static void do_rindex_caseInsensitive () {
6329 const Stackel part = pop, whole = pop;
6330 if (whole->which == Stackel_STRING && part->which == Stackel_STRING) {
6331 char32 *lastSubstring = str32str_caseInsensitive (whole->getString(), part->getString());
6332 if (part->getString() [0] == U'\0') {
6333 const integer result = Melder_length (whole->getString());
6334 pushNumber (result);
6335 } else if (lastSubstring) {
6336 for (;;) {
6337 char32 *substring = str32str_caseInsensitive (lastSubstring + 1, part->getString());
6338 if (! substring)
6339 break;
6340 lastSubstring = substring;
6341 }
6342 pushNumber (lastSubstring - whole->getString() + 1);
6343 } else {
6344 pushNumber (0); // 0 is the special case, meaning "not found"
6345 }
6346 } else if (whole->which == Stackel_STRING_ARRAY && part->which == Stackel_STRING) {
6347 pushNumber (NUMfindLast_caseInsensitive (whole->stringArray, part->getString()));
6348 } else {
6349 Melder_throw (U"The function “rindex_caseInsensitive” requires two strings, not ",
6350 whole->whichText(), U" and ", part->whichText(), U".");
6351 }
6352 }
6353 static void do_index_regex (int backward) {
6354 const Stackel t = pop, s = pop;
6355 if (s->which == Stackel_STRING && t->which == Stackel_STRING) {
6356 conststring32 errorMessage;
6357 regexp *compiled_regexp = CompileRE (t->getString(), & errorMessage, 0);
6358 if (! compiled_regexp) {
6359 Melder_throw (U"index_regex(): ", errorMessage, U".");
6360 } else {
6361 if (ExecRE (compiled_regexp, nullptr, s->getString(), nullptr, backward, U'\0', U'\0', nullptr, nullptr)) {
6362 char32 *location = (char32 *) compiled_regexp -> startp [0];
6363 pushNumber (location - s->getString() + 1);
6364 free (compiled_regexp);
6365 } else {
6366 pushNumber (false);
6367 }
6368 }
6369 } else {
6370 Melder_throw (U"The function “", Formula_instructionNames [parse [programPointer]. symbol],
6371 U"” requires two strings, not ", s->whichText(), U" and ", t->whichText(), U".");
6372 }
6373 }
6374 static void do_stringMatchesCriterion (kMelder_string criterion, bool caseSensitive) {
6375 const Stackel t = pop, s = pop;
6376 if (s->which == Stackel_STRING && t->which == Stackel_STRING) {
6377 const bool result = Melder_stringMatchesCriterion (s->getString(), criterion, t->getString(), caseSensitive);
6378 pushNumber (result);
6379 } else {
6380 Melder_throw (U"The function “", Formula_instructionNames [parse [programPointer]. symbol],
6381 U"” requires two strings, not ", s->whichText(), U" and ", t->whichText(), U".");
6382 }
6383 }
6384 static void do_extractNumber () {
6385 const Stackel t = pop, s = pop;
6386 if (s->which == Stackel_STRING && t->which == Stackel_STRING) {
6387 char32 *substring = str32str (s->getString(), t->getString());
6388 if (! substring) {
6389 pushNumber (undefined);
6390 } else {
6391 /* Skip the prompt. */
6392 substring += Melder_length (t->getString());
6393 /* Skip white space. */
6394 while (Melder_isHorizontalOrVerticalSpace (*substring)) substring ++;
6395 if (substring [0] == U'\0' || str32nequ (substring, U"--undefined--", 13)) {
6396 pushNumber (undefined);
6397 } else {
6398 char32 buffer [101];
6399 int i = 0;
6400 for (; i < 100; i ++) {
6401 buffer [i] = *substring;
6402 substring ++;
6403 if (*substring == U'\0' || Melder_isHorizontalOrVerticalSpace (*substring))
6404 break;
6405 }
6406 if (i >= 100) {
6407 buffer [100] = U'\0';
6408 pushNumber (Melder_atof (buffer));
6409 } else {
6410 buffer [i + 1] = U'\0';
6411 char32 *slash = str32chr (buffer, U'/');
6412 if (slash) {
6413 *slash = U'\0';
6414 double numerator = Melder_atof (buffer), denominator = Melder_atof (slash + 1);
6415 pushNumber (numerator / denominator);
6416 } else {
6417 pushNumber (Melder_atof (buffer));
6418 }
6419 }
6420 }
6421 }
6422 } else {
6423 Melder_throw (U"The function “", Formula_instructionNames [parse [programPointer]. symbol],
6424 U"” requires two strings, not ", s->whichText(), U" and ", t->whichText(), U".");
6425 }
6426 }
6427 static void do_extractText_STR (bool singleWord) {
6428 const Stackel t = pop, s = pop;
6429 if (s->which == Stackel_STRING && t->which == Stackel_STRING) {
6430 char32 *substring = str32str (s->getString(), t->getString());
6431 autostring32 result;
6432 if (! substring) {
6433 result = Melder_dup (U"");
6434 } else {
6435 integer length;
6436 /* Skip the prompt. */
6437 substring += Melder_length (t->getString());
6438 if (singleWord) {
6439 /* Skip white space. */
6440 while (Melder_isHorizontalOrVerticalSpace (*substring)) substring ++;
6441 }
6442 char32 *p = substring;
6443 if (singleWord) {
6444 /* Proceed until next white space. */
6445 while (Melder_staysWithinInk (*p)) p ++;
6446 } else {
6447 /* Proceed until end of line. */
6448 while (Melder_staysWithinLine (*p)) p ++;
6449 }
6450 length = p - substring;
6451 result = autostring32 (length);
6452 str32ncpy (result.get(), substring, length);
6453 }
6454 pushString (result.move());
6455 } else {
6456 Melder_throw (U"The function “", Formula_instructionNames [parse [programPointer]. symbol],
6457 U"” requires two strings, not ", s->whichText(), U" and ", t->whichText(), U".");
6458 }
6459 }
6460 static void do_replace_STR () {
6461 const Stackel x = pop, u = pop, t = pop, s = pop;
6462 if (s->which == Stackel_STRING && t->which == Stackel_STRING && u->which == Stackel_STRING && x->which == Stackel_NUMBER) {
6463 autostring32 result = replace_STR (s->getString(), t->getString(), u->getString(), Melder_iround (x->number));
6464 pushString (result.move());
6465 } else {
6466 Melder_throw (U"The function “replace$” requires three strings and a number.");
6467 }
6468 }
6469 static void do_replace_regex_STR () {
6470 const Stackel x = pop, u = pop, t = pop, s = pop;
6471 if (s->which == Stackel_STRING && t->which == Stackel_STRING && u->which == Stackel_STRING && x->which == Stackel_NUMBER) {
6472 conststring32 errorMessage;
6473 regexp *compiled_regexp = CompileRE (t->getString(), & errorMessage, 0);
6474 if (! compiled_regexp) {
6475 Melder_throw (U"replace_regex$(): ", errorMessage, U".");
6476 } else {
6477 autostring32 result = replace_regex_STR (s->getString(), compiled_regexp, u->getString(), Melder_iround (x->number));
6478 pushString (result.move());
6479 }
6480 } else {
6481 Melder_throw (U"The function “replace_regex$” requires three strings and a number.");
6482 }
6483 }
6484 static void do_selected () {
6485 const Stackel n = pop;
6486 integer result = 0;
6487 if (n->number == 0) {
6488 result = praat_idOfSelected (nullptr, 0);
6489 } else if (n->number == 1) {
6490 const Stackel a = pop;
6491 if (a->which == Stackel_STRING) {
6492 ClassInfo klas = Thing_classFromClassName (a->getString(), nullptr);
6493 result = praat_idOfSelected (klas, 0);
6494 } else if (a->which == Stackel_NUMBER) {
6495 result = praat_idOfSelected (nullptr, Melder_iround (a->number));
6496 } else {
6497 Melder_throw (U"The function “selected” requires a string (an object type name) and/or a number.");
6498 }
6499 } else if (n->number == 2) {
6500 const Stackel x = pop, s = pop;
6501 if (s->which == Stackel_STRING && x->which == Stackel_NUMBER) {
6502 const ClassInfo klas = Thing_classFromClassName (s->getString(), nullptr);
6503 result = praat_idOfSelected (klas, Melder_iround (x->number));
6504 } else {
6505 Melder_throw (U"The function “selected” requires a string (an object type name) and/or a number.");
6506 }
6507 } else {
6508 Melder_throw (U"The function “selected” requires 0, 1, or 2 arguments, not ", n->number, U".");
6509 }
6510 pushNumber (result);
6511 }
6512 static void do_selected_STR () {
6513 const Stackel n = pop;
6514 char32 *resultSource; // purposefully don't initialize, so that the compiler can check that has been assigned to when used
6515 if (n->number == 0) {
6516 resultSource = praat_nameOfSelected (nullptr, 0);
6517 } else if (n->number == 1) {
6518 const Stackel a = pop;
6519 if (a->which == Stackel_STRING) {
6520 const ClassInfo klas = Thing_classFromClassName (a->getString(), nullptr);
6521 resultSource = praat_nameOfSelected (klas, 0);
6522 } else if (a->which == Stackel_NUMBER) {
6523 resultSource = praat_nameOfSelected (nullptr, Melder_iround (a->number));
6524 } else {
6525 Melder_throw (U"The function “selected$” requires a string (an object type name) and/or a number.");
6526 }
6527 } else if (n->number == 2) {
6528 const Stackel x = pop, s = pop;
6529 if (s->which == Stackel_STRING && x->which == Stackel_NUMBER) {
6530 ClassInfo klas = Thing_classFromClassName (s->getString(), nullptr);
6531 resultSource = praat_nameOfSelected (klas, Melder_iround (x->number));
6532 } else {
6533 Melder_throw (U"The function “selected$” requires a string (an object type name) and a number.");
6534 }
6535 } else {
6536 Melder_throw (U"The function “selected$” requires 0, 1, or 2 arguments, not ", n->number, U".");
6537 }
6538 pushString (Melder_dup (resultSource));
6539 }
6540 static void do_numberOfSelected () {
6541 const Stackel n = pop;
6542 integer result = 0;
6543 if (n->number == 0) {
6544 result = praat_numberOfSelected (nullptr);
6545 } else if (n->number == 1) {
6546 const Stackel s = pop;
6547 if (s->which == Stackel_STRING) {
6548 const ClassInfo klas = Thing_classFromClassName (s->getString(), nullptr);
6549 result = praat_numberOfSelected (klas);
6550 } else {
6551 Melder_throw (U"The function “numberOfSelected” requires a string (an object type name), not ", s->whichText(), U".");
6552 }
6553 } else {
6554 Melder_throw (U"The function “numberOfSelected” requires 0 or 1 arguments, not ", n->number, U".");
6555 }
6556 pushNumber (result);
6557 }
6558 static void do_selected_VEC () {
6559 const Stackel n = pop;
6560 autoVEC result;
6561 if (n->number == 0) {
6562 result = praat_idsOfAllSelected (nullptr);
6563 } else if (n->number == 1) {
6564 const Stackel s = pop;
6565 if (s->which == Stackel_STRING) {
6566 const ClassInfo klas = Thing_classFromClassName (s->getString(), nullptr);
6567 result = praat_idsOfAllSelected (klas);
6568 } else {
6569 Melder_throw (U"The function “selected#” requires a string (an object type name), not ", s->whichText(), U".");
6570 }
6571 } else {
6572 Melder_throw (U"The function “selected#” requires 0 or 1 arguments, not ", n->number, U".");
6573 }
6574 pushNumericVector (result.move());
6575 }
6576 static void do_selected_STRVEC () {
6577 const Stackel n = pop;
6578 autoSTRVEC result;
6579 if (n->number == 0) {
6580 result = praat_namesOfAllSelected (nullptr);
6581 } else if (n->number == 1) {
6582 const Stackel s = pop;
6583 if (s->which == Stackel_STRING) {
6584 const ClassInfo klas = Thing_classFromClassName (s->getString(), nullptr);
6585 result = praat_namesOfAllSelected (klas);
6586 } else {
6587 Melder_throw (U"The function “selected$#” requires a string (an object type name), not ", s->whichText(), U".");
6588 }
6589 } else {
6590 Melder_throw (U"The function “selected$#” requires 0 or 1 arguments, not ", n->number, U".");
6591 }
6592 pushStringVector (result.move());
6593 }
6594 static void do_selectObject () {
6595 const Stackel n = pop;
6596 praat_deselectAll ();
6597 for (int iobject = 1; iobject <= n -> number; iobject ++) {
6598 const Stackel object = pop;
6599 if (object -> which == Stackel_NUMBER) {
6600 const integer IOBJECT = praat_findObjectById (Melder_iround (object -> number));
6601 praat_select (IOBJECT);
6602 } else if (object -> which == Stackel_STRING) {
6603 const integer IOBJECT = praat_findObjectByName (object -> getString());
6604 praat_select (IOBJECT);
6605 } else if (object -> which == Stackel_NUMERIC_VECTOR) {
6606 const VEC vec = object -> numericVector;
6607 for (integer ielm = 1; ielm <= vec.size; ielm ++) {
6608 const integer IOBJECT = praat_findObjectById (Melder_iround (vec [ielm]));
6609 praat_select (IOBJECT);
6610 }
6611 } else {
6612 Melder_throw (U"The function “selectObject” takes numbers, strings, or numeric vectors, not ", object->whichText());
6613 }
6614 }
6615 praat_show ();
6616 pushNumber (1);
6617 }
6618 static void do_plusObject () {
6619 const Stackel n = pop;
6620 for (int iobject = 1; iobject <= n -> number; iobject ++) {
6621 const Stackel object = pop;
6622 if (object -> which == Stackel_NUMBER) {
6623 const integer IOBJECT = praat_findObjectById (Melder_iround (object -> number));
6624 praat_select (IOBJECT);
6625 } else if (object -> which == Stackel_STRING) {
6626 const integer IOBJECT = praat_findObjectByName (object -> getString());
6627 praat_select (IOBJECT);
6628 } else if (object -> which == Stackel_NUMERIC_VECTOR) {
6629 const VEC vec = object -> numericVector;
6630 for (integer ielm = 1; ielm <= vec.size; ielm ++) {
6631 const integer IOBJECT = praat_findObjectById (Melder_iround (vec [ielm]));
6632 praat_select (IOBJECT);
6633 }
6634 } else {
6635 Melder_throw (U"The function “plusObject” takes numbers, strings, or numeric vectors, not ", object->whichText(), U".");
6636 }
6637 }
6638 praat_show ();
6639 pushNumber (1);
6640 }
6641 static void do_minusObject () {
6642 const Stackel n = pop;
6643 for (int iobject = 1; iobject <= n -> number; iobject ++) {
6644 const Stackel object = pop;
6645 if (object -> which == Stackel_NUMBER) {
6646 const integer IOBJECT = praat_findObjectById (Melder_iround (object -> number));
6647 praat_deselect (IOBJECT);
6648 } else if (object -> which == Stackel_STRING) {
6649 const integer IOBJECT = praat_findObjectByName (object -> getString());
6650 praat_deselect (IOBJECT);
6651 } else if (object -> which == Stackel_NUMERIC_VECTOR) {
6652 const VEC vec = object -> numericVector;
6653 for (integer ielm = 1; ielm <= vec.size; ielm ++) {
6654 const integer IOBJECT = praat_findObjectById (Melder_iround (vec [ielm]));
6655 praat_deselect (IOBJECT);
6656 }
6657 } else {
6658 Melder_throw (U"The function “minusObject” takes numbers, strings, or numeric vectors, not ", object->whichText(), U".");
6659 }
6660 }
6661 praat_show ();
6662 pushNumber (1);
6663 }
6664 static void do_removeObject () {
6665 const Stackel n = pop;
6666 for (int iobject = 1; iobject <= n -> number; iobject ++) {
6667 const Stackel object = pop;
6668 if (object -> which == Stackel_NUMBER) {
6669 const integer IOBJECT = praat_findObjectById (Melder_iround (object -> number));
6670 praat_removeObject (IOBJECT);
6671 } else if (object -> which == Stackel_STRING) {
6672 const integer IOBJECT = praat_findObjectByName (object -> getString());
6673 praat_removeObject (IOBJECT);
6674 } else if (object -> which == Stackel_NUMERIC_VECTOR) {
6675 const VEC vec = object -> numericVector;
6676 for (integer ielm = 1; ielm <= vec.size; ielm ++) {
6677 const integer IOBJECT = praat_findObjectById (Melder_iround (vec [ielm]));
6678 praat_removeObject (IOBJECT);
6679 }
6680 } else {
6681 Melder_throw (U"The function “removeObject” takes numbers, strings, or numeric vectors, not ", object->whichText(), U".");
6682 }
6683 }
6684 praat_show ();
6685 pushNumber (1);
6686 }
6687 static Daata _do_object (Stackel object, conststring32 expressionMessage) {
6688 Daata data;
6689 if (object -> which == Stackel_NUMBER) {
6690 const integer IOBJECT = praat_findObjectById (Melder_iround (object -> number));
6691 data = OBJECT;
6692 } else if (object -> which == Stackel_STRING) {
6693 const integer IOBJECT = praat_findObjectByName (object -> getString());
6694 data = OBJECT;
6695 } else if (object -> which == Stackel_OBJECT) {
6696 data = object -> object;
6697 } else {
6698 Melder_throw (U"The expression “", expressionMessage, U"” requires xx to be a number or a string, not ", object->whichText(), U".");
6699 }
6700 return data;
6701 }
6702 static void do_object_xmin () {
6703 const Stackel object = pop;
6704 const Daata data = _do_object (object, U"object[xx].xmin");
6705 Melder_require (data -> v_hasGetXmin (),
6706 U"An object of type ", Thing_className (data), U" has no “xmin” attribute.");
6707 pushNumber (data -> v_getXmin ());
6708 }
6709 static void do_object_xmax () {
6710 const Stackel object = pop;
6711 const Daata data = _do_object (object, U"object[xx].xmax");
6712 Melder_require (data -> v_hasGetXmax (),
6713 U"An object of type ", Thing_className (data), U" has no “xmax” attribute.");
6714 pushNumber (data -> v_getXmax ());
6715 }
6716 static void do_object_ymin () {
6717 const Stackel object = pop;
6718 const Daata data = _do_object (object, U"object[xx].ymin");
6719 Melder_require (data -> v_hasGetYmin (),
6720 U"An object of type ", Thing_className (data), U" has no “ymin” attribute.");
6721 pushNumber (data -> v_getYmin ());
6722 }
6723 static void do_object_ymax () {
6724 const Stackel object = pop;
6725 const Daata data = _do_object (object, U"object[xx].ymax");
6726 Melder_require (data -> v_hasGetYmax (),
6727 U"An object of type ", Thing_className (data), U" has no “ymax” attribute.");
6728 pushNumber (data -> v_getYmax ());
6729 }
6730 static void do_object_nx () {
6731 const Stackel object = pop;
6732 const Daata data = _do_object (object, U"object[xx].nx");
6733 Melder_require (data -> v_hasGetNx (),
6734 U"An object of type ", Thing_className (data), U" has no “nx” attribute.");
6735 pushNumber (data -> v_getNx ());
6736 }
6737 static void do_object_ny () {
6738 const Stackel object = pop;
6739 const Daata data = _do_object (object, U"object[xx].ny");
6740 Melder_require (data -> v_hasGetNy (),
6741 U"An object of type ", Thing_className (data), U" has no “ny” attribute.");
6742 pushNumber (data -> v_getNy ());
6743 }
6744 static void do_object_dx () {
6745 const Stackel object = pop;
6746 const Daata data = _do_object (object, U"object[xx].dx");
6747 Melder_require (data -> v_hasGetDx (),
6748 U"An object of type ", Thing_className (data), U" has no “dx” attribute.");
6749 pushNumber (data -> v_getDx ());
6750 }
6751 static void do_object_dy () {
6752 const Stackel object = pop;
6753 const Daata data = _do_object (object, U"object[xx].dy");
6754 Melder_require (data -> v_hasGetDy (),
6755 U"An object of type ", Thing_className (data), U" has no “dy” attribute.");
6756 pushNumber (data -> v_getDy ());
6757 }
6758 static void do_object_nrow () {
6759 const Stackel object = pop;
6760 const Daata data = _do_object (object, U"object[xx].nrow");
6761 Melder_require (data -> v_hasGetNrow (),
6762 U"An object of type ", Thing_className (data), U" has no “nrow” attribute.");
6763 pushNumber (data -> v_getNrow ());
6764 }
6765 static void do_object_ncol () {
6766 const Stackel object = pop;
6767 const Daata data = _do_object (object, U"object[xx].ncol");
6768 Melder_require (data -> v_hasGetNcol (),
6769 U"An object of type ", Thing_className (data), U" has no “ncol” attribute.");
6770 pushNumber (data -> v_getNcol ());
6771 }
6772 static void do_object_row_STR () {
6773 const Stackel index = pop, object = pop;
6774 const Daata data = _do_object (object, U"object[xx].row$[]");
6775 Melder_require (data -> v_hasGetRowStr (),
6776 U"An object of type ", Thing_className (data), U" has no “row$[]” attribute.");
6777 Melder_require (index -> which == Stackel_NUMBER,
6778 U"The expression “object[].row$[xx]” requires xx to be a number, not ", index->whichText(), U".");
6779 const integer number = Melder_iround (index->number);
6780 autostring32 result = Melder_dup (data -> v_getRowStr (number));
6781 if (! result)
6782 Melder_throw (U"Row index out of bounds.");
6783 pushString (result.move());
6784 }
6785 static void do_object_col_STR () {
6786 const Stackel index = pop, object = pop;
6787 const Daata data = _do_object (object, U"object[xx].col$[]");
6788 Melder_require (data -> v_hasGetColStr (),
6789 U"An object of type ", Thing_className (data), U" has no “col$[]” attribute.");
6790 Melder_require (index -> which == Stackel_NUMBER,
6791 U"The expression “object[].col$[xx]” requires xx to be a number, not ", index->whichText(), U".");
6792 const integer number = Melder_iround (index->number);
6793 autostring32 result = Melder_dup (data -> v_getColStr (number));
6794 if (! result)
6795 Melder_throw (U"Column index out of bounds.");
6796 pushString (result.move());
6797 }
6798 static void do_string_STR () {
6799 const Stackel value = pop;
6800 if (value->which == Stackel_NUMBER) {
6801 autostring32 result = Melder_dup (Melder_double (value->number));
6802 pushString (result.move());
6803 } else {
6804 Melder_throw (U"The function “string$” requires a number, not ", value->whichText(), U".");
6805 }
6806 }
6807 static void do_horizontal_STR () {
6808 const Stackel array = pop;
6809 if (array->which == Stackel_STRING_ARRAY) {
6810 pushString (horizontal_STR (array->stringArray));
6811 } else {
6812 Melder_throw (U"The function “horizontal$” requires a string array.");
6813 }
6814 }
6815 static void do_vertical_STR () {
6816 const Stackel array = pop;
6817 if (array->which == Stackel_STRING_ARRAY) {
6818 pushString (vertical_STR (array->stringArray));
6819 } else {
6820 Melder_throw (U"The function “vertical$” requires a string array.");
6821 }
6822 }
6823 static void do_numbers_VEC () {
6824 /*
6825 result# = numbers# (strings$#)
6826 */
6827 const Stackel stringsel = pop;
6828 if (stringsel->which == Stackel_STRING_ARRAY) {
6829 const constSTRVEC strings = stringsel->stringArray;
6830 autoVEC result = zero_VEC (strings.size);
6831 for (integer i = 1; i <= strings.size; i ++)
6832 result [i] = Melder_atof (strings [i]);
6833 pushNumericVector (result.move());
6834 } else {
6835 Melder_throw (U"The function “numbers#” requires a string array, not ", stringsel->whichText(), U".");
6836 }
6837 }
6838 static void do_sleep () {
6839 const Stackel value = pop;
6840 if (value->which == Stackel_NUMBER) {
6841 Melder_sleep (value->number);
6842 pushNumber (1);
6843 } else {
6844 Melder_throw (U"The function “sleep” requires a number, not ", value->whichText(), U".");
6845 }
6846 }
6847 static void do_unicode () {
6848 const Stackel value = pop;
6849 if (value->which == Stackel_STRING) {
6850 pushNumber (value->getString() [0]);
6851 } else {
6852 Melder_throw (U"The function “unicode” requires a character, not ", value->whichText(), U".");
6853 }
6854 }
6855 static void do_unicode_STR () {
6856 const Stackel value = pop;
6857 if (value->which == Stackel_NUMBER) {
6858 Melder_require (value->number >= 0.0 && value->number < (double) (1 << 21),
6859 U"A unicode number cannot be greater than ", (1 << 21) - 1, U".");
6860 Melder_require (value->number < 0xD800 || value->number > 0xDFFF,
6861 U"A unicode number cannot lie between 0xD800 and 0xDFFF. Those are “surrogates”.");
6862 char32 string [2] = { U'\0', U'\0' };
6863 string [0] = (char32) value->number;
6864 pushString (Melder_dup (string).move());
6865 } else {
6866 Melder_throw (U"The function “unicode$” requires a number, not ", value->whichText(), U".");
6867 }
6868 }
6869 static void do_fixed_STR () {
6870 const Stackel precision = pop, value = pop;
6871 if (value->which == Stackel_NUMBER && precision->which == Stackel_NUMBER) {
6872 autostring32 result = Melder_dup (Melder_fixed (value->number, Melder_iround (precision->number)));
6873 pushString (result.move());
6874 } else if (value->which == Stackel_NUMERIC_VECTOR && precision->which == Stackel_NUMBER) {
6875 autostring32 result = Melder_dup (Melder_fixed (value->numericVector, Melder_iround (precision->number)));
6876 pushString (result.move());
6877 } else if (value->which == Stackel_NUMERIC_MATRIX && precision->which == Stackel_NUMBER) {
6878 autostring32 result = Melder_dup (Melder_fixed (value->numericMatrix, Melder_iround (precision->number)));
6879 pushString (result.move());
6880 } else {
6881 Melder_throw (U"The function “fixed$” requires a number or a vector or a matrix, and a number (the precision), not ", value->whichText(), U" and ", precision->whichText(), U".");
6882 }
6883 }
6884 static void do_percent_STR () {
6885 const Stackel precision = pop, value = pop;
6886 if (value->which == Stackel_NUMBER && precision->which == Stackel_NUMBER) {
6887 autostring32 result = Melder_dup (Melder_percent (value->number, Melder_iround (precision->number)));
6888 pushString (result.move());
6889 } else {
6890 Melder_throw (U"The function “percent$” requires two numbers (value and precision), not ", value->whichText(), U" and ", precision->whichText(), U".");
6891 }
6892 }
6893 static void do_graphicalPercent_STR () {
6894 const Stackel precision = pop, value = pop;
6895 if (value->which == Stackel_NUMBER && precision->which == Stackel_NUMBER) {
6896 autostring32 result = Melder_dup (Melder_graphicalPercent (value->number, Melder_iround (precision->number)));
6897 pushString (result.move());
6898 } else {
6899 Melder_throw (U"The function “graphicalPercent$” requires two numbers (value and precision), not ", value->whichText(), U" and ", precision->whichText(), U".");
6900 }
6901 }
6902 static void do_bigInteger_STR () {
6903 const Stackel value = pop;
6904 if (value->which == Stackel_NUMBER) {
6905 if (value->number < INT54_MIN || value->number > INT54_MAX)
6906 Melder_throw (U"bigInteger(): the number ", value->number, U" cannot be represented precisely as an integer.");
6907 autostring32 result = Melder_dup (Melder_bigInteger (int64 (value->number))); // guarded cast
6908 pushString (result.move());
6909 } else {
6910 Melder_throw (U"The function “bigInteger$” requires a number, not ", value->whichText(), U".");
6911 }
6912 }
6913 static void do_half_STR () {
6914 const Stackel value = pop;
6915 if (value->which == Stackel_NUMBER) {
6916 autostring32 result = Melder_dup (Melder_half (value->number));
6917 pushString (result.move());
6918 } else {
6919 Melder_throw (U"The function “half$” requires a number, not ", value->whichText(), U".");
6920 }
6921 }
6922 static void do_graphicalHalf_STR () {
6923 const Stackel value = pop;
6924 if (value->which == Stackel_NUMBER) {
6925 autostring32 result = Melder_dup (Melder_graphicalHalf (value->number));
6926 pushString (result.move());
6927 } else {
6928 Melder_throw (U"The function “graphicalHalf$” requires a number, not ", value->whichText(), U".");
6929 }
6930 }
6931 static void do_single_STR () {
6932 const Stackel value = pop;
6933 if (value->which == Stackel_NUMBER) {
6934 autostring32 result = Melder_dup (Melder_single (value->number));
6935 pushString (result.move());
6936 } else {
6937 Melder_throw (U"The function “single$” requires a number, not ", value->whichText(), U".");
6938 }
6939 }
6940 static void do_graphicalSingle_STR () {
6941 const Stackel value = pop;
6942 if (value->which == Stackel_NUMBER) {
6943 autostring32 result = Melder_dup (Melder_graphicalSingle (value->number));
6944 pushString (result.move());
6945 } else {
6946 Melder_throw (U"The function “graphicalSingle$” requires a number, not ", value->whichText(), U".");
6947 }
6948 }
6949 static void do_double_STR () {
6950 const Stackel value = pop;
6951 if (value->which == Stackel_NUMBER) {
6952 autostring32 result = Melder_dup (Melder_double (value->number));
6953 pushString (result.move());
6954 } else {
6955 Melder_throw (U"The function “double$” requires a number, not ", value->whichText(), U".");
6956 }
6957 }
6958 static void do_graphicalDouble_STR () {
6959 const Stackel value = pop;
6960 if (value->which == Stackel_NUMBER) {
6961 autostring32 result = Melder_dup (Melder_graphicalDouble (value->number));
6962 pushString (result.move());
6963 } else {
6964 Melder_throw (U"The function “graphicalDouble$” requires a number, not ", value->whichText(), U".");
6965 }
6966 }
6967 static void do_naturalLogarithm_STR () {
6968 const Stackel value = pop;
6969 if (value->which == Stackel_NUMBER) {
6970 autostring32 result = Melder_dup (Melder_naturalLogarithm (value->number));
6971 pushString (result.move());
6972 } else {
6973 Melder_throw (U"The function “naturalLogarithm$” requires a number, not ", value->whichText(), U".");
6974 }
6975 }
6976 static void do_graphicalNaturalLogarithm_STR () {
6977 const Stackel value = pop;
6978 if (value->which == Stackel_NUMBER) {
6979 autostring32 result = Melder_dup (Melder_graphicalNaturalLogarithm (value->number));
6980 pushString (result.move());
6981 } else {
6982 Melder_throw (U"The function “graphicalNaturalLogarithm$” requires a number, not ", value->whichText(), U".");
6983 }
6984 }
6985 static void do_hexadecimal_STR () {
6986 const Stackel precision = pop, value = pop;
6987 if (value->which == Stackel_NUMBER && precision->which == Stackel_NUMBER) {
6988 autostring32 result = Melder_dup (Melder_hexadecimal (Melder_iround (value->number), Melder_iround (precision->number)));
6989 pushString (result.move());
6990 } else {
6991 Melder_throw (U"The function “hexadecimal$” requires two numbers (value and precision), not ", value->whichText(), U" and ", precision->whichText(), U".");
6992 }
6993 }
6994 static void do_deleteFile () {
6995 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
6996 U"The function “deleteFile” is not available inside manuals.");
6997 const Stackel f = pop;
6998 if (f->which == Stackel_STRING) {
6999 structMelderFile file { };
7000 Melder_relativePathToFile (f->getString(), & file);
7001 Melder_checkTrust (theInterpreter, U"delete the file\n", & file);
7002 MelderFile_delete (& file);
7003 pushNumber (1);
7004 } else {
7005 Melder_throw (U"The function “deleteFile” requires a string, not ", f->whichText(), U".");
7006 }
7007 }
7008 static void do_moveAndOrRenameFile () {
7009 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7010 U"The function “moveAndOrRenameFile” is not available inside manuals.");
7011 const Stackel to = pop, from = pop;
7012 if (from->which == Stackel_STRING && to->which == Stackel_STRING) {
7013 structMelderFile fromFile { }, toFile { };
7014 Melder_relativePathToFile (from->getString(), & fromFile);
7015 Melder_relativePathToFile (to->getString(), & toFile);
7016 Melder_checkTrust (theInterpreter, U"move or rename the file\n", & fromFile, U" to ", & toFile);
7017 MelderFile_moveAndOrRename (& fromFile, & toFile);
7018 pushNumber (1);
7019 } else {
7020 Melder_throw (U"The function “moveAndOrRenameFile” requires two strings, not ", from->whichText(), U" and ", to->whichText(), U".");
7021 }
7022 }
7023 static void do_createFolder () {
7024 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7025 U"The function “createFolder” is not available inside manuals.");
7026 const Stackel f = pop;
7027 if (f->which == Stackel_STRING) {
7028 structMelderFolder folder { };
7029 Melder_relativePathToFolder (f->getString(), & folder);
7030 if (! MelderFolder_exists (& folder)) { // don't check for trust if the folder exists
7031 Melder_checkTrust (theInterpreter, U"create the folder\n", & folder);
7032 MelderFolder_create (& folder);
7033 }
7034 pushNumber (1);
7035 } else {
7036 Melder_throw (U"The function “createFolder” requires a string, not ", f->whichText(), U".");
7037 }
7038 }
7039 static void do_createDirectory () {
7040 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7041 U"The function “createDirectory” is not available inside manuals.");
7042 const Stackel f = pop;
7043 if (f->which == Stackel_STRING) {
7044 structMelderFolder folder { };
7045 Melder_relativePathToFolder (f->getString(), & folder);
7046 if (! MelderFolder_exists (& folder)) { // don't check for trust if the folder exists
7047 Melder_checkTrust (theInterpreter, U"create the directory\n", & folder);
7048 MelderFolder_create (& folder);
7049 }
7050 pushNumber (1);
7051 } else {
7052 Melder_throw (U"The function “createDirectory” requires a string, not ", f->whichText(), U".");
7053 }
7054 }
7055 static void do_setWorkingDirectory () {
7056 const Stackel f = pop;
7057 if (f->which == Stackel_STRING) {
7058 structMelderFolder folder { };
7059 Melder_relativePathToFolder (f->getString(), & folder);
7060 Melder_setCurrentFolder (& folder);
7061 MelderFolder_copy (& folder, & theInterpreter -> workingDirectory);
7062 Melder_assert (MelderFolder_equal (Melder_peekWorkingDirectory(), & theInterpreter -> workingDirectory));
7063 //TRACE
7064 trace (U"Set the working directory to ", Melder_peekWorkingDirectory());
7065 trace (U"Set the working directory of interpreter ", Melder_pointer (theInterpreter), U" to ", & theInterpreter -> workingDirectory);
7066 pushNumber (1);
7067 } else {
7068 Melder_throw (U"The function “setWorkingDirectory” requires a string, not ", f->whichText(), U".");
7069 }
7070 }
7071 static void do_variableExists () {
7072 const Stackel f = pop;
7073 if (f->which == Stackel_STRING) {
7074 bool result = !! Interpreter_hasVariable (theInterpreter, f->getString());
7075 pushNumber (result);
7076 } else {
7077 Melder_throw (U"The function “variableExists” requires a string, not ", f->whichText(), U".");
7078 }
7079 }
7080 static void do_readFile () {
7081 const Stackel f = pop;
7082 if (f->which == Stackel_STRING) {
7083 structMelderFile file { };
7084 Melder_relativePathToFile (f->getString(), & file);
7085 autostring32 text = MelderFile_readText (& file);
7086 pushNumber (Melder_atof (text.get()));
7087 } else {
7088 Melder_throw (U"The function “readFile” requires a string (a file name), not ", f->whichText(), U".");
7089 }
7090 }
7091 static void do_readFile_STR () {
7092 const Stackel f = pop;
7093 if (f->which == Stackel_STRING) {
7094 structMelderFile file { };
7095 Melder_relativePathToFile (f->getString(), & file);
7096 autostring32 text = MelderFile_readText (& file);
7097 pushString (text.move());
7098 } else {
7099 Melder_throw (U"The function “readFile$” requires a string (a file name), not ", f->whichText(), U".");
7100 }
7101 }
7102 static void do_readFile_VEC () {
7103 const Stackel f = pop;
7104 if (f->which == Stackel_STRING) {
7105 structMelderFile file { };
7106 Melder_relativePathToFile (f->getString(), & file);
7107 autostring32 text = MelderFile_readText (& file);
7108 pushNumericVector (splitByWhitespace_VEC (text.get()));
7109 } else {
7110 Melder_throw (U"The function “readFile#” requires a string (a file name), not ", f->whichText(), U".");
7111 }
7112 }
7113 static void do_readFile_MAT () {
7114 const Stackel f = pop;
7115 if (f->which == Stackel_STRING) {
7116 structMelderFile file { };
7117 Melder_relativePathToFile (f->getString(), & file);
7118 autostring32 text = MelderFile_readText (& file);
7119 pushNumericMatrix (splitByLinesAndWhitespace_MAT (text.get()));
7120 } else {
7121 Melder_throw (U"The function “readFile##” requires a string (a file name), not ", f->whichText(), U".");
7122 }
7123 }
7124 static void do_tensorLiteral () {
7125 const Stackel n = pop;
7126 Melder_assert (n->which == Stackel_NUMBER);
7127 integer numberOfElements = Melder_iround (n->number);
7128 Melder_assert (numberOfElements >= 0);
7129 if (numberOfElements == 0) {
7130 autoVEC result = raw_VEC (0);
7131 pushNumericVector (result.move());
7132 return;
7133 }
7134 /*
7135 The type of the tensor can be a vector, or a matrix, or a tensor3...
7136 This depends on whether the last element is a number, a vector, or a matrix...
7137 */
7138 const Stackel last = pop;
7139 if (last->which == Stackel_NUMBER) {
7140 autoVEC result = raw_VEC (numberOfElements);
7141 result [numberOfElements] = last->number;
7142 for (integer ielement = numberOfElements - 1; ielement > 0; ielement --) {
7143 const Stackel element = pop;
7144 if (element->which != Stackel_NUMBER)
7145 Melder_throw (U"The tensor elements have to be of the same type, not ", element->whichText(), U" and a number.");
7146 result [ielement] = element->number;
7147 }
7148 pushNumericVector (result.move());
7149 } else if (last->which == Stackel_NUMERIC_VECTOR) {
7150 /*@praat
7151 a# = zero# (0) ; edge case
7152 a## = { a#, a# }
7153 assert numberOfRows (a##) = 2
7154 assert numberOfColumns (a##) = 0
7155 @*/
7156 const integer sharedNumberOfColumns = last->numericVector.size;
7157 autoMAT result = raw_MAT (numberOfElements, sharedNumberOfColumns);
7158 result.row (numberOfElements) <<= last->numericVector;
7159 for (integer ielement = numberOfElements - 1; ielement > 0; ielement --) {
7160 const Stackel element = pop;
7161 Melder_require (element->which == Stackel_NUMERIC_VECTOR,
7162 U"The tensor elements have to be of the same type, not ", element->whichText(), U" and a vector.");
7163 Melder_require (element->numericVector.size == sharedNumberOfColumns,
7164 U"The vectors have to be of the same size, not ", element->numericVector.size, U" and ", sharedNumberOfColumns);
7165 result.row (ielement) <<= element->numericVector;
7166 }
7167 pushNumericMatrix (result.move());
7168 } else if (last->which == Stackel_STRING) {
7169 autoSTRVEC result (numberOfElements);
7170 result [numberOfElements] = last->_string.move();
7171 for (integer ielement = numberOfElements - 1; ielement > 0; ielement --) {
7172 const Stackel element = pop;
7173 Melder_require (element->which == Stackel_STRING,
7174 U"The tensor elements have to be of the same type, not ", element->whichText(), U" and a string.");
7175 result [ielement] = element->_string.move();
7176 }
7177 pushStringVector (std::move (result));
7178 } else {
7179 Melder_throw (U"Cannot (yet?) create a tensor containing ", last->whichText(), U".");
7180 }
7181 }
7182 static void do_tensorLiteralCell () {
7183 const Stackel index = pop, nelem = pop;
7184 Melder_assert (nelem->which == Stackel_NUMBER);
7185 const integer numberOfElements = Melder_iround (nelem->number);
7186 Melder_assert (numberOfElements > 0);
7187 const Stackel last = pop;
7188 Melder_require (last->which == Stackel_NUMBER || last->which == Stackel_STRING,
7189 U"Cannot index matrix literals.");
7190 Melder_require (index->which == Stackel_NUMBER,
7191 U"In vector indexing, the element index should be a number, not ", index->whichText(), U".");
7192 Melder_require (isdefined (index->number),
7193 U"The element index is undefined.");
7194 const integer iindex = Melder_iround (index->number);
7195 Melder_require (iindex >= 1,
7196 U"Element index out of bounds. Your index is ", iindex, U", but the index can range only from 1 to ", numberOfElements, U".");
7197 Melder_require (iindex <= numberOfElements,
7198 U"Element index out of bounds. Your index is ", iindex, U", but there are only ", numberOfElements, U" elements.");
7199 if (last->which == Stackel_NUMBER) {
7200 double result = last->number;
7201 for (integer ielement = numberOfElements - 1; ielement > 0; ielement --) {
7202 const Stackel element = pop;
7203 if (element->which != Stackel_NUMBER)
7204 Melder_throw (U"The tensor elements have to be of the same type, not ", element->whichText(), U" and a number.");
7205 if (ielement == iindex)
7206 result = element->number;
7207 }
7208 pushNumber (result);
7209 } else if (last->which == Stackel_STRING) {
7210 autostring32 result = last->_string.move(); // we can move it, because it's been popped off the stack, so we never return there
7211 for (integer ielement = numberOfElements - 1; ielement > 0; ielement --) {
7212 const Stackel element = pop;
7213 if (element->which != Stackel_STRING)
7214 Melder_throw (U"The tensor elements have to be of the same type, not ", element->whichText(), U" and a string.");
7215 if (ielement == iindex)
7216 result = element->_string.move(); // we can move it, because it's been popped off the stack, so we never return there
7217 }
7218 pushString (result.move());
7219 }
7220 }
7221 static void do_row_VEC () {
7222 /*
7223 result# = row# (mat##, rowNumber)
7224 */
7225 const Stackel rowNumber_ = pop, mat_ = pop;
7226 if (mat_->which == Stackel_NUMERIC_MATRIX && rowNumber_->which == Stackel_NUMBER) {
7227 const constMAT mat = mat_->numericMatrix;
7228 const integer rowNumber = Melder_iround (rowNumber_->number);
7229 Melder_require (rowNumber >= 1 && rowNumber <= mat.nrow,
7230 U"In the function “row#”, the row number should be between 1 and ", mat.nrow, U".");
7231 autoVEC result = copy_VEC (mat.row (rowNumber));
7232 pushNumericVector (result.move());
7233 } else {
7234 Melder_throw (U"The function “row#” requires a matrix and a row number, not ", mat_->whichText(), U" and ", rowNumber_->whichText(), U".");
7235 }
7236 }
7237 static void do_col_VEC () {
7238 /*
7239 result# = col# (mat##, colNumber)
7240 */
7241 const Stackel colNumber_ = pop, mat_ = pop;
7242 if (mat_->which == Stackel_NUMERIC_MATRIX && colNumber_->which == Stackel_NUMBER) {
7243 const constMAT mat = mat_->numericMatrix;
7244 const integer colNumber = Melder_iround (colNumber_->number);
7245 Melder_require (colNumber >= 1 && colNumber <= mat.ncol,
7246 U"In the function “col#”, the column number should be between 1 and ", mat.ncol, U".");
7247 autoVEC result = copy_VEC (mat.column (colNumber));
7248 pushNumericVector (result.move());
7249 } else {
7250 Melder_throw (U"The function “col#” requires a matrix and a column number, not ", mat_->whichText(), U" and ", colNumber_->whichText(), U".");
7251 }
7252 }
7253 static void do_inner () {
7254 /*
7255 result = inner (x#, y#)
7256 */
7257 const Stackel y = pop, x = pop;
7258 if (x->which == Stackel_NUMERIC_VECTOR && y->which == Stackel_NUMERIC_VECTOR) {
7259 pushNumber (NUMinner (x->numericVector, y->numericVector));
7260 } else {
7261 Melder_throw (U"The function “inner” requires two vectors, not ", x->whichText(), U" and ", y->whichText(), U".");
7262 }
7263 }
7264 static void do_correlation () {
7265 /*
7266 result = correlation (x#, y#)
7267 */
7268 const Stackel y = pop, x = pop;
7269 if (x->which == Stackel_NUMERIC_VECTOR && y->which == Stackel_NUMERIC_VECTOR) {
7270 pushNumber (NUMcorrelation (x->numericVector, y->numericVector));
7271 } else {
7272 Melder_throw (U"The function “correlation” requires two vectors, not ", x->whichText(), U" and ", y->whichText(), U".");
7273 }
7274 }
7275 static void do_outer_MAT () {
7276 /*
7277 result## = outer## (x#, y#)
7278 */
7279 const Stackel y = pop, x = pop;
7280 if (x->which == Stackel_NUMERIC_VECTOR && y->which == Stackel_NUMERIC_VECTOR) {
7281 autoMAT result = outer_MAT (x->numericVector, y->numericVector);
7282 pushNumericMatrix (result.move());
7283 } else {
7284 Melder_throw (U"The function “outer##” requires two vectors, not ", x->whichText(), U" and ", y->whichText(), U".");
7285 }
7286 }
7287 static void do_mul_VEC () {
7288 /*
7289 result# = mul# (x.., y..)
7290 */
7291 const Stackel y = pop, x = pop;
7292 if (x->which == Stackel_NUMERIC_VECTOR && y->which == Stackel_NUMERIC_MATRIX) {
7293 /*
7294 result# = mul# (x#, y##)
7295 */
7296 const integer xSize = x->numericVector.size, yNrow = y->numericMatrix.nrow;
7297 Melder_require (yNrow == xSize,
7298 U"In the function “mul#”, the dimension of the vector and the number of rows of the matrix should be equal, "
7299 U"not ", xSize, U" and ", yNrow
7300 );
7301 autoVEC result = mul_VEC (x->numericVector, y->numericMatrix);
7302 pushNumericVector (result.move());
7303 } else if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_VECTOR) {
7304 /*
7305 result# = mul# (x##, y#)
7306 */
7307 const integer xNcol = x->numericMatrix.ncol, ySize = y->numericVector.size;
7308 Melder_require (ySize == xNcol,
7309 U"In the function “mul#”, the number of columns of the matrix and the dimension of the vector should be equal, "
7310 U"not ", xNcol, U" and ", ySize, U"."
7311 );
7312 autoVEC result = mul_VEC (x->numericMatrix, y->numericVector);
7313 pushNumericVector (result.move());
7314 } else {
7315 Melder_throw (U"The function “mul#” requires a vector and a matrix, not ", x->whichText(), U" and ", y->whichText(), U".");
7316 }
7317 }
7318 static void do_mul_MAT () {
7319 /*
7320 result## = mul## (x.., y..)
7321 */
7322 const Stackel y = pop, x = pop;
7323 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7324 /*
7325 result# = mul## (x##, y##)
7326 */
7327 const integer xNcol = x->numericMatrix.ncol, yNrow = y->numericMatrix.nrow;
7328 Melder_require (yNrow == xNcol,
7329 U"In the function “mul##”, the number of columns of the first matrix and the number of rows of the second matrix should be equal, "
7330 U"not ", xNcol, U" and ", yNrow, U"."
7331 );
7332 autoMAT result = zero_MAT (x->numericMatrix.nrow, y->numericMatrix.ncol);
7333 _mul_allowAllocation_MAT_out (result.get(), x->numericMatrix, y->numericMatrix);
7334 pushNumericMatrix (result.move());
7335 } else {
7336 Melder_throw (U"The function “mul##” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7337 }
7338 }
7339 static void do_mul_metal_MAT () {
7340 /*
7341 result## = mul## (x.., y..)
7342 */
7343 const Stackel y = pop, x = pop;
7344 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7345 /*
7346 result# = mul## (x##, y##)
7347 */
7348 const integer xNcol = x->numericMatrix.ncol, yNrow = y->numericMatrix.nrow;
7349 Melder_require (yNrow == xNcol,
7350 U"In the function “mul##”, the number of columns of the first matrix and the number of rows of the second matrix should be equal, "
7351 U"not ", xNcol, U" and ", yNrow, U"."
7352 );
7353 autoMAT result = zero_MAT (x->numericMatrix.nrow, y->numericMatrix.ncol);
7354 MATmul_forceMetal_ (result.get(), x->numericMatrix, y->numericMatrix);
7355 pushNumericMatrix (result.move());
7356 } else {
7357 Melder_throw (U"The function “mul_metal##” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7358 }
7359 }
7360 static void do_mul_fast_MAT () {
7361 /*
7362 result## = mul_fast## (x.., y..)
7363 */
7364 const Stackel y = pop, x = pop;
7365 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7366 /*
7367 result# = mul_fast## (x##, y##)
7368 */
7369 const integer xNcol = x->numericMatrix.ncol, yNrow = y->numericMatrix.nrow;
7370 Melder_require (yNrow == xNcol,
7371 U"In the function “mul_fast##”, the number of columns of the first matrix and the number of rows of the second matrix should be equal, "
7372 U"not ", xNcol, U" and ", yNrow, U"."
7373 );
7374 autoMAT result = mul_fast_MAT (x->numericMatrix, y->numericMatrix);
7375 pushNumericMatrix (result.move());
7376 } else {
7377 Melder_throw (U"The function “mul_fast##” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7378 }
7379 }
7380 static void do_mul_tn_MAT () {
7381 /*
7382 result## = mul_tn## (x.., y..)
7383 */
7384 const Stackel y = pop, x = pop;
7385 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7386 /*
7387 result# = mul_tn## (x##, y##)
7388 */
7389 const integer xNrow = x->numericMatrix.nrow, yNrow = y->numericMatrix.nrow;
7390 Melder_require (yNrow == xNrow,
7391 U"In the function “mul_tn##”, the number of rows of the first matrix and the number of rows of the second matrix should be equal, "
7392 U"not ", xNrow, U" and ", yNrow, U"."
7393 );
7394 autoMAT result = mul_allowAllocation_MAT (x->numericMatrix.transpose(), y->numericMatrix);
7395 pushNumericMatrix (result.move());
7396 } else {
7397 Melder_throw (U"The function “mul_tn##” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7398 }
7399 }
7400 static void do_mul_nt_MAT () {
7401 /*
7402 result## = mul_nt## (x.., y..)
7403 */
7404 const Stackel y = pop, x = pop;
7405 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7406 /*
7407 result# = mul_nt## (x##, y##)
7408 */
7409 const integer xNcol = x->numericMatrix.ncol, yNcol = y->numericMatrix.ncol;
7410 Melder_require (yNcol == xNcol,
7411 U"In the function “mul_tn##”, the number of columns of the first matrix and the number of columns of the second matrix should be equal, "
7412 U"not ", xNcol, U" and ", yNcol, U"."
7413 );
7414 autoMAT result = mul_allowAllocation_MAT (x->numericMatrix, y->numericMatrix.transpose());
7415 pushNumericMatrix (result.move());
7416 } else {
7417 Melder_throw (U"The function “mul_nt##” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7418 }
7419 }
7420 static void do_mul_tt_MAT () {
7421 /*
7422 result## = mul_tt## (x.., y..)
7423 */
7424 const Stackel y = pop, x = pop;
7425 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7426 /*
7427 result# = mul_tt## (x##, y##)
7428 */
7429 const integer xNrow = x->numericMatrix.nrow, yNcol = y->numericMatrix.ncol;
7430 Melder_require (yNcol == xNrow,
7431 U"In the function “mul_tt##”, the number of rows of the first matrix and the number of columns of the second matrix should be equal, "
7432 U"not ", xNrow, U" and ", yNcol, U"."
7433 );
7434 autoMAT result = mul_allowAllocation_MAT (x->numericMatrix.transpose(), y->numericMatrix.transpose());
7435 pushNumericMatrix (result.move());
7436 } else {
7437 Melder_throw (U"The function “mul_tt##” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7438 }
7439 }
7440 static void do_transpose_MAT () {
7441 const Stackel x = topOfStack;
7442 if (x->which == Stackel_NUMERIC_MATRIX) {
7443 if (x->owned) {
7444 if (NUMisSquare (x->numericMatrix)) {
7445 /*@praat
7446 assert transpose## ({ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }) = { { 1, 4, 7 }, { 2, 5, 8 }, { 3, 6, 9 } }
7447 @*/
7448 transpose_mustBeSquare_MAT_inout (x->numericMatrix);
7449 } else {
7450 /*@praat
7451 assert transpose## ({ { 1, 2, 3 }, { 4, 5, 6 } }) = { { 1, 4 }, { 2, 5 }, { 3, 6 } }
7452 @*/
7453 autoMAT newMatrix = transpose_MAT (x->numericMatrix);
7454 x->reset();
7455 x->numericMatrix = newMatrix.releaseToAmbiguousOwner();
7456 }
7457 } else {
7458 /*@praat
7459 a## = { { 1, 2, 3 }, { 4, 5, 6 } }
7460 assert transpose## (a##) = { { 1, 4 }, { 2, 5 }, { 3, 6 } }
7461 assert transpose## (transpose## (a##)) = a##
7462 @*/
7463 x->numericMatrix = transpose_MAT (x->numericMatrix). releaseToAmbiguousOwner();
7464 x->owned = true;
7465 }
7466 } else {
7467 Melder_throw (U"The function “transpose##” requires a matrix, not ", x->whichText(), U".");
7468 }
7469 }
7470 static void do_rowSums_VEC () {
7471 const Stackel x = pop;
7472 if (x->which == Stackel_NUMERIC_MATRIX) {
7473 autoVEC result = rowSums_VEC (x->numericMatrix);
7474 pushNumericVector (result.move());
7475 } else {
7476 Melder_throw (U"The function “rowSums#” requires a matrix, not ", x->whichText(), U".");
7477 }
7478 }
7479 static void do_columnSums_VEC () {
7480 const Stackel x = pop;
7481 if (x->which == Stackel_NUMERIC_MATRIX) {
7482 /*@praat
7483 a## = { { 4, 7, -10 }, { 16, 0, 88 } }
7484 result# = columnSums# (a##)
7485 assert result# = { 20, 7, 78 }
7486 @*/
7487 autoVEC result = columnSums_VEC (x->numericMatrix);
7488 pushNumericVector (result.move());
7489 } else {
7490 Melder_throw (U"The function “columnSums#” requires a matrix, not ", x->whichText(), U".");
7491 }
7492 }
7493 static void do_repeat_VEC () {
7494 const Stackel n = pop, x = pop;
7495 if (x->which == Stackel_NUMERIC_VECTOR && n->which == Stackel_NUMBER) {
7496 const integer n_old = x->numericVector.size;
7497 const integer times = Melder_iround (n->number);
7498 autoVEC result = raw_VEC (n_old * times);
7499 for (integer i = 1; i <= times; i ++)
7500 for (integer j = 1; j <= n_old; j ++)
7501 result [(i - 1) * n_old + j] = x->numericVector [j];
7502 pushNumericVector (result.move());
7503 } else {
7504 Melder_throw (U"The function “repeat#” requires a vector and a number, not ", x->whichText(), U" and ", n->whichText(), U".");
7505 }
7506 }
7507 static void do_rowInners_VEC () {
7508 const Stackel y = pop, x = pop;
7509 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7510 Melder_require (x->numericMatrix.nrow == y->numericMatrix.nrow && x->numericMatrix.ncol == y->numericMatrix.ncol,
7511 U"In the function rowInners#, the two matrices should have the same shape, not ",
7512 x->numericMatrix.nrow, U"x", x->numericMatrix.ncol, U" and ", y->numericMatrix.nrow, U"x", y->numericMatrix.ncol
7513 );
7514 pushNumericVector (rowInners_VEC (x->numericMatrix, y->numericMatrix));
7515 } else {
7516 Melder_throw (U"The function “rowInners#” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7517 }
7518 }
7519 static void do_solve_VEC () {
7520 const Stackel y = pop, x = pop;
7521 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_VECTOR) {
7522 Melder_require (x->numericMatrix.nrow == y->numericVector.size,
7523 U"In the function “solve#”, the number of rows of the matrix and the dimension of the vector should be equal, not ",
7524 x->numericMatrix.nrow, U" and ", y->numericVector.size
7525 );
7526 pushNumericVector (solve_VEC (x->numericMatrix, y->numericVector, NUMeps * y->numericVector.size));
7527 } else {
7528 Melder_throw (U"The function “solve#” requires a matrix and a vector, not ", x->whichText(), U" and ", y->whichText(), U".");
7529 }
7530 }
7531
7532 static void do_solveWeaklyConstrained_VEC () {
7533 const Stackel delta = pop, alpha = pop, y = pop, x = pop;
7534 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_VECTOR && alpha->which == Stackel_NUMBER && delta->which == Stackel_NUMBER) {
7535 Melder_require (x->numericMatrix.nrow == y->numericVector.size,
7536 U"In the function “solveWeaklyConstrained#”, the number of rows of the matrix and the dimension of the vector should be equal, not ",
7537 x->numericMatrix.nrow, U" and ", y->numericVector.size
7538 );
7539 Melder_require (alpha->number >= 0.0,
7540 U"Argument 3, the weight coefficient of the penalty function should not be negative.");
7541 Melder_require (delta->number >= 0.0,
7542 U"Argument 4, the squared length of the solution vector should not be negative.");
7543 pushNumericVector (solveWeaklyConstrainedLinearRegression_VEC (x->numericMatrix, y->numericVector, alpha->number, delta->number));
7544 } else {
7545 Melder_throw (U"The function “solveWeaklyConstrained#” requires a matrix, a vector, and two numbers not ", x->whichText(), U", ",
7546 y->whichText(), U", ", alpha->whichText(), U" and ", delta->whichText(), U".");
7547 }
7548 }
7549
7550 static void do_solve_MAT () {
7551 const Stackel y = pop, x = pop;
7552 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7553 Melder_require (x->numericMatrix.nrow == y->numericMatrix.nrow,
7554 U"In the function “solve##”, the two matrices should have the same number of rows, not ",
7555 x->numericMatrix.nrow, U" and ", y->numericMatrix.nrow);
7556 pushNumericMatrix (solve_MAT (x->numericMatrix, y->numericMatrix, NUMeps * x->numericMatrix.nrow * x->numericMatrix.ncol));
7557 } else {
7558 Melder_throw (U"The function “solve##” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7559 }
7560 }
7561
7562 static void do_solveSparse_VEC () {
7563 const Stackel n = pop;
7564 Melder_assert (n -> which == Stackel_NUMBER);
7565 if (n -> number == 6) {
7566 const Stackel info = pop, tol = pop, niter = pop, nonzeros = pop, y = pop, dict = pop;
7567 if (dict->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_VECTOR &&
7568 nonzeros->which == Stackel_NUMBER && niter->which == Stackel_NUMBER &&
7569 tol->which == Stackel_NUMBER && info->which == Stackel_NUMBER) {
7570 const MAT d = dict->numericMatrix;
7571 Melder_require (d.ncol > d.nrow,
7572 U"The number of columns should be larger than the number of rows (sparse!).");
7573 const VEC yy = y->numericVector;
7574 Melder_require (yy.size == d.nrow,
7575 U"The number of rows in the matrix should equal the size of the vector.");
7576 const integer numberOfNonzeros = Melder_iround (nonzeros->number);
7577 const integer maximumNumberOfIterations = Melder_iround (niter ->number);
7578 const integer infoLevel = Melder_iround (info->number);
7579 const double tolerance = tol->number;
7580 pushNumericVector (solveSparse_IHT_VEC (d, yy, numberOfNonzeros, maximumNumberOfIterations, tolerance, infoLevel));
7581 } else {
7582 Melder_throw (U"The function “solveSparse#” requires a matrix, a vector, and four numbers, not ", dict->whichText(), U", ", y->whichText(), U", ", nonzeros->whichText(), U", ",
7583 niter->whichText(), U", ", tol->whichText(), U" and ", info->whichText());
7584 }
7585 } else if (n -> number == 7) {
7586 const Stackel info = pop, tol = pop, niter = pop, nonzeros = pop, xstart = pop, y = pop, dict = pop;
7587 if (dict->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_VECTOR &&
7588 xstart->which == Stackel_NUMERIC_VECTOR &&
7589 nonzeros->which == Stackel_NUMBER && niter->which == Stackel_NUMBER &&
7590 tol->which == Stackel_NUMBER && info->which == Stackel_NUMBER)
7591 {
7592 const constMAT d = dict->numericMatrix;
7593 Melder_require (d.ncol > d.nrow,
7594 U"The number of columns should be larger than the number of rows (sparse!).");
7595 const constVEC yy = y->numericVector;
7596 const VEC x = xstart->numericVector;
7597 Melder_require (yy.size == d.nrow,
7598 U"The number of rows in the matrix should equal the size of the vector.");
7599 Melder_require (x.size == d.ncol,
7600 U"The number of columns in the matrix should equal the size of start vector.");
7601 autoVEC xs = copy_VEC (x);
7602 const integer numberOfNonzeros = Melder_iround (nonzeros->number);
7603 const integer maximumNumberOfIterations = Melder_iround (niter ->number);
7604 const integer infoLevel = Melder_iround (info->number);
7605 const double tolerance = tol->number;
7606 VECsolveSparse_IHT (xs.all(), d, yy, numberOfNonzeros, maximumNumberOfIterations, tolerance, infoLevel);
7607 pushNumericVector (xs.move());
7608 } else {
7609 Melder_throw (U"The function “solveSparse#” requires a matrix, a vector, and four numbers, not ", dict->whichText(), U", ", y->whichText(), U", ", nonzeros->whichText(), U", ",
7610 niter->whichText(), U", ", tol->whichText(), U" and ", info->whichText());
7611 }
7612 } else {
7613 Melder_throw (U"The function “solveSparse#” requires six or seven arguments.");
7614 }
7615 }
7616
7617 static void do_solveNonnegative_VEC () {
7618 const Stackel n = pop;
7619 Melder_assert (n -> which == Stackel_NUMBER);
7620 if (n -> number == 6) {
7621 const Stackel info = pop, tol = pop, itermax = pop, xstart = pop, y = pop, m = pop;
7622 if (m->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_VECTOR &&
7623 xstart->which == Stackel_NUMERIC_VECTOR && itermax->which == Stackel_NUMBER &&
7624 tol->which == Stackel_NUMBER && info->which == Stackel_NUMBER)
7625 {
7626 const double tolerance = tol->number;
7627 const integer maximumNumberOfIterations = Melder_iround (itermax->number);
7628 const integer infoLevel = Melder_iround (info->number);
7629 const constMAT a = m->numericMatrix;
7630 const VEC yy = y->numericVector;
7631 Melder_require (a.nrow == yy.size,
7632 U"The number of rows in the matrix should equal the size of the vector.");
7633 autoVEC x = copy_VEC (xstart->numericVector);
7634 Melder_require (x.size == a.ncol,
7635 U"The size of start vector should equal the number of columns in the matrix.");
7636 VECsolveNonnegativeLeastSquaresRegression (x.get(), a, yy, maximumNumberOfIterations, tolerance, infoLevel);
7637 pushNumericVector (x.move());
7638 } else {
7639 Melder_throw (U"The function “solveNonnegative#” requires a matrix, a vector, a vector and three numbers, not ", m->whichText(), U", ", y->whichText(), U", ", xstart->whichText(), U", ",
7640 itermax->whichText(), U", ", tol->whichText(), U" and ", info->whichText());
7641 }
7642 } else if (n -> number == 5) {
7643 const Stackel info = pop, tol = pop, itermax = pop, y = pop, m = pop;
7644 if (m->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_VECTOR &&
7645 itermax->which == Stackel_NUMBER && tol->which == Stackel_NUMBER && info->which == Stackel_NUMBER)
7646 {
7647 const double tolerance = tol->number;
7648 const integer maximumNumberOfIterations = Melder_iround (itermax->number);
7649 const integer infoLevel = Melder_iround (info->number);
7650 const constMAT a = m->numericMatrix;
7651 const VEC yy = y->numericVector;
7652 Melder_require (a.nrow == yy.size,
7653 U"The number of rows in the matrix should equal the size of the vector.");
7654 pushNumericVector (solveNonnegativeLeastSquaresRegression_VEC (a, yy, maximumNumberOfIterations, tolerance, infoLevel));
7655 } else {
7656 Melder_throw (U"The function “solveNonnegative#” requires a matrix, a vector, and three numbers, not ", m->whichText(), U", ", y->whichText(), U", ", itermax->whichText(), U", ", tol->whichText(), U" and ", info->whichText());
7657 }
7658 } else {
7659 Melder_throw (U"The function “solveNonnegative#” requires five or six arguments.");
7660 }
7661 }
7662
7663 static void do_askForTrust () {
7664 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7665 U"The function “askForTrust” is not available inside manuals.");
7666 const Stackel n = pop;
7667 Melder_require (n->number == 0,
7668 U"The function “askForTrust” should have no arguments.");
7669 const Editor optionalTrustWindowOwningEditor = theInterpreter -> optionalDynamicEnvironmentEditor();
7670 const GuiWindow parentShell = ( optionalTrustWindowOwningEditor ? optionalTrustWindowOwningEditor -> windowForm : theCurrentPraatApplication -> topShell );
7671 const bool isAlreadyTrusted = theInterpreter -> scriptReference && theInterpreter -> scriptReference -> trusted;
7672 if (! isAlreadyTrusted) {
7673 conststring32 message [1+5] = { };
7674 if (theInterpreter -> scriptReference) {
7675 message [1] = U"The script";
7676 message [2] = Melder_cat (U"“", theInterpreter -> scriptReference -> string.get(), U"”");
7677 } else if (theInterpreter -> notebookReference) {
7678 message [1] = U"The notebook";
7679 message [2] = Melder_cat (U"“", theInterpreter -> notebookReference -> string.get(), U"”");
7680 } else
7681 message [1] = U"Your untitled script or notebook";
7682 message [3] = U"requests permission to control your computer (e.g. it may want to overwrite files,\n"
7683 "delete folders, run system commands, and/or access the internet).";
7684 message [4] = U"Allow this only if you fully trust the intentions and skills of the author(s),\n"
7685 "AND the intentions and skills of the author(s) of the script(s) called by this script directly or indirectly.";
7686 conststring32 option1 = U"CANCEL\n(because I don’t completely trust the authors’ skills and/or intentions)";
7687 conststring32 option2 =
7688 theInterpreter -> scriptReference ?
7689 U"Yes, I allow this script to CONTROL MY COMPUTER, because I fully trust the skills and\n"
7690 "intentions of its authors AND of those of the authors of any scripts called by it directly or indirectly."
7691 : theInterpreter -> notebookReference ?
7692 U"Yes, I allow this notebook to CONTROL MY COMPUTER, because I fully trust the skills and\n"
7693 "intentions of its authors AND of those of the authors of any scripts called by it directly or indirectly."
7694 :
7695 U"Yes, I allow this script or notebook to CONTROL MY COMPUTER, because I fully trust the skills and\n"
7696 "intentions of its authors AND of those of the authors of any scripts called by it directly or indirectly.";
7697 const bool trusted = GuiTrust_get (parentShell, optionalTrustWindowOwningEditor,
7698 message [1], message [2], message [3], message [4], message [5],
7699 option1, option2, nullptr, nullptr, nullptr, theInterpreter
7700 );
7701 if (trusted) {
7702 if (theInterpreter -> scriptReference)
7703 theInterpreter -> scriptReference -> trusted = true;
7704 else if (theInterpreter -> notebookReference)
7705 theInterpreter -> notebookReference -> trusted = true;
7706 }
7707 }
7708 pushNumber (1);
7709 }
7710
7711 static void do_beginPause () {
7712 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7713 U"The function “beginPause” is not available inside manuals.");
7714 const Stackel n = pop;
7715 if (n->number == 1) {
7716 const Stackel title = pop;
7717 if (title->which == Stackel_STRING) {
7718 const Editor optionalPauseWindowOwningEditor = theInterpreter -> optionalDynamicEnvironmentEditor();
7719 const GuiWindow parentShell = ( optionalPauseWindowOwningEditor ? optionalPauseWindowOwningEditor -> windowForm : theCurrentPraatApplication -> topShell );
7720 UiPause_begin (parentShell, optionalPauseWindowOwningEditor, title->getString(), theInterpreter);
7721 } else {
7722 Melder_throw (U"The function “beginPause” requires a string (the title), not ", title->whichText(), U".");
7723 }
7724 } else {
7725 Melder_throw (U"The function “beginPause” requires 1 argument (a title), not ", n->number, U".");
7726 }
7727 pushNumber (1);
7728 }
7729 static void do_real () {
7730 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7731 U"The function “real” is not available inside manuals.");
7732 const Stackel n = pop;
7733 Melder_require (n->number == 2,
7734 U"The function “real” requires 2 arguments (a label text and a default value), not ", n->number, U".");
7735 const Stackel defaultValue = pop;
7736 conststring32 defaultString = nullptr;
7737 if (defaultValue->which == Stackel_STRING)
7738 defaultString = defaultValue->getString();
7739 else if (defaultValue->which == Stackel_NUMBER)
7740 defaultString = Melder_double (defaultValue->number);
7741 else
7742 Melder_throw (U"The second argument of “real” (the default value) should be a string or a number, not ", defaultValue->whichText(), U".");
7743 const Stackel label = pop;
7744 Melder_require (label->which == Stackel_STRING,
7745 U"The first argument of “real” (the label text) should be a string, not ", label->whichText(), U".");
7746 UiPause_real (label->getString(), defaultString);
7747 pushNumber (1);
7748 }
7749 static void do_positive () {
7750 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7751 U"The function “positive” is not available inside manuals.");
7752 const Stackel n = pop;
7753 Melder_require (n->number == 2,
7754 U"The function “positive” requires 2 arguments (a label text and a default value), not ", n->number, U".");
7755 const Stackel defaultValue = pop;
7756 conststring32 defaultString = nullptr;
7757 if (defaultValue->which == Stackel_STRING) {
7758 defaultString = defaultValue->getString();
7759 } else if (defaultValue->which == Stackel_NUMBER) {
7760 defaultString = Melder_double (defaultValue->number);
7761 } else {
7762 Melder_throw (U"The second argument of “positive” (the default value) should be a string or a number, not ", defaultValue->whichText(), U".");
7763 }
7764 const Stackel label = pop;
7765 Melder_require (label->which == Stackel_STRING,
7766 U"The first argument of “positive” (the label text) should be a string, not ", label->whichText(), U".");
7767 UiPause_positive (label->getString(), defaultString);
7768 pushNumber (1);
7769 }
7770 static void do_integer () {
7771 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7772 U"The function “integer” is not available inside manuals.");
7773 const Stackel n = pop;
7774 Melder_require (n->number == 2,
7775 U"The function “integer” requires 2 arguments (a label text and a default value), not ", n->number, U".");
7776 const Stackel defaultValue = pop;
7777 conststring32 defaultString = nullptr;
7778 if (defaultValue->which == Stackel_STRING) {
7779 defaultString = defaultValue->getString();
7780 } else if (defaultValue->which == Stackel_NUMBER) {
7781 defaultString = Melder_double (defaultValue->number);
7782 } else {
7783 Melder_throw (U"The second argument of “integer” (the default value) should be a string or a number, not ", defaultValue->whichText(), U".");
7784 }
7785 const Stackel label = pop;
7786 Melder_require (label->which == Stackel_STRING,
7787 U"The first argument of “integer” (the label text) should be a string, not ", label->whichText(), U".");
7788 UiPause_integer (label->getString(), defaultString);
7789 pushNumber (1);
7790 }
7791 static void do_natural () {
7792 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7793 U"The function “natural” is not available inside manuals.");
7794 const Stackel n = pop;
7795 Melder_require (n->number == 2,
7796 U"The function “natural” requires 2 arguments (a label text and a default value), not ", n->number, U".");
7797 const Stackel defaultValue = pop;
7798 conststring32 defaultString = nullptr;
7799 if (defaultValue->which == Stackel_STRING) {
7800 defaultString = defaultValue->getString();
7801 } else if (defaultValue->which == Stackel_NUMBER) {
7802 defaultString = Melder_double (defaultValue->number);
7803 } else {
7804 Melder_throw (U"The second argument of “natural” (the default value) should be a string or a number, not ", defaultValue->whichText(), U".");
7805 }
7806 const Stackel label = pop;
7807 Melder_require (label->which == Stackel_STRING,
7808 U"The first argument of “natural” (the label text) should be a string, not ", label->whichText(), U".");
7809 UiPause_natural (label->getString(), defaultString);
7810 pushNumber (1);
7811 }
7812 static void do_word () {
7813 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7814 U"The function “word” is not available inside manuals.");
7815 const Stackel n = pop;
7816 Melder_require (n->number == 2,
7817 U"The function “word” requires 2 arguments (a label text and a default value), not ", n->number, U".");
7818 const Stackel defaultValue = pop;
7819 Melder_require (defaultValue->which == Stackel_STRING,
7820 U"The second argument of “word” (the default value) should be a string, not ", defaultValue->whichText(), U".");
7821 const Stackel label = pop;
7822 Melder_require (label->which == Stackel_STRING,
7823 U"The first argument of “word” (the label text) should be a string, not ", label->whichText(), U".");
7824 UiPause_word (label->getString(), defaultValue->getString());
7825 pushNumber (1);
7826 }
7827 static void do_sentence () {
7828 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7829 U"The function “sentence” is not available inside manuals.");
7830 const Stackel n = pop;
7831 Melder_require (n->number == 2,
7832 U"The function “sentence” requires 2 arguments (a label text and a default value), not ", n->number, U".");
7833 const Stackel defaultValue = pop;
7834 Melder_require (defaultValue->which == Stackel_STRING,
7835 U"The second argument of “sentence” (the default value) should be a string, not ", defaultValue->whichText(), U".");
7836 const Stackel label = pop;
7837 Melder_require (label->which == Stackel_STRING,
7838 U"The first argument of “sentence” (the label text) should be a string, not ", label->whichText(), U".");
7839 UiPause_sentence (label->getString(), defaultValue->getString());
7840 pushNumber (1);
7841 }
7842 static void do_text () {
7843 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7844 U"The function “text” is not available inside manuals.");
7845 const Stackel n = pop;
7846 Melder_require (n->number >= 2 && n->number <= 3,
7847 U"The function “text” requires 2 or 3 arguments (an optional number of lines, a label text, and a default value), not ", n->number, U".");
7848 integer numberOfLines = 1; // the default
7849 if (n->number == 3) {
7850 /*
7851 For compatibility, the number of lines might be at the end.
7852 */
7853 const Stackel arg3 = pop, arg2 = pop, arg1 = pop;
7854 if (arg1->which == Stackel_STRING && arg2->which == Stackel_STRING && arg3->which == Stackel_NUMBER) {
7855 UiPause_text (arg1->getString(), arg2->getString(), Melder_iround (arg3->number));
7856 pushNumber (1);
7857 return;
7858 }
7859 const Stackel defaultValue = arg3;
7860 Melder_require (defaultValue->which == Stackel_STRING,
7861 U"The third argument of “text” (the default value) should be a string, not ", defaultValue->whichText(), U".");
7862 const Stackel label = arg2;
7863 Melder_require (label->which == Stackel_STRING,
7864 U"The second argument of “text” (the label) should be a string, not ", label->whichText(), U".");
7865 const Stackel _numberOfLines = arg1;
7866 Melder_require (_numberOfLines->which == Stackel_NUMBER,
7867 U"The first argument of “text” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
7868 numberOfLines = Melder_iround (_numberOfLines->number);
7869 UiPause_text (label->getString(), defaultValue->getString(), numberOfLines);
7870 pushNumber (1);
7871 return;
7872 }
7873 const Stackel defaultValue = pop;
7874 Melder_require (defaultValue->which == Stackel_STRING,
7875 U"The second argument of “text” (the default value) should be a string, not ", defaultValue->whichText(), U".");
7876 const Stackel label = pop;
7877 Melder_require (label->which == Stackel_STRING,
7878 U"The first argument of “text” (the label text) should be a string, not ", label->whichText(), U".");
7879 UiPause_text (label->getString(), defaultValue->getString(), numberOfLines);
7880 pushNumber (1);
7881 }
7882 static void do_infile () {
7883 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7884 U"The function “infile” is not available inside manuals.");
7885 const Stackel n = pop;
7886 Melder_require (n->number >= 2 && n->number <= 3,
7887 U"The function “infile” requires 2 or 3 arguments (an optional number of lines, a label text, and a default value), not ", n->number, U".");
7888 integer numberOfLines = 3; // the default
7889 const Stackel defaultValue = pop;
7890 Melder_require (defaultValue->which == Stackel_STRING,
7891 U"The last argument of “infile” (the default value) should be a string, not ", defaultValue->whichText(), U".");
7892 const Stackel label = pop;
7893 Melder_require (label->which == Stackel_STRING,
7894 U"The penultimate argument of “infile” (the label text) should be a string, not ", label->whichText(), U".");
7895 if (n->number == 3) {
7896 const Stackel _numberOfLines = pop;
7897 Melder_require (_numberOfLines->which == Stackel_NUMBER,
7898 U"The first argument of “infile” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
7899 numberOfLines = Melder_iround (_numberOfLines->number);
7900 }
7901 UiPause_infile (label->getString(), defaultValue->getString(), numberOfLines);
7902 pushNumber (1);
7903 }
7904 static void do_outfile () {
7905 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7906 U"The function “outfile” is not available inside manuals.");
7907 const Stackel n = pop;
7908 Melder_require (n->number >= 2 && n->number <= 3,
7909 U"The function “outfile” requires 2 or 3 arguments (an optional number of lines, a label text, and a default value), not ", n->number, U".");
7910 integer numberOfLines = 3; // the default
7911 const Stackel defaultValue = pop;
7912 Melder_require (defaultValue->which == Stackel_STRING,
7913 U"The last argument of “outfile” (the default value) should be a string, not ", defaultValue->whichText(), U".");
7914 const Stackel label = pop;
7915 Melder_require (label->which == Stackel_STRING,
7916 U"The penultimate argument of “outfile” (the label text) should be a string, not ", label->whichText(), U".");
7917 if (n->number == 3) {
7918 const Stackel _numberOfLines = pop;
7919 Melder_require (_numberOfLines->which == Stackel_NUMBER,
7920 U"The first argument of “outfile” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
7921 numberOfLines = Melder_iround (_numberOfLines->number);
7922 }
7923 UiPause_outfile (label->getString(), defaultValue->getString(), numberOfLines);
7924 pushNumber (1);
7925 }
7926 static void do_folder () {
7927 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7928 U"The function “folder” is not available inside manuals.");
7929 const Stackel n = pop;
7930 Melder_require (n->number >= 2 && n->number <= 3,
7931 U"The function “folder” requires 2 or 3 arguments (an optional number of lines, a label text, and a default value), not ", n->number, U".");
7932 integer numberOfLines = 3; // the default
7933 const Stackel defaultValue = pop;
7934 Melder_require (defaultValue->which == Stackel_STRING,
7935 U"The last argument of “folder” (the default value) should be a string, not ", defaultValue->whichText(), U".");
7936 const Stackel label = pop;
7937 Melder_require (label->which == Stackel_STRING,
7938 U"The penultimate argument of “folder” (the label text) should be a string, not ", label->whichText(), U".");
7939 if (n->number == 3) {
7940 const Stackel _numberOfLines = pop;
7941 Melder_require (_numberOfLines->which == Stackel_NUMBER,
7942 U"The first argument of “folder” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
7943 numberOfLines = Melder_iround (_numberOfLines->number);
7944 }
7945 UiPause_folder (label->getString(), defaultValue->getString(), numberOfLines);
7946 pushNumber (1);
7947 }
7948 static void do_realvector () {
7949 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7950 U"The function “realvector” is not available inside manuals.");
7951 const Stackel n = pop;
7952 Melder_require (n->number >= 3 && n->number <= 4,
7953 U"The function “realvector” requires 3 or 4 arguments (an optional number of lines, a label text, a format, and a default value), not ", n->number, U".");
7954 integer numberOfLines = 7; // the default
7955 const Stackel defaultValue = pop;
7956 conststring32 defaultString;
7957 if (defaultValue->which == Stackel_STRING)
7958 defaultString = defaultValue->getString();
7959 else if (defaultValue->which == Stackel_NUMERIC_VECTOR)
7960 defaultString = Melder_VEC (defaultValue->numericVector, true);
7961 else
7962 Melder_throw (U"The last argument of “realvector” (the default value) should be a string or a numeric vector, not ", defaultValue->whichText(), U".");
7963 const Stackel _format = pop;
7964 Melder_require (_format->which == Stackel_STRING,
7965 U"The penultimate argument of “realvector” (the format) should be a string, not ", _format->whichText(), U".");
7966 kUi_realVectorFormat format = kUi_realVectorFormat_getValue (_format->getString());
7967 Melder_require (format != kUi_realVectorFormat::UNDEFINED,
7968 U"The format should be “(whitespace-separated)” or “(formula)”, not “", _format->getString(), U"”.");
7969 const Stackel label = pop;
7970 Melder_require (label->which == Stackel_STRING,
7971 U"The antepenultimate argument of “realvector” (the label text) should be a string, not ", label->whichText(), U".");
7972 if (n->number == 4) {
7973 const Stackel _numberOfLines = pop;
7974 Melder_require (_numberOfLines->which == Stackel_NUMBER,
7975 U"The first argument of “realvector” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
7976 numberOfLines = Melder_iround (_numberOfLines->number);
7977 }
7978 UiPause_realvector (label->getString(), format, defaultString, numberOfLines);
7979 pushNumber (1);
7980 }
7981 static void do_positivevector () {
7982 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7983 U"The function “positivevector” is not available inside manuals.");
7984 const Stackel n = pop;
7985 Melder_require (n->number >= 3 && n->number <= 4,
7986 U"The function “positivevector” requires 3 or 4 arguments (an optional number of lines, a label text, a format, and a default value), not ", n->number, U".");
7987 integer numberOfLines = 7; // the default
7988 const Stackel defaultValue = pop;
7989 conststring32 defaultString;
7990 if (defaultValue->which == Stackel_STRING)
7991 defaultString = defaultValue->getString();
7992 else if (defaultValue->which == Stackel_NUMERIC_VECTOR)
7993 defaultString = Melder_VEC (defaultValue->numericVector, true);
7994 else
7995 Melder_throw (U"The last argument of “positivevector” (the default value) should be a string or a numeric vector, not ", defaultValue->whichText(), U".");
7996 const Stackel _format = pop;
7997 Melder_require (_format->which == Stackel_STRING,
7998 U"The penultimate argument of “positivevector” (the format) should be a string, not ", _format->whichText(), U".");
7999 kUi_realVectorFormat format = kUi_realVectorFormat_getValue (_format->getString());
8000 Melder_require (format != kUi_realVectorFormat::UNDEFINED,
8001 U"The format should be “(whitespace-separated)” or “(formula)”, not “", _format->getString(), U"”.");
8002 const Stackel label = pop;
8003 Melder_require (label->which == Stackel_STRING,
8004 U"The antepenultimate argument of “positivevector” (the label text) should be a string, not ", label->whichText(), U".");
8005 if (n->number == 4) {
8006 const Stackel _numberOfLines = pop;
8007 Melder_require (_numberOfLines->which == Stackel_NUMBER,
8008 U"The first argument of “positivevector” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
8009 numberOfLines = Melder_iround (_numberOfLines->number);
8010 }
8011 UiPause_positivevector (label->getString(), format, defaultString, numberOfLines);
8012 pushNumber (1);
8013 }
8014 static void do_integervector () {
8015 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8016 U"The function “integervector” is not available inside manuals.");
8017 const Stackel n = pop;
8018 Melder_require (n->number >= 3 && n->number <= 4,
8019 U"The function “integervector” requires 3 or 4 arguments (an optional number of lines, a label text, a format, and a default value), not ", n->number, U".");
8020 integer numberOfLines = 7; // the default
8021 const Stackel defaultValue = pop;
8022 conststring32 defaultString;
8023 if (defaultValue->which == Stackel_STRING)
8024 defaultString = defaultValue->getString();
8025 else if (defaultValue->which == Stackel_NUMERIC_VECTOR)
8026 defaultString = Melder_VEC (defaultValue->numericVector, true);
8027 else
8028 Melder_throw (U"The last argument of “integervector” (the default value) should be a string or a numeric vector, not ", defaultValue->whichText(), U".");
8029 const Stackel _format = pop;
8030 Melder_require (_format->which == Stackel_STRING,
8031 U"The penultimate argument of “integervector” (the format) should be a string, not ", _format->whichText(), U".");
8032 kUi_integerVectorFormat format = kUi_integerVectorFormat_getValue (_format->getString());
8033 Melder_require (format != kUi_integerVectorFormat::UNDEFINED,
8034 U"The format should be “(whitespace-separated)”, “(ranges)”, or “(formula)”, not “", _format->getString(), U"”.");
8035 const Stackel label = pop;
8036 Melder_require (label->which == Stackel_STRING,
8037 U"The antepenultimate argument of “integervector” (the label text) should be a string, not ", label->whichText(), U".");
8038 if (n->number == 4) {
8039 const Stackel _numberOfLines = pop;
8040 Melder_require (_numberOfLines->which == Stackel_NUMBER,
8041 U"The first argument of “integervector” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
8042 numberOfLines = Melder_iround (_numberOfLines->number);
8043 }
8044 UiPause_integervector (label->getString(), format, defaultString, numberOfLines);
8045 pushNumber (1);
8046 }
8047 static void do_naturalvector () {
8048 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8049 U"The function “naturalvector” is not available inside manuals.");
8050 const Stackel n = pop;
8051 Melder_require (n->number >= 3 && n->number <= 4,
8052 U"The function “naturalvector” requires 3 or 4 arguments (an optional number of lines, a label text, a format, and a default value), not ", n->number, U".");
8053 integer numberOfLines = 7; // the default
8054 const Stackel defaultValue = pop;
8055 conststring32 defaultString;
8056 if (defaultValue->which == Stackel_STRING)
8057 defaultString = defaultValue->getString();
8058 else if (defaultValue->which == Stackel_NUMERIC_VECTOR)
8059 defaultString = Melder_VEC (defaultValue->numericVector, true);
8060 else
8061 Melder_throw (U"The last argument of “naturalector” (the default value) should be a string or a numeric vector, not ", defaultValue->whichText(), U".");
8062 const Stackel _format = pop;
8063 Melder_require (_format->which == Stackel_STRING,
8064 U"The penultimate argument of “naturalvector” (the format) should be a string, not ", _format->whichText(), U".");
8065 kUi_integerVectorFormat format = kUi_integerVectorFormat_getValue (_format->getString());
8066 Melder_require (format != kUi_integerVectorFormat::UNDEFINED,
8067 U"The format should be “(whitespace-separated)”, “(ranges)”, or “(formula)”, not “", _format->getString(), U"”.");
8068 const Stackel label = pop;
8069 Melder_require (label->which == Stackel_STRING,
8070 U"The antepenultimate argument of “naturalvector” (the label text) should be a string, not ", label->whichText(), U".");
8071 if (n->number == 4) {
8072 const Stackel _numberOfLines = pop;
8073 Melder_require (_numberOfLines->which == Stackel_NUMBER,
8074 U"The first argument of “naturalvector” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
8075 numberOfLines = Melder_iround (_numberOfLines->number);
8076 }
8077 UiPause_naturalvector (label->getString(), format, defaultString, numberOfLines);
8078 pushNumber (1);
8079 }
8080 static void do_boolean () {
8081 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8082 U"The function “boolean” is not available inside manuals.");
8083 const Stackel n = pop;
8084 Melder_require (n->number == 2,
8085 U"The function “boolean” requires 2 arguments (a label text and a default value), not ", n->number, U".");
8086 const Stackel defaultValue = pop;
8087 double defaultNumber = undefined;
8088 if (defaultValue->which == Stackel_STRING) {
8089 conststring32 defaultString = defaultValue->getString();
8090 if (
8091 str32equ (defaultString, U"on") || str32equ (defaultString, U"yes") ||
8092 str32equ (defaultString, U"ON") || str32equ (defaultString, U"YES") ||
8093 str32equ (defaultString, U"On") || str32equ (defaultString, U"Yes")
8094 )
8095 defaultNumber = 1;
8096 else if (
8097 str32equ (defaultString, U"off") || str32equ (defaultString, U"no") ||
8098 str32equ (defaultString, U"OFF") || str32equ (defaultString, U"NO") ||
8099 str32equ (defaultString, U"Off") || str32equ (defaultString, U"No")
8100 )
8101 defaultNumber = 0;
8102 else
8103 Melder_throw (U"If the second argument of “boolean” is a string, it can only be "
8104 "“yes”, “no”, “on”, or “off”, not “", defaultString, U"”.");
8105 } else if (defaultValue->which == Stackel_NUMBER) {
8106 defaultNumber = defaultValue->number;
8107 } else {
8108 Melder_throw (U"The second argument of “boolean” (the default value) should be a number (0 or 1) "
8109 "or a string (“yes”, “no”, “on”, “off”), not ", defaultValue->whichText(), U".");
8110 }
8111 const Stackel label = pop;
8112 Melder_require (label->which == Stackel_STRING,
8113 U"The first argument of “boolean” (the label text) should be a string, not ", label->whichText(), U".");
8114 UiPause_boolean (label->getString(), defaultNumber != 0.0);
8115 pushNumber (1);
8116 }
8117 static void do_choice () {
8118 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8119 U"The function “choice” is not available inside manuals.");
8120 const Stackel n = pop;
8121 Melder_require (n->number == 2,
8122 U"The function “choice” requires 2 arguments (a label text and a default value), not ", n->number, U".");
8123 const Stackel defaultValue = pop;
8124 Melder_require (defaultValue->which == Stackel_NUMBER,
8125 U"The second argument of “choice” (the default value) should be a whole number, not ", defaultValue->whichText(), U".");
8126 const Stackel label = pop;
8127 Melder_require (label->which == Stackel_STRING,
8128 U"The first argument of “choice” (the label text) should be a string, not ", label->whichText(), U".");
8129 UiPause_choice (label->getString(), Melder_iround (defaultValue->number));
8130 pushNumber (1);
8131 }
8132 static void do_optionmenu () {
8133 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8134 U"The function “optionmenu” is not available inside manuals.");
8135 const Stackel n = pop;
8136 Melder_require (n->number == 2,
8137 U"The function “optionmenu” requires 2 arguments (a label text and a default value), not ", n->number, U".");
8138 const Stackel defaultValue = pop;
8139 Melder_require (defaultValue->which == Stackel_NUMBER,
8140 U"The second argument of “optionmenu” (the default value) should be a whole number, not ", defaultValue->whichText(), U".");
8141 const Stackel label = pop;
8142 Melder_require (label->which == Stackel_STRING,
8143 U"The first argument of “optionmenu” (the label text) should be a string, not ", label->whichText(), U".");
8144 UiPause_optionmenu (label->getString(), Melder_iround (defaultValue->number));
8145 pushNumber (1);
8146 }
8147 static void do_option () {
8148 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8149 U"The function “option” is not available inside manuals.");
8150 const Stackel n = pop;
8151 Melder_require (n->number == 1,
8152 U"The function “option” requires 1 argument (a text), not ", n->number, U".");
8153 const Stackel text = pop;
8154 Melder_require (text->which == Stackel_STRING,
8155 U"The argument of “option” should be a string (the text), not ", text->whichText(), U".");
8156 UiPause_option (text->getString());
8157 pushNumber (1);
8158 }
8159 static void do_heading () {
8160 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8161 U"The function “heading” is not available inside manuals.");
8162 const Stackel n = pop;
8163 Melder_require (n->number == 1,
8164 U"The function “heading” requires 1 argument (a text), not ", n->number, U".");
8165 const Stackel text = pop;
8166 Melder_require (text->which == Stackel_STRING,
8167 U"The argument of “heading” should be a string (the text), not ", text->whichText(), U".");
8168 UiPause_heading (text->getString());
8169 pushNumber (1);
8170 }
8171 static void do_comment () {
8172 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8173 U"The function “comment” is not available inside manuals.");
8174 const Stackel n = pop;
8175 Melder_require (n->number == 1,
8176 U"The function “comment” requires 1 argument (a text), not ", n->number, U".");
8177 const Stackel text = pop;
8178 Melder_require (text->which == Stackel_STRING,
8179 U"The argument of “comment” should be a string (the text), not ", text->whichText(), U".");
8180 UiPause_comment (text->getString());
8181 pushNumber (1);
8182 }
8183 static void do_endPause () {
8184 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8185 U"The function “endPause” is not available inside manuals.");
8186 const Stackel n = pop;
8187 if (n->number < 2 || n->number > 12)
8188 Melder_throw (U"The function “endPause” requires 2 to 12 arguments, not ", n->number, U".");
8189 const Stackel d = pop;
8190 if (d->which != Stackel_NUMBER)
8191 Melder_throw (U"The last argument of “endPause” should be a number (the default or cancel continue button), not ", d->whichText(), U".");
8192 /* mutable */ integer numberOfContinueButtons = Melder_iround (n->number) - 1;
8193 /* mutable */ integer cancelContinueButton = 0, defaultContinueButton = Melder_iround (d->number);
8194 Stackel ca = pop;
8195 if (ca->which == Stackel_NUMBER) {
8196 cancelContinueButton = defaultContinueButton;
8197 defaultContinueButton = Melder_iround (ca->number);
8198 numberOfContinueButtons -= 1;
8199 if (cancelContinueButton < 0 || cancelContinueButton > numberOfContinueButtons)
8200 Melder_throw (U"Your last argument of “endPause” is the number of the cancel button; it cannot be ", cancelContinueButton,
8201 U" but should be 0 (no cancel or stop button) or lie between 1 and ", numberOfContinueButtons, U".");
8202 if (cancelContinueButton == 0)
8203 cancelContinueButton = -1;
8204 }
8205 Stackel co [1+10] = { 0 };
8206 for (integer i = numberOfContinueButtons; i >= 1; i --) {
8207 co [i] = ( cancelContinueButton != 0 || i != numberOfContinueButtons ? pop : ca );
8208 if (co[i]->which != Stackel_STRING)
8209 Melder_throw (U"Each of the first ", numberOfContinueButtons,
8210 U" argument(s) of “endPause” should be a string (a button text), not ", co[i]->whichText(), U".");
8211 }
8212 const integer buttonClicked = UiPause_end (numberOfContinueButtons, defaultContinueButton, cancelContinueButton,
8213 ! co [1] ? nullptr : co[1]->getString(), ! co [2] ? nullptr : co[2]->getString(),
8214 ! co [3] ? nullptr : co[3]->getString(), ! co [4] ? nullptr : co[4]->getString(),
8215 ! co [5] ? nullptr : co[5]->getString(), ! co [6] ? nullptr : co[6]->getString(),
8216 ! co [7] ? nullptr : co[7]->getString(), ! co [8] ? nullptr : co[8]->getString(),
8217 ! co [9] ? nullptr : co[9]->getString(), ! co [10] ? nullptr : co[10]->getString(),
8218 theInterpreter);
8219 //Melder_casual (U"Button ", buttonClicked);
8220 pushNumber (buttonClicked);
8221 }
8222 static void do_lowerCaseAppNameStr () {
8223 const Stackel n = pop;
8224 Melder_require (n->number == 0,
8225 U"The function “lowerCaseAppName$” requires 0 arguments, not ", n->number, U".");
8226 return pushString (Melder_dup (Melder_lowerCaseAppName()));
8227 }
8228 static void do_upperCaseAppNameStr () {
8229 const Stackel n = pop;
8230 Melder_require (n->number == 0,
8231 U"The function “upperCaseAppName$” requires 0 arguments, not ", n->number, U".");
8232 return pushString (Melder_dup (Melder_upperCaseAppName()));
8233 }
8234 static void do_clock () {
8235 const Stackel n = pop;
8236 Melder_require (n->number == 0,
8237 U"The function “clock” requires 0 arguments, not ", n->number, U".");
8238 return pushNumber (Melder_clock ());
8239 }
8240 static void do_appVersion () {
8241 const Stackel n = pop;
8242 Melder_require (n->number == 0,
8243 U"The function “appVersion” requires 0 arguments, not ", n->number, U".");
8244 return pushNumber (Melder_appVersion());
8245 }
8246 static void do_appVersionStr () {
8247 const Stackel n = pop;
8248 Melder_require (n->number == 0,
8249 U"The function “appVersion$” requires 0 arguments, not ", n->number, U".");
8250 return pushString (Melder_dup (Melder_appVersionSTR()));
8251 }
8252 static void do_appYear () {
8253 const Stackel n = pop;
8254 Melder_require (n->number == 0,
8255 U"The function “appYear” requires 0 arguments, not ", n->number, U".");
8256 return pushNumber (Melder_appYear());
8257 }
8258 static void do_appMonth () {
8259 const Stackel n = pop;
8260 Melder_require (n->number == 0,
8261 U"The function “appMonth” requires 0 arguments, not ", n->number, U".");
8262 return pushNumber (Melder_appMonth());
8263 }
8264 static void do_appMonthStr () {
8265 const Stackel n = pop;
8266 Melder_require (n->number == 0,
8267 U"The function “appMonth$” requires 0 arguments, not ", n->number, U".");
8268 return pushString (Melder_dup (Melder_appMonthSTR()));
8269 }
8270 static void do_appDay () {
8271 const Stackel n = pop;
8272 Melder_require (n->number == 0,
8273 U"The function “appDay” requires 0 arguments, not ", n->number, U".");
8274 return pushNumber (Melder_appDay());
8275 }
8276 static void do_chooseReadFileStr () {
8277 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8278 U"The function “chooseReadFile$” is not available inside manuals.");
8279 const Stackel n = pop;
8280 Melder_require (n->number == 1,
8281 U"The function “chooseReadFile$” requires 1 argument (a title), not ", n->number, U".");
8282 const Stackel title = pop;
8283 Melder_require (title->which == Stackel_STRING,
8284 U"The argument of “chooseReadFile$” should be a string (the title), not ", title->whichText(), U".");
8285 autoStringSet fileNames = GuiFileSelect_getInfileNames (nullptr, title->getString(), false);
8286 if (fileNames->size == 0)
8287 return pushString (Melder_dup (U""));
8288 SimpleString fileName = fileNames->at [1];
8289 pushString (Melder_dup (fileName -> string.get()));
8290 }
8291 static void do_chooseWriteFileStr () {
8292 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8293 U"The function “chooseWriteFile$” is not available inside manuals.");
8294 const Stackel n = pop;
8295 Melder_require (n->number == 2,
8296 U"The function “chooseWriteFile$” requires 2 arguments (a title and a default name), not ", n->number, U".");
8297 const Stackel defaultName = pop, title = pop;
8298 Melder_require (title->which == Stackel_STRING && defaultName->which == Stackel_STRING,
8299 U"The arguments of “chooseWriteFile$” should be two strings (the title and the default name).");
8300 autostring32 result = GuiFileSelect_getOutfileName (nullptr, title->getString(), defaultName->getString());
8301 if (! result)
8302 result = Melder_dup (U"");
8303 pushString (result.move());
8304 }
8305 static void do_chooseFolder_STR () {
8306 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8307 U"The function “chooseFolder$” is not available inside manuals.");
8308 const Stackel n = pop;
8309 Melder_require (n->number == 1,
8310 U"The function “chooseFolder$” requires 1 argument (a title), not ", n->number, U".");
8311 const Stackel title = pop;
8312 Melder_require (title->which == Stackel_STRING,
8313 U"The argument of “chooseFolder$” should be a string (the title).");
8314 autostring32 result = GuiFileSelect_getFolderName (nullptr, title->getString());
8315 if (! result)
8316 result = Melder_dup (U"");
8317 pushString (result.move());
8318 }
8319 static void do_chooseDirectory_STR () {
8320 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8321 U"The function “chooseDirectory$” is not available inside manuals.");
8322 const Stackel n = pop;
8323 Melder_require (n->number == 1,
8324 U"The function “chooseDirectory$” requires 1 argument (a title), not ", n->number, U".");
8325 const Stackel title = pop;
8326 Melder_require (title->which == Stackel_STRING,
8327 U"The argument of “chooseDirectory$” should be a string (the title).");
8328 autostring32 result = GuiFileSelect_getFolderName (nullptr, title->getString());
8329 if (! result)
8330 result = Melder_dup (U"");
8331 pushString (result.move());
8332 }
8333 static void do_demoWindowTitle () {
8334 const Stackel n = pop;
8335 if (n->number == 1) {
8336 const Stackel title = pop;
8337 if (title->which == Stackel_STRING) {
8338 Demo_windowTitle (title->getString());
8339 } else {
8340 Melder_throw (U"The argument of “demoWindowTitle” should be a string (the title), not ", title->whichText(), U".");
8341 }
8342 } else {
8343 Melder_throw (U"The function “demoWindowTitle” requires 1 argument (a title), not ", n->number, U".");
8344 }
8345 pushNumber (1);
8346 }
8347 static void do_demoShow () {
8348 const Stackel n = pop;
8349 if (n->number != 0)
8350 Melder_throw (U"The function “demoShow” requires 0 arguments, not ", n->number, U".");
8351 Demo_show ();
8352 pushNumber (1);
8353 }
8354 static void do_demoWaitForInput () {
8355 const Stackel n = pop;
8356 if (n->number != 0)
8357 Melder_throw (U"The function “demoWaitForInput” requires 0 arguments, not ", n->number, U".");
8358 Demo_waitForInput (theInterpreter);
8359 pushNumber (1);
8360 }
8361 static void do_demoPeekInput () {
8362 const Stackel n = pop;
8363 if (n->number != 0)
8364 Melder_throw (U"The function “demoPeekInput” requires 0 arguments, not ", n->number, U".");
8365 Demo_peekInput (theInterpreter);
8366 pushNumber (1);
8367 }
8368 static void do_demoInput () {
8369 const Stackel n = pop;
8370 if (n->number == 1) {
8371 const Stackel keys = pop;
8372 if (keys->which == Stackel_STRING) {
8373 const bool result = Demo_input (keys->getString());
8374 pushNumber (result);
8375 } else {
8376 Melder_throw (U"The argument of “demoInput” should be a string (the keys), not ", keys->whichText(), U".");
8377 }
8378 } else {
8379 Melder_throw (U"The function “demoInput” requires 1 argument (keys), not ", n->number, U".");
8380 }
8381 }
8382 static void do_demoClickedIn () {
8383 const Stackel n = pop;
8384 if (n->number == 4) {
8385 const Stackel top = pop, bottom = pop, right = pop, left = pop;
8386 if (left->which == Stackel_NUMBER && right->which == Stackel_NUMBER && bottom->which == Stackel_NUMBER && top->which == Stackel_NUMBER) {
8387 const bool result = Demo_clickedIn (left->number, right->number, bottom->number, top->number);
8388 pushNumber (result);
8389 } else {
8390 Melder_throw (U"All arguments of “demoClickedIn” should be numbers (the x and y ranges).");
8391 }
8392 } else {
8393 Melder_throw (U"The function “demoClickedIn” requires 4 arguments (x and y ranges), not ", n->number, U".");
8394 }
8395 }
8396 static void do_demoClicked () {
8397 const Stackel n = pop;
8398 if (n->number != 0)
8399 Melder_throw (U"The function “demoClicked” requires 0 arguments, not ", n->number, U".");
8400 const bool result = Demo_clicked ();
8401 pushNumber (result);
8402 }
8403 static void do_demoX () {
8404 const Stackel n = pop;
8405 if (n->number != 0)
8406 Melder_throw (U"The function “demoX” requires 0 arguments, not ", n->number, U".");
8407 const double result = Demo_x ();
8408 pushNumber (result);
8409 }
8410 static void do_demoY () {
8411 const Stackel n = pop;
8412 if (n->number != 0)
8413 Melder_throw (U"The function “demoY” requires 0 arguments, not ", n->number, U".");
8414 const double result = Demo_y ();
8415 pushNumber (result);
8416 }
8417 static void do_demoKeyPressed () {
8418 const Stackel n = pop;
8419 if (n->number != 0)
8420 Melder_throw (U"The function “demoKeyPressed” requires 0 arguments, not ", n->number, U".");
8421 const bool result = Demo_keyPressed ();
8422 pushNumber (result);
8423 }
8424 static void do_demoKey () {
8425 const Stackel n = pop;
8426 if (n->number != 0)
8427 Melder_throw (U"The function “demoKey” requires 0 arguments, not ", n->number, U".");
8428 autostring32 key (1);
8429 key [0] = Demo_key ();
8430 pushString (key.move());
8431 }
8432 static void do_demoShiftKeyPressed () {
8433 const Stackel n = pop;
8434 if (n->number != 0)
8435 Melder_throw (U"The function “demoShiftKeyPressed” requires 0 arguments, not ", n->number, U".");
8436 const bool result = Demo_shiftKeyPressed ();
8437 pushNumber (result);
8438 }
8439 static void do_demoCommandKeyPressed () {
8440 const Stackel n = pop;
8441 if (n->number != 0)
8442 Melder_throw (U"The function “demoCommandKeyPressed” requires 0 arguments, not ", n->number, U".");
8443 const bool result = Demo_commandKeyPressed ();
8444 pushNumber (result);
8445 }
8446 static void do_demoOptionKeyPressed () {
8447 const Stackel n = pop;
8448 if (n->number != 0)
8449 Melder_throw (U"The function “demoOptionKeyPressed” requires 0 arguments, not ", n->number, U".");
8450 const bool result = Demo_optionKeyPressed ();
8451 pushNumber (result);
8452 }
8453 static integer Stackel_getRowNumber (Stackel row, Daata thee) {
8454 integer result = 0;
8455 if (row->which == Stackel_NUMBER) {
8456 result = Melder_iround (row->number);
8457 } else if (row->which == Stackel_STRING) {
8458 if (! thy v_hasGetRowIndex ())
8459 Melder_throw (U"Objects of type ", Thing_className (thee), U" do not have row labels, so row indexes have to be numbers.");
8460 result = Melder_iround (thy v_getRowIndex (row->getString()));
8461 if (result == 0)
8462 Melder_throw (U"Object “", thy name.get(), U"” has no row labelled “", row->getString(), U"”.");
8463 } else {
8464 Melder_throw (U"A row index should be a number or a string, not ", row->whichText(), U".");
8465 }
8466 return result;
8467 }
8468 static integer Stackel_getColumnNumber (Stackel column, Daata thee) {
8469 integer result = 0;
8470 if (column->which == Stackel_NUMBER) {
8471 result = Melder_iround (column->number);
8472 } else if (column->which == Stackel_STRING) {
8473 if (! thy v_hasGetColIndex ())
8474 Melder_throw (U"Objects of type ", Thing_className (thee), U" do not have column labels, so column indexes have to be numbers.");
8475 result = Melder_iround (thy v_getColIndex (column->getString()));
8476 if (result == 0)
8477 Melder_throw (U"Object ", thee, U" has no column labelled “", column->getString(), U"”.");
8478 } else {
8479 Melder_throw (U"A column index should be a number or a string, not ", column->whichText(), U".");
8480 }
8481 return result;
8482 }
8483 static void do_self0 (integer irow, integer icol) {
8484 const Daata me = theSource;
8485 if (! me)
8486 Melder_throw (U"The name “self” is restricted to formulas for objects.");
8487 if (my v_hasGetCell ()) {
8488 pushNumber (my v_getCell ());
8489 } else if (my v_hasGetVector ()) {
8490 if (icol == 0) {
8491 Melder_throw (U"We are not in a loop, hence no implicit column index for the current ",
8492 Thing_className (me), U" object (self).\nTry using the [column] index explicitly.");
8493 } else {
8494 pushNumber (my v_getVector (irow, icol));
8495 }
8496 } else if (my v_hasGetMatrix ()) {
8497 if (irow == 0) {
8498 if (icol == 0) {
8499 Melder_throw (U"We are not in a loop over rows and columns,\n"
8500 U"hence no implicit row and column indexing for the current ",
8501 Thing_className (me), U" object (self).\n"
8502 U"Try using both [row, column] indexes explicitly.");
8503 } else {
8504 Melder_throw (U"We are not in a loop over columns only,\n"
8505 U"hence no implicit row index for the current ",
8506 Thing_className (me), U" object (self).\n"
8507 U"Try using the [row] index explicitly.");
8508 }
8509 } else {
8510 pushNumber (my v_getMatrix (irow, icol));
8511 }
8512 } else {
8513 Melder_throw (Thing_className (me), U" objects (like self) accept no [] indexing.");
8514 }
8515 }
8516 static void do_selfStr0 (integer irow, integer icol) {
8517 const Daata me = theSource;
8518 if (! me)
8519 Melder_throw (U"The name “self$” is restricted to formulas for objects.");
8520 if (my v_hasGetCellStr ()) {
8521 pushString (Melder_dup (my v_getCellStr ()));
8522 } else if (my v_hasGetVectorStr ()) {
8523 if (icol == 0) {
8524 Melder_throw (U"We are not in a loop, hence no implicit column index for the current ",
8525 Thing_className (me), U" object (self).\nTry using the [column] index explicitly.");
8526 } else {
8527 pushString (Melder_dup (my v_getVectorStr (icol)));
8528 }
8529 } else if (my v_hasGetMatrixStr ()) {
8530 if (irow == 0) {
8531 if (icol == 0) {
8532 Melder_throw (U"We are not in a loop over rows and columns,\n"
8533 U"hence no implicit row and column indexing for the current ",
8534 Thing_className (me), U" object (self).\n"
8535 U"Try using both [row, column] indexes explicitly.");
8536 } else {
8537 Melder_throw (U"We are not in a loop over columns only,\n"
8538 U"hence no implicit row index for the current ",
8539 Thing_className (me), U" object (self).\n"
8540 U"Try using the [row] index explicitly.");
8541 }
8542 } else {
8543 pushString (Melder_dup (my v_getMatrixStr (irow, icol)));
8544 }
8545 } else {
8546 Melder_throw (Thing_className (me), U" objects (like self) accept no [] indexing.");
8547 }
8548 }
8549 static void do_toObject () {
8550 const Stackel object = pop;
8551 Daata thee = nullptr;
8552 if (object->which == Stackel_NUMBER) {
8553 integer i = theCurrentPraatObjects -> n;
8554 while (i > 0 && object->number != theCurrentPraatObjects -> list [i]. id)
8555 i --;
8556 if (i == 0)
8557 Melder_throw (U"No such object: ", object->number);
8558 thee = (Daata) theCurrentPraatObjects -> list [i]. object;
8559 } else if (object->which == Stackel_STRING) {
8560 integer i = theCurrentPraatObjects -> n;
8561 while (i > 0 && ! Melder_equ (object->getString(), theCurrentPraatObjects -> list [i]. name.get()))
8562 i --;
8563 if (i == 0)
8564 Melder_throw (U"No such object: ", object->getString());
8565 thee = (Daata) theCurrentPraatObjects -> list [i]. object;
8566 } else {
8567 Melder_throw (U"The first argument to “object” should be a number (unique ID) or a string (name), not ", object->whichText(), U".");
8568 }
8569 pushObject (thee);
8570 }
8571 static void do_objectCell0 (integer irow, integer icol) {
8572 const Stackel object = pop;
8573 const Daata thee = object->object;
8574 if (thy v_hasGetCell ()) {
8575 pushNumber (thy v_getCell ());
8576 } else if (thy v_hasGetVector ()) {
8577 if (icol == 0) {
8578 Melder_throw (U"We are not in a loop,\n"
8579 U"hence no implicit column index for this ", Thing_className (thee), U" object.\n"
8580 U"Try using: object [id, column].");
8581 } else {
8582 pushNumber (thy v_getVector (irow, icol));
8583 }
8584 } else if (thy v_hasGetMatrix ()) {
8585 if (irow == 0) {
8586 if (icol == 0) {
8587 Melder_throw (U"We are not in a loop over rows and columns,\n"
8588 U"hence no implicit row and column indexing for this ", Thing_className (thee), U" object.\n"
8589 U"Try using: object [id, row, column].");
8590 } else {
8591 Melder_throw (U"We are not in a loop over columns only,\n"
8592 U"hence no implicit row index for this ", Thing_className (thee), U" object.\n"
8593 U"Try using: object [id, row].");
8594 }
8595 } else {
8596 pushNumber (thy v_getMatrix (irow, icol));
8597 }
8598 } else {
8599 Melder_throw (Thing_className (thee), U" objects accept no [] indexing.");
8600 }
8601 }
8602 static void do_matrix0 (integer irow, integer icol) {
8603 const Daata thee = parse [programPointer]. content.object;
8604 if (thy v_hasGetCell ()) {
8605 pushNumber (thy v_getCell ());
8606 } else if (thy v_hasGetVector ()) {
8607 if (icol == 0) {
8608 Melder_throw (U"We are not in a loop,\n"
8609 U"hence no implicit column index for this ", Thing_className (thee), U" object.\n"
8610 U"Try using the [column] index explicitly.");
8611 } else {
8612 pushNumber (thy v_getVector (irow, icol));
8613 }
8614 } else if (thy v_hasGetMatrix ()) {
8615 if (irow == 0) {
8616 if (icol == 0) {
8617 Melder_throw (U"We are not in a loop over rows and columns,\n"
8618 U"hence no implicit row and column indexing for this ", Thing_className (thee), U" object.\n"
8619 U"Try using both [row, column] indexes explicitly.");
8620 } else {
8621 Melder_throw (U"We are not in a loop over columns only,\n"
8622 U"hence no implicit row index for this ", Thing_className (thee), U" object.\n"
8623 U"Try using the [row] index explicitly.");
8624 }
8625 } else {
8626 pushNumber (thy v_getMatrix (irow, icol));
8627 }
8628 } else {
8629 Melder_throw (Thing_className (thee), U" objects accept no [] indexing.");
8630 }
8631 }
8632 static void do_selfMatrix1 (integer irow) {
8633 const Daata me = theSource;
8634 const Stackel column = pop;
8635 if (! me)
8636 Melder_throw (U"The name “self” is restricted to formulas for objects.");
8637 integer icol = Stackel_getColumnNumber (column, me);
8638 if (my v_hasGetVector ()) {
8639 pushNumber (my v_getVector (irow, icol));
8640 } else if (my v_hasGetMatrix ()) {
8641 if (irow == 0) {
8642 Melder_throw (U"We are not in a loop,\n"
8643 U"hence no implicit row index for the current ", Thing_className (me), U" object (self).\n"
8644 U"Try using both [row, column] indexes instead.");
8645 } else {
8646 pushNumber (my v_getMatrix (irow, icol));
8647 }
8648 } else {
8649 Melder_throw (Thing_className (me), U" objects (like self) accept no [column] indexes.");
8650 }
8651 }
8652 static void do_selfMatrix1_STR (integer irow) {
8653 const Daata me = theSource;
8654 const Stackel column = pop;
8655 if (! me)
8656 Melder_throw (U"The name “self$” is restricted to formulas for objects.");
8657 const integer icol = Stackel_getColumnNumber (column, me);
8658 if (my v_hasGetVectorStr ()) {
8659 pushString (Melder_dup (my v_getVectorStr (icol)));
8660 } else if (my v_hasGetMatrixStr ()) {
8661 if (irow == 0) {
8662 Melder_throw (U"We are not in a loop,\n"
8663 U"hence no implicit row index for the current ", Thing_className (me), U" object (self).\n"
8664 U"Try using both [row, column] indexes instead.");
8665 } else {
8666 pushString (Melder_dup (my v_getMatrixStr (irow, icol)));
8667 }
8668 } else {
8669 Melder_throw (Thing_className (me), U" objects (like self) accept no [column] indexes.");
8670 }
8671 }
8672 static void do_objectCell1 (integer irow) {
8673 const Stackel column = pop, object = pop;
8674 const Daata thee = object->object;
8675 const integer icol = Stackel_getColumnNumber (column, thee);
8676 if (thy v_hasGetVector ()) {
8677 pushNumber (thy v_getVector (irow, icol));
8678 } else if (thy v_hasGetMatrix ()) {
8679 if (irow == 0) {
8680 Melder_throw (U"We are not in a loop,\n"
8681 U"hence no implicit row index for this ", Thing_className (thee), U" object.\n"
8682 U"Try using: object [id, row, column].");
8683 } else {
8684 pushNumber (thy v_getMatrix (irow, icol));
8685 }
8686 } else {
8687 Melder_throw (Thing_className (thee), U" objects accept no [column] indexes.");
8688 }
8689 }
8690 static void do_matrix1 (integer irow) {
8691 const Daata thee = parse [programPointer]. content.object;
8692 const Stackel column = pop;
8693 const integer icol = Stackel_getColumnNumber (column, thee);
8694 if (thy v_hasGetVector ()) {
8695 pushNumber (thy v_getVector (irow, icol));
8696 } else if (thy v_hasGetMatrix ()) {
8697 if (irow == 0) {
8698 Melder_throw (U"We are not in a loop,\n"
8699 U"hence no implicit row index for this ", Thing_className (thee), U" object.\n"
8700 U"Try using both [row, column] indexes instead.");
8701 } else {
8702 pushNumber (thy v_getMatrix (irow, icol));
8703 }
8704 } else {
8705 Melder_throw (Thing_className (thee), U" objects accept no [column] indexes.");
8706 }
8707 }
8708 static void do_objectCell1_STR (integer irow) {
8709 const Stackel column = pop, object = pop;
8710 const Daata thee = object->object;
8711 const integer icol = Stackel_getColumnNumber (column, thee);
8712 if (thy v_hasGetVectorStr ()) {
8713 pushString (Melder_dup (thy v_getVectorStr (icol)));
8714 } else if (thy v_hasGetMatrixStr ()) {
8715 if (irow == 0) {
8716 Melder_throw (U"We are not in a loop,\n"
8717 U"hence no implicit row index for this ", Thing_className (thee), U" object.\n"
8718 U"Try using: object [id, row, column].");
8719 } else {
8720 pushString (Melder_dup (thy v_getMatrixStr (irow, icol)));
8721 }
8722 } else {
8723 Melder_throw (Thing_className (thee), U" objects accept no [column] indexes for string cells.");
8724 }
8725 }
8726 static void do_matrix1_STR (integer irow) {
8727 const Daata thee = parse [programPointer]. content.object;
8728 const Stackel column = pop;
8729 const integer icol = Stackel_getColumnNumber (column, thee);
8730 if (thy v_hasGetVectorStr ()) {
8731 pushString (Melder_dup (thy v_getVectorStr (icol)));
8732 } else if (thy v_hasGetMatrixStr ()) {
8733 if (irow == 0) {
8734 Melder_throw (U"We are not in a loop,\n"
8735 U"hence no implicit row index for this ", Thing_className (thee), U" object.\n"
8736 U"Try using both [row, column] indexes instead.");
8737 } else {
8738 pushString (Melder_dup (thy v_getMatrixStr (irow, icol)));
8739 }
8740 } else {
8741 Melder_throw (Thing_className (thee), U" objects accept no [column] indexes for string cells.");
8742 }
8743 }
8744 static void do_selfMatrix2 () {
8745 const Daata me = theSource;
8746 Stackel column = pop, row = pop;
8747 if (! me)
8748 Melder_throw (U"The name “self” is restricted to formulas for objects.");
8749 const integer irow = Stackel_getRowNumber (row, me);
8750 const integer icol = Stackel_getColumnNumber (column, me);
8751 if (! my v_hasGetMatrix ())
8752 Melder_throw (Thing_className (me), U" objects like “self” accept no [row, column] indexing.");
8753 pushNumber (my v_getMatrix (irow, icol));
8754 }
8755 static void do_selfMatrix2_STR () {
8756 const Daata me = theSource;
8757 const Stackel column = pop, row = pop;
8758 if (! me)
8759 Melder_throw (U"The name “self$” is restricted to formulas for objects.");
8760 const integer irow = Stackel_getRowNumber (row, me);
8761 const integer icol = Stackel_getColumnNumber (column, me);
8762 if (! my v_hasGetMatrixStr ())
8763 Melder_throw (Thing_className (me), U" objects like “self$” accept no [row, column] indexing for string cells.");
8764 pushString (Melder_dup (my v_getMatrixStr (irow, icol)));
8765 }
8766 static void do_objectCell2 () {
8767 const Stackel column = pop, row = pop, object = pop;
8768 const Daata thee = object->object;
8769 const integer irow = Stackel_getRowNumber (row, thee);
8770 const integer icol = Stackel_getColumnNumber (column, thee);
8771 if (! thy v_hasGetMatrix ())
8772 Melder_throw (Thing_className (thee), U" objects accept no [id, row, column] indexing.");
8773 pushNumber (thy v_getMatrix (irow, icol));
8774 }
8775 static void do_matrix2 () {
8776 const Daata thee = parse [programPointer]. content.object;
8777 const Stackel column = pop, row = pop;
8778 const integer irow = Stackel_getRowNumber (row, thee);
8779 const integer icol = Stackel_getColumnNumber (column, thee);
8780 if (! thy v_hasGetMatrix ())
8781 Melder_throw (Thing_className (thee), U" objects accept no [row, column] indexing.");
8782 pushNumber (thy v_getMatrix (irow, icol));
8783 }
8784 static void do_objectCell2_STR () {
8785 const Stackel column = pop, row = pop, object = pop;
8786 const Daata thee = object->object;
8787 const integer irow = Stackel_getRowNumber (row, thee);
8788 const integer icol = Stackel_getColumnNumber (column, thee);
8789 if (! thy v_hasGetMatrixStr ())
8790 Melder_throw (Thing_className (thee), U" objects accept no [id, row, column] indexing for string cells.");
8791 pushString (Melder_dup (thy v_getMatrixStr (irow, icol)));
8792 }
8793 static void do_matrix2_STR () {
8794 const Daata thee = parse [programPointer]. content.object;
8795 const Stackel column = pop, row = pop;
8796 const integer irow = Stackel_getRowNumber (row, thee);
8797 const integer icol = Stackel_getColumnNumber (column, thee);
8798 if (! thy v_hasGetMatrixStr ())
8799 Melder_throw (Thing_className (thee), U" objects accept no [row, column] indexing for string cells.");
8800 pushString (Melder_dup (thy v_getMatrixStr (irow, icol)));
8801 }
8802 static void do_objectLocation0 (integer irow, integer icol) {
8803 const Stackel object = pop;
8804 const Daata thee = object->object;
8805 if (thy v_hasGetFunction0 ()) {
8806 pushNumber (thy v_getFunction0 ());
8807 } else if (thy v_hasGetFunction1 ()) {
8808 const Daata me = theSource;
8809 if (! me)
8810 Melder_throw (U"No current object (we are not in a Formula command),\n"
8811 U"hence no implicit x value for this ", Thing_className (thee), U" object.\n"
8812 U"Try using: object (id, x).");
8813 if (! my v_hasGetX ())
8814 Melder_throw (U"The current ", Thing_className (me),
8815 U" object gives no implicit x values,\nhence no implicit x value for this ",
8816 Thing_className (thee), " object.\n"
8817 U"Try using: object (id, x).");
8818 const double x = my v_getX (icol);
8819 pushNumber (thy v_getFunction1 (irow, x));
8820 } else if (thy v_hasGetFunction2 ()) {
8821 const Daata me = theSource;
8822 if (! me)
8823 Melder_throw (U"No current object (we are not in a Formula command),\n"
8824 U"hence no implicit x or y values for this ", Thing_className (thee), U" object.\n"
8825 U"Try using: object (id, x, y).");
8826 if (! my v_hasGetX ())
8827 Melder_throw (U"The current ", Thing_className (me), U" object gives no implicit x values,\n"
8828 U"hence no implicit x value for this ", Thing_className (thee), U" object.\n"
8829 U"Try using: object (id, x, y).");
8830 const double x = my v_getX (icol);
8831 if (! my v_hasGetY ())
8832 Melder_throw (U"The current ", Thing_className (me), U" object gives no implicit y values,\n"
8833 U"hence no implicit y value for this ", Thing_className (thee), U" object.\n"
8834 U"Try using: object (id, y).");
8835 const double y = my v_getY (irow);
8836 pushNumber (thy v_getFunction2 (x, y));
8837 } else {
8838 Melder_throw (Thing_className (thee), U" objects accept no () values.");
8839 }
8840 }
8841 static void do_function0 (integer irow, integer icol) {
8842 const Daata thee = parse [programPointer]. content.object;
8843 if (thy v_hasGetFunction0 ()) {
8844 pushNumber (thy v_getFunction0 ());
8845 } else if (thy v_hasGetFunction1 ()) {
8846 const Daata me = theSource;
8847 if (! me)
8848 Melder_throw (U"No current object (we are not in a Formula command),\n"
8849 U"hence no implicit x value for this ", Thing_className (thee), U" object.\n"
8850 U"Try using the (x) argument explicitly.");
8851 if (! my v_hasGetX ())
8852 Melder_throw (U"The current ", Thing_className (me),
8853 U" object gives no implicit x values,\nhence no implicit x value for this ",
8854 Thing_className (thee), U" object.\n"
8855 U"Try using the (x) argument explicitly.");
8856 const double x = my v_getX (icol);
8857 pushNumber (thy v_getFunction1 (irow, x));
8858 } else if (thy v_hasGetFunction2 ()) {
8859 const Daata me = theSource;
8860 if (! me)
8861 Melder_throw (U"No current object (we are not in a Formula command),\n"
8862 U"hence no implicit x or y values for this ", Thing_className (thee), U" object.\n"
8863 U"Try using both (x, y) arguments explicitly.");
8864 if (! my v_hasGetX ())
8865 Melder_throw (U"The current ", Thing_className (me), U" object gives no implicit x values,\n"
8866 U"hence no implicit x value for this ", Thing_className (thee), U" object.\n"
8867 U"Try using both (x, y) arguments explicitly.");
8868 const double x = my v_getX (icol);
8869 if (! my v_hasGetY ())
8870 Melder_throw (U"The current ", Thing_className (me), U" object gives no implicit y values,\n"
8871 U"hence no implicit y value for this ", Thing_className (thee), U" object.\n"
8872 U"Try using the (y) argument explicitly.");
8873 const double y = my v_getY (irow);
8874 pushNumber (thy v_getFunction2 (x, y));
8875 } else {
8876 Melder_throw (Thing_className (thee), U" objects accept no () values.");
8877 }
8878 }
8879 static void do_selfFunction1 (integer irow) {
8880 const Daata me = theSource;
8881 const Stackel x = pop;
8882 if (x->which == Stackel_NUMBER) {
8883 if (! me)
8884 Melder_throw (U"The name “self” is restricted to formulas for objects.");
8885 if (my v_hasGetFunction1 ()) {
8886 pushNumber (my v_getFunction1 (irow, x->number));
8887 } else if (my v_hasGetFunction2 ()) {
8888 if (! my v_hasGetY ())
8889 Melder_throw (U"The current ", Thing_className (me), U" object (self) accepts no implicit y values.\n"
8890 U"Try using both (x, y) arguments instead.");
8891 const double y = my v_getY (irow);
8892 pushNumber (my v_getFunction2 (x->number, y));
8893 } else {
8894 Melder_throw (Thing_className (me), U" objects like “self” accept no (x) values.");
8895 }
8896 } else {
8897 Melder_throw (Thing_className (me), U" objects like “self” accept only numeric x values.");
8898 }
8899 }
8900 static void do_objectLocation1 (integer irow) {
8901 const Stackel x = pop, object = pop;
8902 const Daata thee = object->object;
8903 if (x->which == Stackel_NUMBER) {
8904 if (thy v_hasGetFunction1 ()) {
8905 pushNumber (thy v_getFunction1 (irow, x->number));
8906 } else if (thy v_hasGetFunction2 ()) {
8907 const Daata me = theSource;
8908 if (! me)
8909 Melder_throw (U"No current object (we are not in a Formula command),\n"
8910 U"hence no implicit y value for this ", Thing_className (thee), U" object.\n"
8911 U"Try using: object (id, x, y).");
8912 if (! my v_hasGetY ())
8913 Melder_throw (U"The current ", Thing_className (me), U" object gives no implicit y values,\n"
8914 U"hence no implicit y value for this ", Thing_className (thee), U" object.\n"
8915 U"Try using: object (id, x, y).");
8916 const double y = my v_getY (irow);
8917 pushNumber (thy v_getFunction2 (x->number, y));
8918 } else {
8919 Melder_throw (Thing_className (thee), U" objects accept no (x) values.");
8920 }
8921 } else {
8922 Melder_throw (Thing_className (thee), U" objects accept only numeric x values.");
8923 }
8924 }
8925 static void do_function1 (integer irow) {
8926 const Daata thee = parse [programPointer]. content.object;
8927 const Stackel x = pop;
8928 if (x->which == Stackel_NUMBER) {
8929 if (thy v_hasGetFunction1 ()) {
8930 pushNumber (thy v_getFunction1 (irow, x->number));
8931 } else if (thy v_hasGetFunction2 ()) {
8932 const Daata me = theSource;
8933 if (! me)
8934 Melder_throw (U"No current object (we are not in a Formula command),\n"
8935 U"hence no implicit y value for this ", Thing_className (thee), U" object.\n"
8936 U"Try using both (x, y) arguments instead.");
8937 if (! my v_hasGetY ())
8938 Melder_throw (U"The current ", Thing_className (me), U" object gives no implicit y values,\n"
8939 U"hence no implicit y value for this ", Thing_className (thee), U" object.\n"
8940 U"Try using both (x, y) arguments instead.");
8941 const double y = my v_getY (irow);
8942 pushNumber (thy v_getFunction2 (x->number, y));
8943 } else {
8944 Melder_throw (Thing_className (thee), U" objects accept no (x) values.");
8945 }
8946 } else {
8947 Melder_throw (Thing_className (thee), U" objects accept only numeric x values.");
8948 }
8949 }
8950 static void do_selfFunction2 () {
8951 const Daata me = theSource;
8952 const Stackel y = pop, x = pop;
8953 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
8954 if (! me)
8955 Melder_throw (U"The name “self” is restricted to formulas for objects.");
8956 if (! my v_hasGetFunction2 ())
8957 Melder_throw (Thing_className (me), U" objects like “self” accept no (x, y) values.");
8958 pushNumber (my v_getFunction2 (x->number, y->number));
8959 } else {
8960 Melder_throw (Thing_className (me), U" objects accept only numeric x values.");
8961 }
8962 }
8963 static void do_objectLocation2 () {
8964 const Stackel y = pop, x = pop, object = pop;
8965 const Daata thee = object->object;
8966 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
8967 if (! thy v_hasGetFunction2 ())
8968 Melder_throw (Thing_className (thee), U" objects accept no (x, y) values.");
8969 pushNumber (thy v_getFunction2 (x->number, y->number));
8970 } else {
8971 Melder_throw (Thing_className (thee), U" objects accept only numeric x values.");
8972 }
8973 }
8974 static void do_function2 () {
8975 const Daata thee = parse [programPointer]. content.object;
8976 const Stackel y = pop, x = pop;
8977 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
8978 if (! thy v_hasGetFunction2 ())
8979 Melder_throw (Thing_className (thee), U" objects accept no (x, y) values.");
8980 pushNumber (thy v_getFunction2 (x->number, y->number));
8981 } else {
8982 Melder_throw (Thing_className (thee), U" objects accept only numeric x values.");
8983 }
8984 }
8985 static void do_row_STR () {
8986 const Daata thee = parse [programPointer]. content.object;
8987 const Stackel row = pop;
8988 const integer irow = Stackel_getRowNumber (row, thee);
8989 autostring32 result = Melder_dup (thy v_getRowStr (irow));
8990 if (! result)
8991 Melder_throw (U"Row index out of bounds.");
8992 pushString (result.move());
8993 }
8994 static void do_col_STR () {
8995 const Daata thee = parse [programPointer]. content.object;
8996 const Stackel col = pop;
8997 const integer icol = Stackel_getColumnNumber (col, thee);
8998 autostring32 result = Melder_dup (thy v_getColStr (icol));
8999 if (! result)
9000 Melder_throw (U"Column index out of bounds.");
9001 pushString (result.move());
9002 }
9003
9004 static double NUMerf (double x) {
9005 return 1.0 - NUMerfcc (x);
9006 }
9007
9008 void Formula_run (integer row, integer col, Formula_Result *result) {
9009 FormulaInstruction f = parse;
9010 programPointer = 1; // first symbol of the program
9011 if (! theStack) {
9012 theStack = Melder_calloc_f (structStackel, 1+Formula_MAXIMUM_STACK_SIZE);
9013 if (! theStack)
9014 Melder_throw (U"Out of memory during formula computation.");
9015 }
9016 stackPointer = 0; // start new stack
9017 stackPointerMax = 0; // start new stack
9018 try {
9019 while (programPointer <= numberOfInstructions) {
9020 integer symbol;
9021 switch (symbol = f [programPointer]. symbol) {
9022
9023 case NUMBER_: { pushNumber (f [programPointer]. content.number);
9024 } break; case STOPWATCH_: { pushNumber (Melder_stopwatch ());
9025 } break; case ROW_: { pushNumber (row);
9026 } break; case COL_: { pushNumber (col);
9027 } break; case X_: {
9028 Daata me = theSource;
9029 Melder_require (my v_hasGetX (),
9030 U"No values for “x” for this object.");
9031 pushNumber (my v_getX (col));
9032 } break; case Y_: {
9033 Daata me = theSource;
9034 Melder_require (my v_hasGetY (),
9035 U"No values for “y” for this object.");
9036 pushNumber (my v_getY (row));
9037 } break; case NOT_: { do_not ();
9038 } break; case EQ_: { do_eq ();
9039 } break; case NE_: { do_ne ();
9040 } break; case LE_: { do_le ();
9041 } break; case LT_: { do_lt ();
9042 } break; case GE_: { do_ge ();
9043 } break; case GT_: { do_gt ();
9044 } break; case ADD_: { do_add ();
9045 } break; case SUB_: { do_sub ();
9046 } break; case MUL_: { do_mul ();
9047 } break; case RDIV_: { do_rdiv ();
9048 } break; case IDIV_: { do_idiv ();
9049 } break; case MOD_: { do_mod ();
9050 } break; case MINUS_: { do_minus ();
9051 } break; case POWER_: { do_power ();
9052 /********** Functions of 1 variable: **********/
9053
9054 #define CASE_NUM_WITH_TENSORS(label, function) \
9055 } break; case label: { function (); \
9056 } break; case label##VEC_: { function##_VEC (); \
9057 } break; case label##MAT_: { function##_MAT ();
9058 CASE_NUM_WITH_TENSORS (ABS_, do_abs)
9059 CASE_NUM_WITH_TENSORS (ROUND_, do_round)
9060 CASE_NUM_WITH_TENSORS (FLOOR_, do_floor)
9061 CASE_NUM_WITH_TENSORS (CEILING_, do_ceiling)
9062 CASE_NUM_WITH_TENSORS (RECTIFY_, do_rectify)
9063 CASE_NUM_WITH_TENSORS (SQRT_, do_sqrt)
9064 CASE_NUM_WITH_TENSORS (SIN_, do_sin)
9065 CASE_NUM_WITH_TENSORS (COS_, do_cos)
9066 CASE_NUM_WITH_TENSORS (TAN_, do_tan)
9067 CASE_NUM_WITH_TENSORS (ARCSIN_, do_arcsin)
9068 CASE_NUM_WITH_TENSORS (ARCCOS_, do_arccos)
9069 CASE_NUM_WITH_TENSORS (ARCTAN_, do_arctan)
9070 } break; case SINC_: { do_function_n_n (NUMsinc);
9071 } break; case SINCPI_: { do_function_n_n (NUMsincpi);
9072 CASE_NUM_WITH_TENSORS (EXP_, do_exp)
9073 CASE_NUM_WITH_TENSORS (SINH_, do_sinh)
9074 CASE_NUM_WITH_TENSORS (COSH_, do_cosh)
9075 CASE_NUM_WITH_TENSORS (TANH_, do_tanh)
9076 CASE_NUM_WITH_TENSORS (ARCSINH_, do_arcsinh)
9077 CASE_NUM_WITH_TENSORS (ARCCOSH_, do_arccosh)
9078 CASE_NUM_WITH_TENSORS (ARCTANH_, do_arctanh)
9079 CASE_NUM_WITH_TENSORS (SIGMOID_, do_sigmoid)
9080 CASE_NUM_WITH_TENSORS (INV_SIGMOID_, do_invSigmoid)
9081 } break; case SOFTMAX_VEC_: { do_softmax_VEC ();
9082 } break; case SOFTMAX_PER_ROW_MAT_: { do_softmaxPerRow_MAT ();
9083 } break; case ERF_: { do_function_n_n (NUMerf);
9084 } break; case ERFC_: { do_function_n_n (NUMerfcc);
9085 } break; case GAUSS_P_: { do_function_n_n (NUMgaussP);
9086 } break; case GAUSS_Q_: { do_function_n_n (NUMgaussQ);
9087 } break; case INV_GAUSS_Q_: { do_function_n_n (NUMinvGaussQ);
9088 } break; case RANDOM_BERNOULLI_: { do_function_n_n (NUMrandomBernoulli_real);
9089 } break; case RANDOM_BERNOULLI_VEC_: { do_functionvec_n_n (NUMrandomBernoulli_real);
9090 } break; case RANDOM_POISSON_: { do_function_n_n (NUMrandomPoisson);
9091 } break; case TRANSPOSE_MAT_: { do_transpose_MAT ();
9092 } break; case ROW_SUMS_VEC_: { do_rowSums_VEC ();
9093 } break; case COLUMN_SUMS_VEC_: { do_columnSums_VEC ();
9094 CASE_NUM_WITH_TENSORS (LOG2_, do_log2)
9095 CASE_NUM_WITH_TENSORS (LN_, do_ln)
9096 CASE_NUM_WITH_TENSORS (LOG10_, do_log10)
9097 } break; case LN_GAMMA_: { do_function_n_n (NUMlnGamma);
9098 } break; case HERTZ_TO_BARK_: { do_function_n_n (NUMhertzToBark);
9099 } break; case BARK_TO_HERTZ_: { do_function_n_n (NUMbarkToHertz);
9100 } break; case PHON_TO_DIFFERENCE_LIMENS_: { do_function_n_n (NUMphonToDifferenceLimens);
9101 } break; case DIFFERENCE_LIMENS_TO_PHON_: { do_function_n_n (NUMdifferenceLimensToPhon);
9102 } break; case HERTZ_TO_MEL_: { do_function_n_n (NUMhertzToMel);
9103 } break; case MEL_TO_HERTZ_: { do_function_n_n (NUMmelToHertz);
9104 } break; case HERTZ_TO_SEMITONES_: { do_function_n_n (NUMhertzToSemitones);
9105 } break; case SEMITONES_TO_HERTZ_: { do_function_n_n (NUMsemitonesToHertz);
9106 } break; case ERB_: { do_function_n_n (NUMerb);
9107 } break; case HERTZ_TO_ERB_: { do_function_n_n (NUMhertzToErb);
9108 } break; case ERB_TO_HERTZ_: { do_function_n_n (NUMerbToHertz);
9109 } break; case SUM_: { do_sum ();
9110 } break; case MEAN_: { do_mean ();
9111 } break; case STDEV_: { do_stdev ();
9112 } break; case CENTER_: { do_center ();
9113 } break; case RANDOM_IMAX_: { do_randomImax ();
9114 } break; case EVALUATE_: { do_evaluate ();
9115 } break; case EVALUATE_NOCHECK_: { do_evaluate_nocheck ();
9116 } break; case EVALUATE_STR_: { do_evaluate_STR ();
9117 } break; case EVALUATE_NOCHECK_STR_: { do_evaluate_nocheck_STR ();
9118 /********** Functions of 2 numerical variables: **********/
9119 } break; case ARCTAN2_: { do_function_dd_d (atan2);
9120 } break; case RANDOM_UNIFORM_: { do_function_dd_d (NUMrandomUniform);
9121 } break; case RANDOM_INTEGER_: { do_function_ll_l (NUMrandomInteger);
9122 } break; case RANDOM_GAUSS_: { do_function_dd_d (NUMrandomGauss);
9123 } break; case RANDOM_BINOMIAL_: { do_function_dl_d (NUMrandomBinomial_real);
9124 } break; case RANDOM_GAMMA_: { do_function_dd_d (NUMrandomGamma);
9125 } break; case CHI_SQUARE_P_: { do_function_dd_d (NUMchiSquareP);
9126 } break; case CHI_SQUARE_Q_: { do_function_dd_d (NUMchiSquareQ);
9127 } break; case INCOMPLETE_GAMMAP_: { do_function_dd_d (NUMincompleteGammaP);
9128 } break; case INV_CHI_SQUARE_Q_: { do_function_dd_d (NUMinvChiSquareQ);
9129 } break; case STUDENT_P_: { do_function_dd_d (NUMstudentP);
9130 } break; case STUDENT_Q_: { do_function_dd_d (NUMstudentQ);
9131 } break; case INV_STUDENT_Q_: { do_function_dd_d (NUMinvStudentQ);
9132 } break; case BETA_: { do_function_dd_d (NUMbeta);
9133 } break; case BETA2_: { do_function_dd_d (NUMbeta2);
9134 } break; case BESSEL_I_: { do_function_ld_d (NUMbesselI);
9135 } break; case BESSEL_K_: { do_function_ld_d (NUMbesselK);
9136 } break; case LN_BETA_: { do_function_dd_d (NUMlnBeta);
9137 } break; case SOUND_PRESSURE_TO_PHON_: { do_function_dd_d (NUMsoundPressureToPhon);
9138 } break; case OBJECTS_ARE_IDENTICAL_: { do_objects_are_identical ();
9139 /********** Functions of 3 numerical variables: **********/
9140 } break; case FISHER_P_: { do_function_ddd_d (NUMfisherP);
9141 } break; case FISHER_Q_: { do_function_ddd_d (NUMfisherQ);
9142 } break; case INV_FISHER_Q_: { do_function_ddd_d (NUMinvFisherQ);
9143 } break; case BINOMIAL_P_: { do_function_ddd_d (NUMbinomialP);
9144 } break; case BINOMIAL_Q_: { do_function_ddd_d (NUMbinomialQ);
9145 } break; case INCOMPLETE_BETA_: { do_function_ddd_d (NUMincompleteBeta);
9146 } break; case INV_BINOMIAL_P_: { do_function_ddd_d (NUMinvBinomialP);
9147 } break; case INV_BINOMIAL_Q_: { do_function_ddd_d (NUMinvBinomialQ);
9148 /********** Functions of a variable number of variables: **********/
9149 } break; case DO_ : { do_do ();
9150 } break; case DOSTR_: { do_do_STR ();
9151 } break; case WRITE_INFO_ : { do_writeInfo ();
9152 } break; case WRITE_INFO_LINE_ : { do_writeInfoLine ();
9153 } break; case APPEND_INFO_ : { do_appendInfo ();
9154 } break; case APPEND_INFO_LINE_: { do_appendInfoLine ();
9155 } break; case WRITE_FILE_ : { do_writeFile ();
9156 } break; case WRITE_FILE_LINE_ : { do_writeFileLine ();
9157 } break; case APPEND_FILE_ : { do_appendFile ();
9158 } break; case APPEND_FILE_LINE_: { do_appendFileLine ();
9159 } break; case PAUSE_SCRIPT_: { do_pauseScript ();
9160 } break; case EXIT_SCRIPT_: { do_exitScript ();
9161 } break; case RUN_SCRIPT_: { do_runScript ();
9162 } break; case RUN_SCRIPT_WITH_FORM_: { do_runScriptWithForm ();
9163 } break; case RUN_NOTEBOOK_: { do_runNotebook ();
9164 } break; case RUN_SYSTEM_: { do_runSystem ();
9165 } break; case RUN_SYSTEM_STR_: { do_runSystem_STR ();
9166 } break; case RUN_SYSTEM_NOCHECK_: { do_runSystem_nocheck ();
9167 } break; case RUN_SUBPROCESS_: { do_runSubprocess ();
9168 } break; case RUN_SUBPROCESS_STR_: { do_runSubprocess_STR ();
9169 } break; case MIN_: { do_min ();
9170 } break; case MIN_E_: { do_min_e ();
9171 } break; case MIN_IGNORE_UNDEFINED_: { do_min_removeUndefined ();
9172 } break; case MAX_: { do_max ();
9173 } break; case MAX_E_: { do_max_e ();
9174 } break; case MAX_IGNORE_UNDEFINED_: { do_max_removeUndefined ();
9175 } break; case IMIN_: { do_imin ();
9176 } break; case IMIN_E_: { do_imin_e ();
9177 } break; case IMIN_IGNORE_UNDEFINED_: { do_imin_removeUndefined ();
9178 } break; case IMAX_: { do_imax ();
9179 } break; case IMAX_E_: { do_imax_e ();
9180 } break; case IMAX_IGNORE_UNDEFINED_: { do_imax_removeUndefined ();
9181 } break; case QUANTILE_: { do_quantile ();
9182 } break; case NORM_: { do_norm ();
9183 } break; case ZERO_VEC_: { do_zero_VEC ();
9184 } break; case ZERO_MAT_: { do_zero_MAT ();
9185 } break; case LINEAR_VEC_: { do_linear_VEC ();
9186 } break; case TO_VEC_: { do_to_VEC ();
9187 } break; case FROM_TO_VEC_: { do_from_to_VEC ();
9188 } break; case FROM_TO_BY_VEC_: { do_from_to_by_VEC ();
9189 } break; case FROM_TO_COUNT_VEC_: { do_from_to_count_VEC ();
9190 } break; case BETWEEN_BY_VEC_: { do_between_by_VEC ();
9191 } break; case BETWEEN_COUNT_VEC_: { do_between_count_VEC ();
9192 } break; case SORT_VEC_: { do_sort_VEC ();
9193 } break; case SORT_REMOVE_UNDEFINED_VEC_: { do_sort_removeUndefined_VEC ();
9194 } break; case SORT_STRVEC_: { do_sort_STRVEC ();
9195 } break; case SORT_NUMBER_AWARE_STRVEC_: { do_sort_numberAware_STRVEC ();
9196 } break; case SHUFFLE_VEC_: { do_shuffle_VEC ();
9197 } break; case SHUFFLE_STRVEC_: { do_shuffle_STRVEC ();
9198 } break; case RANDOM_UNIFORM_VEC_: { do_function_VECdd_d (NUMrandomUniform);
9199 } break; case RANDOM_UNIFORM_MAT_: { do_function_MATdd_d (NUMrandomUniform);
9200 } break; case RANDOM_INTEGER_VEC_: { do_function_VECll_l (NUMrandomInteger);
9201 } break; case RANDOM_INTEGER_MAT_: { do_function_MATll_l (NUMrandomInteger);
9202 } break; case RANDOM_GAUSS_VEC_: { do_function_VECdd_d (NUMrandomGauss);
9203 } break; case RANDOM_GAUSS_MAT_: { do_function_MATdd_d (NUMrandomGauss);
9204 } break; case RANDOM_GAMMA_VEC_: { do_function_VECdd_d (NUMrandomGamma);
9205 } break; case RANDOM_GAMMA_MAT_: { do_function_MATdd_d (NUMrandomGamma);
9206 } break; case SOLVE_SPARSE_VEC_ : { do_solveSparse_VEC ();
9207 } break; case SOLVE_NONNEGATIVE_VEC_ : { do_solveNonnegative_VEC ();
9208 } break; case PEAKS_MAT_: { do_peaks_MAT ();
9209 } break; case SIZE_: { do_size ();
9210 } break; case NUMBER_OF_ROWS_: { do_numberOfRows ();
9211 } break; case NUMBER_OF_COLUMNS_: { do_numberOfColumns ();
9212 } break; case COMBINE_VEC_: { do_combine_VEC ();
9213 } break; case BLAKE3_VEC_: { do_blake3_VEC ();
9214 } break; case PART_VEC_: { do_part_VEC ();
9215 } break; case PART_MAT_: { do_part_MAT ();
9216 } break; case EDITOR_: { do_editor ();
9217 } break; case RANDOM__INITIALIZE_WITH_SEED_UNSAFELY_BUT_PREDICTABLY_: { do_random_initializeWithSeedUnsafelyButPredictably ();
9218 } break; case RANDOM__INITIALIZE_SAFELY_AND_UNPREDICTABLY_: { do_random_initializeSafelyAndUnpredictably ();
9219 } break; case HASH_: { do_hash ();
9220 } break; case HEX_STR_: { do_hex_STR ();
9221 } break; case UNHEX_STR_: { do_unhex_STR ();
9222 } break; case EMPTY_STRVEC_: { do_empty_STRVEC ();
9223 } break; case READ_LINES_FROM_FILE_STRVEC_: { do_readLinesFromFile_STRVEC ();
9224 } break; case FILE_NAMES_STRVEC_: { do_fileNames_STRVEC ();
9225 } break; case FOLDER_NAMES_STRVEC_: { do_folderNames_STRVEC ();
9226 } break; case FILE_NAMES_CASE_INSENSITIVE_STRVEC_: { do_fileNames_caseInsensitive_STRVEC ();
9227 } break; case FOLDER_NAMES_CASE_INSENSITIVE_STRVEC_: { do_folderNames_caseInsensitive_STRVEC ();
9228 } break; case SPLIT_BY_WHITESPACE_STRVEC_: { do_splitByWhitespace_STRVEC ();
9229 } break; case SPLIT_BY_STRVEC_: { do_splitBy_STRVEC ();
9230 } break; case LOWER_CASE_STR_: { do_lowerCase_STR ();
9231 } break; case LOWER_CAMEL_CASE_STR_: { do_lowerCamelCase_STR ();
9232 } break; case LOWER_SNAKE_CASE_STR_: { do_lowerSnakeCase_STR ();
9233 } break; case UPPER_CASE_STR_: { do_upperCase_STR ();
9234 } break; case UPPER_CAMEL_CASE_STR_: { do_upperCamelCase_STR ();
9235 } break; case UPPER_SNAKE_CASE_STR_: { do_upperSnakeCase_STR ();
9236 /********** String functions of 1 variable: **********/
9237 } break; case LENGTH_: { do_length ();
9238 } break; case STRING_TO_NUMBER_: { do_number ();
9239 } break; case FILE_READABLE_: { do_fileReadable ();
9240 } break; case FOLDER_EXISTS_: { do_folderExists ();
9241 } break; case TRY_TO_WRITE_FILE_: { do_tryToWriteFile ();
9242 } break; case TRY_TO_APPEND_FILE_: { do_tryToAppendFile ();
9243 /********** String functions of 0 variables: **********/
9244 } break; case DATE_STR_: { do_date_STR ();
9245 } break; case DATE_UTC_STR_: { do_date_utc_STR ();
9246 } break; case DATE_ISO_STR_: { do_date_iso_STR ();
9247 } break; case DATE_UTC_ISO_STR_: { do_date_utc_iso_STR ();
9248 } break; case DATE_VEC_: { do_date_VEC ();
9249 } break; case DATE_UTC_VEC_: { do_date_utc_VEC ();
9250 } break; case INFO_STR_: { do_info_STR ();
9251 /********** String functions of 2 variables: **********/
9252 } break; case LEFT_STR_: { do_left_STR ();
9253 } break; case RIGHT_STR_: { do_right_STR ();
9254 } break; case MID_STR_: { do_mid_STR ();
9255 } break; case PAD_LEFT_STR_: { do_padLeft_STR ();
9256 } break; case PAD_RIGHT_STR_: { do_padRight_STR ();
9257 } break; case TRUNCATE_LEFT_STR_: { do_truncateLeft_STR ();
9258 } break; case TRUNCATE_RIGHT_STR_: { do_truncateRight_STR ();
9259 } break; case PAD_OR_TRUNCATE_LEFT_STR_: { do_padOrTruncateLeft_STR ();
9260 } break; case PAD_OR_TRUNCATE_RIGHT_STR_: { do_padOrTruncateRight_STR ();
9261 } break; case UNICODE_TO_BACKSLASH_TRIGRAPHS_STR_: { do_unicodeToBackslashTrigraphs_STR ();
9262 } break; case BACKSLASH_TRIGRAPHS_TO_UNICODE_STR_: { do_backslashTrigraphsToUnicode_STR ();
9263 } break; case ENVIRONMENT_STR_: { do_environment_STR ();
9264 } break; case INDEX_: { do_index ();
9265 } break; case INDEX_CASE_INSENSITIVE_: { do_index_caseInsensitive ();
9266 } break; case RINDEX_: { do_rindex ();
9267 } break; case RINDEX_CASE_INSENSITIVE_: { do_rindex_caseInsensitive ();
9268 } break; case STARTS_WITH_: { do_stringMatchesCriterion (kMelder_string::STARTS_WITH, true);
9269 } break; case STARTS_WITH_CASE_INSENSITIVE_: { do_stringMatchesCriterion (kMelder_string::STARTS_WITH, false);
9270 } break; case ENDS_WITH_: { do_stringMatchesCriterion (kMelder_string::ENDS_WITH, true);
9271 } break; case ENDS_WITH_CASE_INSENSITIVE_: { do_stringMatchesCriterion (kMelder_string::ENDS_WITH, false);
9272 } break; case INDEX_REGEX_: { do_index_regex (false);
9273 } break; case RINDEX_REGEX_: { do_index_regex (true);
9274 } break; case EXTRACT_NUMBER_: { do_extractNumber ();
9275 /********** Other string functions: **********/
9276 } break; case EXTRACT_WORD_STR_: { do_extractText_STR (true);
9277 } break; case EXTRACT_LINE_STR_: { do_extractText_STR (false);
9278 } break; case REPLACE_STR_: { do_replace_STR ();
9279 } break; case REPLACE_REGEX_STR_: { do_replace_regex_STR ();
9280 } break; case SELECTED_: { do_selected ();
9281 } break; case SELECTED_STR_: { do_selected_STR ();
9282 } break; case NUMBER_OF_SELECTED_: { do_numberOfSelected ();
9283 } break; case SELECTED_VEC_: { do_selected_VEC ();
9284 } break; case SELECTED_STRVEC_: { do_selected_STRVEC ();
9285 } break; case SELECT_OBJECT_: { do_selectObject ();
9286 } break; case PLUS_OBJECT_ : { do_plusObject ();
9287 } break; case MINUS_OBJECT_ : { do_minusObject ();
9288 } break; case REMOVE_OBJECT_: { do_removeObject ();
9289 } break; case OBJECT_XMIN_: { do_object_xmin ();
9290 } break; case OBJECT_XMAX_: { do_object_xmax ();
9291 } break; case OBJECT_YMIN_: { do_object_ymin ();
9292 } break; case OBJECT_YMAX_: { do_object_ymax ();
9293 } break; case OBJECT_NX_: { do_object_nx ();
9294 } break; case OBJECT_NY_: { do_object_ny ();
9295 } break; case OBJECT_DX_: { do_object_dx ();
9296 } break; case OBJECT_DY_: { do_object_dy ();
9297 } break; case OBJECT_NROW_: { do_object_nrow ();
9298 } break; case OBJECT_NCOL_: { do_object_ncol ();
9299 } break; case OBJECT_ROW_STR_: { do_object_row_STR ();
9300 } break; case OBJECT_COL_STR_: { do_object_col_STR ();
9301 } break; case STRING_STR_: { do_string_STR ();
9302 } break; case HORIZONTAL_STR_: { do_horizontal_STR ();
9303 } break; case VERTICAL_STR_: { do_vertical_STR ();
9304 } break; case NUMBERS_VEC_: { do_numbers_VEC ();
9305 } break; case SLEEP_: { do_sleep ();
9306 } break; case UNICODE_: { do_unicode ();
9307 } break; case UNICODE_STR_: { do_unicode_STR ();
9308 } break; case FIXED_STR_: { do_fixed_STR ();
9309 } break; case PERCENT_STR_: { do_percent_STR ();
9310 } break; case GRAPHICAL_PERCENT_STR_: { do_graphicalPercent_STR ();
9311 } break; case BIG_INTEGER_STR_: { do_bigInteger_STR ();
9312 } break; case HALF_STR_: { do_half_STR ();
9313 } break; case GRAPHICAL_HALF_STR_: { do_graphicalHalf_STR ();
9314 } break; case SINGLE_STR_: { do_single_STR ();
9315 } break; case GRAPHICAL_SINGLE_STR_: { do_graphicalSingle_STR ();
9316 } break; case DOUBLE_STR_: { do_double_STR ();
9317 } break; case GRAPHICAL_DOUBLE_STR_: { do_graphicalDouble_STR ();
9318 } break; case NATURAL_LOGARITHM_STR_: { do_naturalLogarithm_STR ();
9319 } break; case GRAPHICAL_NATURAL_LOGARITHM_STR_: { do_graphicalNaturalLogarithm_STR ();
9320 } break; case HEXADECIMAL_STR_: { do_hexadecimal_STR ();
9321 } break; case DELETE_FILE_: { do_deleteFile ();
9322 } break; case MOVE_AND_OR_RENAME_FILE_: { do_moveAndOrRenameFile ();
9323 } break; case CREATE_FOLDER_: { do_createFolder ();
9324 } break; case CREATE_DIRECTORY_: { do_createDirectory (); // deprecated 2020
9325 } break; case SET_WORKING_DIRECTORY_: { do_setWorkingDirectory (); // deprecated 2020
9326 } break; case VARIABLE_EXISTS_: { do_variableExists ();
9327 } break; case READ_FILE_: { do_readFile ();
9328 } break; case READ_FILE_STR_: { do_readFile_STR ();
9329 } break; case READ_FILE_VEC_: { do_readFile_VEC ();
9330 } break; case READ_FILE_MAT_: { do_readFile_MAT ();
9331 /********** Matrix functions: **********/
9332 } break; case ROW_VEC_: { do_row_VEC ();
9333 } break; case COL_VEC_: { do_col_VEC ();
9334 } break; case INNER_: { do_inner ();
9335 } break; case CORRELATION_: { do_correlation ();
9336 } break; case OUTER_MAT_: { do_outer_MAT ();
9337 } break; case MUL_VEC_: { do_mul_VEC ();
9338 } break; case MUL_MAT_: { do_mul_MAT ();
9339 } break; case MUL_FAST_MAT_: { do_mul_fast_MAT ();
9340 } break; case MUL_METAL_MAT_: { do_mul_metal_MAT ();
9341 } break; case MUL_TN_MAT_: { do_mul_tn_MAT ();
9342 } break; case MUL_NT_MAT_: { do_mul_nt_MAT ();
9343 } break; case MUL_TT_MAT_: { do_mul_tt_MAT ();
9344 } break; case REPEAT_VEC_: { do_repeat_VEC ();
9345 } break; case ROW_INNERS_VEC_: { do_rowInners_VEC ();
9346 } break; case SOLVE_VEC_: { do_solve_VEC ();
9347 } break; case SOLVE_MAT_: { do_solve_MAT ();
9348 } break; case SOLVE_WEAKLYCONSTRAINED_VEC_: { do_solveWeaklyConstrained_VEC ();
9349 /********** Pause window functions: **********/
9350 } break; case ASK_FOR_TRUST_: { do_askForTrust ();
9351 } break; case BEGIN_PAUSE_: { do_beginPause ();
9352 } break; case REAL_: { do_real ();
9353 } break; case POSITIVE_: { do_positive ();
9354 } break; case INTEGER_: { do_integer ();
9355 } break; case NATURAL_: { do_natural ();
9356 } break; case WORD_: { do_word ();
9357 } break; case SENTENCE_: { do_sentence ();
9358 } break; case TEXT_: { do_text ();
9359 } break; case BOOLEAN_: { do_boolean ();
9360 } break; case CHOICE_: { do_choice ();
9361 } break; case OPTIONMENU_: { do_optionmenu ();
9362 } break; case OPTION_MENU_: { do_optionmenu (); // alternative spelling, deprecated 2023
9363 } break; case OPTION_: { do_option ();
9364 } break; case INFILE_: { do_infile ();
9365 } break; case OUTFILE_: { do_outfile ();
9366 } break; case FOLDER_: { do_folder ();
9367 } break; case REALVECTOR_: { do_realvector ();
9368 } break; case POSITIVEVECTOR_: { do_positivevector ();
9369 } break; case INTEGERVECTOR_: { do_integervector ();
9370 } break; case NATURALVECTOR_: { do_naturalvector ();
9371 } break; case HEADING_: { do_heading ();
9372 } break; case COMMENT_: { do_comment ();
9373 } break; case END_PAUSE_: { do_endPause ();
9374 } break; case LOWER_CASE_APP_NAME_STR_: { do_lowerCaseAppNameStr ();
9375 } break; case UPPER_CASE_APP_NAME_STR_: { do_upperCaseAppNameStr ();
9376 } break; case CLOCK_: { do_clock ();
9377 } break; case APP_VERSION_: { do_appVersion ();
9378 } break; case APP_VERSION_STR_: { do_appVersionStr ();
9379 } break; case APP_YEAR_: { do_appYear ();
9380 } break; case APP_MONTH_: { do_appMonth ();
9381 } break; case APP_MONTH_STR_: { do_appMonthStr ();
9382 } break; case APP_DAY_: { do_appDay ();
9383 } break; case CHOOSE_READ_FILE_STR_: { do_chooseReadFileStr ();
9384 } break; case CHOOSE_WRITE_FILE_STR_: { do_chooseWriteFileStr ();
9385 } break; case CHOOSE_FOLDER_STR_: { do_chooseFolder_STR ();
9386 } break; case CHOOSE_DIRECTORY_STR_: { do_chooseDirectory_STR (); // deprecated 2020
9387 /********** Demo window functions: **********/
9388 } break; case DEMO_WINDOW_TITLE_: { do_demoWindowTitle ();
9389 } break; case DEMO_SHOW_: { do_demoShow ();
9390 } break; case DEMO_WAIT_FOR_INPUT_: { do_demoWaitForInput ();
9391 } break; case DEMO_PEEK_INPUT_: { do_demoPeekInput ();
9392 } break; case DEMO_INPUT_: { do_demoInput ();
9393 } break; case DEMO_CLICKED_IN_: { do_demoClickedIn ();
9394 } break; case DEMO_CLICKED_: { do_demoClicked ();
9395 } break; case DEMO_X_: { do_demoX ();
9396 } break; case DEMO_Y_: { do_demoY ();
9397 } break; case DEMO_KEY_PRESSED_: { do_demoKeyPressed ();
9398 } break; case DEMO_KEY_: { do_demoKey ();
9399 } break; case DEMO_SHIFT_KEY_PRESSED_: { do_demoShiftKeyPressed ();
9400 } break; case DEMO_COMMAND_KEY_PRESSED_: { do_demoCommandKeyPressed ();
9401 } break; case DEMO_OPTION_KEY_PRESSED_: { do_demoOptionKeyPressed ();
9402 /********** **********/
9403 } break; case TRUE_: {
9404 pushNumber (1.0);
9405 } break; case FALSE_: {
9406 pushNumber (0.0);
9407 } break; case IFTRUE_: {
9408 Stackel condition = pop;
9409 if (condition->which == Stackel_NUMBER) {
9410 if (condition->number != 0.0) {
9411 /* Possible compiler BUG: some compilers cannot handle the following assignment. */
9412 /* Those compilers will have trouble with praat's AND and OR. */
9413 programPointer = f [programPointer]. content.label - theOptimize;
9414 }
9415 } else {
9416 Melder_throw (U"A condition between “if” and “then” should be a number, not ", condition->whichText(), U".");
9417 }
9418 } break; case IFFALSE_: {
9419 Stackel condition = pop;
9420 if (condition->which == Stackel_NUMBER) {
9421 if (condition->number == 0.0) {
9422 programPointer = f [programPointer]. content.label - theOptimize;
9423 }
9424 } else {
9425 Melder_throw (U"A condition between “if” and “then” should be a number, not ", condition->whichText(), U".");
9426 }
9427 } break; case GOTO_: {
9428 programPointer = f [programPointer]. content.label - theOptimize;
9429 } break; case LABEL_: {
9430 ;
9431 } break; case DECREMENT_AND_ASSIGN_: {
9432 Stackel x = pop, v = pop;
9433 InterpreterVariable var = v->variable;
9434 var -> numericValue = x->number - 1.0;
9435 //Melder_casual (U"starting value ", var -> numericValue);
9436 pushVariable (var);
9437 } break; case INCREMENT_GREATER_GOTO_: {
9438 //Melder_casual (U"top of loop, stack depth ", stackPointer);
9439 Stackel e = & theStack [stackPointer], v = & theStack [stackPointer - 1];
9440 Melder_assert (e->which == Stackel_NUMBER);
9441 Melder_assert (v->which == Stackel_VARIABLE);
9442 InterpreterVariable var = v->variable;
9443 //Melder_casual (U"loop variable ", var -> numericValue);
9444 var -> numericValue += 1.0;
9445 //Melder_casual (U"loop variable ", var -> numericValue);
9446 //Melder_casual (U"end value ", e->number);
9447 if (var -> numericValue > e->number) {
9448 programPointer = f [programPointer]. content.label - theOptimize;
9449 }
9450 } break; case ADD_3DOWN_: {
9451 Stackel x = pop, s = & theStack [stackPointer - 2];
9452 Melder_assert (x->which == Stackel_NUMBER);
9453 Melder_assert (s->which == Stackel_NUMBER);
9454 //Melder_casual (U"to add ", x->number);
9455 s->number += x->number;
9456 //Melder_casual (U"sum ", s->number);
9457 } break; case POP_2_: {
9458 stackPointer -= 2;
9459 //Melder_casual (U"total ", theStack [stackPointer]. number);
9460 } break; case VEC_CELL_: { do_numericVectorElement ();
9461 } break; case MAT_CELL_: { do_numericMatrixElement ();
9462 } break; case STRVEC_CELL_: { do_stringVectorElement ();
9463 } break; case INDEXED_NUMERIC_VARIABLE_: { do_indexedNumericVariable ();
9464 } break; case INDEXED_STRING_VARIABLE_: { do_indexedStringVariable ();
9465 } break; case VARIABLE_REFERENCE_: {
9466 InterpreterVariable var = f [programPointer]. content.variable;
9467 pushVariable (var);
9468 } break; case SELF0_: { do_self0 (row, col);
9469 } break; case SELFSTR0_: { do_selfStr0 (row, col);
9470 } break; case OBJECT_: { pushObject (f [programPointer]. content.object);
9471 } break; case TO_OBJECT_: { do_toObject ();
9472 } break; case SELFMATRIX1_: { do_selfMatrix1 (row);
9473 } break; case SELFMATRIX1_STR_: { do_selfMatrix1_STR (row);
9474 } break; case SELFMATRIX2_: { do_selfMatrix2 ();
9475 } break; case SELFMATRIX2_STR_: { do_selfMatrix2_STR ();
9476 } break; case SELFFUNCTION1_: { do_selfFunction1 (row);
9477 } break; case SELFFUNCTION2_: { do_selfFunction2 ();
9478 } break; case OBJECTCELL0_: { do_objectCell0 (row, col);
9479 } break; case OBJECTCELL1_: { do_objectCell1 (row);
9480 } break; case OBJECTCELL1_STR_: { do_objectCell1_STR (row);
9481 } break; case OBJECTCELL2_: { do_objectCell2 ();
9482 } break; case OBJECTCELL2_STR_: { do_objectCell2_STR ();
9483 } break; case OBJECTLOCATION0_: { do_objectLocation0 (row, col);
9484 } break; case OBJECTLOCATION1_: { do_objectLocation1 (row);
9485 } break; case OBJECTLOCATION2_: { do_objectLocation2 ();
9486 } break; case MATRIX0_: { do_matrix0 (row, col);
9487 } break; case MATRIX1_: { do_matrix1 (row);
9488 } break; case MATRIX1_STR_: { do_matrix1_STR (row);
9489 } break; case MATRIX2_: { do_matrix2 ();
9490 } break; case MATRIX2_STR_: { do_matrix2_STR ();
9491 } break; case FUNCTION0_: { do_function0 (row, col);
9492 } break; case FUNCTION1_: { do_function1 (row);
9493 } break; case FUNCTION2_: { do_function2 ();
9494 } break; case ROW_STR_: { do_row_STR ();
9495 } break; case COL_STR_: { do_col_STR ();
9496 } break; case SQR_: { do_sqr ();
9497 } break; case STRING_: {
9498 autostring32 string = Melder_dup (f [programPointer]. content.string);
9499 pushString (string.move());
9500 } break; case TENSOR_LITERAL_: { do_tensorLiteral ();
9501 } break; case TENSOR_LITERAL_CELL_: { do_tensorLiteralCell ();
9502 } break; case NUMERIC_VARIABLE_: {
9503 InterpreterVariable var = f [programPointer]. content.variable;
9504 pushNumber (var -> numericValue);
9505 } break; case NUMERIC_VECTOR_VARIABLE_: {
9506 InterpreterVariable var = f [programPointer]. content.variable;
9507 pushNumericVectorReference (var -> numericVectorValue.get());
9508 } break; case NUMERIC_MATRIX_VARIABLE_: {
9509 InterpreterVariable var = f [programPointer]. content.variable;
9510 pushNumericMatrixReference (var -> numericMatrixValue.get());
9511 } break; case STRING_VARIABLE_: {
9512 InterpreterVariable var = f [programPointer]. content.variable;
9513 autostring32 string = Melder_dup (var -> stringValue.get());
9514 pushString (string.move());
9515 } break; case STRING_ARRAY_VARIABLE_: {
9516 InterpreterVariable var = f [programPointer]. content.variable;
9517 pushStringVectorReference (var -> stringArrayValue.get());
9518 } break; default: Melder_throw (U"Symbol “", Formula_instructionNames [parse [programPointer]. symbol], U"” without action.");
9519 } // endswitch
9520 programPointer ++;
9521 } // endwhile
9522 if (stackPointer != 1)
9523 Melder_crash (U"Formula: stackpointer ends at ", stackPointer, U" instead of 1.");
9524 /*
9525 Move the result from the stack to `result`.
9526 */
9527 result -> reset();
9528 if (theExpressionType [theLevel] == kFormula_EXPRESSION_TYPE_NUMERIC) {
9529 if (theStack [1]. which == Stackel_STRING)
9530 Melder_throw (U"Found a string expression instead of a numeric expression.");
9531 if (theStack [1]. which == Stackel_NUMERIC_VECTOR)
9532 Melder_throw (U"Found a vector expression instead of a numeric expression.");
9533 if (theStack [1]. which == Stackel_NUMERIC_MATRIX)
9534 Melder_throw (U"Found a matrix expression instead of a numeric expression.");
9535 if (theStack [1]. which == Stackel_STRING_ARRAY)
9536 Melder_throw (U"Found a string vector expression instead of a numeric expression.");
9537 Melder_assert (theStack [1]. which == Stackel_NUMBER);
9538 result -> expressionType = kFormula_EXPRESSION_TYPE_NUMERIC;
9539 result -> numericResult = theStack [1]. number;
9540 } else if (theExpressionType [theLevel] == kFormula_EXPRESSION_TYPE_STRING) {
9541 if (theStack [1]. which == Stackel_NUMBER)
9542 Melder_throw (U"Found a numeric expression (value ", theStack [1]. number, U") instead of a string expression.");
9543 if (theStack [1]. which == Stackel_NUMERIC_VECTOR)
9544 Melder_throw (U"Found a vector expression instead of a string expression.");
9545 if (theStack [1]. which == Stackel_NUMERIC_MATRIX)
9546 Melder_throw (U"Found a matrix expression instead of a string expression.");
9547 if (theStack [1]. which == Stackel_STRING_ARRAY)
9548 Melder_throw (U"Found a string vector expression instead of a string expression.");
9549 Melder_assert (theStack [1]. which == Stackel_STRING);
9550 result -> expressionType = kFormula_EXPRESSION_TYPE_STRING;
9551 Melder_assert (! result -> stringResult);
9552 result -> stringResult = theStack [1]. moveString();
9553 Melder_assert (theStack [1]. which == Stackel_STRING);
9554 Melder_assert (! theStack [1]. getString());
9555 } else if (theExpressionType [theLevel] == kFormula_EXPRESSION_TYPE_NUMERIC_VECTOR) {
9556 if (theStack [1]. which == Stackel_NUMBER)
9557 Melder_throw (U"Found a numeric expression instead of a vector expression.");
9558 if (theStack [1]. which == Stackel_STRING)
9559 Melder_throw (U"Found a string expression instead of a vector expression.");
9560 if (theStack [1]. which == Stackel_NUMERIC_MATRIX)
9561 Melder_throw (U"Found a matrix expression instead of a vector expression.");
9562 if (theStack [1]. which == Stackel_STRING_ARRAY)
9563 Melder_throw (U"Found a string vector expression instead of a numeric vector expression.");
9564 Melder_assert (theStack [1]. which == Stackel_NUMERIC_VECTOR);
9565 result -> expressionType = kFormula_EXPRESSION_TYPE_NUMERIC_VECTOR;
9566 result -> numericVectorResult = theStack [1]. numericVector;
9567 result -> owned = theStack [1]. owned;
9568 theStack [1]. owned = false;
9569 } else if (theExpressionType [theLevel] == kFormula_EXPRESSION_TYPE_NUMERIC_MATRIX) {
9570 if (theStack [1]. which == Stackel_NUMBER)
9571 Melder_throw (U"Found a numeric expression instead of a matrix expression.");
9572 if (theStack [1]. which == Stackel_STRING)
9573 Melder_throw (U"Found a string expression instead of a matrix expression.");
9574 if (theStack [1]. which == Stackel_NUMERIC_VECTOR)
9575 Melder_throw (U"Found a vector expression instead of a matrix expression.");
9576 if (theStack [1]. which == Stackel_STRING_ARRAY)
9577 Melder_throw (U"Found a string vector expression instead of a numeric matrix expression.");
9578 Melder_assert (theStack [1]. which == Stackel_NUMERIC_MATRIX);
9579 result -> expressionType = kFormula_EXPRESSION_TYPE_NUMERIC_MATRIX;
9580 result -> numericMatrixResult = theStack [1]. numericMatrix;
9581 result -> owned = theStack [1]. owned;
9582 theStack [1]. owned = false;
9583 } else if (theExpressionType [theLevel] == kFormula_EXPRESSION_TYPE_STRING_ARRAY) {
9584 if (theStack [1]. which == Stackel_NUMBER)
9585 Melder_throw (U"Found a numeric expression instead of a string vector expression.");
9586 if (theStack [1]. which == Stackel_STRING)
9587 Melder_throw (U"Found a string expression instead of a string vector expression.");
9588 if (theStack [1]. which == Stackel_NUMERIC_VECTOR)
9589 Melder_throw (U"Found a vector expression instead of a string vector expression.");
9590 if (theStack [1]. which == Stackel_NUMERIC_MATRIX)
9591 Melder_throw (U"Found a matrix expression instead of a string vector expression.");
9592 Melder_assert (theStack [1]. which == Stackel_STRING_ARRAY);
9593 result -> expressionType = kFormula_EXPRESSION_TYPE_STRING_ARRAY;
9594 result -> stringArrayResult = theStack [1]. stringArray;
9595 result -> owned = theStack [1]. owned;
9596 theStack [1]. owned = false;
9597 } else {
9598 Melder_assert (theExpressionType [theLevel] == kFormula_EXPRESSION_TYPE_UNKNOWN);
9599 if (theStack [1]. which == Stackel_NUMBER) {
9600 result -> expressionType = kFormula_EXPRESSION_TYPE_NUMERIC;
9601 result -> numericResult = theStack [1]. number;
9602 } else if (theStack [1]. which == Stackel_STRING) {
9603 result -> expressionType = kFormula_EXPRESSION_TYPE_STRING;
9604 Melder_assert (! result -> stringResult);
9605 result -> stringResult = theStack [1]. moveString();
9606 Melder_assert (theStack [1]. which == Stackel_STRING);
9607 Melder_assert (! theStack [1]. getString());
9608 } else if (theStack [1]. which == Stackel_NUMERIC_VECTOR) {
9609 result -> expressionType = kFormula_EXPRESSION_TYPE_NUMERIC_VECTOR;
9610 result -> numericVectorResult = theStack [1]. numericVector;
9611 result -> owned = theStack [1]. owned;
9612 theStack [1]. owned = false;
9613 } else if (theStack [1]. which == Stackel_NUMERIC_MATRIX) {
9614 result -> expressionType = kFormula_EXPRESSION_TYPE_NUMERIC_MATRIX;
9615 result -> numericMatrixResult = theStack [1]. numericMatrix;
9616 result -> owned = theStack [1]. owned;
9617 theStack [1]. owned = false;
9618 } else if (theStack [1]. which == Stackel_STRING_ARRAY) {
9619 result -> expressionType = kFormula_EXPRESSION_TYPE_STRING_ARRAY;
9620 result -> stringArrayResult = theStack [1]. stringArray;
9621 result -> owned = theStack [1]. owned;
9622 theStack [1]. owned = false;
9623 } else {
9624 Melder_throw (U"Don't know yet how to write ", theStack [1]. whichText(), U".");
9625 }
9626 }
9627 /*
9628 Clean up the stack (theStack [1] has probably been disowned).
9629 */
9630 for (stackPointer = stackPointerMax; stackPointer > 0; stackPointer --)
9631 theStack [stackPointer]. reset();
9632 } catch (MelderError) {
9633 /*
9634 Clean up the stack (theStack [1] has probably not been disowned).
9635 */
9636 for (stackPointer = stackPointerMax; stackPointer > 0; stackPointer --)
9637 theStack [stackPointer]. reset();
9638 if (Melder_hasError (U"Script exited.")) {
9639 throw;
9640 } else {
9641 Melder_throw (U"Formula not run.");
9642 }
9643 }
9644 }
9645
9646 /* End of file Formula.cpp */