Debian Codegraph @

sys/Formula.cpp

raw symbols SCIP
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 const integer numberOfArguments = Melder_iround (narg->number);
5457 Melder_require (narg->number == 1,
5458 U"The function “blake3#” requires exactly one argument (namely a matrix), not the ", narg->number, U" given.");
5459 const Stackel arg = pop;
5460 Melder_require (arg->which == Stackel_NUMERIC_MATRIX,
5461 U"The argument of the function “blake3#” should be a numeric matrix, not ", arg->whichText(), U".");
5462 const constMAT mat = arg->numericMatrix;
5463 pushNumericVector (blake3_VEC (mat));
5464 }
5465 static void do_part_VEC () {
5466 /*
5467 Check the number of arguments: always 3.
5468 */
5469 const Stackel s_narg = pop;
5470 Melder_assert (s_narg->which == Stackel_NUMBER);
5471 const integer narg = s_narg->number;
5472 Melder_require (narg == 3,
5473 U"The function “part#” requires exactly three arguments (namely a vector, a starting index, and an end index), not the ", narg, U" given.");
5474 /*
5475 Check the types of the arguments: always vector, number, number.
5476 */
5477 const Stackel s_last = pop, s_first = pop, s_vec = pop;
5478 Melder_require (s_vec->which == Stackel_NUMERIC_VECTOR,
5479 U"The first argument of the function “part#” should be a numeric vector, not ", s_vec->whichText(), U".");
5480 Melder_require (s_first->which == Stackel_NUMBER,
5481 U"The second argument of the function “part#” should be a number (the starting index), not ", s_first->whichText(), U".");
5482 Melder_require (s_last->which == Stackel_NUMBER,
5483 U"The third argument of the function “part#” should be a number (the end index), not ", s_last->whichText(), U".");
5484 /*
5485 Check the preconditions of the arguments.
5486 */
5487 const constVEC vec = s_vec->numericVector;
5488 const integer numberOfElements = vec.size;
5489 const integer first = Melder_iround (s_first->number);
5490 Melder_require (first > 0,
5491 U"The second argument of the function “part#” (the starting index) should (after rounding) be a positive whole number, not ", first, U".");
5492 Melder_require (first <= numberOfElements,
5493 U"The second argument of the function “part#” (the starting index) should (after rounding) be at most the number of elements (",
5494 numberOfElements, U"), not ", first, U"."
5495 );
5496 const integer last = Melder_iround (s_last->number);
5497 Melder_require (last > 0,
5498 U"The third argument of the function “part#” (the end index) should (after rounding) be a positive whole number, not ", last, U".");
5499 Melder_require (last <= numberOfElements,
5500 U"The third argument of the function “part#” (the end index) should (after rounding) be at most the number of elements (",
5501 numberOfElements, U"), not ", last, U"."
5502 );
5503
5504 const integer newSize = last - (first - 1);
5505 if (newSize > 0)
5506 pushNumericVector (copy_VEC (vec.part (first, last)));
5507 else
5508 pushNumericVector (autoVEC ());
5509 }
5510 static void do_part_MAT () {
5511 /*
5512 Check the number of arguments: always 5.
5513 */
5514 const Stackel s_narg = pop;
5515 Melder_assert (s_narg->which == Stackel_NUMBER);
5516 const integer narg = s_narg->number;
5517 Melder_require (narg == 5,
5518 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..");
5519 /*
5520 Check the types of the arguments: always matrix, number, number, number, number.
5521 */
5522 const Stackel s_endColumn = pop, s_startingColumn = pop, s_endRow = pop, s_startingRow = pop, s_mat = pop;
5523 Melder_require (s_mat->which == Stackel_NUMERIC_MATRIX,
5524 U"The first argument of the function “part##” should be a numeric matrix, not ", s_mat->whichText(), U".");
5525 Melder_require (s_startingRow->which == Stackel_NUMBER,
5526 U"The second argument of the function “part##” should be a number (the starting row), not ", s_startingRow->whichText(), U".");
5527 Melder_require (s_endRow->which == Stackel_NUMBER,
5528 U"The third argument of the function “part##” should be a number (the end row), not ", s_endRow->whichText(), U".");
5529 Melder_require (s_startingColumn->which == Stackel_NUMBER,
5530 U"The fourth argument of the function “part##” should be a number (the starting column), not ", s_startingColumn->whichText(), U".");
5531 Melder_require (s_endColumn->which == Stackel_NUMBER,
5532 U"The fifth argument of the function “part##” should be a number (the end column), not ", s_endColumn->whichText(), U".");
5533 /*
5534 Check the preconditions of the arguments.
5535 */
5536 const constMAT mat = s_mat->numericMatrix;
5537 const integer numberOfRows = mat.nrow, numberOfColumns = mat.ncol;
5538 const integer startingRow = Melder_iround (s_startingRow->number);
5539 Melder_require (startingRow > 0,
5540 U"The second argument of the function “part##” (the starting row) should (after rounding) be a positive whole number, not ", startingRow, U".");
5541 Melder_require (startingRow <= numberOfRows,
5542 U"The second argument of the function “part##” (the starting row) should (after rounding) be at most the number of rows (",
5543 numberOfRows, U"), not ", startingRow, U"."
5544 );
5545 const integer endRow = Melder_iround (s_endRow->number);
5546 Melder_require (endRow > 0,
5547 U"The third argument of the function “part##” (the end row) should (after rounding) be a positive whole number, not ", endRow, U".");
5548 Melder_require (endRow <= numberOfRows,
5549 U"The third argument of the function “part##” (the end row) should (after rounding) be at most the number of rows (",
5550 numberOfRows, U"), not ", endRow, U"."
5551 );
5552 const integer startingColumn = Melder_iround (s_startingColumn->number);
5553 Melder_require (startingColumn > 0,
5554 U"The fourth argument of the function “part##” (the starting column) should (after rounding) be a positive whole number, not ", startingColumn, U".");
5555 Melder_require (startingColumn <= numberOfColumns,
5556 U"The fourth argument of the function “part##” (the starting column) should (after rounding) be at most the number of columns (",
5557 numberOfColumns, U"), not ", startingColumn, U"."
5558 );
5559 const integer endColumn = Melder_iround (s_endColumn->number);
5560 Melder_require (endColumn > 0,
5561 U"The fifth argument of the function “part##” (the end column) should (after rounding) be a positive whole number, not ", endColumn, U".");
5562 Melder_require (endColumn <= numberOfColumns,
5563 U"The fifth argument of the function “part##” (the end column) should (after rounding) be at most the number of columns (",
5564 numberOfColumns, U"), not ", endColumn, U"."
5565 );
5566 pushNumericMatrix (copy_MAT (mat.part (startingRow, endRow, startingColumn, endColumn)));
5567 }
5568 static void do_editor () {
5569 const Stackel narg = pop;
5570 Melder_assert (narg->which == Stackel_NUMBER);
5571 if (narg->number == 0) {
5572 /*
5573 No editor mentioned, so switch back to the already existing editor.
5574 */
5575 if (theInterpreter && theInterpreter -> wasStartedFromEditorEnvironment())
5576 theInterpreter -> setDynamicFromOwningEditorEnvironment ();
5577 else
5578 Melder_throw (U"The function “editor” requires an argument when called from outside an editor.");
5579 } else if (narg->number == 1) {
5580 const Stackel editor = pop;
5581 if (editor->which == Stackel_STRING) {
5582 theInterpreter -> setDynamicEditorEnvironmentFromEditor (praat_findEditorFromString (editor->getString()));
5583 } else if (editor->which == Stackel_NUMBER) {
5584 theInterpreter -> setDynamicEditorEnvironmentFromEditor (praat_findEditorById (Melder_iround (editor->number)));
5585 } else {
5586 Melder_throw (U"The function “editor” requires a numeric or string argument, not ", editor->whichText(), U".");
5587 }
5588 } else {
5589 Melder_throw (U"The function “editor” requires 0 or 1 arguments, not ", narg->number, U".");
5590 }
5591 pushNumber (1);
5592 }
5593 static void do_random_initializeWithSeedUnsafelyButPredictably () {
5594 /*@praat
5595 #
5596 # A published test: the 10,000th element of the default 64-bit Mersenne Twister random sequence
5597 # should be 9'981'545'732'273'789'042.
5598 #
5599 random_initializeWithSeedUnsafelyButPredictably (5489)
5600 for i to 10000
5601 a = randomUniform (0, 1)
5602 endfor
5603 random_initializeSafelyAndUnpredictably ()
5604 a *= 2 ^ 64
5605 roundingError = a - 9981545732273789042
5606 writeInfoLine: fixed$ (a, 0), " ", roundingError
5607 assert roundingError <= 2048 ; actually usually zero
5608 @*/
5609 const Stackel narg = pop;
5610 if (narg->number == 1) {
5611 const Stackel s = pop;
5612 if (s->which == Stackel_NUMBER) {
5613 const double seed = s->number;
5614 if (seed < 0.0 || seed > double (INT54_MAX))
5615 Melder_throw (U"For the function “random_initializeWithSeedUnsafelyButPredictably”, "
5616 "the seed should be between 0 and ", double (INT54_MAX), U".");
5617 NUMrandom_initializeWithSeedUnsafelyButPredictably (uint64 (round (seed)));
5618 } else {
5619 Melder_throw (U"The function “hash” requires a string, not ", s->whichText(), U".");
5620 }
5621 } else {
5622 Melder_throw (U"The function “random_initializeWithSeedUnsafelyButPredictably” requires 1 argument (the seed), not ", narg->number, U".");
5623 }
5624 pushNumber (1);
5625 }
5626 static void do_random_initializeSafelyAndUnpredictably () {
5627 const Stackel narg = pop;
5628 Melder_require (narg->number == 0,
5629 U"The function “random_initializeSafelyAndUnpredictably” requires 0 arguments, not ", narg->number, U".");
5630 NUMrandom_initializeSafelyAndUnpredictably ();
5631 pushNumber (1);
5632 }
5633 static void do_hash () {
5634 const Stackel narg = pop;
5635 Melder_assert (narg->which == Stackel_NUMBER);
5636 if (narg->number == 1) {
5637 const Stackel s = pop;
5638 if (s->which == Stackel_STRING) {
5639 const double result = NUMhashString (s->getString());
5640 pushNumber (result);
5641 } else {
5642 Melder_throw (U"The function “hash” requires a string, not ", s->whichText(), U".");
5643 }
5644 } else {
5645 Melder_throw (U"The function “hash” requires 1 argument, not ", narg->number, U".");
5646 }
5647 }
5648 static void do_hex_STR () {
5649 const Stackel narg = pop;
5650 Melder_assert (narg->which == Stackel_NUMBER);
5651 if (narg->number == 1) {
5652 const Stackel s = pop;
5653 if (s->which == Stackel_STRING) {
5654 autostring32 result = hex_STR (s->getString());
5655 pushString (result.move());
5656 } else {
5657 Melder_throw (U"The function “hex$” requires a string, not ", s->whichText(), U".");
5658 }
5659 } else if (narg->number == 2) {
5660 const Stackel k = pop, s = pop;
5661 if (s->which == Stackel_STRING && k->which == Stackel_NUMBER) {
5662 autostring32 result = hex_STR (s->getString(), uint64 (round (k->number)));
5663 pushString (result.move());
5664 } else {
5665 Melder_throw (U"The function “hex$” requires a string and a number, not ", s->whichText(), U".");
5666 }
5667 } else {
5668 Melder_throw (U"The function “hex$” requires 1 or 2 arguments, not ", narg->number, U".");
5669 }
5670 }
5671 static void do_unhex_STR () {
5672 const Stackel narg = pop;
5673 Melder_assert (narg->which == Stackel_NUMBER);
5674 if (narg->number == 1) {
5675 const Stackel s = pop;
5676 if (s->which == Stackel_STRING) {
5677 autostring32 result = unhex_STR (s->getString());
5678 pushString (result.move());
5679 } else {
5680 Melder_throw (U"The function “unhex$” requires a string, not ", s->whichText(), U".");
5681 }
5682 } else if (narg->number == 2) {
5683 const Stackel k = pop, s = pop;
5684 if (s->which == Stackel_STRING && k->which == Stackel_NUMBER) {
5685 autostring32 result = unhex_STR (s->getString(), uint64 (round (k->number)));
5686 pushString (result.move());
5687 } else {
5688 Melder_throw (U"The function “unhex$” requires a string and a number, not ", s->whichText(), U".");
5689 }
5690 } else {
5691 Melder_throw (U"The function “unhex$” requires 1 or 2 arguments, not ", narg->number, U".");
5692 }
5693 }
5694 static void do_empty_STRVEC () {
5695 const Stackel narg = pop;
5696 Melder_assert (narg->which == Stackel_NUMBER);
5697 Melder_require (narg->number == 1,
5698 U"The function “empty$#” requires one argument, namely the number of elements.");
5699 const Stackel numberOfElements = pop;
5700 Melder_require (numberOfElements->which == Stackel_NUMBER,
5701 U"The argument of the function “empty$#” should be a number (namely the number of elements), not ", numberOfElements->whichText(), U".");
5702 autoSTRVEC result { Melder_iround (numberOfElements->number) };
5703 pushStringVector (result.move());
5704 }
5705 static void do_readLinesFromFile_STRVEC () {
5706 const Stackel narg = pop;
5707 Melder_assert (narg->which == Stackel_NUMBER);
5708 Melder_require (narg->number == 1,
5709 U"The function “readLinesFromFile$#” requires one argument, namely the file pattern.");
5710 const Stackel fileName = pop;
5711 if (fileName->which != Stackel_STRING)
5712 Melder_throw (U"The argument of the function “readLinesFromFile$#” should be a string (namely the file pattern), not ", fileName->whichText(), U".");
5713 structMelderFile file { };
5714 Melder_relativePathToFile (fileName->getString(), & file);
5715 autoSTRVEC result = readLinesFromFile_STRVEC (& file);
5716 pushStringVector (result.move());
5717 }
5718 static void do_fileNames_STRVEC () {
5719 const Stackel narg = pop;
5720 Melder_assert (narg->which == Stackel_NUMBER);
5721 Melder_require (narg->number == 1,
5722 U"The function “fileNames$#” requires one argument, namely the file pattern.");
5723 const Stackel filePattern = pop;
5724 if (filePattern->which != Stackel_STRING)
5725 Melder_throw (U"The argument of the function “fileNames$#” should be a string (namely the file path and pattern), not ", filePattern->whichText(), U".");
5726 autoSTRVEC result = fileNames_STRVEC (filePattern->getString());
5727 pushStringVector (result.move());
5728 }
5729 static void do_folderNames_STRVEC () {
5730 const Stackel narg = pop;
5731 Melder_assert (narg->which == Stackel_NUMBER);
5732 Melder_require (narg->number == 1,
5733 U"The function “folderNames$#” requires one argument, namely the file pattern.");
5734 const Stackel folderPattern = pop;
5735 Melder_require (folderPattern->which == Stackel_STRING,
5736 U"The argument of the function “folderNames$#” should be a string (namely the folder path), not ", folderPattern->whichText(), U".");
5737 autoSTRVEC result = folderNames_STRVEC (folderPattern->getString());
5738 pushStringVector (result.move());
5739 }
5740 static void do_fileNames_caseInsensitive_STRVEC () {
5741 const Stackel narg = pop;
5742 Melder_assert (narg->which == Stackel_NUMBER);
5743 Melder_require (narg->number == 1,
5744 U"The function “fileNames_caseInsensitive$#” requires one argument, namely the file pattern.");
5745 const Stackel filePattern = pop;
5746 if (filePattern->which != Stackel_STRING)
5747 Melder_throw (U"The argument of the function “fileNames_caseInsensitive$#” should be a string (namely the file path and pattern), not ", filePattern->whichText(), U".");
5748 autoSTRVEC result = fileNames_caseInsensitive_STRVEC (filePattern->getString());
5749 pushStringVector (result.move());
5750 }
5751 static void do_folderNames_caseInsensitive_STRVEC () {
5752 const Stackel narg = pop;
5753 Melder_assert (narg->which == Stackel_NUMBER);
5754 Melder_require (narg->number == 1,
5755 U"The function “folderNames_caseInsensitive$#” requires one argument, namely the file pattern.");
5756 const Stackel folderPattern = pop;
5757 Melder_require (folderPattern->which == Stackel_STRING,
5758 U"The argument of the function “folderNames_caseInsensitive$#” should be a string (namely the folder path), not ", folderPattern->whichText(), U".");
5759 autoSTRVEC result = folderNames_caseInsensitive_STRVEC (folderPattern->getString());
5760 pushStringVector (result.move());
5761 }
5762 static void do_splitByWhitespace_STRVEC () {
5763 const Stackel narg = pop;
5764 Melder_assert (narg -> which == Stackel_NUMBER);
5765 Melder_require (narg->number == 1,
5766 U"The function “splitByWhitespace$#” requires one argument, namely the string to split.");
5767 const Stackel string = pop;
5768 Melder_require (string->which == Stackel_STRING,
5769 U"The argument of the function “splitByWhitespace$#” should be a string, not ", string->whichText(), U".");
5770 autoSTRVEC result = splitByWhitespace_STRVEC (string->getString());
5771 pushStringVector (result.move());
5772 }
5773 static void do_splitBy_STRVEC () {
5774 const Stackel narg = pop;
5775 Melder_assert (narg -> which == Stackel_NUMBER);
5776 Melder_require (narg->number == 2,
5777 U"The function “splitBy$#” requires two arguments, namely the string to split and the separator.");
5778 const Stackel separator = pop, string = pop;
5779 Melder_require (string->which == Stackel_STRING,
5780 U"The first argument of the function “splitBy$#” should be a string, not ", string->whichText(), U".");
5781 Melder_require (separator->which == Stackel_STRING,
5782 U"The second argument of the function “splitBy$#” (the separator) should be a string, not ", string->whichText(), U".");
5783 autoSTRVEC result = splitBy_STRVEC (string->getString(), separator->getString());
5784 pushStringVector (result.move());
5785 }
5786 static void do_lowerCase_STR () {
5787 const Stackel narg = pop;
5788 Melder_assert (narg->which == Stackel_NUMBER);
5789 if (narg->number == 1) {
5790 const Stackel s = pop;
5791 if (s->which == Stackel_STRING) {
5792 autostring32 result = lowerCase_STR (s->getString());
5793 pushString (result.move());
5794 } else {
5795 Melder_throw (U"The function “lowerCase$” requires a string, not ", s->whichText(), U".");
5796 }
5797 } else {
5798 Melder_throw (U"The function “lowerCase$” requires 1 argument, not ", narg->number, U".");
5799 }
5800 }
5801 static void do_lowerCamelCase_STR () {
5802 const Stackel narg = pop;
5803 Melder_assert (narg->which == Stackel_NUMBER);
5804 if (narg->number == 1) {
5805 const Stackel s = pop;
5806 if (s->which == Stackel_STRING) {
5807 autostring32 result = lowerCamelCase_STR (s->getString());
5808 pushString (result.move());
5809 } else {
5810 Melder_throw (U"The function “lowerCamelCase$” requires a string, not ", s->whichText(), U".");
5811 }
5812 } else {
5813 Melder_throw (U"The function “lowerCamelCase$” requires 1 argument, not ", narg->number, U".");
5814 }
5815 }
5816 static void do_lowerSnakeCase_STR () {
5817 const Stackel narg = pop;
5818 Melder_assert (narg->which == Stackel_NUMBER);
5819 if (narg->number == 1) {
5820 const Stackel s = pop;
5821 if (s->which == Stackel_STRING) {
5822 autostring32 result = lowerSnakeCase_STR (s->getString());
5823 pushString (result.move());
5824 } else {
5825 Melder_throw (U"The function “lowerSnakeCase$” requires a string, not ", s->whichText(), U".");
5826 }
5827 } else {
5828 Melder_throw (U"The function “lowerSnakeCase$” requires 1 argument, not ", narg->number, U".");
5829 }
5830 }
5831 static void do_upperCase_STR () {
5832 const Stackel narg = pop;
5833 Melder_assert (narg->which == Stackel_NUMBER);
5834 if (narg->number == 1) {
5835 const Stackel s = pop;
5836 if (s->which == Stackel_STRING) {
5837 autostring32 result = upperCase_STR (s->getString());
5838 pushString (result.move());
5839 } else {
5840 Melder_throw (U"The function “upperCase$” requires a string, not ", s->whichText(), U".");
5841 }
5842 } else {
5843 Melder_throw (U"The function “upperCase$” requires 1 argument, not ", narg->number, U".");
5844 }
5845 }
5846 static void do_upperCamelCase_STR () {
5847 const Stackel narg = pop;
5848 Melder_assert (narg->which == Stackel_NUMBER);
5849 if (narg->number == 1) {
5850 const Stackel s = pop;
5851 if (s->which == Stackel_STRING) {
5852 autostring32 result = upperCamelCase_STR (s->getString());
5853 pushString (result.move());
5854 } else {
5855 Melder_throw (U"The function “upperCamelCase$” requires a string, not ", s->whichText(), U".");
5856 }
5857 } else {
5858 Melder_throw (U"The function “upperCamelCase$” requires 1 argument, not ", narg->number, U".");
5859 }
5860 }
5861 static void do_upperSnakeCase_STR () {
5862 const Stackel narg = pop;
5863 Melder_assert (narg->which == Stackel_NUMBER);
5864 if (narg->number == 1) {
5865 const Stackel s = pop;
5866 if (s->which == Stackel_STRING) {
5867 autostring32 result = upperSnakeCase_STR (s->getString());
5868 pushString (result.move());
5869 } else {
5870 Melder_throw (U"The function “upperSnakeCase$” requires a string, not ", s->whichText(), U".");
5871 }
5872 } else {
5873 Melder_throw (U"The function “upperSnakeCase$” requires 1 argument, not ", narg->number, U".");
5874 }
5875 }
5876 static void do_numericVectorElement () {
5877 InterpreterVariable vector = parse [programPointer]. content.variable;
5878 const Stackel element = pop;
5879 Melder_require (element->which == Stackel_NUMBER,
5880 U"In vector indexing, the index should be a number, not ", element->whichText(), U".");
5881 Melder_require (isdefined (element->number),
5882 U"The element index is undefined.");
5883 const integer ielement = Melder_iround (element->number);
5884 Melder_require (ielement > 0,
5885 U"In vector indexing, the element index should be positive.");
5886 Melder_require (ielement <= vector->numericVectorValue.size,
5887 U"Element index out of bounds. Looking for element ", ielement,
5888 U", but there are only ", vector->numericVectorValue.size, U" elements."
5889 );
5890 pushNumber (vector->numericVectorValue [ielement]);
5891 }
5892 static void do_numericMatrixElement () {
5893 InterpreterVariable matrix = parse [programPointer]. content.variable;
5894 const Stackel column = pop;
5895 Melder_require (column->which == Stackel_NUMBER,
5896 U"In matrix indexing, the column index should be a number, not ", column->whichText(), U".");
5897 Melder_require (isdefined (column->number),
5898 U"The column index is undefined.");
5899 const integer icolumn = Melder_iround (column->number);
5900 Melder_require (icolumn > 0,
5901 U"In matrix indexing, the column index should be positive.");
5902 Melder_require (icolumn <= matrix->numericMatrixValue. ncol,
5903 U"Column index out of bounds. Looking for column ", icolumn,
5904 U", but there are only ", matrix->numericMatrixValue. ncol, U" columns."
5905 );
5906 const Stackel row = pop;
5907 Melder_require (row->which == Stackel_NUMBER,
5908 U"In matrix indexing, the row index should be a number, not ", row->whichText(), U".");
5909 Melder_require (isdefined (row->number),
5910 U"The row index is undefined.");
5911 const integer irow = Melder_iround (row->number);
5912 Melder_require (irow > 0,
5913 U"In matrix indexing, the row index should be positive.");
5914 Melder_require (irow <= matrix->numericMatrixValue. nrow,
5915 U"Row index out of bounds. Looking for row ", irow,
5916 U", but there are only ", matrix->numericMatrixValue. nrow, U" rows."
5917 );
5918 pushNumber (matrix->numericMatrixValue [irow] [icolumn]);
5919 }
5920 static void do_stringVectorElement () {
5921 InterpreterVariable vector = parse [programPointer]. content.variable;
5922 const Stackel element = pop;
5923 Melder_require (element->which == Stackel_NUMBER,
5924 U"In vector indexing, the index should be a number, not ", element->whichText(), U".");
5925 Melder_require (isdefined (element->number),
5926 U"The element index is undefined.");
5927 const integer ielement = Melder_iround (element->number);
5928 Melder_require (ielement > 0,
5929 U"In vector indexing, the element index should be positive.");
5930 Melder_require (ielement <= vector->stringArrayValue.size,
5931 U"Element index out of bounds. Looking for element ", ielement,
5932 U", but there are only ", vector->stringArrayValue.size, U" elements."
5933 );
5934 pushString (Melder_dup (vector->stringArrayValue [ielement].get()));
5935 }
5936 static void do_indexedNumericVariable () {
5937 const Stackel narg = pop;
5938 Melder_assert (narg->which == Stackel_NUMBER);
5939 const integer nindex = Melder_iround (narg->number);
5940 Melder_require (nindex >= 1,
5941 U"Indexed variables require at least one index.");
5942 char32 *indexedVariableName = parse [programPointer]. content.string;
5943 static MelderString totalVariableName;
5944 MelderString_copy (& totalVariableName, indexedVariableName, U"[");
5945 stackPointer -= nindex;
5946 for (int iindex = 1; iindex <= nindex; iindex ++) {
5947 const Stackel index = & theStack [stackPointer + iindex];
5948 if (index->which == Stackel_NUMBER) {
5949 MelderString_append (& totalVariableName, index->number, iindex == nindex ? U"]" : U",");
5950 } else if (index -> which == Stackel_STRING) {
5951 MelderString_append (& totalVariableName, U"\"", index->getString(), U"\"", iindex == nindex ? U"]" : U",");
5952 } else {
5953 Melder_throw (U"In indexed variables, the index should be a number or a string, not ", index->whichText(), U".");
5954 }
5955 }
5956 InterpreterVariable var = Interpreter_hasVariable (theInterpreter, totalVariableName.string);
5957 Melder_require (!! var,
5958 U"Undefined indexed variable «", totalVariableName.string, U"».");
5959 pushNumber (var -> numericValue);
5960 }
5961 static void do_indexedStringVariable () {
5962 const Stackel narg = pop;
5963 Melder_assert (narg->which == Stackel_NUMBER);
5964 const integer nindex = Melder_iround (narg->number);
5965 Melder_require (nindex >= 1,
5966 U"Indexed variables require at least one index.");
5967 char32 *indexedVariableName = parse [programPointer]. content.string;
5968 static MelderString totalVariableName;
5969 MelderString_copy (& totalVariableName, indexedVariableName, U"[");
5970 stackPointer -= nindex;
5971 for (int iindex = 1; iindex <= nindex; iindex ++) {
5972 const Stackel index = & theStack [stackPointer + iindex];
5973 if (index->which == Stackel_NUMBER) {
5974 MelderString_append (& totalVariableName, index -> number, iindex == nindex ? U"]" : U",");
5975 } else if (index -> which == Stackel_STRING) {
5976 MelderString_append (& totalVariableName, U"\"", index -> getString(), U"\"", iindex == nindex ? U"]" : U",");
5977 } else {
5978 Melder_throw (U"In indexed variables, the index should be a number or a string, not ", index->whichText(), U".");
5979 }
5980 }
5981 InterpreterVariable var = Interpreter_hasVariable (theInterpreter, totalVariableName.string);
5982 Melder_require (!! var,
5983 U"Undefined indexed variable «", totalVariableName.string, U"».");
5984 autostring32 result = Melder_dup (var -> stringValue.get());
5985 pushString (result.move());
5986 }
5987 static void do_length () {
5988 const Stackel s = pop;
5989 if (s->which == Stackel_STRING) {
5990 const double result = NUMlength (s->getString());
5991 pushNumber (result);
5992 } else {
5993 Melder_throw (U"The function “length” requires a string, not ", s->whichText(), U".");
5994 }
5995 }
5996 static void do_number () {
5997 const Stackel s = pop;
5998 if (s->which == Stackel_STRING) {
5999 double result = Melder_atof (s->getString());
6000 pushNumber (result);
6001 } else {
6002 Melder_throw (U"The function “number” requires a string, not ", s->whichText(), U".");
6003 }
6004 }
6005 static void do_fileReadable () {
6006 const Stackel s = pop;
6007 if (s->which == Stackel_STRING) {
6008 structMelderFile file { };
6009 Melder_relativePathToFile (s->getString(), & file);
6010 pushNumber (MelderFile_readable (& file));
6011 } else {
6012 Melder_throw (U"The function “fileReadable” requires a string, not ", s->whichText(), U".");
6013 }
6014 }
6015 static void do_folderExists () {
6016 const Stackel s = pop;
6017 if (s->which == Stackel_STRING) {
6018 structMelderFolder folder { };
6019 Melder_relativePathToFolder (s->getString(), & folder);
6020 pushNumber (MelderFolder_exists (& folder));
6021 } else {
6022 Melder_throw (U"The function “folderExists” requires a string, not ", s->whichText(), U".");
6023 }
6024 }
6025 static void do_tryToWriteFile () {
6026 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
6027 U"The function “tryToWriteFile” is not available inside manuals.");
6028 const Stackel s = pop;
6029 if (s->which == Stackel_STRING) {
6030 structMelderFile file { };
6031 Melder_relativePathToFile (s->getString(), & file);
6032 Melder_checkTrust (theInterpreter, U"try to write to the file\n", & file);
6033 pushNumber (Melder_tryToWriteFile (& file));
6034 } else {
6035 Melder_throw (U"The function “tryToWriteFile” requires a string, not ", s->whichText(), U".");
6036 }
6037 }
6038 static void do_tryToAppendFile () {
6039 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
6040 U"The function “tryToAppendFile” is not available inside manuals.");
6041 const Stackel s = pop;
6042 if (s->which == Stackel_STRING) {
6043 structMelderFile file { };
6044 Melder_relativePathToFile (s->getString(), & file);
6045 Melder_checkTrust (theInterpreter, U"try to append to the file\n", & file);
6046 pushNumber (Melder_tryToAppendFile (& file));
6047 } else {
6048 Melder_throw (U"The function “tryToAppendFile” requires a string, not ", s->whichText(), U".");
6049 }
6050 }
6051 static void do_date_STR () {
6052 pushString (date_STR ());
6053 }
6054 static void do_date_utc_STR () {
6055 pushString (date_utc_STR ());
6056 }
6057 static void do_date_iso_STR () {
6058 pushString (date_iso_STR ());
6059 }
6060 static void do_date_utc_iso_STR () {
6061 pushString (date_utc_iso_STR ());
6062 }
6063 static void do_date_VEC () {
6064 pushNumericVector (date_VEC ());
6065 }
6066 static void do_date_utc_VEC () {
6067 pushNumericVector (date_utc_VEC ());
6068 }
6069 static void do_info_STR () {
6070 autostring32 info = Melder_dup (Melder_getInfo ());
6071 pushString (info.move());
6072 }
6073 static void do_left_STR () {
6074 const Stackel narg = pop;
6075 if (narg->number == 1) {
6076 const Stackel s = pop;
6077 if (s->which == Stackel_STRING) {
6078 pushString (left_STR (s->getString()));
6079 } else {
6080 Melder_throw (U"The function “left$” requires a string (or a string and a number).");
6081 }
6082 } else if (narg->number == 2) {
6083 const Stackel n = pop, s = pop;
6084 if (s->which == Stackel_STRING && n->which == Stackel_NUMBER) {
6085 pushString (left_STR (s->getString(), Melder_iround (n->number)));
6086 } else {
6087 Melder_throw (U"The function “left$” requires a string and a number (or a string only).");
6088 }
6089 } else {
6090 Melder_throw (U"The function “left$” requires one or two arguments: a string and optionally a number.");
6091 }
6092 trace (U"exit");
6093 }
6094 static void do_right_STR () {
6095 const Stackel narg = pop;
6096 if (narg->number == 1) {
6097 const Stackel s = pop;
6098 if (s->which == Stackel_STRING) {
6099 pushString (right_STR (s->getString()));
6100 } else {
6101 Melder_throw (U"The function “right$” requires a string (or a string and a number).");
6102 }
6103 } else if (narg->number == 2) {
6104 const Stackel n = pop, s = pop;
6105 if (s->which == Stackel_STRING && n->which == Stackel_NUMBER) {
6106 pushString (right_STR (s->getString(), Melder_iround (n->number)));
6107 } else {
6108 Melder_throw (U"The function “right$” requires a string and a number (or a string only).");
6109 }
6110 } else {
6111 Melder_throw (U"The function “right$” requires one or two arguments: a string and optionally a number.");
6112 }
6113 }
6114 static void do_mid_STR () {
6115 const Stackel narg = pop;
6116 if (narg->number == 2) {
6117 const Stackel position = pop, str = pop;
6118 if (str->which == Stackel_STRING && position->which == Stackel_NUMBER) {
6119 pushString (mid_STR (str->getString(), Melder_iround (position->number)));
6120 } else {
6121 Melder_throw (U"The function “mid$” requires a string and a number (or two).");
6122 }
6123 } else if (narg->number == 3) {
6124 const Stackel numberOfCharacters = pop, startingPosition = pop, str = pop;
6125 if (str->which == Stackel_STRING && startingPosition->which == Stackel_NUMBER && numberOfCharacters->which == Stackel_NUMBER) {
6126 pushString (mid_STR (str->getString(), Melder_iround (startingPosition->number), Melder_iround (numberOfCharacters->number)));
6127 } else {
6128 Melder_throw (U"The function “mid$” requires a string and two numbers (or one).");
6129 }
6130 } else {
6131 Melder_throw (U"The function “mid$” requires two or three arguments.");
6132 }
6133 }
6134 static void do_padLeft_STR () {
6135 const Stackel narg = pop;
6136 if (narg->number == 2) {
6137 const Stackel width = pop, str = pop;
6138 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER)
6139 pushString (padLeft_STR (str->getString(), Melder_iround (width->number)));
6140 else
6141 Melder_throw (U"The two arguments to “padLeft$” should be a string and a number (the desired width), not ",
6142 str->whichText(), U" and ", width->whichText(), U".");
6143 } else if (narg->number == 3) {
6144 const Stackel pad = pop, width = pop, str = pop;
6145 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER && pad->which == Stackel_STRING)
6146 pushString (padLeft_STR (str->getString(), Melder_iround (width->number), pad->getString()));
6147 else
6148 Melder_throw (U"The three arguments to “padLeft$” should be a string, a number (the desired width),"
6149 U" and a string (the pad), not ", str->whichText(), U", ", width->whichText(),
6150 U" and ", pad->whichText(), U"."
6151 );
6152 } else
6153 Melder_throw (U"The function “padLeft$” requires two or three arguments (a string, a number, and an optional pad string).");
6154 }
6155 static void do_padRight_STR () {
6156 const Stackel narg = pop;
6157 if (narg->number == 2) {
6158 const Stackel width = pop, str = pop;
6159 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER)
6160 pushString (padRight_STR (str->getString(), Melder_iround (width->number)));
6161 else
6162 Melder_throw (U"The two arguments to “padRight$” should be a string and a number (the desired width), not ",
6163 str->whichText(), U" and ", width->whichText(), U".");
6164 } else if (narg->number == 3) {
6165 const Stackel pad = pop, width = pop, str = pop;
6166 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER && pad->which == Stackel_STRING)
6167 pushString (padRight_STR (str->getString(), Melder_iround (width->number), pad->getString()));
6168 else
6169 Melder_throw (U"The three arguments to “padRight$” should be a string, a number (the desired width),"
6170 U" and a string (the pad), not ", str->whichText(), U", ", width->whichText(),
6171 U" and ", pad->whichText(), U"."
6172 );
6173 } else
6174 Melder_throw (U"The function “padRight$” requires two or three arguments (a string, a number, and an optional pad string).");
6175 }
6176 static void do_truncateLeft_STR () {
6177 const Stackel narg = pop;
6178 if (narg->number == 2) {
6179 const Stackel width = pop, str = pop;
6180 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER)
6181 pushString (truncateLeft_STR (str->getString(), Melder_iround (width->number)));
6182 else
6183 Melder_throw (U"The two arguments to “truncateLeft$” should be a string and a number (the desired width), not ",
6184 str->whichText(), U" and ", width->whichText(), U".");
6185 } else
6186 Melder_throw (U"The function “truncateLeft$” requires two arguments: a string and a number (the desired width).");
6187 }
6188 static void do_truncateRight_STR () {
6189 const Stackel narg = pop;
6190 if (narg->number == 2) {
6191 const Stackel width = pop, str = pop;
6192 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER)
6193 pushString (truncateRight_STR (str->getString(), Melder_iround (width->number)));
6194 else
6195 Melder_throw (U"The two arguments to “truncateRight$” should be a string and a number (the desired width), not ",
6196 str->whichText(), U" and ", width->whichText(), U".");
6197 } else
6198 Melder_throw (U"The function “truncateRight$” requires two arguments: a string and a number (the desired width).");
6199 }
6200 static void do_padOrTruncateLeft_STR () {
6201 const Stackel narg = pop;
6202 if (narg->number == 2) {
6203 const Stackel width = pop, str = pop;
6204 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER)
6205 pushString (padOrTruncateLeft_STR (str->getString(), Melder_iround (width->number)));
6206 else
6207 Melder_throw (U"The two arguments to “padOrTruncateLeft$” should be a string and a number (the desired width), not ",
6208 str->whichText(), U" and ", width->whichText(), U".");
6209 } else if (narg->number == 3) {
6210 const Stackel pad = pop, width = pop, str = pop;
6211 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER && pad->which == Stackel_STRING)
6212 pushString (padOrTruncateLeft_STR (str->getString(), Melder_iround (width->number), pad->getString()));
6213 else
6214 Melder_throw (U"The three arguments to “padOrTruncateLeft$” should be a string, a number (the desired width),"
6215 U" and a string (the pad), not ", str->whichText(), U", ", width->whichText(),
6216 U" and ", pad->whichText(), U"."
6217 );
6218 } else
6219 Melder_throw (U"The function “padOrTruncateLeft$” requires two or three arguments (a string, a number, and an optional pad string).");
6220 }
6221 static void do_padOrTruncateRight_STR () {
6222 const Stackel narg = pop;
6223 if (narg->number == 2) {
6224 const Stackel width = pop, str = pop;
6225 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER)
6226 pushString (padOrTruncateRight_STR (str->getString(), Melder_iround (width->number)));
6227 else
6228 Melder_throw (U"The two arguments to “padOrTruncateRight$” should be a string and a number (the desired width), not ",
6229 str->whichText(), U" and ", width->whichText(), U".");
6230 } else if (narg->number == 3) {
6231 const Stackel pad = pop, width = pop, str = pop;
6232 if (str->which == Stackel_STRING && width->which == Stackel_NUMBER && pad->which == Stackel_STRING)
6233 pushString (padOrTruncateRight_STR (str->getString(), Melder_iround (width->number), pad->getString()));
6234 else
6235 Melder_throw (U"The three arguments to “padOrTruncateRight$” should be a string, a number (the desired width),"
6236 U" and a string (the pad), not ", str->whichText(), U", ", width->whichText(),
6237 U" and ", pad->whichText(), U"."
6238 );
6239 } else
6240 Melder_throw (U"The function “padOrTruncateRight$” requires two or three arguments (a string, a number, and an optional pad string).");
6241 }
6242 static void do_unicodeToBackslashTrigraphs_STR () {
6243 const Stackel s = pop;
6244 if (s->which == Stackel_STRING) {
6245 const integer length = Melder_length (s->getString());
6246 autostring32 trigraphs (3 * length);
6247 Longchar_genericize (s->getString(), trigraphs.get());
6248 pushString (trigraphs.move());
6249 } else {
6250 Melder_throw (U"The function “unicodeToBackslashTrigraphs$” requires a string, not ", s->whichText(), U".");
6251 }
6252 }
6253 static void do_backslashTrigraphsToUnicode_STR () {
6254 const Stackel s = pop;
6255 if (s->which == Stackel_STRING) {
6256 const integer length = Melder_length (s->getString());
6257 autostring32 unicode (length);
6258 Longchar_nativize (s->getString(), unicode.get(), false); // noexcept
6259 pushString (unicode.move());
6260 } else {
6261 Melder_throw (U"The function “unicodeToBackslashTrigraphs$” requires a string, not ", s->whichText(), U".");
6262 }
6263 }
6264 static void do_environment_STR () {
6265 const Stackel s = pop;
6266 if (s->which == Stackel_STRING) {
6267 const conststring32 value = Melder_getenv (s->getString());
6268 autostring32 result = Melder_dup (value ? value : U"");
6269 pushString (result.move());
6270 } else {
6271 Melder_throw (U"The function “environment$” requires a string, not ", s->whichText(), U".");
6272 }
6273 }
6274 static void do_index () {
6275 const Stackel t = pop, s = pop;
6276 if (s->which == Stackel_STRING && t->which == Stackel_STRING) {
6277 char32 *substring = str32str (s->getString(), t->getString());
6278 const integer result = ( substring ? substring - s->getString() + 1 : 0 ); // 0 is the special case, meaning "not found"
6279 pushNumber (result);
6280 } else if (s->which == Stackel_STRING_ARRAY && t->which == Stackel_STRING) {
6281 pushNumber (NUMfindFirst (s->stringArray, t->getString()));
6282 } else {
6283 Melder_throw (U"The function “index” requires two strings, not ",
6284 s->whichText(), U" and ", t->whichText(), U".");
6285 }
6286 }
6287 static void do_index_caseInsensitive () {
6288 const Stackel t = pop, s = pop;
6289 if (s->which == Stackel_STRING && t->which == Stackel_STRING) {
6290 char32 *substring = str32str_caseInsensitive (s->getString(), t->getString());
6291 const integer result = ( substring ? substring - s->getString() + 1 : 0 ); // 0 is the special case, meaning "not found"
6292 pushNumber (result);
6293 } else if (s->which == Stackel_STRING_ARRAY && t->which == Stackel_STRING) {
6294 pushNumber (NUMfindFirst_caseInsensitive (s->stringArray, t->getString()));
6295 } else {
6296 Melder_throw (U"The function “index_caseInsensitive” requires two strings, not ",
6297 s->whichText(), U" and ", t->whichText(), U".");
6298 }
6299 }
6300 static void do_rindex () {
6301 const Stackel part = pop, whole = pop;
6302 if (whole->which == Stackel_STRING && part->which == Stackel_STRING) {
6303 char32 *lastSubstring = str32str (whole->getString(), part->getString());
6304 if (part->getString() [0] == U'\0') {
6305 const integer result = Melder_length (whole->getString());
6306 pushNumber (result);
6307 } else if (lastSubstring) {
6308 for (;;) {
6309 char32 *substring = str32str (lastSubstring + 1, part->getString());
6310 if (! substring)
6311 break;
6312 lastSubstring = substring;
6313 }
6314 pushNumber (lastSubstring - whole->getString() + 1);
6315 } else {
6316 pushNumber (0); // 0 is the special case, meaning "not found"
6317 }
6318 } else if (whole->which == Stackel_STRING_ARRAY && part->which == Stackel_STRING) {
6319 pushNumber (NUMfindLast (whole->stringArray, part->getString()));
6320 } else {
6321 Melder_throw (U"The function “rindex” requires two strings, not ",
6322 whole->whichText(), U" and ", part->whichText(), U".");
6323 }
6324 }
6325 static void do_rindex_caseInsensitive () {
6326 const Stackel part = pop, whole = pop;
6327 if (whole->which == Stackel_STRING && part->which == Stackel_STRING) {
6328 char32 *lastSubstring = str32str_caseInsensitive (whole->getString(), part->getString());
6329 if (part->getString() [0] == U'\0') {
6330 const integer result = Melder_length (whole->getString());
6331 pushNumber (result);
6332 } else if (lastSubstring) {
6333 for (;;) {
6334 char32 *substring = str32str_caseInsensitive (lastSubstring + 1, part->getString());
6335 if (! substring)
6336 break;
6337 lastSubstring = substring;
6338 }
6339 pushNumber (lastSubstring - whole->getString() + 1);
6340 } else {
6341 pushNumber (0); // 0 is the special case, meaning "not found"
6342 }
6343 } else if (whole->which == Stackel_STRING_ARRAY && part->which == Stackel_STRING) {
6344 pushNumber (NUMfindLast_caseInsensitive (whole->stringArray, part->getString()));
6345 } else {
6346 Melder_throw (U"The function “rindex_caseInsensitive” requires two strings, not ",
6347 whole->whichText(), U" and ", part->whichText(), U".");
6348 }
6349 }
6350 static void do_index_regex (int backward) {
6351 const Stackel t = pop, s = pop;
6352 if (s->which == Stackel_STRING && t->which == Stackel_STRING) {
6353 conststring32 errorMessage;
6354 regexp *compiled_regexp = CompileRE (t->getString(), & errorMessage, 0);
6355 if (! compiled_regexp) {
6356 Melder_throw (U"index_regex(): ", errorMessage, U".");
6357 } else {
6358 if (ExecRE (compiled_regexp, nullptr, s->getString(), nullptr, backward, U'\0', U'\0', nullptr, nullptr)) {
6359 char32 *location = (char32 *) compiled_regexp -> startp [0];
6360 pushNumber (location - s->getString() + 1);
6361 free (compiled_regexp);
6362 } else {
6363 pushNumber (false);
6364 }
6365 }
6366 } else {
6367 Melder_throw (U"The function “", Formula_instructionNames [parse [programPointer]. symbol],
6368 U"” requires two strings, not ", s->whichText(), U" and ", t->whichText(), U".");
6369 }
6370 }
6371 static void do_stringMatchesCriterion (kMelder_string criterion, bool caseSensitive) {
6372 const Stackel t = pop, s = pop;
6373 if (s->which == Stackel_STRING && t->which == Stackel_STRING) {
6374 const bool result = Melder_stringMatchesCriterion (s->getString(), criterion, t->getString(), caseSensitive);
6375 pushNumber (result);
6376 } else {
6377 Melder_throw (U"The function “", Formula_instructionNames [parse [programPointer]. symbol],
6378 U"” requires two strings, not ", s->whichText(), U" and ", t->whichText(), U".");
6379 }
6380 }
6381 static void do_extractNumber () {
6382 const Stackel t = pop, s = pop;
6383 if (s->which == Stackel_STRING && t->which == Stackel_STRING) {
6384 char32 *substring = str32str (s->getString(), t->getString());
6385 if (! substring) {
6386 pushNumber (undefined);
6387 } else {
6388 /* Skip the prompt. */
6389 substring += Melder_length (t->getString());
6390 /* Skip white space. */
6391 while (Melder_isHorizontalOrVerticalSpace (*substring)) substring ++;
6392 if (substring [0] == U'\0' || str32nequ (substring, U"--undefined--", 13)) {
6393 pushNumber (undefined);
6394 } else {
6395 char32 buffer [101];
6396 int i = 0;
6397 for (; i < 100; i ++) {
6398 buffer [i] = *substring;
6399 substring ++;
6400 if (*substring == U'\0' || Melder_isHorizontalOrVerticalSpace (*substring))
6401 break;
6402 }
6403 if (i >= 100) {
6404 buffer [100] = U'\0';
6405 pushNumber (Melder_atof (buffer));
6406 } else {
6407 buffer [i + 1] = U'\0';
6408 char32 *slash = str32chr (buffer, U'/');
6409 if (slash) {
6410 *slash = U'\0';
6411 double numerator = Melder_atof (buffer), denominator = Melder_atof (slash + 1);
6412 pushNumber (numerator / denominator);
6413 } else {
6414 pushNumber (Melder_atof (buffer));
6415 }
6416 }
6417 }
6418 }
6419 } else {
6420 Melder_throw (U"The function “", Formula_instructionNames [parse [programPointer]. symbol],
6421 U"” requires two strings, not ", s->whichText(), U" and ", t->whichText(), U".");
6422 }
6423 }
6424 static void do_extractText_STR (bool singleWord) {
6425 const Stackel t = pop, s = pop;
6426 if (s->which == Stackel_STRING && t->which == Stackel_STRING) {
6427 char32 *substring = str32str (s->getString(), t->getString());
6428 autostring32 result;
6429 if (! substring) {
6430 result = Melder_dup (U"");
6431 } else {
6432 integer length;
6433 /* Skip the prompt. */
6434 substring += Melder_length (t->getString());
6435 if (singleWord) {
6436 /* Skip white space. */
6437 while (Melder_isHorizontalOrVerticalSpace (*substring)) substring ++;
6438 }
6439 char32 *p = substring;
6440 if (singleWord) {
6441 /* Proceed until next white space. */
6442 while (Melder_staysWithinInk (*p)) p ++;
6443 } else {
6444 /* Proceed until end of line. */
6445 while (Melder_staysWithinLine (*p)) p ++;
6446 }
6447 length = p - substring;
6448 result = autostring32 (length);
6449 str32ncpy (result.get(), substring, length);
6450 }
6451 pushString (result.move());
6452 } else {
6453 Melder_throw (U"The function “", Formula_instructionNames [parse [programPointer]. symbol],
6454 U"” requires two strings, not ", s->whichText(), U" and ", t->whichText(), U".");
6455 }
6456 }
6457 static void do_replace_STR () {
6458 const Stackel x = pop, u = pop, t = pop, s = pop;
6459 if (s->which == Stackel_STRING && t->which == Stackel_STRING && u->which == Stackel_STRING && x->which == Stackel_NUMBER) {
6460 autostring32 result = replace_STR (s->getString(), t->getString(), u->getString(), Melder_iround (x->number));
6461 pushString (result.move());
6462 } else {
6463 Melder_throw (U"The function “replace$” requires three strings and a number.");
6464 }
6465 }
6466 static void do_replace_regex_STR () {
6467 const Stackel x = pop, u = pop, t = pop, s = pop;
6468 if (s->which == Stackel_STRING && t->which == Stackel_STRING && u->which == Stackel_STRING && x->which == Stackel_NUMBER) {
6469 conststring32 errorMessage;
6470 regexp *compiled_regexp = CompileRE (t->getString(), & errorMessage, 0);
6471 if (! compiled_regexp) {
6472 Melder_throw (U"replace_regex$(): ", errorMessage, U".");
6473 } else {
6474 autostring32 result = replace_regex_STR (s->getString(), compiled_regexp, u->getString(), Melder_iround (x->number));
6475 pushString (result.move());
6476 }
6477 } else {
6478 Melder_throw (U"The function “replace_regex$” requires three strings and a number.");
6479 }
6480 }
6481 static void do_selected () {
6482 const Stackel n = pop;
6483 integer result = 0;
6484 if (n->number == 0) {
6485 result = praat_idOfSelected (nullptr, 0);
6486 } else if (n->number == 1) {
6487 const Stackel a = pop;
6488 if (a->which == Stackel_STRING) {
6489 ClassInfo klas = Thing_classFromClassName (a->getString(), nullptr);
6490 result = praat_idOfSelected (klas, 0);
6491 } else if (a->which == Stackel_NUMBER) {
6492 result = praat_idOfSelected (nullptr, Melder_iround (a->number));
6493 } else {
6494 Melder_throw (U"The function “selected” requires a string (an object type name) and/or a number.");
6495 }
6496 } else if (n->number == 2) {
6497 const Stackel x = pop, s = pop;
6498 if (s->which == Stackel_STRING && x->which == Stackel_NUMBER) {
6499 const ClassInfo klas = Thing_classFromClassName (s->getString(), nullptr);
6500 result = praat_idOfSelected (klas, Melder_iround (x->number));
6501 } else {
6502 Melder_throw (U"The function “selected” requires a string (an object type name) and/or a number.");
6503 }
6504 } else {
6505 Melder_throw (U"The function “selected” requires 0, 1, or 2 arguments, not ", n->number, U".");
6506 }
6507 pushNumber (result);
6508 }
6509 static void do_selected_STR () {
6510 const Stackel n = pop;
6511 char32 *resultSource; // purposefully don't initialize, so that the compiler can check that has been assigned to when used
6512 if (n->number == 0) {
6513 resultSource = praat_nameOfSelected (nullptr, 0);
6514 } else if (n->number == 1) {
6515 const Stackel a = pop;
6516 if (a->which == Stackel_STRING) {
6517 const ClassInfo klas = Thing_classFromClassName (a->getString(), nullptr);
6518 resultSource = praat_nameOfSelected (klas, 0);
6519 } else if (a->which == Stackel_NUMBER) {
6520 resultSource = praat_nameOfSelected (nullptr, Melder_iround (a->number));
6521 } else {
6522 Melder_throw (U"The function “selected$” requires a string (an object type name) and/or a number.");
6523 }
6524 } else if (n->number == 2) {
6525 const Stackel x = pop, s = pop;
6526 if (s->which == Stackel_STRING && x->which == Stackel_NUMBER) {
6527 ClassInfo klas = Thing_classFromClassName (s->getString(), nullptr);
6528 resultSource = praat_nameOfSelected (klas, Melder_iround (x->number));
6529 } else {
6530 Melder_throw (U"The function “selected$” requires a string (an object type name) and a number.");
6531 }
6532 } else {
6533 Melder_throw (U"The function “selected$” requires 0, 1, or 2 arguments, not ", n->number, U".");
6534 }
6535 pushString (Melder_dup (resultSource));
6536 }
6537 static void do_numberOfSelected () {
6538 const Stackel n = pop;
6539 integer result = 0;
6540 if (n->number == 0) {
6541 result = praat_numberOfSelected (nullptr);
6542 } else if (n->number == 1) {
6543 const Stackel s = pop;
6544 if (s->which == Stackel_STRING) {
6545 const ClassInfo klas = Thing_classFromClassName (s->getString(), nullptr);
6546 result = praat_numberOfSelected (klas);
6547 } else {
6548 Melder_throw (U"The function “numberOfSelected” requires a string (an object type name), not ", s->whichText(), U".");
6549 }
6550 } else {
6551 Melder_throw (U"The function “numberOfSelected” requires 0 or 1 arguments, not ", n->number, U".");
6552 }
6553 pushNumber (result);
6554 }
6555 static void do_selected_VEC () {
6556 const Stackel n = pop;
6557 autoVEC result;
6558 if (n->number == 0) {
6559 result = praat_idsOfAllSelected (nullptr);
6560 } else if (n->number == 1) {
6561 const Stackel s = pop;
6562 if (s->which == Stackel_STRING) {
6563 const ClassInfo klas = Thing_classFromClassName (s->getString(), nullptr);
6564 result = praat_idsOfAllSelected (klas);
6565 } else {
6566 Melder_throw (U"The function “selected#” requires a string (an object type name), not ", s->whichText(), U".");
6567 }
6568 } else {
6569 Melder_throw (U"The function “selected#” requires 0 or 1 arguments, not ", n->number, U".");
6570 }
6571 pushNumericVector (result.move());
6572 }
6573 static void do_selected_STRVEC () {
6574 const Stackel n = pop;
6575 autoSTRVEC result;
6576 if (n->number == 0) {
6577 result = praat_namesOfAllSelected (nullptr);
6578 } else if (n->number == 1) {
6579 const Stackel s = pop;
6580 if (s->which == Stackel_STRING) {
6581 const ClassInfo klas = Thing_classFromClassName (s->getString(), nullptr);
6582 result = praat_namesOfAllSelected (klas);
6583 } else {
6584 Melder_throw (U"The function “selected$#” requires a string (an object type name), not ", s->whichText(), U".");
6585 }
6586 } else {
6587 Melder_throw (U"The function “selected$#” requires 0 or 1 arguments, not ", n->number, U".");
6588 }
6589 pushStringVector (result.move());
6590 }
6591 static void do_selectObject () {
6592 const Stackel n = pop;
6593 praat_deselectAll ();
6594 for (int iobject = 1; iobject <= n -> number; iobject ++) {
6595 const Stackel object = pop;
6596 if (object -> which == Stackel_NUMBER) {
6597 const integer IOBJECT = praat_findObjectById (Melder_iround (object -> number));
6598 praat_select (IOBJECT);
6599 } else if (object -> which == Stackel_STRING) {
6600 const integer IOBJECT = praat_findObjectByName (object -> getString());
6601 praat_select (IOBJECT);
6602 } else if (object -> which == Stackel_NUMERIC_VECTOR) {
6603 const VEC vec = object -> numericVector;
6604 for (integer ielm = 1; ielm <= vec.size; ielm ++) {
6605 const integer IOBJECT = praat_findObjectById (Melder_iround (vec [ielm]));
6606 praat_select (IOBJECT);
6607 }
6608 } else {
6609 Melder_throw (U"The function “selectObject” takes numbers, strings, or numeric vectors, not ", object->whichText());
6610 }
6611 }
6612 praat_show ();
6613 pushNumber (1);
6614 }
6615 static void do_plusObject () {
6616 const Stackel n = pop;
6617 for (int iobject = 1; iobject <= n -> number; iobject ++) {
6618 const Stackel object = pop;
6619 if (object -> which == Stackel_NUMBER) {
6620 const integer IOBJECT = praat_findObjectById (Melder_iround (object -> number));
6621 praat_select (IOBJECT);
6622 } else if (object -> which == Stackel_STRING) {
6623 const integer IOBJECT = praat_findObjectByName (object -> getString());
6624 praat_select (IOBJECT);
6625 } else if (object -> which == Stackel_NUMERIC_VECTOR) {
6626 const VEC vec = object -> numericVector;
6627 for (integer ielm = 1; ielm <= vec.size; ielm ++) {
6628 const integer IOBJECT = praat_findObjectById (Melder_iround (vec [ielm]));
6629 praat_select (IOBJECT);
6630 }
6631 } else {
6632 Melder_throw (U"The function “plusObject” takes numbers, strings, or numeric vectors, not ", object->whichText(), U".");
6633 }
6634 }
6635 praat_show ();
6636 pushNumber (1);
6637 }
6638 static void do_minusObject () {
6639 const Stackel n = pop;
6640 for (int iobject = 1; iobject <= n -> number; iobject ++) {
6641 const Stackel object = pop;
6642 if (object -> which == Stackel_NUMBER) {
6643 const integer IOBJECT = praat_findObjectById (Melder_iround (object -> number));
6644 praat_deselect (IOBJECT);
6645 } else if (object -> which == Stackel_STRING) {
6646 const integer IOBJECT = praat_findObjectByName (object -> getString());
6647 praat_deselect (IOBJECT);
6648 } else if (object -> which == Stackel_NUMERIC_VECTOR) {
6649 const VEC vec = object -> numericVector;
6650 for (integer ielm = 1; ielm <= vec.size; ielm ++) {
6651 const integer IOBJECT = praat_findObjectById (Melder_iround (vec [ielm]));
6652 praat_deselect (IOBJECT);
6653 }
6654 } else {
6655 Melder_throw (U"The function “minusObject” takes numbers, strings, or numeric vectors, not ", object->whichText(), U".");
6656 }
6657 }
6658 praat_show ();
6659 pushNumber (1);
6660 }
6661 static void do_removeObject () {
6662 const Stackel n = pop;
6663 for (int iobject = 1; iobject <= n -> number; iobject ++) {
6664 const Stackel object = pop;
6665 if (object -> which == Stackel_NUMBER) {
6666 const integer IOBJECT = praat_findObjectById (Melder_iround (object -> number));
6667 praat_removeObject (IOBJECT);
6668 } else if (object -> which == Stackel_STRING) {
6669 const integer IOBJECT = praat_findObjectByName (object -> getString());
6670 praat_removeObject (IOBJECT);
6671 } else if (object -> which == Stackel_NUMERIC_VECTOR) {
6672 const VEC vec = object -> numericVector;
6673 for (integer ielm = 1; ielm <= vec.size; ielm ++) {
6674 const integer IOBJECT = praat_findObjectById (Melder_iround (vec [ielm]));
6675 praat_removeObject (IOBJECT);
6676 }
6677 } else {
6678 Melder_throw (U"The function “removeObject” takes numbers, strings, or numeric vectors, not ", object->whichText(), U".");
6679 }
6680 }
6681 praat_show ();
6682 pushNumber (1);
6683 }
6684 static Daata _do_object (Stackel object, conststring32 expressionMessage) {
6685 Daata data;
6686 if (object -> which == Stackel_NUMBER) {
6687 const integer IOBJECT = praat_findObjectById (Melder_iround (object -> number));
6688 data = OBJECT;
6689 } else if (object -> which == Stackel_STRING) {
6690 const integer IOBJECT = praat_findObjectByName (object -> getString());
6691 data = OBJECT;
6692 } else if (object -> which == Stackel_OBJECT) {
6693 data = object -> object;
6694 } else {
6695 Melder_throw (U"The expression “", expressionMessage, U"” requires xx to be a number or a string, not ", object->whichText(), U".");
6696 }
6697 return data;
6698 }
6699 static void do_object_xmin () {
6700 const Stackel object = pop;
6701 const Daata data = _do_object (object, U"object[xx].xmin");
6702 Melder_require (data -> v_hasGetXmin (),
6703 U"An object of type ", Thing_className (data), U" has no “xmin” attribute.");
6704 pushNumber (data -> v_getXmin ());
6705 }
6706 static void do_object_xmax () {
6707 const Stackel object = pop;
6708 const Daata data = _do_object (object, U"object[xx].xmax");
6709 Melder_require (data -> v_hasGetXmax (),
6710 U"An object of type ", Thing_className (data), U" has no “xmax” attribute.");
6711 pushNumber (data -> v_getXmax ());
6712 }
6713 static void do_object_ymin () {
6714 const Stackel object = pop;
6715 const Daata data = _do_object (object, U"object[xx].ymin");
6716 Melder_require (data -> v_hasGetYmin (),
6717 U"An object of type ", Thing_className (data), U" has no “ymin” attribute.");
6718 pushNumber (data -> v_getYmin ());
6719 }
6720 static void do_object_ymax () {
6721 const Stackel object = pop;
6722 const Daata data = _do_object (object, U"object[xx].ymax");
6723 Melder_require (data -> v_hasGetYmax (),
6724 U"An object of type ", Thing_className (data), U" has no “ymax” attribute.");
6725 pushNumber (data -> v_getYmax ());
6726 }
6727 static void do_object_nx () {
6728 const Stackel object = pop;
6729 const Daata data = _do_object (object, U"object[xx].nx");
6730 Melder_require (data -> v_hasGetNx (),
6731 U"An object of type ", Thing_className (data), U" has no “nx” attribute.");
6732 pushNumber (data -> v_getNx ());
6733 }
6734 static void do_object_ny () {
6735 const Stackel object = pop;
6736 const Daata data = _do_object (object, U"object[xx].ny");
6737 Melder_require (data -> v_hasGetNy (),
6738 U"An object of type ", Thing_className (data), U" has no “ny” attribute.");
6739 pushNumber (data -> v_getNy ());
6740 }
6741 static void do_object_dx () {
6742 const Stackel object = pop;
6743 const Daata data = _do_object (object, U"object[xx].dx");
6744 Melder_require (data -> v_hasGetDx (),
6745 U"An object of type ", Thing_className (data), U" has no “dx” attribute.");
6746 pushNumber (data -> v_getDx ());
6747 }
6748 static void do_object_dy () {
6749 const Stackel object = pop;
6750 const Daata data = _do_object (object, U"object[xx].dy");
6751 Melder_require (data -> v_hasGetDy (),
6752 U"An object of type ", Thing_className (data), U" has no “dy” attribute.");
6753 pushNumber (data -> v_getDy ());
6754 }
6755 static void do_object_nrow () {
6756 const Stackel object = pop;
6757 const Daata data = _do_object (object, U"object[xx].nrow");
6758 Melder_require (data -> v_hasGetNrow (),
6759 U"An object of type ", Thing_className (data), U" has no “nrow” attribute.");
6760 pushNumber (data -> v_getNrow ());
6761 }
6762 static void do_object_ncol () {
6763 const Stackel object = pop;
6764 const Daata data = _do_object (object, U"object[xx].ncol");
6765 Melder_require (data -> v_hasGetNcol (),
6766 U"An object of type ", Thing_className (data), U" has no “ncol” attribute.");
6767 pushNumber (data -> v_getNcol ());
6768 }
6769 static void do_object_row_STR () {
6770 const Stackel index = pop, object = pop;
6771 const Daata data = _do_object (object, U"object[xx].row$[]");
6772 Melder_require (data -> v_hasGetRowStr (),
6773 U"An object of type ", Thing_className (data), U" has no “row$[]” attribute.");
6774 Melder_require (index -> which == Stackel_NUMBER,
6775 U"The expression “object[].row$[xx]” requires xx to be a number, not ", index->whichText(), U".");
6776 const integer number = Melder_iround (index->number);
6777 autostring32 result = Melder_dup (data -> v_getRowStr (number));
6778 if (! result)
6779 Melder_throw (U"Row index out of bounds.");
6780 pushString (result.move());
6781 }
6782 static void do_object_col_STR () {
6783 const Stackel index = pop, object = pop;
6784 const Daata data = _do_object (object, U"object[xx].col$[]");
6785 Melder_require (data -> v_hasGetColStr (),
6786 U"An object of type ", Thing_className (data), U" has no “col$[]” attribute.");
6787 Melder_require (index -> which == Stackel_NUMBER,
6788 U"The expression “object[].col$[xx]” requires xx to be a number, not ", index->whichText(), U".");
6789 const integer number = Melder_iround (index->number);
6790 autostring32 result = Melder_dup (data -> v_getColStr (number));
6791 if (! result)
6792 Melder_throw (U"Column index out of bounds.");
6793 pushString (result.move());
6794 }
6795 static void do_string_STR () {
6796 const Stackel value = pop;
6797 if (value->which == Stackel_NUMBER) {
6798 autostring32 result = Melder_dup (Melder_double (value->number));
6799 pushString (result.move());
6800 } else {
6801 Melder_throw (U"The function “string$” requires a number, not ", value->whichText(), U".");
6802 }
6803 }
6804 static void do_horizontal_STR () {
6805 const Stackel array = pop;
6806 if (array->which == Stackel_STRING_ARRAY) {
6807 pushString (horizontal_STR (array->stringArray));
6808 } else {
6809 Melder_throw (U"The function “horizontal$” requires a string array.");
6810 }
6811 }
6812 static void do_vertical_STR () {
6813 const Stackel array = pop;
6814 if (array->which == Stackel_STRING_ARRAY) {
6815 pushString (vertical_STR (array->stringArray));
6816 } else {
6817 Melder_throw (U"The function “vertical$” requires a string array.");
6818 }
6819 }
6820 static void do_numbers_VEC () {
6821 /*
6822 result# = numbers# (strings$#)
6823 */
6824 const Stackel stringsel = pop;
6825 if (stringsel->which == Stackel_STRING_ARRAY) {
6826 const constSTRVEC strings = stringsel->stringArray;
6827 autoVEC result = zero_VEC (strings.size);
6828 for (integer i = 1; i <= strings.size; i ++)
6829 result [i] = Melder_atof (strings [i]);
6830 pushNumericVector (result.move());
6831 } else {
6832 Melder_throw (U"The function “numbers#” requires a string array, not ", stringsel->whichText(), U".");
6833 }
6834 }
6835 static void do_sleep () {
6836 const Stackel value = pop;
6837 if (value->which == Stackel_NUMBER) {
6838 Melder_sleep (value->number);
6839 pushNumber (1);
6840 } else {
6841 Melder_throw (U"The function “sleep” requires a number, not ", value->whichText(), U".");
6842 }
6843 }
6844 static void do_unicode () {
6845 const Stackel value = pop;
6846 if (value->which == Stackel_STRING) {
6847 pushNumber (value->getString() [0]);
6848 } else {
6849 Melder_throw (U"The function “unicode” requires a character, not ", value->whichText(), U".");
6850 }
6851 }
6852 static void do_unicode_STR () {
6853 const Stackel value = pop;
6854 if (value->which == Stackel_NUMBER) {
6855 Melder_require (value->number >= 0.0 && value->number < (double) (1 << 21),
6856 U"A unicode number cannot be greater than ", (1 << 21) - 1, U".");
6857 Melder_require (value->number < 0xD800 || value->number > 0xDFFF,
6858 U"A unicode number cannot lie between 0xD800 and 0xDFFF. Those are “surrogates”.");
6859 char32 string [2] = { U'\0', U'\0' };
6860 string [0] = (char32) value->number;
6861 pushString (Melder_dup (string).move());
6862 } else {
6863 Melder_throw (U"The function “unicode$” requires a number, not ", value->whichText(), U".");
6864 }
6865 }
6866 static void do_fixed_STR () {
6867 const Stackel precision = pop, value = pop;
6868 if (value->which == Stackel_NUMBER && precision->which == Stackel_NUMBER) {
6869 autostring32 result = Melder_dup (Melder_fixed (value->number, Melder_iround (precision->number)));
6870 pushString (result.move());
6871 } else if (value->which == Stackel_NUMERIC_VECTOR && precision->which == Stackel_NUMBER) {
6872 autostring32 result = Melder_dup (Melder_fixed (value->numericVector, Melder_iround (precision->number)));
6873 pushString (result.move());
6874 } else if (value->which == Stackel_NUMERIC_MATRIX && precision->which == Stackel_NUMBER) {
6875 autostring32 result = Melder_dup (Melder_fixed (value->numericMatrix, Melder_iround (precision->number)));
6876 pushString (result.move());
6877 } else {
6878 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".");
6879 }
6880 }
6881 static void do_percent_STR () {
6882 const Stackel precision = pop, value = pop;
6883 if (value->which == Stackel_NUMBER && precision->which == Stackel_NUMBER) {
6884 autostring32 result = Melder_dup (Melder_percent (value->number, Melder_iround (precision->number)));
6885 pushString (result.move());
6886 } else {
6887 Melder_throw (U"The function “percent$” requires two numbers (value and precision), not ", value->whichText(), U" and ", precision->whichText(), U".");
6888 }
6889 }
6890 static void do_graphicalPercent_STR () {
6891 const Stackel precision = pop, value = pop;
6892 if (value->which == Stackel_NUMBER && precision->which == Stackel_NUMBER) {
6893 autostring32 result = Melder_dup (Melder_graphicalPercent (value->number, Melder_iround (precision->number)));
6894 pushString (result.move());
6895 } else {
6896 Melder_throw (U"The function “graphicalPercent$” requires two numbers (value and precision), not ", value->whichText(), U" and ", precision->whichText(), U".");
6897 }
6898 }
6899 static void do_bigInteger_STR () {
6900 const Stackel value = pop;
6901 if (value->which == Stackel_NUMBER) {
6902 if (value->number < INT54_MIN || value->number > INT54_MAX)
6903 Melder_throw (U"bigInteger(): the number ", value->number, U" cannot be represented precisely as an integer.");
6904 autostring32 result = Melder_dup (Melder_bigInteger (int64 (value->number))); // guarded cast
6905 pushString (result.move());
6906 } else {
6907 Melder_throw (U"The function “bigInteger$” requires a number, not ", value->whichText(), U".");
6908 }
6909 }
6910 static void do_half_STR () {
6911 const Stackel value = pop;
6912 if (value->which == Stackel_NUMBER) {
6913 autostring32 result = Melder_dup (Melder_half (value->number));
6914 pushString (result.move());
6915 } else {
6916 Melder_throw (U"The function “half$” requires a number, not ", value->whichText(), U".");
6917 }
6918 }
6919 static void do_graphicalHalf_STR () {
6920 const Stackel value = pop;
6921 if (value->which == Stackel_NUMBER) {
6922 autostring32 result = Melder_dup (Melder_graphicalHalf (value->number));
6923 pushString (result.move());
6924 } else {
6925 Melder_throw (U"The function “graphicalHalf$” requires a number, not ", value->whichText(), U".");
6926 }
6927 }
6928 static void do_single_STR () {
6929 const Stackel value = pop;
6930 if (value->which == Stackel_NUMBER) {
6931 autostring32 result = Melder_dup (Melder_single (value->number));
6932 pushString (result.move());
6933 } else {
6934 Melder_throw (U"The function “single$” requires a number, not ", value->whichText(), U".");
6935 }
6936 }
6937 static void do_graphicalSingle_STR () {
6938 const Stackel value = pop;
6939 if (value->which == Stackel_NUMBER) {
6940 autostring32 result = Melder_dup (Melder_graphicalSingle (value->number));
6941 pushString (result.move());
6942 } else {
6943 Melder_throw (U"The function “graphicalSingle$” requires a number, not ", value->whichText(), U".");
6944 }
6945 }
6946 static void do_double_STR () {
6947 const Stackel value = pop;
6948 if (value->which == Stackel_NUMBER) {
6949 autostring32 result = Melder_dup (Melder_double (value->number));
6950 pushString (result.move());
6951 } else {
6952 Melder_throw (U"The function “double$” requires a number, not ", value->whichText(), U".");
6953 }
6954 }
6955 static void do_graphicalDouble_STR () {
6956 const Stackel value = pop;
6957 if (value->which == Stackel_NUMBER) {
6958 autostring32 result = Melder_dup (Melder_graphicalDouble (value->number));
6959 pushString (result.move());
6960 } else {
6961 Melder_throw (U"The function “graphicalDouble$” requires a number, not ", value->whichText(), U".");
6962 }
6963 }
6964 static void do_naturalLogarithm_STR () {
6965 const Stackel value = pop;
6966 if (value->which == Stackel_NUMBER) {
6967 autostring32 result = Melder_dup (Melder_naturalLogarithm (value->number));
6968 pushString (result.move());
6969 } else {
6970 Melder_throw (U"The function “naturalLogarithm$” requires a number, not ", value->whichText(), U".");
6971 }
6972 }
6973 static void do_graphicalNaturalLogarithm_STR () {
6974 const Stackel value = pop;
6975 if (value->which == Stackel_NUMBER) {
6976 autostring32 result = Melder_dup (Melder_graphicalNaturalLogarithm (value->number));
6977 pushString (result.move());
6978 } else {
6979 Melder_throw (U"The function “graphicalNaturalLogarithm$” requires a number, not ", value->whichText(), U".");
6980 }
6981 }
6982 static void do_hexadecimal_STR () {
6983 const Stackel precision = pop, value = pop;
6984 if (value->which == Stackel_NUMBER && precision->which == Stackel_NUMBER) {
6985 autostring32 result = Melder_dup (Melder_hexadecimal (Melder_iround (value->number), Melder_iround (precision->number)));
6986 pushString (result.move());
6987 } else {
6988 Melder_throw (U"The function “hexadecimal$” requires two numbers (value and precision), not ", value->whichText(), U" and ", precision->whichText(), U".");
6989 }
6990 }
6991 static void do_deleteFile () {
6992 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
6993 U"The function “deleteFile” is not available inside manuals.");
6994 const Stackel f = pop;
6995 if (f->which == Stackel_STRING) {
6996 structMelderFile file { };
6997 Melder_relativePathToFile (f->getString(), & file);
6998 Melder_checkTrust (theInterpreter, U"delete the file\n", & file);
6999 MelderFile_delete (& file);
7000 pushNumber (1);
7001 } else {
7002 Melder_throw (U"The function “deleteFile” requires a string, not ", f->whichText(), U".");
7003 }
7004 }
7005 static void do_moveAndOrRenameFile () {
7006 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7007 U"The function “moveAndOrRenameFile” is not available inside manuals.");
7008 const Stackel to = pop, from = pop;
7009 if (from->which == Stackel_STRING && to->which == Stackel_STRING) {
7010 structMelderFile fromFile { }, toFile { };
7011 Melder_relativePathToFile (from->getString(), & fromFile);
7012 Melder_relativePathToFile (to->getString(), & toFile);
7013 Melder_checkTrust (theInterpreter, U"move or rename the file\n", & fromFile, U" to ", & toFile);
7014 MelderFile_moveAndOrRename (& fromFile, & toFile);
7015 pushNumber (1);
7016 } else {
7017 Melder_throw (U"The function “moveAndOrRenameFile” requires two strings, not ", from->whichText(), U" and ", to->whichText(), U".");
7018 }
7019 }
7020 static void do_createFolder () {
7021 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7022 U"The function “createFolder” is not available inside manuals.");
7023 const Stackel f = pop;
7024 if (f->which == Stackel_STRING) {
7025 structMelderFolder folder { };
7026 Melder_relativePathToFolder (f->getString(), & folder);
7027 if (! MelderFolder_exists (& folder)) { // don't check for trust if the folder exists
7028 Melder_checkTrust (theInterpreter, U"create the folder\n", & folder);
7029 MelderFolder_create (& folder);
7030 }
7031 pushNumber (1);
7032 } else {
7033 Melder_throw (U"The function “createFolder” requires a string, not ", f->whichText(), U".");
7034 }
7035 }
7036 static void do_createDirectory () {
7037 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7038 U"The function “createDirectory” is not available inside manuals.");
7039 const Stackel f = pop;
7040 if (f->which == Stackel_STRING) {
7041 structMelderFolder folder { };
7042 Melder_relativePathToFolder (f->getString(), & folder);
7043 if (! MelderFolder_exists (& folder)) { // don't check for trust if the folder exists
7044 Melder_checkTrust (theInterpreter, U"create the directory\n", & folder);
7045 MelderFolder_create (& folder);
7046 }
7047 pushNumber (1);
7048 } else {
7049 Melder_throw (U"The function “createDirectory” requires a string, not ", f->whichText(), U".");
7050 }
7051 }
7052 static void do_setWorkingDirectory () {
7053 const Stackel f = pop;
7054 if (f->which == Stackel_STRING) {
7055 structMelderFolder folder { };
7056 Melder_relativePathToFolder (f->getString(), & folder);
7057 Melder_setCurrentFolder (& folder);
7058 MelderFolder_copy (& folder, & theInterpreter -> workingDirectory);
7059 Melder_assert (MelderFolder_equal (Melder_peekWorkingDirectory(), & theInterpreter -> workingDirectory));
7060 //TRACE
7061 trace (U"Set the working directory to ", Melder_peekWorkingDirectory());
7062 trace (U"Set the working directory of interpreter ", Melder_pointer (theInterpreter), U" to ", & theInterpreter -> workingDirectory);
7063 pushNumber (1);
7064 } else {
7065 Melder_throw (U"The function “setWorkingDirectory” requires a string, not ", f->whichText(), U".");
7066 }
7067 }
7068 static void do_variableExists () {
7069 const Stackel f = pop;
7070 if (f->which == Stackel_STRING) {
7071 bool result = !! Interpreter_hasVariable (theInterpreter, f->getString());
7072 pushNumber (result);
7073 } else {
7074 Melder_throw (U"The function “variableExists” requires a string, not ", f->whichText(), U".");
7075 }
7076 }
7077 static void do_readFile () {
7078 const Stackel f = pop;
7079 if (f->which == Stackel_STRING) {
7080 structMelderFile file { };
7081 Melder_relativePathToFile (f->getString(), & file);
7082 autostring32 text = MelderFile_readText (& file);
7083 pushNumber (Melder_atof (text.get()));
7084 } else {
7085 Melder_throw (U"The function “readFile” requires a string (a file name), not ", f->whichText(), U".");
7086 }
7087 }
7088 static void do_readFile_STR () {
7089 const Stackel f = pop;
7090 if (f->which == Stackel_STRING) {
7091 structMelderFile file { };
7092 Melder_relativePathToFile (f->getString(), & file);
7093 autostring32 text = MelderFile_readText (& file);
7094 pushString (text.move());
7095 } else {
7096 Melder_throw (U"The function “readFile$” requires a string (a file name), not ", f->whichText(), U".");
7097 }
7098 }
7099 static void do_readFile_VEC () {
7100 const Stackel f = pop;
7101 if (f->which == Stackel_STRING) {
7102 structMelderFile file { };
7103 Melder_relativePathToFile (f->getString(), & file);
7104 autostring32 text = MelderFile_readText (& file);
7105 pushNumericVector (splitByWhitespace_VEC (text.get()));
7106 } else {
7107 Melder_throw (U"The function “readFile#” requires a string (a file name), not ", f->whichText(), U".");
7108 }
7109 }
7110 static void do_readFile_MAT () {
7111 const Stackel f = pop;
7112 if (f->which == Stackel_STRING) {
7113 structMelderFile file { };
7114 Melder_relativePathToFile (f->getString(), & file);
7115 autostring32 text = MelderFile_readText (& file);
7116 pushNumericMatrix (splitByLinesAndWhitespace_MAT (text.get()));
7117 } else {
7118 Melder_throw (U"The function “readFile##” requires a string (a file name), not ", f->whichText(), U".");
7119 }
7120 }
7121 static void do_tensorLiteral () {
7122 const Stackel n = pop;
7123 Melder_assert (n->which == Stackel_NUMBER);
7124 integer numberOfElements = Melder_iround (n->number);
7125 Melder_assert (numberOfElements >= 0);
7126 if (numberOfElements == 0) {
7127 autoVEC result = raw_VEC (0);
7128 pushNumericVector (result.move());
7129 return;
7130 }
7131 /*
7132 The type of the tensor can be a vector, or a matrix, or a tensor3...
7133 This depends on whether the last element is a number, a vector, or a matrix...
7134 */
7135 const Stackel last = pop;
7136 if (last->which == Stackel_NUMBER) {
7137 autoVEC result = raw_VEC (numberOfElements);
7138 result [numberOfElements] = last->number;
7139 for (integer ielement = numberOfElements - 1; ielement > 0; ielement --) {
7140 const Stackel element = pop;
7141 if (element->which != Stackel_NUMBER)
7142 Melder_throw (U"The tensor elements have to be of the same type, not ", element->whichText(), U" and a number.");
7143 result [ielement] = element->number;
7144 }
7145 pushNumericVector (result.move());
7146 } else if (last->which == Stackel_NUMERIC_VECTOR) {
7147 /*@praat
7148 a# = zero# (0) ; edge case
7149 a## = { a#, a# }
7150 assert numberOfRows (a##) = 2
7151 assert numberOfColumns (a##) = 0
7152 @*/
7153 const integer sharedNumberOfColumns = last->numericVector.size;
7154 autoMAT result = raw_MAT (numberOfElements, sharedNumberOfColumns);
7155 result.row (numberOfElements) <<= last->numericVector;
7156 for (integer ielement = numberOfElements - 1; ielement > 0; ielement --) {
7157 const Stackel element = pop;
7158 Melder_require (element->which == Stackel_NUMERIC_VECTOR,
7159 U"The tensor elements have to be of the same type, not ", element->whichText(), U" and a vector.");
7160 Melder_require (element->numericVector.size == sharedNumberOfColumns,
7161 U"The vectors have to be of the same size, not ", element->numericVector.size, U" and ", sharedNumberOfColumns);
7162 result.row (ielement) <<= element->numericVector;
7163 }
7164 pushNumericMatrix (result.move());
7165 } else if (last->which == Stackel_STRING) {
7166 autoSTRVEC result (numberOfElements);
7167 result [numberOfElements] = last->_string.move();
7168 for (integer ielement = numberOfElements - 1; ielement > 0; ielement --) {
7169 const Stackel element = pop;
7170 Melder_require (element->which == Stackel_STRING,
7171 U"The tensor elements have to be of the same type, not ", element->whichText(), U" and a string.");
7172 result [ielement] = element->_string.move();
7173 }
7174 pushStringVector (std::move (result));
7175 } else {
7176 Melder_throw (U"Cannot (yet?) create a tensor containing ", last->whichText(), U".");
7177 }
7178 }
7179 static void do_tensorLiteralCell () {
7180 const Stackel index = pop, nelem = pop;
7181 Melder_assert (nelem->which == Stackel_NUMBER);
7182 const integer numberOfElements = Melder_iround (nelem->number);
7183 Melder_assert (numberOfElements > 0);
7184 const Stackel last = pop;
7185 Melder_require (last->which == Stackel_NUMBER || last->which == Stackel_STRING,
7186 U"Cannot index matrix literals.");
7187 Melder_require (index->which == Stackel_NUMBER,
7188 U"In vector indexing, the element index should be a number, not ", index->whichText(), U".");
7189 Melder_require (isdefined (index->number),
7190 U"The element index is undefined.");
7191 const integer iindex = Melder_iround (index->number);
7192 Melder_require (iindex >= 1,
7193 U"Element index out of bounds. Your index is ", iindex, U", but the index can range only from 1 to ", numberOfElements, U".");
7194 Melder_require (iindex <= numberOfElements,
7195 U"Element index out of bounds. Your index is ", iindex, U", but there are only ", numberOfElements, U" elements.");
7196 if (last->which == Stackel_NUMBER) {
7197 double result = last->number;
7198 for (integer ielement = numberOfElements - 1; ielement > 0; ielement --) {
7199 const Stackel element = pop;
7200 if (element->which != Stackel_NUMBER)
7201 Melder_throw (U"The tensor elements have to be of the same type, not ", element->whichText(), U" and a number.");
7202 if (ielement == iindex)
7203 result = element->number;
7204 }
7205 pushNumber (result);
7206 } else if (last->which == Stackel_STRING) {
7207 autostring32 result = last->_string.move(); // we can move it, because it's been popped off the stack, so we never return there
7208 for (integer ielement = numberOfElements - 1; ielement > 0; ielement --) {
7209 const Stackel element = pop;
7210 if (element->which != Stackel_STRING)
7211 Melder_throw (U"The tensor elements have to be of the same type, not ", element->whichText(), U" and a string.");
7212 if (ielement == iindex)
7213 result = element->_string.move(); // we can move it, because it's been popped off the stack, so we never return there
7214 }
7215 pushString (result.move());
7216 }
7217 }
7218 static void do_row_VEC () {
7219 /*
7220 result# = row# (mat##, rowNumber)
7221 */
7222 const Stackel rowNumber_ = pop, mat_ = pop;
7223 if (mat_->which == Stackel_NUMERIC_MATRIX && rowNumber_->which == Stackel_NUMBER) {
7224 const constMAT mat = mat_->numericMatrix;
7225 const integer rowNumber = Melder_iround (rowNumber_->number);
7226 Melder_require (rowNumber >= 1 && rowNumber <= mat.nrow,
7227 U"In the function “row#”, the row number should be between 1 and ", mat.nrow, U".");
7228 autoVEC result = copy_VEC (mat.row (rowNumber));
7229 pushNumericVector (result.move());
7230 } else {
7231 Melder_throw (U"The function “row#” requires a matrix and a row number, not ", mat_->whichText(), U" and ", rowNumber_->whichText(), U".");
7232 }
7233 }
7234 static void do_col_VEC () {
7235 /*
7236 result# = col# (mat##, colNumber)
7237 */
7238 const Stackel colNumber_ = pop, mat_ = pop;
7239 if (mat_->which == Stackel_NUMERIC_MATRIX && colNumber_->which == Stackel_NUMBER) {
7240 const constMAT mat = mat_->numericMatrix;
7241 const integer colNumber = Melder_iround (colNumber_->number);
7242 Melder_require (colNumber >= 1 && colNumber <= mat.ncol,
7243 U"In the function “col#”, the column number should be between 1 and ", mat.ncol, U".");
7244 autoVEC result = copy_VEC (mat.column (colNumber));
7245 pushNumericVector (result.move());
7246 } else {
7247 Melder_throw (U"The function “col#” requires a matrix and a column number, not ", mat_->whichText(), U" and ", colNumber_->whichText(), U".");
7248 }
7249 }
7250 static void do_inner () {
7251 /*
7252 result = inner (x#, y#)
7253 */
7254 const Stackel y = pop, x = pop;
7255 if (x->which == Stackel_NUMERIC_VECTOR && y->which == Stackel_NUMERIC_VECTOR) {
7256 pushNumber (NUMinner (x->numericVector, y->numericVector));
7257 } else {
7258 Melder_throw (U"The function “inner” requires two vectors, not ", x->whichText(), U" and ", y->whichText(), U".");
7259 }
7260 }
7261 static void do_correlation () {
7262 /*
7263 result = correlation (x#, y#)
7264 */
7265 const Stackel y = pop, x = pop;
7266 if (x->which == Stackel_NUMERIC_VECTOR && y->which == Stackel_NUMERIC_VECTOR) {
7267 pushNumber (NUMcorrelation (x->numericVector, y->numericVector));
7268 } else {
7269 Melder_throw (U"The function “correlation” requires two vectors, not ", x->whichText(), U" and ", y->whichText(), U".");
7270 }
7271 }
7272 static void do_outer_MAT () {
7273 /*
7274 result## = outer## (x#, y#)
7275 */
7276 const Stackel y = pop, x = pop;
7277 if (x->which == Stackel_NUMERIC_VECTOR && y->which == Stackel_NUMERIC_VECTOR) {
7278 autoMAT result = outer_MAT (x->numericVector, y->numericVector);
7279 pushNumericMatrix (result.move());
7280 } else {
7281 Melder_throw (U"The function “outer##” requires two vectors, not ", x->whichText(), U" and ", y->whichText(), U".");
7282 }
7283 }
7284 static void do_mul_VEC () {
7285 /*
7286 result# = mul# (x.., y..)
7287 */
7288 const Stackel y = pop, x = pop;
7289 if (x->which == Stackel_NUMERIC_VECTOR && y->which == Stackel_NUMERIC_MATRIX) {
7290 /*
7291 result# = mul# (x#, y##)
7292 */
7293 const integer xSize = x->numericVector.size, yNrow = y->numericMatrix.nrow;
7294 Melder_require (yNrow == xSize,
7295 U"In the function “mul#”, the dimension of the vector and the number of rows of the matrix should be equal, "
7296 U"not ", xSize, U" and ", yNrow
7297 );
7298 autoVEC result = mul_VEC (x->numericVector, y->numericMatrix);
7299 pushNumericVector (result.move());
7300 } else if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_VECTOR) {
7301 /*
7302 result# = mul# (x##, y#)
7303 */
7304 const integer xNcol = x->numericMatrix.ncol, ySize = y->numericVector.size;
7305 Melder_require (ySize == xNcol,
7306 U"In the function “mul#”, the number of columns of the matrix and the dimension of the vector should be equal, "
7307 U"not ", xNcol, U" and ", ySize, U"."
7308 );
7309 autoVEC result = mul_VEC (x->numericMatrix, y->numericVector);
7310 pushNumericVector (result.move());
7311 } else {
7312 Melder_throw (U"The function “mul#” requires a vector and a matrix, not ", x->whichText(), U" and ", y->whichText(), U".");
7313 }
7314 }
7315 static void do_mul_MAT () {
7316 /*
7317 result## = mul## (x.., y..)
7318 */
7319 const Stackel y = pop, x = pop;
7320 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7321 /*
7322 result# = mul## (x##, y##)
7323 */
7324 const integer xNcol = x->numericMatrix.ncol, yNrow = y->numericMatrix.nrow;
7325 Melder_require (yNrow == xNcol,
7326 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, "
7327 U"not ", xNcol, U" and ", yNrow, U"."
7328 );
7329 autoMAT result = zero_MAT (x->numericMatrix.nrow, y->numericMatrix.ncol);
7330 _mul_allowAllocation_MAT_out (result.get(), x->numericMatrix, y->numericMatrix);
7331 pushNumericMatrix (result.move());
7332 } else {
7333 Melder_throw (U"The function “mul##” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7334 }
7335 }
7336 static void do_mul_metal_MAT () {
7337 /*
7338 result## = mul## (x.., y..)
7339 */
7340 const Stackel y = pop, x = pop;
7341 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7342 /*
7343 result# = mul## (x##, y##)
7344 */
7345 const integer xNcol = x->numericMatrix.ncol, yNrow = y->numericMatrix.nrow;
7346 Melder_require (yNrow == xNcol,
7347 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, "
7348 U"not ", xNcol, U" and ", yNrow, U"."
7349 );
7350 autoMAT result = zero_MAT (x->numericMatrix.nrow, y->numericMatrix.ncol);
7351 MATmul_forceMetal_ (result.get(), x->numericMatrix, y->numericMatrix);
7352 pushNumericMatrix (result.move());
7353 } else {
7354 Melder_throw (U"The function “mul_metal##” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7355 }
7356 }
7357 static void do_mul_fast_MAT () {
7358 /*
7359 result## = mul_fast## (x.., y..)
7360 */
7361 const Stackel y = pop, x = pop;
7362 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7363 /*
7364 result# = mul_fast## (x##, y##)
7365 */
7366 const integer xNcol = x->numericMatrix.ncol, yNrow = y->numericMatrix.nrow;
7367 Melder_require (yNrow == xNcol,
7368 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, "
7369 U"not ", xNcol, U" and ", yNrow, U"."
7370 );
7371 autoMAT result = mul_fast_MAT (x->numericMatrix, y->numericMatrix);
7372 pushNumericMatrix (result.move());
7373 } else {
7374 Melder_throw (U"The function “mul_fast##” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7375 }
7376 }
7377 static void do_mul_tn_MAT () {
7378 /*
7379 result## = mul_tn## (x.., y..)
7380 */
7381 const Stackel y = pop, x = pop;
7382 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7383 /*
7384 result# = mul_tn## (x##, y##)
7385 */
7386 const integer xNrow = x->numericMatrix.nrow, yNrow = y->numericMatrix.nrow;
7387 Melder_require (yNrow == xNrow,
7388 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, "
7389 U"not ", xNrow, U" and ", yNrow, U"."
7390 );
7391 autoMAT result = mul_allowAllocation_MAT (x->numericMatrix.transpose(), y->numericMatrix);
7392 pushNumericMatrix (result.move());
7393 } else {
7394 Melder_throw (U"The function “mul_tn##” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7395 }
7396 }
7397 static void do_mul_nt_MAT () {
7398 /*
7399 result## = mul_nt## (x.., y..)
7400 */
7401 const Stackel y = pop, x = pop;
7402 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7403 /*
7404 result# = mul_nt## (x##, y##)
7405 */
7406 const integer xNcol = x->numericMatrix.ncol, yNcol = y->numericMatrix.ncol;
7407 Melder_require (yNcol == xNcol,
7408 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, "
7409 U"not ", xNcol, U" and ", yNcol, U"."
7410 );
7411 autoMAT result = mul_allowAllocation_MAT (x->numericMatrix, y->numericMatrix.transpose());
7412 pushNumericMatrix (result.move());
7413 } else {
7414 Melder_throw (U"The function “mul_nt##” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7415 }
7416 }
7417 static void do_mul_tt_MAT () {
7418 /*
7419 result## = mul_tt## (x.., y..)
7420 */
7421 const Stackel y = pop, x = pop;
7422 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7423 /*
7424 result# = mul_tt## (x##, y##)
7425 */
7426 const integer xNrow = x->numericMatrix.nrow, yNcol = y->numericMatrix.ncol;
7427 Melder_require (yNcol == xNrow,
7428 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, "
7429 U"not ", xNrow, U" and ", yNcol, U"."
7430 );
7431 autoMAT result = mul_allowAllocation_MAT (x->numericMatrix.transpose(), y->numericMatrix.transpose());
7432 pushNumericMatrix (result.move());
7433 } else {
7434 Melder_throw (U"The function “mul_tt##” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7435 }
7436 }
7437 static void do_transpose_MAT () {
7438 const Stackel x = topOfStack;
7439 if (x->which == Stackel_NUMERIC_MATRIX) {
7440 if (x->owned) {
7441 if (NUMisSquare (x->numericMatrix)) {
7442 /*@praat
7443 assert transpose## ({ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }) = { { 1, 4, 7 }, { 2, 5, 8 }, { 3, 6, 9 } }
7444 @*/
7445 transpose_mustBeSquare_MAT_inout (x->numericMatrix);
7446 } else {
7447 /*@praat
7448 assert transpose## ({ { 1, 2, 3 }, { 4, 5, 6 } }) = { { 1, 4 }, { 2, 5 }, { 3, 6 } }
7449 @*/
7450 autoMAT newMatrix = transpose_MAT (x->numericMatrix);
7451 x->reset();
7452 x->numericMatrix = newMatrix.releaseToAmbiguousOwner();
7453 }
7454 } else {
7455 /*@praat
7456 a## = { { 1, 2, 3 }, { 4, 5, 6 } }
7457 assert transpose## (a##) = { { 1, 4 }, { 2, 5 }, { 3, 6 } }
7458 assert transpose## (transpose## (a##)) = a##
7459 @*/
7460 x->numericMatrix = transpose_MAT (x->numericMatrix). releaseToAmbiguousOwner();
7461 x->owned = true;
7462 }
7463 } else {
7464 Melder_throw (U"The function “transpose##” requires a matrix, not ", x->whichText(), U".");
7465 }
7466 }
7467 static void do_rowSums_VEC () {
7468 const Stackel x = pop;
7469 if (x->which == Stackel_NUMERIC_MATRIX) {
7470 autoVEC result = rowSums_VEC (x->numericMatrix);
7471 pushNumericVector (result.move());
7472 } else {
7473 Melder_throw (U"The function “rowSums#” requires a matrix, not ", x->whichText(), U".");
7474 }
7475 }
7476 static void do_columnSums_VEC () {
7477 const Stackel x = pop;
7478 if (x->which == Stackel_NUMERIC_MATRIX) {
7479 /*@praat
7480 a## = { { 4, 7, -10 }, { 16, 0, 88 } }
7481 result# = columnSums# (a##)
7482 assert result# = { 20, 7, 78 }
7483 @*/
7484 autoVEC result = columnSums_VEC (x->numericMatrix);
7485 pushNumericVector (result.move());
7486 } else {
7487 Melder_throw (U"The function “columnSums#” requires a matrix, not ", x->whichText(), U".");
7488 }
7489 }
7490 static void do_repeat_VEC () {
7491 const Stackel n = pop, x = pop;
7492 if (x->which == Stackel_NUMERIC_VECTOR && n->which == Stackel_NUMBER) {
7493 const integer n_old = x->numericVector.size;
7494 const integer times = Melder_iround (n->number);
7495 autoVEC result = raw_VEC (n_old * times);
7496 for (integer i = 1; i <= times; i ++)
7497 for (integer j = 1; j <= n_old; j ++)
7498 result [(i - 1) * n_old + j] = x->numericVector [j];
7499 pushNumericVector (result.move());
7500 } else {
7501 Melder_throw (U"The function “repeat#” requires a vector and a number, not ", x->whichText(), U" and ", n->whichText(), U".");
7502 }
7503 }
7504 static void do_rowInners_VEC () {
7505 const Stackel y = pop, x = pop;
7506 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7507 Melder_require (x->numericMatrix.nrow == y->numericMatrix.nrow && x->numericMatrix.ncol == y->numericMatrix.ncol,
7508 U"In the function rowInners#, the two matrices should have the same shape, not ",
7509 x->numericMatrix.nrow, U"x", x->numericMatrix.ncol, U" and ", y->numericMatrix.nrow, U"x", y->numericMatrix.ncol
7510 );
7511 pushNumericVector (rowInners_VEC (x->numericMatrix, y->numericMatrix));
7512 } else {
7513 Melder_throw (U"The function “rowInners#” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7514 }
7515 }
7516 static void do_solve_VEC () {
7517 const Stackel y = pop, x = pop;
7518 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_VECTOR) {
7519 Melder_require (x->numericMatrix.nrow == y->numericVector.size,
7520 U"In the function “solve#”, the number of rows of the matrix and the dimension of the vector should be equal, not ",
7521 x->numericMatrix.nrow, U" and ", y->numericVector.size
7522 );
7523 pushNumericVector (solve_VEC (x->numericMatrix, y->numericVector, NUMeps * y->numericVector.size));
7524 } else {
7525 Melder_throw (U"The function “solve#” requires a matrix and a vector, not ", x->whichText(), U" and ", y->whichText(), U".");
7526 }
7527 }
7528
7529 static void do_solveWeaklyConstrained_VEC () {
7530 const Stackel delta = pop, alpha = pop, y = pop, x = pop;
7531 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_VECTOR && alpha->which == Stackel_NUMBER && delta->which == Stackel_NUMBER) {
7532 Melder_require (x->numericMatrix.nrow == y->numericVector.size,
7533 U"In the function “solveWeaklyConstrained#”, the number of rows of the matrix and the dimension of the vector should be equal, not ",
7534 x->numericMatrix.nrow, U" and ", y->numericVector.size
7535 );
7536 Melder_require (alpha->number >= 0.0,
7537 U"Argument 3, the weight coefficient of the penalty function should not be negative.");
7538 Melder_require (delta->number >= 0.0,
7539 U"Argument 4, the squared length of the solution vector should not be negative.");
7540 pushNumericVector (solveWeaklyConstrainedLinearRegression_VEC (x->numericMatrix, y->numericVector, alpha->number, delta->number));
7541 } else {
7542 Melder_throw (U"The function “solveWeaklyConstrained#” requires a matrix, a vector, and two numbers not ", x->whichText(), U", ",
7543 y->whichText(), U", ", alpha->whichText(), U" and ", delta->whichText(), U".");
7544 }
7545 }
7546
7547 static void do_solve_MAT () {
7548 const Stackel y = pop, x = pop;
7549 if (x->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_MATRIX) {
7550 Melder_require (x->numericMatrix.nrow == y->numericMatrix.nrow,
7551 U"In the function “solve##”, the two matrices should have the same number of rows, not ",
7552 x->numericMatrix.nrow, U" and ", y->numericMatrix.nrow);
7553 pushNumericMatrix (solve_MAT (x->numericMatrix, y->numericMatrix, NUMeps * x->numericMatrix.nrow * x->numericMatrix.ncol));
7554 } else {
7555 Melder_throw (U"The function “solve##” requires two matrices, not ", x->whichText(), U" and ", y->whichText(), U".");
7556 }
7557 }
7558
7559 static void do_solveSparse_VEC () {
7560 const Stackel n = pop;
7561 Melder_assert (n -> which == Stackel_NUMBER);
7562 if (n -> number == 6) {
7563 const Stackel info = pop, tol = pop, niter = pop, nonzeros = pop, y = pop, dict = pop;
7564 if (dict->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_VECTOR &&
7565 nonzeros->which == Stackel_NUMBER && niter->which == Stackel_NUMBER &&
7566 tol->which == Stackel_NUMBER && info->which == Stackel_NUMBER) {
7567 const MAT d = dict->numericMatrix;
7568 Melder_require (d.ncol > d.nrow,
7569 U"The number of columns should be larger than the number of rows (sparse!).");
7570 const VEC yy = y->numericVector;
7571 Melder_require (yy.size == d.nrow,
7572 U"The number of rows in the matrix should equal the size of the vector.");
7573 const integer numberOfNonzeros = Melder_iround (nonzeros->number);
7574 const integer maximumNumberOfIterations = Melder_iround (niter ->number);
7575 const integer infoLevel = Melder_iround (info->number);
7576 const double tolerance = tol->number;
7577 pushNumericVector (solveSparse_IHT_VEC (d, yy, numberOfNonzeros, maximumNumberOfIterations, tolerance, infoLevel));
7578 } else {
7579 Melder_throw (U"The function “solveSparse#” requires a matrix, a vector, and four numbers, not ", dict->whichText(), U", ", y->whichText(), U", ", nonzeros->whichText(), U", ",
7580 niter->whichText(), U", ", tol->whichText(), U" and ", info->whichText());
7581 }
7582 } else if (n -> number == 7) {
7583 const Stackel info = pop, tol = pop, niter = pop, nonzeros = pop, xstart = pop, y = pop, dict = pop;
7584 if (dict->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_VECTOR &&
7585 xstart->which == Stackel_NUMERIC_VECTOR &&
7586 nonzeros->which == Stackel_NUMBER && niter->which == Stackel_NUMBER &&
7587 tol->which == Stackel_NUMBER && info->which == Stackel_NUMBER)
7588 {
7589 const constMAT d = dict->numericMatrix;
7590 Melder_require (d.ncol > d.nrow,
7591 U"The number of columns should be larger than the number of rows (sparse!).");
7592 const constVEC yy = y->numericVector;
7593 const VEC x = xstart->numericVector;
7594 Melder_require (yy.size == d.nrow,
7595 U"The number of rows in the matrix should equal the size of the vector.");
7596 Melder_require (x.size == d.ncol,
7597 U"The number of columns in the matrix should equal the size of start vector.");
7598 autoVEC xs = copy_VEC (x);
7599 const integer numberOfNonzeros = Melder_iround (nonzeros->number);
7600 const integer maximumNumberOfIterations = Melder_iround (niter ->number);
7601 const integer infoLevel = Melder_iround (info->number);
7602 const double tolerance = tol->number;
7603 VECsolveSparse_IHT (xs.all(), d, yy, numberOfNonzeros, maximumNumberOfIterations, tolerance, infoLevel);
7604 pushNumericVector (xs.move());
7605 } else {
7606 Melder_throw (U"The function “solveSparse#” requires a matrix, a vector, and four numbers, not ", dict->whichText(), U", ", y->whichText(), U", ", nonzeros->whichText(), U", ",
7607 niter->whichText(), U", ", tol->whichText(), U" and ", info->whichText());
7608 }
7609 } else {
7610 Melder_throw (U"The function “solveSparse#” requires six or seven arguments.");
7611 }
7612 }
7613
7614 static void do_solveNonnegative_VEC () {
7615 const Stackel n = pop;
7616 Melder_assert (n -> which == Stackel_NUMBER);
7617 if (n -> number == 6) {
7618 const Stackel info = pop, tol = pop, itermax = pop, xstart = pop, y = pop, m = pop;
7619 if (m->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_VECTOR &&
7620 xstart->which == Stackel_NUMERIC_VECTOR && itermax->which == Stackel_NUMBER &&
7621 tol->which == Stackel_NUMBER && info->which == Stackel_NUMBER)
7622 {
7623 const double tolerance = tol->number;
7624 const integer maximumNumberOfIterations = Melder_iround (itermax->number);
7625 const integer infoLevel = Melder_iround (info->number);
7626 const constMAT a = m->numericMatrix;
7627 const VEC yy = y->numericVector;
7628 Melder_require (a.nrow == yy.size,
7629 U"The number of rows in the matrix should equal the size of the vector.");
7630 autoVEC x = copy_VEC (xstart->numericVector);
7631 Melder_require (x.size == a.ncol,
7632 U"The size of start vector should equal the number of columns in the matrix.");
7633 VECsolveNonnegativeLeastSquaresRegression (x.get(), a, yy, maximumNumberOfIterations, tolerance, infoLevel);
7634 pushNumericVector (x.move());
7635 } else {
7636 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", ",
7637 itermax->whichText(), U", ", tol->whichText(), U" and ", info->whichText());
7638 }
7639 } else if (n -> number == 5) {
7640 const Stackel info = pop, tol = pop, itermax = pop, y = pop, m = pop;
7641 if (m->which == Stackel_NUMERIC_MATRIX && y->which == Stackel_NUMERIC_VECTOR &&
7642 itermax->which == Stackel_NUMBER && tol->which == Stackel_NUMBER && info->which == Stackel_NUMBER)
7643 {
7644 const double tolerance = tol->number;
7645 const integer maximumNumberOfIterations = Melder_iround (itermax->number);
7646 const integer infoLevel = Melder_iround (info->number);
7647 const constMAT a = m->numericMatrix;
7648 const VEC yy = y->numericVector;
7649 Melder_require (a.nrow == yy.size,
7650 U"The number of rows in the matrix should equal the size of the vector.");
7651 pushNumericVector (solveNonnegativeLeastSquaresRegression_VEC (a, yy, maximumNumberOfIterations, tolerance, infoLevel));
7652 } else {
7653 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());
7654 }
7655 } else {
7656 Melder_throw (U"The function “solveNonnegative#” requires five or six arguments.");
7657 }
7658 }
7659
7660 static void do_askForTrust () {
7661 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7662 U"The function “askForTrust” is not available inside manuals.");
7663 const Stackel n = pop;
7664 Melder_require (n->number == 0,
7665 U"The function “askForTrust” should have no arguments.");
7666 const Editor optionalTrustWindowOwningEditor = theInterpreter -> optionalDynamicEnvironmentEditor();
7667 const GuiWindow parentShell = ( optionalTrustWindowOwningEditor ? optionalTrustWindowOwningEditor -> windowForm : theCurrentPraatApplication -> topShell );
7668 const bool isAlreadyTrusted = theInterpreter -> scriptReference && theInterpreter -> scriptReference -> trusted;
7669 if (! isAlreadyTrusted) {
7670 conststring32 message [1+5] = { };
7671 if (theInterpreter -> scriptReference) {
7672 message [1] = U"The script";
7673 message [2] = Melder_cat (U"“", theInterpreter -> scriptReference -> string.get(), U"”");
7674 } else if (theInterpreter -> notebookReference) {
7675 message [1] = U"The notebook";
7676 message [2] = Melder_cat (U"“", theInterpreter -> notebookReference -> string.get(), U"”");
7677 } else
7678 message [1] = U"Your untitled script or notebook";
7679 message [3] = U"requests permission to control your computer (e.g. it may want to overwrite files,\n"
7680 "delete folders, run system commands, and/or access the internet).";
7681 message [4] = U"Allow this only if you fully trust the intentions and skills of the author(s),\n"
7682 "AND the intentions and skills of the author(s) of the script(s) called by this script directly or indirectly.";
7683 conststring32 option1 = U"CANCEL\n(because I don’t completely trust the authors’ skills and/or intentions)";
7684 conststring32 option2 =
7685 theInterpreter -> scriptReference ?
7686 U"Yes, I allow this script to CONTROL MY COMPUTER, because I fully trust the skills and\n"
7687 "intentions of its authors AND of those of the authors of any scripts called by it directly or indirectly."
7688 : theInterpreter -> notebookReference ?
7689 U"Yes, I allow this notebook 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 :
7692 U"Yes, I allow this script or 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 const bool trusted = GuiTrust_get (parentShell, optionalTrustWindowOwningEditor,
7695 message [1], message [2], message [3], message [4], message [5],
7696 option1, option2, nullptr, nullptr, nullptr, theInterpreter
7697 );
7698 if (trusted) {
7699 if (theInterpreter -> scriptReference)
7700 theInterpreter -> scriptReference -> trusted = true;
7701 else if (theInterpreter -> notebookReference)
7702 theInterpreter -> notebookReference -> trusted = true;
7703 }
7704 }
7705 pushNumber (1);
7706 }
7707
7708 static void do_beginPause () {
7709 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7710 U"The function “beginPause” is not available inside manuals.");
7711 const Stackel n = pop;
7712 if (n->number == 1) {
7713 const Stackel title = pop;
7714 if (title->which == Stackel_STRING) {
7715 const Editor optionalPauseWindowOwningEditor = theInterpreter -> optionalDynamicEnvironmentEditor();
7716 const GuiWindow parentShell = ( optionalPauseWindowOwningEditor ? optionalPauseWindowOwningEditor -> windowForm : theCurrentPraatApplication -> topShell );
7717 UiPause_begin (parentShell, optionalPauseWindowOwningEditor, title->getString(), theInterpreter);
7718 } else {
7719 Melder_throw (U"The function “beginPause” requires a string (the title), not ", title->whichText(), U".");
7720 }
7721 } else {
7722 Melder_throw (U"The function “beginPause” requires 1 argument (a title), not ", n->number, U".");
7723 }
7724 pushNumber (1);
7725 }
7726 static void do_real () {
7727 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7728 U"The function “real” is not available inside manuals.");
7729 const Stackel n = pop;
7730 Melder_require (n->number == 2,
7731 U"The function “real” requires 2 arguments (a label text and a default value), not ", n->number, U".");
7732 const Stackel defaultValue = pop;
7733 conststring32 defaultString = nullptr;
7734 if (defaultValue->which == Stackel_STRING)
7735 defaultString = defaultValue->getString();
7736 else if (defaultValue->which == Stackel_NUMBER)
7737 defaultString = Melder_double (defaultValue->number);
7738 else
7739 Melder_throw (U"The second argument of “real” (the default value) should be a string or a number, not ", defaultValue->whichText(), U".");
7740 const Stackel label = pop;
7741 Melder_require (label->which == Stackel_STRING,
7742 U"The first argument of “real” (the label text) should be a string, not ", label->whichText(), U".");
7743 UiPause_real (label->getString(), defaultString);
7744 pushNumber (1);
7745 }
7746 static void do_positive () {
7747 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7748 U"The function “positive” is not available inside manuals.");
7749 const Stackel n = pop;
7750 Melder_require (n->number == 2,
7751 U"The function “positive” requires 2 arguments (a label text and a default value), not ", n->number, U".");
7752 const Stackel defaultValue = pop;
7753 conststring32 defaultString = nullptr;
7754 if (defaultValue->which == Stackel_STRING) {
7755 defaultString = defaultValue->getString();
7756 } else if (defaultValue->which == Stackel_NUMBER) {
7757 defaultString = Melder_double (defaultValue->number);
7758 } else {
7759 Melder_throw (U"The second argument of “positive” (the default value) should be a string or a number, not ", defaultValue->whichText(), U".");
7760 }
7761 const Stackel label = pop;
7762 Melder_require (label->which == Stackel_STRING,
7763 U"The first argument of “positive” (the label text) should be a string, not ", label->whichText(), U".");
7764 UiPause_positive (label->getString(), defaultString);
7765 pushNumber (1);
7766 }
7767 static void do_integer () {
7768 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7769 U"The function “integer” is not available inside manuals.");
7770 const Stackel n = pop;
7771 Melder_require (n->number == 2,
7772 U"The function “integer” requires 2 arguments (a label text and a default value), not ", n->number, U".");
7773 const Stackel defaultValue = pop;
7774 conststring32 defaultString = nullptr;
7775 if (defaultValue->which == Stackel_STRING) {
7776 defaultString = defaultValue->getString();
7777 } else if (defaultValue->which == Stackel_NUMBER) {
7778 defaultString = Melder_double (defaultValue->number);
7779 } else {
7780 Melder_throw (U"The second argument of “integer” (the default value) should be a string or a number, not ", defaultValue->whichText(), U".");
7781 }
7782 const Stackel label = pop;
7783 Melder_require (label->which == Stackel_STRING,
7784 U"The first argument of “integer” (the label text) should be a string, not ", label->whichText(), U".");
7785 UiPause_integer (label->getString(), defaultString);
7786 pushNumber (1);
7787 }
7788 static void do_natural () {
7789 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7790 U"The function “natural” is not available inside manuals.");
7791 const Stackel n = pop;
7792 Melder_require (n->number == 2,
7793 U"The function “natural” requires 2 arguments (a label text and a default value), not ", n->number, U".");
7794 const Stackel defaultValue = pop;
7795 conststring32 defaultString = nullptr;
7796 if (defaultValue->which == Stackel_STRING) {
7797 defaultString = defaultValue->getString();
7798 } else if (defaultValue->which == Stackel_NUMBER) {
7799 defaultString = Melder_double (defaultValue->number);
7800 } else {
7801 Melder_throw (U"The second argument of “natural” (the default value) should be a string or a number, not ", defaultValue->whichText(), U".");
7802 }
7803 const Stackel label = pop;
7804 Melder_require (label->which == Stackel_STRING,
7805 U"The first argument of “natural” (the label text) should be a string, not ", label->whichText(), U".");
7806 UiPause_natural (label->getString(), defaultString);
7807 pushNumber (1);
7808 }
7809 static void do_word () {
7810 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7811 U"The function “word” is not available inside manuals.");
7812 const Stackel n = pop;
7813 Melder_require (n->number == 2,
7814 U"The function “word” requires 2 arguments (a label text and a default value), not ", n->number, U".");
7815 const Stackel defaultValue = pop;
7816 Melder_require (defaultValue->which == Stackel_STRING,
7817 U"The second argument of “word” (the default value) should be a string, not ", defaultValue->whichText(), U".");
7818 const Stackel label = pop;
7819 Melder_require (label->which == Stackel_STRING,
7820 U"The first argument of “word” (the label text) should be a string, not ", label->whichText(), U".");
7821 UiPause_word (label->getString(), defaultValue->getString());
7822 pushNumber (1);
7823 }
7824 static void do_sentence () {
7825 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7826 U"The function “sentence” is not available inside manuals.");
7827 const Stackel n = pop;
7828 Melder_require (n->number == 2,
7829 U"The function “sentence” requires 2 arguments (a label text and a default value), not ", n->number, U".");
7830 const Stackel defaultValue = pop;
7831 Melder_require (defaultValue->which == Stackel_STRING,
7832 U"The second argument of “sentence” (the default value) should be a string, not ", defaultValue->whichText(), U".");
7833 const Stackel label = pop;
7834 Melder_require (label->which == Stackel_STRING,
7835 U"The first argument of “sentence” (the label text) should be a string, not ", label->whichText(), U".");
7836 UiPause_sentence (label->getString(), defaultValue->getString());
7837 pushNumber (1);
7838 }
7839 static void do_text () {
7840 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7841 U"The function “text” is not available inside manuals.");
7842 const Stackel n = pop;
7843 Melder_require (n->number >= 2 && n->number <= 3,
7844 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".");
7845 integer numberOfLines = 1; // the default
7846 if (n->number == 3) {
7847 /*
7848 For compatibility, the number of lines might be at the end.
7849 */
7850 const Stackel arg3 = pop, arg2 = pop, arg1 = pop;
7851 if (arg1->which == Stackel_STRING && arg2->which == Stackel_STRING && arg3->which == Stackel_NUMBER) {
7852 UiPause_text (arg1->getString(), arg2->getString(), Melder_iround (arg3->number));
7853 pushNumber (1);
7854 return;
7855 }
7856 const Stackel defaultValue = arg3;
7857 Melder_require (defaultValue->which == Stackel_STRING,
7858 U"The third argument of “text” (the default value) should be a string, not ", defaultValue->whichText(), U".");
7859 const Stackel label = arg2;
7860 Melder_require (label->which == Stackel_STRING,
7861 U"The second argument of “text” (the label) should be a string, not ", label->whichText(), U".");
7862 const Stackel _numberOfLines = arg1;
7863 Melder_require (_numberOfLines->which == Stackel_NUMBER,
7864 U"The first argument of “text” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
7865 numberOfLines = Melder_iround (_numberOfLines->number);
7866 UiPause_text (label->getString(), defaultValue->getString(), numberOfLines);
7867 pushNumber (1);
7868 return;
7869 }
7870 const Stackel defaultValue = pop;
7871 Melder_require (defaultValue->which == Stackel_STRING,
7872 U"The second argument of “text” (the default value) should be a string, not ", defaultValue->whichText(), U".");
7873 const Stackel label = pop;
7874 Melder_require (label->which == Stackel_STRING,
7875 U"The first argument of “text” (the label text) should be a string, not ", label->whichText(), U".");
7876 UiPause_text (label->getString(), defaultValue->getString(), numberOfLines);
7877 pushNumber (1);
7878 }
7879 static void do_infile () {
7880 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7881 U"The function “infile” is not available inside manuals.");
7882 const Stackel n = pop;
7883 Melder_require (n->number >= 2 && n->number <= 3,
7884 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".");
7885 integer numberOfLines = 3; // the default
7886 const Stackel defaultValue = pop;
7887 Melder_require (defaultValue->which == Stackel_STRING,
7888 U"The last argument of “infile” (the default value) should be a string, not ", defaultValue->whichText(), U".");
7889 const Stackel label = pop;
7890 Melder_require (label->which == Stackel_STRING,
7891 U"The penultimate argument of “infile” (the label text) should be a string, not ", label->whichText(), U".");
7892 if (n->number == 3) {
7893 const Stackel _numberOfLines = pop;
7894 Melder_require (_numberOfLines->which == Stackel_NUMBER,
7895 U"The first argument of “infile” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
7896 numberOfLines = Melder_iround (_numberOfLines->number);
7897 }
7898 UiPause_infile (label->getString(), defaultValue->getString(), numberOfLines);
7899 pushNumber (1);
7900 }
7901 static void do_outfile () {
7902 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7903 U"The function “outfile” is not available inside manuals.");
7904 const Stackel n = pop;
7905 Melder_require (n->number >= 2 && n->number <= 3,
7906 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".");
7907 integer numberOfLines = 3; // the default
7908 const Stackel defaultValue = pop;
7909 Melder_require (defaultValue->which == Stackel_STRING,
7910 U"The last argument of “outfile” (the default value) should be a string, not ", defaultValue->whichText(), U".");
7911 const Stackel label = pop;
7912 Melder_require (label->which == Stackel_STRING,
7913 U"The penultimate argument of “outfile” (the label text) should be a string, not ", label->whichText(), U".");
7914 if (n->number == 3) {
7915 const Stackel _numberOfLines = pop;
7916 Melder_require (_numberOfLines->which == Stackel_NUMBER,
7917 U"The first argument of “outfile” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
7918 numberOfLines = Melder_iround (_numberOfLines->number);
7919 }
7920 UiPause_outfile (label->getString(), defaultValue->getString(), numberOfLines);
7921 pushNumber (1);
7922 }
7923 static void do_folder () {
7924 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7925 U"The function “folder” is not available inside manuals.");
7926 const Stackel n = pop;
7927 Melder_require (n->number >= 2 && n->number <= 3,
7928 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".");
7929 integer numberOfLines = 3; // the default
7930 const Stackel defaultValue = pop;
7931 Melder_require (defaultValue->which == Stackel_STRING,
7932 U"The last argument of “folder” (the default value) should be a string, not ", defaultValue->whichText(), U".");
7933 const Stackel label = pop;
7934 Melder_require (label->which == Stackel_STRING,
7935 U"The penultimate argument of “folder” (the label text) should be a string, not ", label->whichText(), U".");
7936 if (n->number == 3) {
7937 const Stackel _numberOfLines = pop;
7938 Melder_require (_numberOfLines->which == Stackel_NUMBER,
7939 U"The first argument of “folder” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
7940 numberOfLines = Melder_iround (_numberOfLines->number);
7941 }
7942 UiPause_folder (label->getString(), defaultValue->getString(), numberOfLines);
7943 pushNumber (1);
7944 }
7945 static void do_realvector () {
7946 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7947 U"The function “realvector” is not available inside manuals.");
7948 const Stackel n = pop;
7949 Melder_require (n->number >= 3 && n->number <= 4,
7950 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".");
7951 integer numberOfLines = 7; // the default
7952 const Stackel defaultValue = pop;
7953 conststring32 defaultString;
7954 if (defaultValue->which == Stackel_STRING)
7955 defaultString = defaultValue->getString();
7956 else if (defaultValue->which == Stackel_NUMERIC_VECTOR)
7957 defaultString = Melder_VEC (defaultValue->numericVector, true);
7958 else
7959 Melder_throw (U"The last argument of “realvector” (the default value) should be a string or a numeric vector, not ", defaultValue->whichText(), U".");
7960 const Stackel _format = pop;
7961 Melder_require (_format->which == Stackel_STRING,
7962 U"The penultimate argument of “realvector” (the format) should be a string, not ", _format->whichText(), U".");
7963 kUi_realVectorFormat format = kUi_realVectorFormat_getValue (_format->getString());
7964 Melder_require (format != kUi_realVectorFormat::UNDEFINED,
7965 U"The format should be “(whitespace-separated)” or “(formula)”, not “", _format->getString(), U"”.");
7966 const Stackel label = pop;
7967 Melder_require (label->which == Stackel_STRING,
7968 U"The antepenultimate argument of “realvector” (the label text) should be a string, not ", label->whichText(), U".");
7969 if (n->number == 4) {
7970 const Stackel _numberOfLines = pop;
7971 Melder_require (_numberOfLines->which == Stackel_NUMBER,
7972 U"The first argument of “realvector” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
7973 numberOfLines = Melder_iround (_numberOfLines->number);
7974 }
7975 UiPause_realvector (label->getString(), format, defaultString, numberOfLines);
7976 pushNumber (1);
7977 }
7978 static void do_positivevector () {
7979 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
7980 U"The function “positivevector” is not available inside manuals.");
7981 const Stackel n = pop;
7982 Melder_require (n->number >= 3 && n->number <= 4,
7983 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".");
7984 integer numberOfLines = 7; // the default
7985 const Stackel defaultValue = pop;
7986 conststring32 defaultString;
7987 if (defaultValue->which == Stackel_STRING)
7988 defaultString = defaultValue->getString();
7989 else if (defaultValue->which == Stackel_NUMERIC_VECTOR)
7990 defaultString = Melder_VEC (defaultValue->numericVector, true);
7991 else
7992 Melder_throw (U"The last argument of “positivevector” (the default value) should be a string or a numeric vector, not ", defaultValue->whichText(), U".");
7993 const Stackel _format = pop;
7994 Melder_require (_format->which == Stackel_STRING,
7995 U"The penultimate argument of “positivevector” (the format) should be a string, not ", _format->whichText(), U".");
7996 kUi_realVectorFormat format = kUi_realVectorFormat_getValue (_format->getString());
7997 Melder_require (format != kUi_realVectorFormat::UNDEFINED,
7998 U"The format should be “(whitespace-separated)” or “(formula)”, not “", _format->getString(), U"”.");
7999 const Stackel label = pop;
8000 Melder_require (label->which == Stackel_STRING,
8001 U"The antepenultimate argument of “positivevector” (the label text) should be a string, not ", label->whichText(), U".");
8002 if (n->number == 4) {
8003 const Stackel _numberOfLines = pop;
8004 Melder_require (_numberOfLines->which == Stackel_NUMBER,
8005 U"The first argument of “positivevector” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
8006 numberOfLines = Melder_iround (_numberOfLines->number);
8007 }
8008 UiPause_positivevector (label->getString(), format, defaultString, numberOfLines);
8009 pushNumber (1);
8010 }
8011 static void do_integervector () {
8012 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8013 U"The function “integervector” is not available inside manuals.");
8014 const Stackel n = pop;
8015 Melder_require (n->number >= 3 && n->number <= 4,
8016 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".");
8017 integer numberOfLines = 7; // the default
8018 const Stackel defaultValue = pop;
8019 conststring32 defaultString;
8020 if (defaultValue->which == Stackel_STRING)
8021 defaultString = defaultValue->getString();
8022 else if (defaultValue->which == Stackel_NUMERIC_VECTOR)
8023 defaultString = Melder_VEC (defaultValue->numericVector, true);
8024 else
8025 Melder_throw (U"The last argument of “integervector” (the default value) should be a string or a numeric vector, not ", defaultValue->whichText(), U".");
8026 const Stackel _format = pop;
8027 Melder_require (_format->which == Stackel_STRING,
8028 U"The penultimate argument of “integervector” (the format) should be a string, not ", _format->whichText(), U".");
8029 kUi_integerVectorFormat format = kUi_integerVectorFormat_getValue (_format->getString());
8030 Melder_require (format != kUi_integerVectorFormat::UNDEFINED,
8031 U"The format should be “(whitespace-separated)”, “(ranges)”, or “(formula)”, not “", _format->getString(), U"”.");
8032 const Stackel label = pop;
8033 Melder_require (label->which == Stackel_STRING,
8034 U"The antepenultimate argument of “integervector” (the label text) should be a string, not ", label->whichText(), U".");
8035 if (n->number == 4) {
8036 const Stackel _numberOfLines = pop;
8037 Melder_require (_numberOfLines->which == Stackel_NUMBER,
8038 U"The first argument of “integervector” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
8039 numberOfLines = Melder_iround (_numberOfLines->number);
8040 }
8041 UiPause_integervector (label->getString(), format, defaultString, numberOfLines);
8042 pushNumber (1);
8043 }
8044 static void do_naturalvector () {
8045 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8046 U"The function “naturalvector” is not available inside manuals.");
8047 const Stackel n = pop;
8048 Melder_require (n->number >= 3 && n->number <= 4,
8049 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".");
8050 integer numberOfLines = 7; // the default
8051 const Stackel defaultValue = pop;
8052 conststring32 defaultString;
8053 if (defaultValue->which == Stackel_STRING)
8054 defaultString = defaultValue->getString();
8055 else if (defaultValue->which == Stackel_NUMERIC_VECTOR)
8056 defaultString = Melder_VEC (defaultValue->numericVector, true);
8057 else
8058 Melder_throw (U"The last argument of “naturalector” (the default value) should be a string or a numeric vector, not ", defaultValue->whichText(), U".");
8059 const Stackel _format = pop;
8060 Melder_require (_format->which == Stackel_STRING,
8061 U"The penultimate argument of “naturalvector” (the format) should be a string, not ", _format->whichText(), U".");
8062 kUi_integerVectorFormat format = kUi_integerVectorFormat_getValue (_format->getString());
8063 Melder_require (format != kUi_integerVectorFormat::UNDEFINED,
8064 U"The format should be “(whitespace-separated)”, “(ranges)”, or “(formula)”, not “", _format->getString(), U"”.");
8065 const Stackel label = pop;
8066 Melder_require (label->which == Stackel_STRING,
8067 U"The antepenultimate argument of “naturalvector” (the label text) should be a string, not ", label->whichText(), U".");
8068 if (n->number == 4) {
8069 const Stackel _numberOfLines = pop;
8070 Melder_require (_numberOfLines->which == Stackel_NUMBER,
8071 U"The first argument of “naturalvector” (the number of lines) should be a number, not ", _numberOfLines->whichText(), U".");
8072 numberOfLines = Melder_iround (_numberOfLines->number);
8073 }
8074 UiPause_naturalvector (label->getString(), format, defaultString, numberOfLines);
8075 pushNumber (1);
8076 }
8077 static void do_boolean () {
8078 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8079 U"The function “boolean” is not available inside manuals.");
8080 const Stackel n = pop;
8081 Melder_require (n->number == 2,
8082 U"The function “boolean” requires 2 arguments (a label text and a default value), not ", n->number, U".");
8083 const Stackel defaultValue = pop;
8084 double defaultNumber = undefined;
8085 if (defaultValue->which == Stackel_STRING) {
8086 conststring32 defaultString = defaultValue->getString();
8087 if (
8088 str32equ (defaultString, U"on") || str32equ (defaultString, U"yes") ||
8089 str32equ (defaultString, U"ON") || str32equ (defaultString, U"YES") ||
8090 str32equ (defaultString, U"On") || str32equ (defaultString, U"Yes")
8091 )
8092 defaultNumber = 1;
8093 else if (
8094 str32equ (defaultString, U"off") || str32equ (defaultString, U"no") ||
8095 str32equ (defaultString, U"OFF") || str32equ (defaultString, U"NO") ||
8096 str32equ (defaultString, U"Off") || str32equ (defaultString, U"No")
8097 )
8098 defaultNumber = 0;
8099 else
8100 Melder_throw (U"If the second argument of “boolean” is a string, it can only be "
8101 "“yes”, “no”, “on”, or “off”, not “", defaultString, U"”.");
8102 } else if (defaultValue->which == Stackel_NUMBER) {
8103 defaultNumber = defaultValue->number;
8104 } else {
8105 Melder_throw (U"The second argument of “boolean” (the default value) should be a number (0 or 1) "
8106 "or a string (“yes”, “no”, “on”, “off”), not ", defaultValue->whichText(), U".");
8107 }
8108 const Stackel label = pop;
8109 Melder_require (label->which == Stackel_STRING,
8110 U"The first argument of “boolean” (the label text) should be a string, not ", label->whichText(), U".");
8111 UiPause_boolean (label->getString(), defaultNumber != 0.0);
8112 pushNumber (1);
8113 }
8114 static void do_choice () {
8115 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8116 U"The function “choice” is not available inside manuals.");
8117 const Stackel n = pop;
8118 Melder_require (n->number == 2,
8119 U"The function “choice” requires 2 arguments (a label text and a default value), not ", n->number, U".");
8120 const Stackel defaultValue = pop;
8121 Melder_require (defaultValue->which == Stackel_NUMBER,
8122 U"The second argument of “choice” (the default value) should be a whole number, not ", defaultValue->whichText(), U".");
8123 const Stackel label = pop;
8124 Melder_require (label->which == Stackel_STRING,
8125 U"The first argument of “choice” (the label text) should be a string, not ", label->whichText(), U".");
8126 UiPause_choice (label->getString(), Melder_iround (defaultValue->number));
8127 pushNumber (1);
8128 }
8129 static void do_optionmenu () {
8130 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8131 U"The function “optionmenu” is not available inside manuals.");
8132 const Stackel n = pop;
8133 Melder_require (n->number == 2,
8134 U"The function “optionmenu” requires 2 arguments (a label text and a default value), not ", n->number, U".");
8135 const Stackel defaultValue = pop;
8136 Melder_require (defaultValue->which == Stackel_NUMBER,
8137 U"The second argument of “optionmenu” (the default value) should be a whole number, not ", defaultValue->whichText(), U".");
8138 const Stackel label = pop;
8139 Melder_require (label->which == Stackel_STRING,
8140 U"The first argument of “optionmenu” (the label text) should be a string, not ", label->whichText(), U".");
8141 UiPause_optionmenu (label->getString(), Melder_iround (defaultValue->number));
8142 pushNumber (1);
8143 }
8144 static void do_option () {
8145 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8146 U"The function “option” is not available inside manuals.");
8147 const Stackel n = pop;
8148 Melder_require (n->number == 1,
8149 U"The function “option” requires 1 argument (a text), not ", n->number, U".");
8150 const Stackel text = pop;
8151 Melder_require (text->which == Stackel_STRING,
8152 U"The argument of “option” should be a string (the text), not ", text->whichText(), U".");
8153 UiPause_option (text->getString());
8154 pushNumber (1);
8155 }
8156 static void do_heading () {
8157 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8158 U"The function “heading” is not available inside manuals.");
8159 const Stackel n = pop;
8160 Melder_require (n->number == 1,
8161 U"The function “heading” requires 1 argument (a text), not ", n->number, U".");
8162 const Stackel text = pop;
8163 Melder_require (text->which == Stackel_STRING,
8164 U"The argument of “heading” should be a string (the text), not ", text->whichText(), U".");
8165 UiPause_heading (text->getString());
8166 pushNumber (1);
8167 }
8168 static void do_comment () {
8169 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8170 U"The function “comment” is not available inside manuals.");
8171 const Stackel n = pop;
8172 Melder_require (n->number == 1,
8173 U"The function “comment” requires 1 argument (a text), not ", n->number, U".");
8174 const Stackel text = pop;
8175 Melder_require (text->which == Stackel_STRING,
8176 U"The argument of “comment” should be a string (the text), not ", text->whichText(), U".");
8177 UiPause_comment (text->getString());
8178 pushNumber (1);
8179 }
8180 static void do_endPause () {
8181 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8182 U"The function “endPause” is not available inside manuals.");
8183 const Stackel n = pop;
8184 if (n->number < 2 || n->number > 12)
8185 Melder_throw (U"The function “endPause” requires 2 to 12 arguments, not ", n->number, U".");
8186 const Stackel d = pop;
8187 if (d->which != Stackel_NUMBER)
8188 Melder_throw (U"The last argument of “endPause” should be a number (the default or cancel continue button), not ", d->whichText(), U".");
8189 /* mutable */ integer numberOfContinueButtons = Melder_iround (n->number) - 1;
8190 /* mutable */ integer cancelContinueButton = 0, defaultContinueButton = Melder_iround (d->number);
8191 Stackel ca = pop;
8192 if (ca->which == Stackel_NUMBER) {
8193 cancelContinueButton = defaultContinueButton;
8194 defaultContinueButton = Melder_iround (ca->number);
8195 numberOfContinueButtons -= 1;
8196 if (cancelContinueButton < 0 || cancelContinueButton > numberOfContinueButtons)
8197 Melder_throw (U"Your last argument of “endPause” is the number of the cancel button; it cannot be ", cancelContinueButton,
8198 U" but should be 0 (no cancel or stop button) or lie between 1 and ", numberOfContinueButtons, U".");
8199 if (cancelContinueButton == 0)
8200 cancelContinueButton = -1;
8201 }
8202 Stackel co [1+10] = { 0 };
8203 for (integer i = numberOfContinueButtons; i >= 1; i --) {
8204 co [i] = ( cancelContinueButton != 0 || i != numberOfContinueButtons ? pop : ca );
8205 if (co[i]->which != Stackel_STRING)
8206 Melder_throw (U"Each of the first ", numberOfContinueButtons,
8207 U" argument(s) of “endPause” should be a string (a button text), not ", co[i]->whichText(), U".");
8208 }
8209 const integer buttonClicked = UiPause_end (numberOfContinueButtons, defaultContinueButton, cancelContinueButton,
8210 ! co [1] ? nullptr : co[1]->getString(), ! co [2] ? nullptr : co[2]->getString(),
8211 ! co [3] ? nullptr : co[3]->getString(), ! co [4] ? nullptr : co[4]->getString(),
8212 ! co [5] ? nullptr : co[5]->getString(), ! co [6] ? nullptr : co[6]->getString(),
8213 ! co [7] ? nullptr : co[7]->getString(), ! co [8] ? nullptr : co[8]->getString(),
8214 ! co [9] ? nullptr : co[9]->getString(), ! co [10] ? nullptr : co[10]->getString(),
8215 theInterpreter);
8216 //Melder_casual (U"Button ", buttonClicked);
8217 pushNumber (buttonClicked);
8218 }
8219 static void do_lowerCaseAppNameStr () {
8220 const Stackel n = pop;
8221 Melder_require (n->number == 0,
8222 U"The function “lowerCaseAppName$” requires 0 arguments, not ", n->number, U".");
8223 return pushString (Melder_dup (Melder_lowerCaseAppName()));
8224 }
8225 static void do_upperCaseAppNameStr () {
8226 const Stackel n = pop;
8227 Melder_require (n->number == 0,
8228 U"The function “upperCaseAppName$” requires 0 arguments, not ", n->number, U".");
8229 return pushString (Melder_dup (Melder_upperCaseAppName()));
8230 }
8231 static void do_clock () {
8232 const Stackel n = pop;
8233 Melder_require (n->number == 0,
8234 U"The function “clock” requires 0 arguments, not ", n->number, U".");
8235 return pushNumber (Melder_clock ());
8236 }
8237 static void do_appVersion () {
8238 const Stackel n = pop;
8239 Melder_require (n->number == 0,
8240 U"The function “appVersion” requires 0 arguments, not ", n->number, U".");
8241 return pushNumber (Melder_appVersion());
8242 }
8243 static void do_appVersionStr () {
8244 const Stackel n = pop;
8245 Melder_require (n->number == 0,
8246 U"The function “appVersion$” requires 0 arguments, not ", n->number, U".");
8247 return pushString (Melder_dup (Melder_appVersionSTR()));
8248 }
8249 static void do_appYear () {
8250 const Stackel n = pop;
8251 Melder_require (n->number == 0,
8252 U"The function “appYear” requires 0 arguments, not ", n->number, U".");
8253 return pushNumber (Melder_appYear());
8254 }
8255 static void do_appMonth () {
8256 const Stackel n = pop;
8257 Melder_require (n->number == 0,
8258 U"The function “appMonth” requires 0 arguments, not ", n->number, U".");
8259 return pushNumber (Melder_appMonth());
8260 }
8261 static void do_appMonthStr () {
8262 const Stackel n = pop;
8263 Melder_require (n->number == 0,
8264 U"The function “appMonth$” requires 0 arguments, not ", n->number, U".");
8265 return pushString (Melder_dup (Melder_appMonthSTR()));
8266 }
8267 static void do_appDay () {
8268 const Stackel n = pop;
8269 Melder_require (n->number == 0,
8270 U"The function “appDay” requires 0 arguments, not ", n->number, U".");
8271 return pushNumber (Melder_appDay());
8272 }
8273 static void do_chooseReadFileStr () {
8274 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8275 U"The function “chooseReadFile$” is not available inside manuals.");
8276 const Stackel n = pop;
8277 Melder_require (n->number == 1,
8278 U"The function “chooseReadFile$” requires 1 argument (a title), not ", n->number, U".");
8279 const Stackel title = pop;
8280 Melder_require (title->which == Stackel_STRING,
8281 U"The argument of “chooseReadFile$” should be a string (the title), not ", title->whichText(), U".");
8282 autoStringSet fileNames = GuiFileSelect_getInfileNames (nullptr, title->getString(), false);
8283 if (fileNames->size == 0)
8284 return pushString (Melder_dup (U""));
8285 SimpleString fileName = fileNames->at [1];
8286 pushString (Melder_dup (fileName -> string.get()));
8287 }
8288 static void do_chooseWriteFileStr () {
8289 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8290 U"The function “chooseWriteFile$” is not available inside manuals.");
8291 const Stackel n = pop;
8292 Melder_require (n->number == 2,
8293 U"The function “chooseWriteFile$” requires 2 arguments (a title and a default name), not ", n->number, U".");
8294 const Stackel defaultName = pop, title = pop;
8295 Melder_require (title->which == Stackel_STRING && defaultName->which == Stackel_STRING,
8296 U"The arguments of “chooseWriteFile$” should be two strings (the title and the default name).");
8297 autostring32 result = GuiFileSelect_getOutfileName (nullptr, title->getString(), defaultName->getString());
8298 if (! result)
8299 result = Melder_dup (U"");
8300 pushString (result.move());
8301 }
8302 static void do_chooseFolder_STR () {
8303 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8304 U"The function “chooseFolder$” is not available inside manuals.");
8305 const Stackel n = pop;
8306 Melder_require (n->number == 1,
8307 U"The function “chooseFolder$” requires 1 argument (a title), not ", n->number, U".");
8308 const Stackel title = pop;
8309 Melder_require (title->which == Stackel_STRING,
8310 U"The argument of “chooseFolder$” should be a string (the title).");
8311 autostring32 result = GuiFileSelect_getFolderName (nullptr, title->getString());
8312 if (! result)
8313 result = Melder_dup (U"");
8314 pushString (result.move());
8315 }
8316 static void do_chooseDirectory_STR () {
8317 Melder_require (praat_commandsWithExternalSideEffectsAreAllowed (),
8318 U"The function “chooseDirectory$” is not available inside manuals.");
8319 const Stackel n = pop;
8320 Melder_require (n->number == 1,
8321 U"The function “chooseDirectory$” requires 1 argument (a title), not ", n->number, U".");
8322 const Stackel title = pop;
8323 Melder_require (title->which == Stackel_STRING,
8324 U"The argument of “chooseDirectory$” should be a string (the title).");
8325 autostring32 result = GuiFileSelect_getFolderName (nullptr, title->getString());
8326 if (! result)
8327 result = Melder_dup (U"");
8328 pushString (result.move());
8329 }
8330 static void do_demoWindowTitle () {
8331 const Stackel n = pop;
8332 if (n->number == 1) {
8333 const Stackel title = pop;
8334 if (title->which == Stackel_STRING) {
8335 Demo_windowTitle (title->getString());
8336 } else {
8337 Melder_throw (U"The argument of “demoWindowTitle” should be a string (the title), not ", title->whichText(), U".");
8338 }
8339 } else {
8340 Melder_throw (U"The function “demoWindowTitle” requires 1 argument (a title), not ", n->number, U".");
8341 }
8342 pushNumber (1);
8343 }
8344 static void do_demoShow () {
8345 const Stackel n = pop;
8346 if (n->number != 0)
8347 Melder_throw (U"The function “demoShow” requires 0 arguments, not ", n->number, U".");
8348 Demo_show ();
8349 pushNumber (1);
8350 }
8351 static void do_demoWaitForInput () {
8352 const Stackel n = pop;
8353 if (n->number != 0)
8354 Melder_throw (U"The function “demoWaitForInput” requires 0 arguments, not ", n->number, U".");
8355 Demo_waitForInput (theInterpreter);
8356 pushNumber (1);
8357 }
8358 static void do_demoPeekInput () {
8359 const Stackel n = pop;
8360 if (n->number != 0)
8361 Melder_throw (U"The function “demoPeekInput” requires 0 arguments, not ", n->number, U".");
8362 Demo_peekInput (theInterpreter);
8363 pushNumber (1);
8364 }
8365 static void do_demoInput () {
8366 const Stackel n = pop;
8367 if (n->number == 1) {
8368 const Stackel keys = pop;
8369 if (keys->which == Stackel_STRING) {
8370 const bool result = Demo_input (keys->getString());
8371 pushNumber (result);
8372 } else {
8373 Melder_throw (U"The argument of “demoInput” should be a string (the keys), not ", keys->whichText(), U".");
8374 }
8375 } else {
8376 Melder_throw (U"The function “demoInput” requires 1 argument (keys), not ", n->number, U".");
8377 }
8378 }
8379 static void do_demoClickedIn () {
8380 const Stackel n = pop;
8381 if (n->number == 4) {
8382 const Stackel top = pop, bottom = pop, right = pop, left = pop;
8383 if (left->which == Stackel_NUMBER && right->which == Stackel_NUMBER && bottom->which == Stackel_NUMBER && top->which == Stackel_NUMBER) {
8384 const bool result = Demo_clickedIn (left->number, right->number, bottom->number, top->number);
8385 pushNumber (result);
8386 } else {
8387 Melder_throw (U"All arguments of “demoClickedIn” should be numbers (the x and y ranges).");
8388 }
8389 } else {
8390 Melder_throw (U"The function “demoClickedIn” requires 4 arguments (x and y ranges), not ", n->number, U".");
8391 }
8392 }
8393 static void do_demoClicked () {
8394 const Stackel n = pop;
8395 if (n->number != 0)
8396 Melder_throw (U"The function “demoClicked” requires 0 arguments, not ", n->number, U".");
8397 const bool result = Demo_clicked ();
8398 pushNumber (result);
8399 }
8400 static void do_demoX () {
8401 const Stackel n = pop;
8402 if (n->number != 0)
8403 Melder_throw (U"The function “demoX” requires 0 arguments, not ", n->number, U".");
8404 const double result = Demo_x ();
8405 pushNumber (result);
8406 }
8407 static void do_demoY () {
8408 const Stackel n = pop;
8409 if (n->number != 0)
8410 Melder_throw (U"The function “demoY” requires 0 arguments, not ", n->number, U".");
8411 const double result = Demo_y ();
8412 pushNumber (result);
8413 }
8414 static void do_demoKeyPressed () {
8415 const Stackel n = pop;
8416 if (n->number != 0)
8417 Melder_throw (U"The function “demoKeyPressed” requires 0 arguments, not ", n->number, U".");
8418 const bool result = Demo_keyPressed ();
8419 pushNumber (result);
8420 }
8421 static void do_demoKey () {
8422 const Stackel n = pop;
8423 if (n->number != 0)
8424 Melder_throw (U"The function “demoKey” requires 0 arguments, not ", n->number, U".");
8425 autostring32 key (1);
8426 key [0] = Demo_key ();
8427 pushString (key.move());
8428 }
8429 static void do_demoShiftKeyPressed () {
8430 const Stackel n = pop;
8431 if (n->number != 0)
8432 Melder_throw (U"The function “demoShiftKeyPressed” requires 0 arguments, not ", n->number, U".");
8433 const bool result = Demo_shiftKeyPressed ();
8434 pushNumber (result);
8435 }
8436 static void do_demoCommandKeyPressed () {
8437 const Stackel n = pop;
8438 if (n->number != 0)
8439 Melder_throw (U"The function “demoCommandKeyPressed” requires 0 arguments, not ", n->number, U".");
8440 const bool result = Demo_commandKeyPressed ();
8441 pushNumber (result);
8442 }
8443 static void do_demoOptionKeyPressed () {
8444 const Stackel n = pop;
8445 if (n->number != 0)
8446 Melder_throw (U"The function “demoOptionKeyPressed” requires 0 arguments, not ", n->number, U".");
8447 const bool result = Demo_optionKeyPressed ();
8448 pushNumber (result);
8449 }
8450 static integer Stackel_getRowNumber (Stackel row, Daata thee) {
8451 integer result = 0;
8452 if (row->which == Stackel_NUMBER) {
8453 result = Melder_iround (row->number);
8454 } else if (row->which == Stackel_STRING) {
8455 if (! thy v_hasGetRowIndex ())
8456 Melder_throw (U"Objects of type ", Thing_className (thee), U" do not have row labels, so row indexes have to be numbers.");
8457 result = Melder_iround (thy v_getRowIndex (row->getString()));
8458 if (result == 0)
8459 Melder_throw (U"Object “", thy name.get(), U"” has no row labelled “", row->getString(), U"”.");
8460 } else {
8461 Melder_throw (U"A row index should be a number or a string, not ", row->whichText(), U".");
8462 }
8463 return result;
8464 }
8465 static integer Stackel_getColumnNumber (Stackel column, Daata thee) {
8466 integer result = 0;
8467 if (column->which == Stackel_NUMBER) {
8468 result = Melder_iround (column->number);
8469 } else if (column->which == Stackel_STRING) {
8470 if (! thy v_hasGetColIndex ())
8471 Melder_throw (U"Objects of type ", Thing_className (thee), U" do not have column labels, so column indexes have to be numbers.");
8472 result = Melder_iround (thy v_getColIndex (column->getString()));
8473 if (result == 0)
8474 Melder_throw (U"Object ", thee, U" has no column labelled “", column->getString(), U"”.");
8475 } else {
8476 Melder_throw (U"A column index should be a number or a string, not ", column->whichText(), U".");
8477 }
8478 return result;
8479 }
8480 static void do_self0 (integer irow, integer icol) {
8481 const Daata me = theSource;
8482 if (! me)
8483 Melder_throw (U"The name “self” is restricted to formulas for objects.");
8484 if (my v_hasGetCell ()) {
8485 pushNumber (my v_getCell ());
8486 } else if (my v_hasGetVector ()) {
8487 if (icol == 0) {
8488 Melder_throw (U"We are not in a loop, hence no implicit column index for the current ",
8489 Thing_className (me), U" object (self).\nTry using the [column] index explicitly.");
8490 } else {
8491 pushNumber (my v_getVector (irow, icol));
8492 }
8493 } else if (my v_hasGetMatrix ()) {
8494 if (irow == 0) {
8495 if (icol == 0) {
8496 Melder_throw (U"We are not in a loop over rows and columns,\n"
8497 U"hence no implicit row and column indexing for the current ",
8498 Thing_className (me), U" object (self).\n"
8499 U"Try using both [row, column] indexes explicitly.");
8500 } else {
8501 Melder_throw (U"We are not in a loop over columns only,\n"
8502 U"hence no implicit row index for the current ",
8503 Thing_className (me), U" object (self).\n"
8504 U"Try using the [row] index explicitly.");
8505 }
8506 } else {
8507 pushNumber (my v_getMatrix (irow, icol));
8508 }
8509 } else {
8510 Melder_throw (Thing_className (me), U" objects (like self) accept no [] indexing.");
8511 }
8512 }
8513 static void do_selfStr0 (integer irow, integer icol) {
8514 const Daata me = theSource;
8515 if (! me)
8516 Melder_throw (U"The name “self$” is restricted to formulas for objects.");
8517 if (my v_hasGetCellStr ()) {
8518 pushString (Melder_dup (my v_getCellStr ()));
8519 } else if (my v_hasGetVectorStr ()) {
8520 if (icol == 0) {
8521 Melder_throw (U"We are not in a loop, hence no implicit column index for the current ",
8522 Thing_className (me), U" object (self).\nTry using the [column] index explicitly.");
8523 } else {
8524 pushString (Melder_dup (my v_getVectorStr (icol)));
8525 }
8526 } else if (my v_hasGetMatrixStr ()) {
8527 if (irow == 0) {
8528 if (icol == 0) {
8529 Melder_throw (U"We are not in a loop over rows and columns,\n"
8530 U"hence no implicit row and column indexing for the current ",
8531 Thing_className (me), U" object (self).\n"
8532 U"Try using both [row, column] indexes explicitly.");
8533 } else {
8534 Melder_throw (U"We are not in a loop over columns only,\n"
8535 U"hence no implicit row index for the current ",
8536 Thing_className (me), U" object (self).\n"
8537 U"Try using the [row] index explicitly.");
8538 }
8539 } else {
8540 pushString (Melder_dup (my v_getMatrixStr (irow, icol)));
8541 }
8542 } else {
8543 Melder_throw (Thing_className (me), U" objects (like self) accept no [] indexing.");
8544 }
8545 }
8546 static void do_toObject () {
8547 const Stackel object = pop;
8548 Daata thee = nullptr;
8549 if (object->which == Stackel_NUMBER) {
8550 integer i = theCurrentPraatObjects -> n;
8551 while (i > 0 && object->number != theCurrentPraatObjects -> list [i]. id)
8552 i --;
8553 if (i == 0)
8554 Melder_throw (U"No such object: ", object->number);
8555 thee = (Daata) theCurrentPraatObjects -> list [i]. object;
8556 } else if (object->which == Stackel_STRING) {
8557 integer i = theCurrentPraatObjects -> n;
8558 while (i > 0 && ! Melder_equ (object->getString(), theCurrentPraatObjects -> list [i]. name.get()))
8559 i --;
8560 if (i == 0)
8561 Melder_throw (U"No such object: ", object->getString());
8562 thee = (Daata) theCurrentPraatObjects -> list [i]. object;
8563 } else {
8564 Melder_throw (U"The first argument to “object” should be a number (unique ID) or a string (name), not ", object->whichText(), U".");
8565 }
8566 pushObject (thee);
8567 }
8568 static void do_objectCell0 (integer irow, integer icol) {
8569 const Stackel object = pop;
8570 const Daata thee = object->object;
8571 if (thy v_hasGetCell ()) {
8572 pushNumber (thy v_getCell ());
8573 } else if (thy v_hasGetVector ()) {
8574 if (icol == 0) {
8575 Melder_throw (U"We are not in a loop,\n"
8576 U"hence no implicit column index for this ", Thing_className (thee), U" object.\n"
8577 U"Try using: object [id, column].");
8578 } else {
8579 pushNumber (thy v_getVector (irow, icol));
8580 }
8581 } else if (thy v_hasGetMatrix ()) {
8582 if (irow == 0) {
8583 if (icol == 0) {
8584 Melder_throw (U"We are not in a loop over rows and columns,\n"
8585 U"hence no implicit row and column indexing for this ", Thing_className (thee), U" object.\n"
8586 U"Try using: object [id, row, column].");
8587 } else {
8588 Melder_throw (U"We are not in a loop over columns only,\n"
8589 U"hence no implicit row index for this ", Thing_className (thee), U" object.\n"
8590 U"Try using: object [id, row].");
8591 }
8592 } else {
8593 pushNumber (thy v_getMatrix (irow, icol));
8594 }
8595 } else {
8596 Melder_throw (Thing_className (thee), U" objects accept no [] indexing.");
8597 }
8598 }
8599 static void do_matrix0 (integer irow, integer icol) {
8600 const Daata thee = parse [programPointer]. content.object;
8601 if (thy v_hasGetCell ()) {
8602 pushNumber (thy v_getCell ());
8603 } else if (thy v_hasGetVector ()) {
8604 if (icol == 0) {
8605 Melder_throw (U"We are not in a loop,\n"
8606 U"hence no implicit column index for this ", Thing_className (thee), U" object.\n"
8607 U"Try using the [column] index explicitly.");
8608 } else {
8609 pushNumber (thy v_getVector (irow, icol));
8610 }
8611 } else if (thy v_hasGetMatrix ()) {
8612 if (irow == 0) {
8613 if (icol == 0) {
8614 Melder_throw (U"We are not in a loop over rows and columns,\n"
8615 U"hence no implicit row and column indexing for this ", Thing_className (thee), U" object.\n"
8616 U"Try using both [row, column] indexes explicitly.");
8617 } else {
8618 Melder_throw (U"We are not in a loop over columns only,\n"
8619 U"hence no implicit row index for this ", Thing_className (thee), U" object.\n"
8620 U"Try using the [row] index explicitly.");
8621 }
8622 } else {
8623 pushNumber (thy v_getMatrix (irow, icol));
8624 }
8625 } else {
8626 Melder_throw (Thing_className (thee), U" objects accept no [] indexing.");
8627 }
8628 }
8629 static void do_selfMatrix1 (integer irow) {
8630 const Daata me = theSource;
8631 const Stackel column = pop;
8632 if (! me)
8633 Melder_throw (U"The name “self” is restricted to formulas for objects.");
8634 integer icol = Stackel_getColumnNumber (column, me);
8635 if (my v_hasGetVector ()) {
8636 pushNumber (my v_getVector (irow, icol));
8637 } else if (my v_hasGetMatrix ()) {
8638 if (irow == 0) {
8639 Melder_throw (U"We are not in a loop,\n"
8640 U"hence no implicit row index for the current ", Thing_className (me), U" object (self).\n"
8641 U"Try using both [row, column] indexes instead.");
8642 } else {
8643 pushNumber (my v_getMatrix (irow, icol));
8644 }
8645 } else {
8646 Melder_throw (Thing_className (me), U" objects (like self) accept no [column] indexes.");
8647 }
8648 }
8649 static void do_selfMatrix1_STR (integer irow) {
8650 const Daata me = theSource;
8651 const Stackel column = pop;
8652 if (! me)
8653 Melder_throw (U"The name “self$” is restricted to formulas for objects.");
8654 const integer icol = Stackel_getColumnNumber (column, me);
8655 if (my v_hasGetVectorStr ()) {
8656 pushString (Melder_dup (my v_getVectorStr (icol)));
8657 } else if (my v_hasGetMatrixStr ()) {
8658 if (irow == 0) {
8659 Melder_throw (U"We are not in a loop,\n"
8660 U"hence no implicit row index for the current ", Thing_className (me), U" object (self).\n"
8661 U"Try using both [row, column] indexes instead.");
8662 } else {
8663 pushString (Melder_dup (my v_getMatrixStr (irow, icol)));
8664 }
8665 } else {
8666 Melder_throw (Thing_className (me), U" objects (like self) accept no [column] indexes.");
8667 }
8668 }
8669 static void do_objectCell1 (integer irow) {
8670 const Stackel column = pop, object = pop;
8671 const Daata thee = object->object;
8672 const integer icol = Stackel_getColumnNumber (column, thee);
8673 if (thy v_hasGetVector ()) {
8674 pushNumber (thy v_getVector (irow, icol));
8675 } else if (thy v_hasGetMatrix ()) {
8676 if (irow == 0) {
8677 Melder_throw (U"We are not in a loop,\n"
8678 U"hence no implicit row index for this ", Thing_className (thee), U" object.\n"
8679 U"Try using: object [id, row, column].");
8680 } else {
8681 pushNumber (thy v_getMatrix (irow, icol));
8682 }
8683 } else {
8684 Melder_throw (Thing_className (thee), U" objects accept no [column] indexes.");
8685 }
8686 }
8687 static void do_matrix1 (integer irow) {
8688 const Daata thee = parse [programPointer]. content.object;
8689 const Stackel column = pop;
8690 const integer icol = Stackel_getColumnNumber (column, thee);
8691 if (thy v_hasGetVector ()) {
8692 pushNumber (thy v_getVector (irow, icol));
8693 } else if (thy v_hasGetMatrix ()) {
8694 if (irow == 0) {
8695 Melder_throw (U"We are not in a loop,\n"
8696 U"hence no implicit row index for this ", Thing_className (thee), U" object.\n"
8697 U"Try using both [row, column] indexes instead.");
8698 } else {
8699 pushNumber (thy v_getMatrix (irow, icol));
8700 }
8701 } else {
8702 Melder_throw (Thing_className (thee), U" objects accept no [column] indexes.");
8703 }
8704 }
8705 static void do_objectCell1_STR (integer irow) {
8706 const Stackel column = pop, object = pop;
8707 const Daata thee = object->object;
8708 const integer icol = Stackel_getColumnNumber (column, thee);
8709 if (thy v_hasGetVectorStr ()) {
8710 pushString (Melder_dup (thy v_getVectorStr (icol)));
8711 } else if (thy v_hasGetMatrixStr ()) {
8712 if (irow == 0) {
8713 Melder_throw (U"We are not in a loop,\n"
8714 U"hence no implicit row index for this ", Thing_className (thee), U" object.\n"
8715 U"Try using: object [id, row, column].");
8716 } else {
8717 pushString (Melder_dup (thy v_getMatrixStr (irow, icol)));
8718 }
8719 } else {
8720 Melder_throw (Thing_className (thee), U" objects accept no [column] indexes for string cells.");
8721 }
8722 }
8723 static void do_matrix1_STR (integer irow) {
8724 const Daata thee = parse [programPointer]. content.object;
8725 const Stackel column = pop;
8726 const integer icol = Stackel_getColumnNumber (column, thee);
8727 if (thy v_hasGetVectorStr ()) {
8728 pushString (Melder_dup (thy v_getVectorStr (icol)));
8729 } else if (thy v_hasGetMatrixStr ()) {
8730 if (irow == 0) {
8731 Melder_throw (U"We are not in a loop,\n"
8732 U"hence no implicit row index for this ", Thing_className (thee), U" object.\n"
8733 U"Try using both [row, column] indexes instead.");
8734 } else {
8735 pushString (Melder_dup (thy v_getMatrixStr (irow, icol)));
8736 }
8737 } else {
8738 Melder_throw (Thing_className (thee), U" objects accept no [column] indexes for string cells.");
8739 }
8740 }
8741 static void do_selfMatrix2 () {
8742 const Daata me = theSource;
8743 Stackel column = pop, row = pop;
8744 if (! me)
8745 Melder_throw (U"The name “self” is restricted to formulas for objects.");
8746 const integer irow = Stackel_getRowNumber (row, me);
8747 const integer icol = Stackel_getColumnNumber (column, me);
8748 if (! my v_hasGetMatrix ())
8749 Melder_throw (Thing_className (me), U" objects like “self” accept no [row, column] indexing.");
8750 pushNumber (my v_getMatrix (irow, icol));
8751 }
8752 static void do_selfMatrix2_STR () {
8753 const Daata me = theSource;
8754 const Stackel column = pop, row = pop;
8755 if (! me)
8756 Melder_throw (U"The name “self$” is restricted to formulas for objects.");
8757 const integer irow = Stackel_getRowNumber (row, me);
8758 const integer icol = Stackel_getColumnNumber (column, me);
8759 if (! my v_hasGetMatrixStr ())
8760 Melder_throw (Thing_className (me), U" objects like “self$” accept no [row, column] indexing for string cells.");
8761 pushString (Melder_dup (my v_getMatrixStr (irow, icol)));
8762 }
8763 static void do_objectCell2 () {
8764 const Stackel column = pop, row = pop, object = pop;
8765 const Daata thee = object->object;
8766 const integer irow = Stackel_getRowNumber (row, thee);
8767 const integer icol = Stackel_getColumnNumber (column, thee);
8768 if (! thy v_hasGetMatrix ())
8769 Melder_throw (Thing_className (thee), U" objects accept no [id, row, column] indexing.");
8770 pushNumber (thy v_getMatrix (irow, icol));
8771 }
8772 static void do_matrix2 () {
8773 const Daata thee = parse [programPointer]. content.object;
8774 const Stackel column = pop, row = pop;
8775 const integer irow = Stackel_getRowNumber (row, thee);
8776 const integer icol = Stackel_getColumnNumber (column, thee);
8777 if (! thy v_hasGetMatrix ())
8778 Melder_throw (Thing_className (thee), U" objects accept no [row, column] indexing.");
8779 pushNumber (thy v_getMatrix (irow, icol));
8780 }
8781 static void do_objectCell2_STR () {
8782 const Stackel column = pop, row = pop, object = pop;
8783 const Daata thee = object->object;
8784 const integer irow = Stackel_getRowNumber (row, thee);
8785 const integer icol = Stackel_getColumnNumber (column, thee);
8786 if (! thy v_hasGetMatrixStr ())
8787 Melder_throw (Thing_className (thee), U" objects accept no [id, row, column] indexing for string cells.");
8788 pushString (Melder_dup (thy v_getMatrixStr (irow, icol)));
8789 }
8790 static void do_matrix2_STR () {
8791 const Daata thee = parse [programPointer]. content.object;
8792 const Stackel column = pop, row = pop;
8793 const integer irow = Stackel_getRowNumber (row, thee);
8794 const integer icol = Stackel_getColumnNumber (column, thee);
8795 if (! thy v_hasGetMatrixStr ())
8796 Melder_throw (Thing_className (thee), U" objects accept no [row, column] indexing for string cells.");
8797 pushString (Melder_dup (thy v_getMatrixStr (irow, icol)));
8798 }
8799 static void do_objectLocation0 (integer irow, integer icol) {
8800 const Stackel object = pop;
8801 const Daata thee = object->object;
8802 if (thy v_hasGetFunction0 ()) {
8803 pushNumber (thy v_getFunction0 ());
8804 } else if (thy v_hasGetFunction1 ()) {
8805 const Daata me = theSource;
8806 if (! me)
8807 Melder_throw (U"No current object (we are not in a Formula command),\n"
8808 U"hence no implicit x value for this ", Thing_className (thee), U" object.\n"
8809 U"Try using: object (id, x).");
8810 if (! my v_hasGetX ())
8811 Melder_throw (U"The current ", Thing_className (me),
8812 U" object gives no implicit x values,\nhence no implicit x value for this ",
8813 Thing_className (thee), " object.\n"
8814 U"Try using: object (id, x).");
8815 const double x = my v_getX (icol);
8816 pushNumber (thy v_getFunction1 (irow, x));
8817 } else if (thy v_hasGetFunction2 ()) {
8818 const Daata me = theSource;
8819 if (! me)
8820 Melder_throw (U"No current object (we are not in a Formula command),\n"
8821 U"hence no implicit x or y values for this ", Thing_className (thee), U" object.\n"
8822 U"Try using: object (id, x, y).");
8823 if (! my v_hasGetX ())
8824 Melder_throw (U"The current ", Thing_className (me), U" object gives no implicit x values,\n"
8825 U"hence no implicit x value for this ", Thing_className (thee), U" object.\n"
8826 U"Try using: object (id, x, y).");
8827 const double x = my v_getX (icol);
8828 if (! my v_hasGetY ())
8829 Melder_throw (U"The current ", Thing_className (me), U" object gives no implicit y values,\n"
8830 U"hence no implicit y value for this ", Thing_className (thee), U" object.\n"
8831 U"Try using: object (id, y).");
8832 const double y = my v_getY (irow);
8833 pushNumber (thy v_getFunction2 (x, y));
8834 } else {
8835 Melder_throw (Thing_className (thee), U" objects accept no () values.");
8836 }
8837 }
8838 static void do_function0 (integer irow, integer icol) {
8839 const Daata thee = parse [programPointer]. content.object;
8840 if (thy v_hasGetFunction0 ()) {
8841 pushNumber (thy v_getFunction0 ());
8842 } else if (thy v_hasGetFunction1 ()) {
8843 const Daata me = theSource;
8844 if (! me)
8845 Melder_throw (U"No current object (we are not in a Formula command),\n"
8846 U"hence no implicit x value for this ", Thing_className (thee), U" object.\n"
8847 U"Try using the (x) argument explicitly.");
8848 if (! my v_hasGetX ())
8849 Melder_throw (U"The current ", Thing_className (me),
8850 U" object gives no implicit x values,\nhence no implicit x value for this ",
8851 Thing_className (thee), U" object.\n"
8852 U"Try using the (x) argument explicitly.");
8853 const double x = my v_getX (icol);
8854 pushNumber (thy v_getFunction1 (irow, x));
8855 } else if (thy v_hasGetFunction2 ()) {
8856 const Daata me = theSource;
8857 if (! me)
8858 Melder_throw (U"No current object (we are not in a Formula command),\n"
8859 U"hence no implicit x or y values for this ", Thing_className (thee), U" object.\n"
8860 U"Try using both (x, y) arguments explicitly.");
8861 if (! my v_hasGetX ())
8862 Melder_throw (U"The current ", Thing_className (me), U" object gives no implicit x values,\n"
8863 U"hence no implicit x value for this ", Thing_className (thee), U" object.\n"
8864 U"Try using both (x, y) arguments explicitly.");
8865 const double x = my v_getX (icol);
8866 if (! my v_hasGetY ())
8867 Melder_throw (U"The current ", Thing_className (me), U" object gives no implicit y values,\n"
8868 U"hence no implicit y value for this ", Thing_className (thee), U" object.\n"
8869 U"Try using the (y) argument explicitly.");
8870 const double y = my v_getY (irow);
8871 pushNumber (thy v_getFunction2 (x, y));
8872 } else {
8873 Melder_throw (Thing_className (thee), U" objects accept no () values.");
8874 }
8875 }
8876 static void do_selfFunction1 (integer irow) {
8877 const Daata me = theSource;
8878 const Stackel x = pop;
8879 if (x->which == Stackel_NUMBER) {
8880 if (! me)
8881 Melder_throw (U"The name “self” is restricted to formulas for objects.");
8882 if (my v_hasGetFunction1 ()) {
8883 pushNumber (my v_getFunction1 (irow, x->number));
8884 } else if (my v_hasGetFunction2 ()) {
8885 if (! my v_hasGetY ())
8886 Melder_throw (U"The current ", Thing_className (me), U" object (self) accepts no implicit y values.\n"
8887 U"Try using both (x, y) arguments instead.");
8888 const double y = my v_getY (irow);
8889 pushNumber (my v_getFunction2 (x->number, y));
8890 } else {
8891 Melder_throw (Thing_className (me), U" objects like “self” accept no (x) values.");
8892 }
8893 } else {
8894 Melder_throw (Thing_className (me), U" objects like “self” accept only numeric x values.");
8895 }
8896 }
8897 static void do_objectLocation1 (integer irow) {
8898 const Stackel x = pop, object = pop;
8899 const Daata thee = object->object;
8900 if (x->which == Stackel_NUMBER) {
8901 if (thy v_hasGetFunction1 ()) {
8902 pushNumber (thy v_getFunction1 (irow, x->number));
8903 } else if (thy v_hasGetFunction2 ()) {
8904 const Daata me = theSource;
8905 if (! me)
8906 Melder_throw (U"No current object (we are not in a Formula command),\n"
8907 U"hence no implicit y value for this ", Thing_className (thee), U" object.\n"
8908 U"Try using: object (id, x, y).");
8909 if (! my v_hasGetY ())
8910 Melder_throw (U"The current ", Thing_className (me), U" object gives no implicit y values,\n"
8911 U"hence no implicit y value for this ", Thing_className (thee), U" object.\n"
8912 U"Try using: object (id, x, y).");
8913 const double y = my v_getY (irow);
8914 pushNumber (thy v_getFunction2 (x->number, y));
8915 } else {
8916 Melder_throw (Thing_className (thee), U" objects accept no (x) values.");
8917 }
8918 } else {
8919 Melder_throw (Thing_className (thee), U" objects accept only numeric x values.");
8920 }
8921 }
8922 static void do_function1 (integer irow) {
8923 const Daata thee = parse [programPointer]. content.object;
8924 const Stackel x = pop;
8925 if (x->which == Stackel_NUMBER) {
8926 if (thy v_hasGetFunction1 ()) {
8927 pushNumber (thy v_getFunction1 (irow, x->number));
8928 } else if (thy v_hasGetFunction2 ()) {
8929 const Daata me = theSource;
8930 if (! me)
8931 Melder_throw (U"No current object (we are not in a Formula command),\n"
8932 U"hence no implicit y value for this ", Thing_className (thee), U" object.\n"
8933 U"Try using both (x, y) arguments instead.");
8934 if (! my v_hasGetY ())
8935 Melder_throw (U"The current ", Thing_className (me), U" object gives no implicit y values,\n"
8936 U"hence no implicit y value for this ", Thing_className (thee), U" object.\n"
8937 U"Try using both (x, y) arguments instead.");
8938 const double y = my v_getY (irow);
8939 pushNumber (thy v_getFunction2 (x->number, y));
8940 } else {
8941 Melder_throw (Thing_className (thee), U" objects accept no (x) values.");
8942 }
8943 } else {
8944 Melder_throw (Thing_className (thee), U" objects accept only numeric x values.");
8945 }
8946 }
8947 static void do_selfFunction2 () {
8948 const Daata me = theSource;
8949 const Stackel y = pop, x = pop;
8950 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
8951 if (! me)
8952 Melder_throw (U"The name “self” is restricted to formulas for objects.");
8953 if (! my v_hasGetFunction2 ())
8954 Melder_throw (Thing_className (me), U" objects like “self” accept no (x, y) values.");
8955 pushNumber (my v_getFunction2 (x->number, y->number));
8956 } else {
8957 Melder_throw (Thing_className (me), U" objects accept only numeric x values.");
8958 }
8959 }
8960 static void do_objectLocation2 () {
8961 const Stackel y = pop, x = pop, object = pop;
8962 const Daata thee = object->object;
8963 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
8964 if (! thy v_hasGetFunction2 ())
8965 Melder_throw (Thing_className (thee), U" objects accept no (x, y) values.");
8966 pushNumber (thy v_getFunction2 (x->number, y->number));
8967 } else {
8968 Melder_throw (Thing_className (thee), U" objects accept only numeric x values.");
8969 }
8970 }
8971 static void do_function2 () {
8972 const Daata thee = parse [programPointer]. content.object;
8973 const Stackel y = pop, x = pop;
8974 if (x->which == Stackel_NUMBER && y->which == Stackel_NUMBER) {
8975 if (! thy v_hasGetFunction2 ())
8976 Melder_throw (Thing_className (thee), U" objects accept no (x, y) values.");
8977 pushNumber (thy v_getFunction2 (x->number, y->number));
8978 } else {
8979 Melder_throw (Thing_className (thee), U" objects accept only numeric x values.");
8980 }
8981 }
8982 static void do_row_STR () {
8983 const Daata thee = parse [programPointer]. content.object;
8984 const Stackel row = pop;
8985 const integer irow = Stackel_getRowNumber (row, thee);
8986 autostring32 result = Melder_dup (thy v_getRowStr (irow));
8987 if (! result)
8988 Melder_throw (U"Row index out of bounds.");
8989 pushString (result.move());
8990 }
8991 static void do_col_STR () {
8992 const Daata thee = parse [programPointer]. content.object;
8993 const Stackel col = pop;
8994 const integer icol = Stackel_getColumnNumber (col, thee);
8995 autostring32 result = Melder_dup (thy v_getColStr (icol));
8996 if (! result)
8997 Melder_throw (U"Column index out of bounds.");
8998 pushString (result.move());
8999 }
9000
9001 static double NUMerf (double x) {
9002 return 1.0 - NUMerfcc (x);
9003 }
9004
9005 void Formula_run (integer row, integer col, Formula_Result *result) {
9006 FormulaInstruction f = parse;
9007 programPointer = 1; // first symbol of the program
9008 if (! theStack) {
9009 theStack = Melder_calloc_f (structStackel, 1+Formula_MAXIMUM_STACK_SIZE);
9010 if (! theStack)
9011 Melder_throw (U"Out of memory during formula computation.");
9012 }
9013 stackPointer = 0; // start new stack
9014 stackPointerMax = 0; // start new stack
9015 try {
9016 while (programPointer <= numberOfInstructions) {
9017 integer symbol;
9018 switch (symbol = f [programPointer]. symbol) {
9019
9020 case NUMBER_: { pushNumber (f [programPointer]. content.number);
9021 } break; case STOPWATCH_: { pushNumber (Melder_stopwatch ());
9022 } break; case ROW_: { pushNumber (row);
9023 } break; case COL_: { pushNumber (col);
9024 } break; case X_: {
9025 Daata me = theSource;
9026 Melder_require (my v_hasGetX (),
9027 U"No values for “x” for this object.");
9028 pushNumber (my v_getX (col));
9029 } break; case Y_: {
9030 Daata me = theSource;
9031 Melder_require (my v_hasGetY (),
9032 U"No values for “y” for this object.");
9033 pushNumber (my v_getY (row));
9034 } break; case NOT_: { do_not ();
9035 } break; case EQ_: { do_eq ();
9036 } break; case NE_: { do_ne ();
9037 } break; case LE_: { do_le ();
9038 } break; case LT_: { do_lt ();
9039 } break; case GE_: { do_ge ();
9040 } break; case GT_: { do_gt ();
9041 } break; case ADD_: { do_add ();
9042 } break; case SUB_: { do_sub ();
9043 } break; case MUL_: { do_mul ();
9044 } break; case RDIV_: { do_rdiv ();
9045 } break; case IDIV_: { do_idiv ();
9046 } break; case MOD_: { do_mod ();
9047 } break; case MINUS_: { do_minus ();
9048 } break; case POWER_: { do_power ();
9049 /********** Functions of 1 variable: **********/
9050
9051 #define CASE_NUM_WITH_TENSORS(label, function) \
9052 } break; case label: { function (); \
9053 } break; case label##VEC_: { function##_VEC (); \
9054 } break; case label##MAT_: { function##_MAT ();
9055 CASE_NUM_WITH_TENSORS (ABS_, do_abs)
9056 CASE_NUM_WITH_TENSORS (ROUND_, do_round)
9057 CASE_NUM_WITH_TENSORS (FLOOR_, do_floor)
9058 CASE_NUM_WITH_TENSORS (CEILING_, do_ceiling)
9059 CASE_NUM_WITH_TENSORS (RECTIFY_, do_rectify)
9060 CASE_NUM_WITH_TENSORS (SQRT_, do_sqrt)
9061 CASE_NUM_WITH_TENSORS (SIN_, do_sin)
9062 CASE_NUM_WITH_TENSORS (COS_, do_cos)
9063 CASE_NUM_WITH_TENSORS (TAN_, do_tan)
9064 CASE_NUM_WITH_TENSORS (ARCSIN_, do_arcsin)
9065 CASE_NUM_WITH_TENSORS (ARCCOS_, do_arccos)
9066 CASE_NUM_WITH_TENSORS (ARCTAN_, do_arctan)
9067 } break; case SINC_: { do_function_n_n (NUMsinc);
9068 } break; case SINCPI_: { do_function_n_n (NUMsincpi);
9069 CASE_NUM_WITH_TENSORS (EXP_, do_exp)
9070 CASE_NUM_WITH_TENSORS (SINH_, do_sinh)
9071 CASE_NUM_WITH_TENSORS (COSH_, do_cosh)
9072 CASE_NUM_WITH_TENSORS (TANH_, do_tanh)
9073 CASE_NUM_WITH_TENSORS (ARCSINH_, do_arcsinh)
9074 CASE_NUM_WITH_TENSORS (ARCCOSH_, do_arccosh)
9075 CASE_NUM_WITH_TENSORS (ARCTANH_, do_arctanh)
9076 CASE_NUM_WITH_TENSORS (SIGMOID_, do_sigmoid)
9077 CASE_NUM_WITH_TENSORS (INV_SIGMOID_, do_invSigmoid)
9078 } break; case SOFTMAX_VEC_: { do_softmax_VEC ();
9079 } break; case SOFTMAX_PER_ROW_MAT_: { do_softmaxPerRow_MAT ();
9080 } break; case ERF_: { do_function_n_n (NUMerf);
9081 } break; case ERFC_: { do_function_n_n (NUMerfcc);
9082 } break; case GAUSS_P_: { do_function_n_n (NUMgaussP);
9083 } break; case GAUSS_Q_: { do_function_n_n (NUMgaussQ);
9084 } break; case INV_GAUSS_Q_: { do_function_n_n (NUMinvGaussQ);
9085 } break; case RANDOM_BERNOULLI_: { do_function_n_n (NUMrandomBernoulli_real);
9086 } break; case RANDOM_BERNOULLI_VEC_: { do_functionvec_n_n (NUMrandomBernoulli_real);
9087 } break; case RANDOM_POISSON_: { do_function_n_n (NUMrandomPoisson);
9088 } break; case TRANSPOSE_MAT_: { do_transpose_MAT ();
9089 } break; case ROW_SUMS_VEC_: { do_rowSums_VEC ();
9090 } break; case COLUMN_SUMS_VEC_: { do_columnSums_VEC ();
9091 CASE_NUM_WITH_TENSORS (LOG2_, do_log2)
9092 CASE_NUM_WITH_TENSORS (LN_, do_ln)
9093 CASE_NUM_WITH_TENSORS (LOG10_, do_log10)
9094 } break; case LN_GAMMA_: { do_function_n_n (NUMlnGamma);
9095 } break; case HERTZ_TO_BARK_: { do_function_n_n (NUMhertzToBark);
9096 } break; case BARK_TO_HERTZ_: { do_function_n_n (NUMbarkToHertz);
9097 } break; case PHON_TO_DIFFERENCE_LIMENS_: { do_function_n_n (NUMphonToDifferenceLimens);
9098 } break; case DIFFERENCE_LIMENS_TO_PHON_: { do_function_n_n (NUMdifferenceLimensToPhon);
9099 } break; case HERTZ_TO_MEL_: { do_function_n_n (NUMhertzToMel);
9100 } break; case MEL_TO_HERTZ_: { do_function_n_n (NUMmelToHertz);
9101 } break; case HERTZ_TO_SEMITONES_: { do_function_n_n (NUMhertzToSemitones);
9102 } break; case SEMITONES_TO_HERTZ_: { do_function_n_n (NUMsemitonesToHertz);
9103 } break; case ERB_: { do_function_n_n (NUMerb);
9104 } break; case HERTZ_TO_ERB_: { do_function_n_n (NUMhertzToErb);
9105 } break; case ERB_TO_HERTZ_: { do_function_n_n (NUMerbToHertz);
9106 } break; case SUM_: { do_sum ();
9107 } break; case MEAN_: { do_mean ();
9108 } break; case STDEV_: { do_stdev ();
9109 } break; case CENTER_: { do_center ();
9110 } break; case RANDOM_IMAX_: { do_randomImax ();
9111 } break; case EVALUATE_: { do_evaluate ();
9112 } break; case EVALUATE_NOCHECK_: { do_evaluate_nocheck ();
9113 } break; case EVALUATE_STR_: { do_evaluate_STR ();
9114 } break; case EVALUATE_NOCHECK_STR_: { do_evaluate_nocheck_STR ();
9115 /********** Functions of 2 numerical variables: **********/
9116 } break; case ARCTAN2_: { do_function_dd_d (atan2);
9117 } break; case RANDOM_UNIFORM_: { do_function_dd_d (NUMrandomUniform);
9118 } break; case RANDOM_INTEGER_: { do_function_ll_l (NUMrandomInteger);
9119 } break; case RANDOM_GAUSS_: { do_function_dd_d (NUMrandomGauss);
9120 } break; case RANDOM_BINOMIAL_: { do_function_dl_d (NUMrandomBinomial_real);
9121 } break; case RANDOM_GAMMA_: { do_function_dd_d (NUMrandomGamma);
9122 } break; case CHI_SQUARE_P_: { do_function_dd_d (NUMchiSquareP);
9123 } break; case CHI_SQUARE_Q_: { do_function_dd_d (NUMchiSquareQ);
9124 } break; case INCOMPLETE_GAMMAP_: { do_function_dd_d (NUMincompleteGammaP);
9125 } break; case INV_CHI_SQUARE_Q_: { do_function_dd_d (NUMinvChiSquareQ);
9126 } break; case STUDENT_P_: { do_function_dd_d (NUMstudentP);
9127 } break; case STUDENT_Q_: { do_function_dd_d (NUMstudentQ);
9128 } break; case INV_STUDENT_Q_: { do_function_dd_d (NUMinvStudentQ);
9129 } break; case BETA_: { do_function_dd_d (NUMbeta);
9130 } break; case BETA2_: { do_function_dd_d (NUMbeta2);
9131 } break; case BESSEL_I_: { do_function_ld_d (NUMbesselI);
9132 } break; case BESSEL_K_: { do_function_ld_d (NUMbesselK);
9133 } break; case LN_BETA_: { do_function_dd_d (NUMlnBeta);
9134 } break; case SOUND_PRESSURE_TO_PHON_: { do_function_dd_d (NUMsoundPressureToPhon);
9135 } break; case OBJECTS_ARE_IDENTICAL_: { do_objects_are_identical ();
9136 /********** Functions of 3 numerical variables: **********/
9137 } break; case FISHER_P_: { do_function_ddd_d (NUMfisherP);
9138 } break; case FISHER_Q_: { do_function_ddd_d (NUMfisherQ);
9139 } break; case INV_FISHER_Q_: { do_function_ddd_d (NUMinvFisherQ);
9140 } break; case BINOMIAL_P_: { do_function_ddd_d (NUMbinomialP);
9141 } break; case BINOMIAL_Q_: { do_function_ddd_d (NUMbinomialQ);
9142 } break; case INCOMPLETE_BETA_: { do_function_ddd_d (NUMincompleteBeta);
9143 } break; case INV_BINOMIAL_P_: { do_function_ddd_d (NUMinvBinomialP);
9144 } break; case INV_BINOMIAL_Q_: { do_function_ddd_d (NUMinvBinomialQ);
9145 /********** Functions of a variable number of variables: **********/
9146 } break; case DO_ : { do_do ();
9147 } break; case DOSTR_: { do_do_STR ();
9148 } break; case WRITE_INFO_ : { do_writeInfo ();
9149 } break; case WRITE_INFO_LINE_ : { do_writeInfoLine ();
9150 } break; case APPEND_INFO_ : { do_appendInfo ();
9151 } break; case APPEND_INFO_LINE_: { do_appendInfoLine ();
9152 } break; case WRITE_FILE_ : { do_writeFile ();
9153 } break; case WRITE_FILE_LINE_ : { do_writeFileLine ();
9154 } break; case APPEND_FILE_ : { do_appendFile ();
9155 } break; case APPEND_FILE_LINE_: { do_appendFileLine ();
9156 } break; case PAUSE_SCRIPT_: { do_pauseScript ();
9157 } break; case EXIT_SCRIPT_: { do_exitScript ();
9158 } break; case RUN_SCRIPT_: { do_runScript ();
9159 } break; case RUN_SCRIPT_WITH_FORM_: { do_runScriptWithForm ();
9160 } break; case RUN_NOTEBOOK_: { do_runNotebook ();
9161 } break; case RUN_SYSTEM_: { do_runSystem ();
9162 } break; case RUN_SYSTEM_STR_: { do_runSystem_STR ();
9163 } break; case RUN_SYSTEM_NOCHECK_: { do_runSystem_nocheck ();
9164 } break; case RUN_SUBPROCESS_: { do_runSubprocess ();
9165 } break; case RUN_SUBPROCESS_STR_: { do_runSubprocess_STR ();
9166 } break; case MIN_: { do_min ();
9167 } break; case MIN_E_: { do_min_e ();
9168 } break; case MIN_IGNORE_UNDEFINED_: { do_min_removeUndefined ();
9169 } break; case MAX_: { do_max ();
9170 } break; case MAX_E_: { do_max_e ();
9171 } break; case MAX_IGNORE_UNDEFINED_: { do_max_removeUndefined ();
9172 } break; case IMIN_: { do_imin ();
9173 } break; case IMIN_E_: { do_imin_e ();
9174 } break; case IMIN_IGNORE_UNDEFINED_: { do_imin_removeUndefined ();
9175 } break; case IMAX_: { do_imax ();
9176 } break; case IMAX_E_: { do_imax_e ();
9177 } break; case IMAX_IGNORE_UNDEFINED_: { do_imax_removeUndefined ();
9178 } break; case QUANTILE_: { do_quantile ();
9179 } break; case NORM_: { do_norm ();
9180 } break; case ZERO_VEC_: { do_zero_VEC ();
9181 } break; case ZERO_MAT_: { do_zero_MAT ();
9182 } break; case LINEAR_VEC_: { do_linear_VEC ();
9183 } break; case TO_VEC_: { do_to_VEC ();
9184 } break; case FROM_TO_VEC_: { do_from_to_VEC ();
9185 } break; case FROM_TO_BY_VEC_: { do_from_to_by_VEC ();
9186 } break; case FROM_TO_COUNT_VEC_: { do_from_to_count_VEC ();
9187 } break; case BETWEEN_BY_VEC_: { do_between_by_VEC ();
9188 } break; case BETWEEN_COUNT_VEC_: { do_between_count_VEC ();
9189 } break; case SORT_VEC_: { do_sort_VEC ();
9190 } break; case SORT_REMOVE_UNDEFINED_VEC_: { do_sort_removeUndefined_VEC ();
9191 } break; case SORT_STRVEC_: { do_sort_STRVEC ();
9192 } break; case SORT_NUMBER_AWARE_STRVEC_: { do_sort_numberAware_STRVEC ();
9193 } break; case SHUFFLE_VEC_: { do_shuffle_VEC ();
9194 } break; case SHUFFLE_STRVEC_: { do_shuffle_STRVEC ();
9195 } break; case RANDOM_UNIFORM_VEC_: { do_function_VECdd_d (NUMrandomUniform);
9196 } break; case RANDOM_UNIFORM_MAT_: { do_function_MATdd_d (NUMrandomUniform);
9197 } break; case RANDOM_INTEGER_VEC_: { do_function_VECll_l (NUMrandomInteger);
9198 } break; case RANDOM_INTEGER_MAT_: { do_function_MATll_l (NUMrandomInteger);
9199 } break; case RANDOM_GAUSS_VEC_: { do_function_VECdd_d (NUMrandomGauss);
9200 } break; case RANDOM_GAUSS_MAT_: { do_function_MATdd_d (NUMrandomGauss);
9201 } break; case RANDOM_GAMMA_VEC_: { do_function_VECdd_d (NUMrandomGamma);
9202 } break; case RANDOM_GAMMA_MAT_: { do_function_MATdd_d (NUMrandomGamma);
9203 } break; case SOLVE_SPARSE_VEC_ : { do_solveSparse_VEC ();
9204 } break; case SOLVE_NONNEGATIVE_VEC_ : { do_solveNonnegative_VEC ();
9205 } break; case PEAKS_MAT_: { do_peaks_MAT ();
9206 } break; case SIZE_: { do_size ();
9207 } break; case NUMBER_OF_ROWS_: { do_numberOfRows ();
9208 } break; case NUMBER_OF_COLUMNS_: { do_numberOfColumns ();
9209 } break; case COMBINE_VEC_: { do_combine_VEC ();
9210 } break; case BLAKE3_VEC_: { do_blake3_VEC ();
9211 } break; case PART_VEC_: { do_part_VEC ();
9212 } break; case PART_MAT_: { do_part_MAT ();
9213 } break; case EDITOR_: { do_editor ();
9214 } break; case RANDOM__INITIALIZE_WITH_SEED_UNSAFELY_BUT_PREDICTABLY_: { do_random_initializeWithSeedUnsafelyButPredictably ();
9215 } break; case RANDOM__INITIALIZE_SAFELY_AND_UNPREDICTABLY_: { do_random_initializeSafelyAndUnpredictably ();
9216 } break; case HASH_: { do_hash ();
9217 } break; case HEX_STR_: { do_hex_STR ();
9218 } break; case UNHEX_STR_: { do_unhex_STR ();
9219 } break; case EMPTY_STRVEC_: { do_empty_STRVEC ();
9220 } break; case READ_LINES_FROM_FILE_STRVEC_: { do_readLinesFromFile_STRVEC ();
9221 } break; case FILE_NAMES_STRVEC_: { do_fileNames_STRVEC ();
9222 } break; case FOLDER_NAMES_STRVEC_: { do_folderNames_STRVEC ();
9223 } break; case FILE_NAMES_CASE_INSENSITIVE_STRVEC_: { do_fileNames_caseInsensitive_STRVEC ();
9224 } break; case FOLDER_NAMES_CASE_INSENSITIVE_STRVEC_: { do_folderNames_caseInsensitive_STRVEC ();
9225 } break; case SPLIT_BY_WHITESPACE_STRVEC_: { do_splitByWhitespace_STRVEC ();
9226 } break; case SPLIT_BY_STRVEC_: { do_splitBy_STRVEC ();
9227 } break; case LOWER_CASE_STR_: { do_lowerCase_STR ();
9228 } break; case LOWER_CAMEL_CASE_STR_: { do_lowerCamelCase_STR ();
9229 } break; case LOWER_SNAKE_CASE_STR_: { do_lowerSnakeCase_STR ();
9230 } break; case UPPER_CASE_STR_: { do_upperCase_STR ();
9231 } break; case UPPER_CAMEL_CASE_STR_: { do_upperCamelCase_STR ();
9232 } break; case UPPER_SNAKE_CASE_STR_: { do_upperSnakeCase_STR ();
9233 /********** String functions of 1 variable: **********/
9234 } break; case LENGTH_: { do_length ();
9235 } break; case STRING_TO_NUMBER_: { do_number ();
9236 } break; case FILE_READABLE_: { do_fileReadable ();
9237 } break; case FOLDER_EXISTS_: { do_folderExists ();
9238 } break; case TRY_TO_WRITE_FILE_: { do_tryToWriteFile ();
9239 } break; case TRY_TO_APPEND_FILE_: { do_tryToAppendFile ();
9240 /********** String functions of 0 variables: **********/
9241 } break; case DATE_STR_: { do_date_STR ();
9242 } break; case DATE_UTC_STR_: { do_date_utc_STR ();
9243 } break; case DATE_ISO_STR_: { do_date_iso_STR ();
9244 } break; case DATE_UTC_ISO_STR_: { do_date_utc_iso_STR ();
9245 } break; case DATE_VEC_: { do_date_VEC ();
9246 } break; case DATE_UTC_VEC_: { do_date_utc_VEC ();
9247 } break; case INFO_STR_: { do_info_STR ();
9248 /********** String functions of 2 variables: **********/
9249 } break; case LEFT_STR_: { do_left_STR ();
9250 } break; case RIGHT_STR_: { do_right_STR ();
9251 } break; case MID_STR_: { do_mid_STR ();
9252 } break; case PAD_LEFT_STR_: { do_padLeft_STR ();
9253 } break; case PAD_RIGHT_STR_: { do_padRight_STR ();
9254 } break; case TRUNCATE_LEFT_STR_: { do_truncateLeft_STR ();
9255 } break; case TRUNCATE_RIGHT_STR_: { do_truncateRight_STR ();
9256 } break; case PAD_OR_TRUNCATE_LEFT_STR_: { do_padOrTruncateLeft_STR ();
9257 } break; case PAD_OR_TRUNCATE_RIGHT_STR_: { do_padOrTruncateRight_STR ();
9258 } break; case UNICODE_TO_BACKSLASH_TRIGRAPHS_STR_: { do_unicodeToBackslashTrigraphs_STR ();
9259 } break; case BACKSLASH_TRIGRAPHS_TO_UNICODE_STR_: { do_backslashTrigraphsToUnicode_STR ();
9260 } break; case ENVIRONMENT_STR_: { do_environment_STR ();
9261 } break; case INDEX_: { do_index ();
9262 } break; case INDEX_CASE_INSENSITIVE_: { do_index_caseInsensitive ();
9263 } break; case RINDEX_: { do_rindex ();
9264 } break; case RINDEX_CASE_INSENSITIVE_: { do_rindex_caseInsensitive ();
9265 } break; case STARTS_WITH_: { do_stringMatchesCriterion (kMelder_string::STARTS_WITH, true);
9266 } break; case STARTS_WITH_CASE_INSENSITIVE_: { do_stringMatchesCriterion (kMelder_string::STARTS_WITH, false);
9267 } break; case ENDS_WITH_: { do_stringMatchesCriterion (kMelder_string::ENDS_WITH, true);
9268 } break; case ENDS_WITH_CASE_INSENSITIVE_: { do_stringMatchesCriterion (kMelder_string::ENDS_WITH, false);
9269 } break; case INDEX_REGEX_: { do_index_regex (false);
9270 } break; case RINDEX_REGEX_: { do_index_regex (true);
9271 } break; case EXTRACT_NUMBER_: { do_extractNumber ();
9272 /********** Other string functions: **********/
9273 } break; case EXTRACT_WORD_STR_: { do_extractText_STR (true);
9274 } break; case EXTRACT_LINE_STR_: { do_extractText_STR (false);
9275 } break; case REPLACE_STR_: { do_replace_STR ();
9276 } break; case REPLACE_REGEX_STR_: { do_replace_regex_STR ();
9277 } break; case SELECTED_: { do_selected ();
9278 } break; case SELECTED_STR_: { do_selected_STR ();
9279 } break; case NUMBER_OF_SELECTED_: { do_numberOfSelected ();
9280 } break; case SELECTED_VEC_: { do_selected_VEC ();
9281 } break; case SELECTED_STRVEC_: { do_selected_STRVEC ();
9282 } break; case SELECT_OBJECT_: { do_selectObject ();
9283 } break; case PLUS_OBJECT_ : { do_plusObject ();
9284 } break; case MINUS_OBJECT_ : { do_minusObject ();
9285 } break; case REMOVE_OBJECT_: { do_removeObject ();
9286 } break; case OBJECT_XMIN_: { do_object_xmin ();
9287 } break; case OBJECT_XMAX_: { do_object_xmax ();
9288 } break; case OBJECT_YMIN_: { do_object_ymin ();
9289 } break; case OBJECT_YMAX_: { do_object_ymax ();
9290 } break; case OBJECT_NX_: { do_object_nx ();
9291 } break; case OBJECT_NY_: { do_object_ny ();
9292 } break; case OBJECT_DX_: { do_object_dx ();
9293 } break; case OBJECT_DY_: { do_object_dy ();
9294 } break; case OBJECT_NROW_: { do_object_nrow ();
9295 } break; case OBJECT_NCOL_: { do_object_ncol ();
9296 } break; case OBJECT_ROW_STR_: { do_object_row_STR ();
9297 } break; case OBJECT_COL_STR_: { do_object_col_STR ();
9298 } break; case STRING_STR_: { do_string_STR ();
9299 } break; case HORIZONTAL_STR_: { do_horizontal_STR ();
9300 } break; case VERTICAL_STR_: { do_vertical_STR ();
9301 } break; case NUMBERS_VEC_: { do_numbers_VEC ();
9302 } break; case SLEEP_: { do_sleep ();
9303 } break; case UNICODE_: { do_unicode ();
9304 } break; case UNICODE_STR_: { do_unicode_STR ();
9305 } break; case FIXED_STR_: { do_fixed_STR ();
9306 } break; case PERCENT_STR_: { do_percent_STR ();
9307 } break; case GRAPHICAL_PERCENT_STR_: { do_graphicalPercent_STR ();
9308 } break; case BIG_INTEGER_STR_: { do_bigInteger_STR ();
9309 } break; case HALF_STR_: { do_half_STR ();
9310 } break; case GRAPHICAL_HALF_STR_: { do_graphicalHalf_STR ();
9311 } break; case SINGLE_STR_: { do_single_STR ();
9312 } break; case GRAPHICAL_SINGLE_STR_: { do_graphicalSingle_STR ();
9313 } break; case DOUBLE_STR_: { do_double_STR ();
9314 } break; case GRAPHICAL_DOUBLE_STR_: { do_graphicalDouble_STR ();
9315 } break; case NATURAL_LOGARITHM_STR_: { do_naturalLogarithm_STR ();
9316 } break; case GRAPHICAL_NATURAL_LOGARITHM_STR_: { do_graphicalNaturalLogarithm_STR ();
9317 } break; case HEXADECIMAL_STR_: { do_hexadecimal_STR ();
9318 } break; case DELETE_FILE_: { do_deleteFile ();
9319 } break; case MOVE_AND_OR_RENAME_FILE_: { do_moveAndOrRenameFile ();
9320 } break; case CREATE_FOLDER_: { do_createFolder ();
9321 } break; case CREATE_DIRECTORY_: { do_createDirectory (); // deprecated 2020
9322 } break; case SET_WORKING_DIRECTORY_: { do_setWorkingDirectory (); // deprecated 2020
9323 } break; case VARIABLE_EXISTS_: { do_variableExists ();
9324 } break; case READ_FILE_: { do_readFile ();
9325 } break; case READ_FILE_STR_: { do_readFile_STR ();
9326 } break; case READ_FILE_VEC_: { do_readFile_VEC ();
9327 } break; case READ_FILE_MAT_: { do_readFile_MAT ();
9328 /********** Matrix functions: **********/
9329 } break; case ROW_VEC_: { do_row_VEC ();
9330 } break; case COL_VEC_: { do_col_VEC ();
9331 } break; case INNER_: { do_inner ();
9332 } break; case CORRELATION_: { do_correlation ();
9333 } break; case OUTER_MAT_: { do_outer_MAT ();
9334 } break; case MUL_VEC_: { do_mul_VEC ();
9335 } break; case MUL_MAT_: { do_mul_MAT ();
9336 } break; case MUL_FAST_MAT_: { do_mul_fast_MAT ();
9337 } break; case MUL_METAL_MAT_: { do_mul_metal_MAT ();
9338 } break; case MUL_TN_MAT_: { do_mul_tn_MAT ();
9339 } break; case MUL_NT_MAT_: { do_mul_nt_MAT ();
9340 } break; case MUL_TT_MAT_: { do_mul_tt_MAT ();
9341 } break; case REPEAT_VEC_: { do_repeat_VEC ();
9342 } break; case ROW_INNERS_VEC_: { do_rowInners_VEC ();
9343 } break; case SOLVE_VEC_: { do_solve_VEC ();
9344 } break; case SOLVE_MAT_: { do_solve_MAT ();
9345 } break; case SOLVE_WEAKLYCONSTRAINED_VEC_: { do_solveWeaklyConstrained_VEC ();
9346 /********** Pause window functions: **********/
9347 } break; case ASK_FOR_TRUST_: { do_askForTrust ();
9348 } break; case BEGIN_PAUSE_: { do_beginPause ();
9349 } break; case REAL_: { do_real ();
9350 } break; case POSITIVE_: { do_positive ();
9351 } break; case INTEGER_: { do_integer ();
9352 } break; case NATURAL_: { do_natural ();
9353 } break; case WORD_: { do_word ();
9354 } break; case SENTENCE_: { do_sentence ();
9355 } break; case TEXT_: { do_text ();
9356 } break; case BOOLEAN_: { do_boolean ();
9357 } break; case CHOICE_: { do_choice ();
9358 } break; case OPTIONMENU_: { do_optionmenu ();
9359 } break; case OPTION_MENU_: { do_optionmenu (); // alternative spelling, deprecated 2023
9360 } break; case OPTION_: { do_option ();
9361 } break; case INFILE_: { do_infile ();
9362 } break; case OUTFILE_: { do_outfile ();
9363 } break; case FOLDER_: { do_folder ();
9364 } break; case REALVECTOR_: { do_realvector ();
9365 } break; case POSITIVEVECTOR_: { do_positivevector ();
9366 } break; case INTEGERVECTOR_: { do_integervector ();
9367 } break; case NATURALVECTOR_: { do_naturalvector ();
9368 } break; case HEADING_: { do_heading ();
9369 } break; case COMMENT_: { do_comment ();
9370 } break; case END_PAUSE_: { do_endPause ();
9371 } break; case LOWER_CASE_APP_NAME_STR_: { do_lowerCaseAppNameStr ();
9372 } break; case UPPER_CASE_APP_NAME_STR_: { do_upperCaseAppNameStr ();
9373 } break; case CLOCK_: { do_clock ();
9374 } break; case APP_VERSION_: { do_appVersion ();
9375 } break; case APP_VERSION_STR_: { do_appVersionStr ();
9376 } break; case APP_YEAR_: { do_appYear ();
9377 } break; case APP_MONTH_: { do_appMonth ();
9378 } break; case APP_MONTH_STR_: { do_appMonthStr ();
9379 } break; case APP_DAY_: { do_appDay ();
9380 } break; case CHOOSE_READ_FILE_STR_: { do_chooseReadFileStr ();
9381 } break; case CHOOSE_WRITE_FILE_STR_: { do_chooseWriteFileStr ();
9382 } break; case CHOOSE_FOLDER_STR_: { do_chooseFolder_STR ();
9383 } break; case CHOOSE_DIRECTORY_STR_: { do_chooseDirectory_STR (); // deprecated 2020
9384 /********** Demo window functions: **********/
9385 } break; case DEMO_WINDOW_TITLE_: { do_demoWindowTitle ();
9386 } break; case DEMO_SHOW_: { do_demoShow ();
9387 } break; case DEMO_WAIT_FOR_INPUT_: { do_demoWaitForInput ();
9388 } break; case DEMO_PEEK_INPUT_: { do_demoPeekInput ();
9389 } break; case DEMO_INPUT_: { do_demoInput ();
9390 } break; case DEMO_CLICKED_IN_: { do_demoClickedIn ();
9391 } break; case DEMO_CLICKED_: { do_demoClicked ();
9392 } break; case DEMO_X_: { do_demoX ();
9393 } break; case DEMO_Y_: { do_demoY ();
9394 } break; case DEMO_KEY_PRESSED_: { do_demoKeyPressed ();
9395 } break; case DEMO_KEY_: { do_demoKey ();
9396 } break; case DEMO_SHIFT_KEY_PRESSED_: { do_demoShiftKeyPressed ();
9397 } break; case DEMO_COMMAND_KEY_PRESSED_: { do_demoCommandKeyPressed ();
9398 } break; case DEMO_OPTION_KEY_PRESSED_: { do_demoOptionKeyPressed ();
9399 /********** **********/
9400 } break; case TRUE_: {
9401 pushNumber (1.0);
9402 } break; case FALSE_: {
9403 pushNumber (0.0);
9404 } break; case IFTRUE_: {
9405 Stackel condition = pop;
9406 if (condition->which == Stackel_NUMBER) {
9407 if (condition->number != 0.0) {
9408 /* Possible compiler BUG: some compilers cannot handle the following assignment. */
9409 /* Those compilers will have trouble with praat's AND and OR. */
9410 programPointer = f [programPointer]. content.label - theOptimize;
9411 }
9412 } else {
9413 Melder_throw (U"A condition between “if” and “then” should be a number, not ", condition->whichText(), U".");
9414 }
9415 } break; case IFFALSE_: {
9416 Stackel condition = pop;
9417 if (condition->which == Stackel_NUMBER) {
9418 if (condition->number == 0.0) {
9419 programPointer = f [programPointer]. content.label - theOptimize;
9420 }
9421 } else {
9422 Melder_throw (U"A condition between “if” and “then” should be a number, not ", condition->whichText(), U".");
9423 }
9424 } break; case GOTO_: {
9425 programPointer = f [programPointer]. content.label - theOptimize;
9426 } break; case LABEL_: {
9427 ;
9428 } break; case DECREMENT_AND_ASSIGN_: {
9429 Stackel x = pop, v = pop;
9430 InterpreterVariable var = v->variable;
9431 var -> numericValue = x->number - 1.0;
9432 //Melder_casual (U"starting value ", var -> numericValue);
9433 pushVariable (var);
9434 } break; case INCREMENT_GREATER_GOTO_: {
9435 //Melder_casual (U"top of loop, stack depth ", stackPointer);
9436 Stackel e = & theStack [stackPointer], v = & theStack [stackPointer - 1];
9437 Melder_assert (e->which == Stackel_NUMBER);
9438 Melder_assert (v->which == Stackel_VARIABLE);
9439 InterpreterVariable var = v->variable;
9440 //Melder_casual (U"loop variable ", var -> numericValue);
9441 var -> numericValue += 1.0;
9442 //Melder_casual (U"loop variable ", var -> numericValue);
9443 //Melder_casual (U"end value ", e->number);
9444 if (var -> numericValue > e->number) {
9445 programPointer = f [programPointer]. content.label - theOptimize;
9446 }
9447 } break; case ADD_3DOWN_: {
9448 Stackel x = pop, s = & theStack [stackPointer - 2];
9449 Melder_assert (x->which == Stackel_NUMBER);
9450 Melder_assert (s->which == Stackel_NUMBER);
9451 //Melder_casual (U"to add ", x->number);
9452 s->number += x->number;
9453 //Melder_casual (U"sum ", s->number);
9454 } break; case POP_2_: {
9455 stackPointer -= 2;
9456 //Melder_casual (U"total ", theStack [stackPointer]. number);
9457 } break; case VEC_CELL_: { do_numericVectorElement ();
9458 } break; case MAT_CELL_: { do_numericMatrixElement ();
9459 } break; case STRVEC_CELL_: { do_stringVectorElement ();
9460 } break; case INDEXED_NUMERIC_VARIABLE_: { do_indexedNumericVariable ();
9461 } break; case INDEXED_STRING_VARIABLE_: { do_indexedStringVariable ();
9462 } break; case VARIABLE_REFERENCE_: {
9463 InterpreterVariable var = f [programPointer]. content.variable;
9464 pushVariable (var);
9465 } break; case SELF0_: { do_self0 (row, col);
9466 } break; case SELFSTR0_: { do_selfStr0 (row, col);
9467 } break; case OBJECT_: { pushObject (f [programPointer]. content.object);
9468 } break; case TO_OBJECT_: { do_toObject ();
9469 } break; case SELFMATRIX1_: { do_selfMatrix1 (row);
9470 } break; case SELFMATRIX1_STR_: { do_selfMatrix1_STR (row);
9471 } break; case SELFMATRIX2_: { do_selfMatrix2 ();
9472 } break; case SELFMATRIX2_STR_: { do_selfMatrix2_STR ();
9473 } break; case SELFFUNCTION1_: { do_selfFunction1 (row);
9474 } break; case SELFFUNCTION2_: { do_selfFunction2 ();
9475 } break; case OBJECTCELL0_: { do_objectCell0 (row, col);
9476 } break; case OBJECTCELL1_: { do_objectCell1 (row);
9477 } break; case OBJECTCELL1_STR_: { do_objectCell1_STR (row);
9478 } break; case OBJECTCELL2_: { do_objectCell2 ();
9479 } break; case OBJECTCELL2_STR_: { do_objectCell2_STR ();
9480 } break; case OBJECTLOCATION0_: { do_objectLocation0 (row, col);
9481 } break; case OBJECTLOCATION1_: { do_objectLocation1 (row);
9482 } break; case OBJECTLOCATION2_: { do_objectLocation2 ();
9483 } break; case MATRIX0_: { do_matrix0 (row, col);
9484 } break; case MATRIX1_: { do_matrix1 (row);
9485 } break; case MATRIX1_STR_: { do_matrix1_STR (row);
9486 } break; case MATRIX2_: { do_matrix2 ();
9487 } break; case MATRIX2_STR_: { do_matrix2_STR ();
9488 } break; case FUNCTION0_: { do_function0 (row, col);
9489 } break; case FUNCTION1_: { do_function1 (row);
9490 } break; case FUNCTION2_: { do_function2 ();
9491 } break; case ROW_STR_: { do_row_STR ();
9492 } break; case COL_STR_: { do_col_STR ();
9493 } break; case SQR_: { do_sqr ();
9494 } break; case STRING_: {
9495 autostring32 string = Melder_dup (f [programPointer]. content.string);
9496 pushString (string.move());
9497 } break; case TENSOR_LITERAL_: { do_tensorLiteral ();
9498 } break; case TENSOR_LITERAL_CELL_: { do_tensorLiteralCell ();
9499 } break; case NUMERIC_VARIABLE_: {
9500 InterpreterVariable var = f [programPointer]. content.variable;
9501 pushNumber (var -> numericValue);
9502 } break; case NUMERIC_VECTOR_VARIABLE_: {
9503 InterpreterVariable var = f [programPointer]. content.variable;
9504 pushNumericVectorReference (var -> numericVectorValue.get());
9505 } break; case NUMERIC_MATRIX_VARIABLE_: {
9506 InterpreterVariable var = f [programPointer]. content.variable;
9507 pushNumericMatrixReference (var -> numericMatrixValue.get());
9508 } break; case STRING_VARIABLE_: {
9509 InterpreterVariable var = f [programPointer]. content.variable;
9510 autostring32 string = Melder_dup (var -> stringValue.get());
9511 pushString (string.move());
9512 } break; case STRING_ARRAY_VARIABLE_: {
9513 InterpreterVariable var = f [programPointer]. content.variable;
9514 pushStringVectorReference (var -> stringArrayValue.get());
9515 } break; default: Melder_throw (U"Symbol “", Formula_instructionNames [parse [programPointer]. symbol], U"” without action.");
9516 } // endswitch
9517 programPointer ++;
9518 } // endwhile
9519 if (stackPointer != 1)
9520 Melder_crash (U"Formula: stackpointer ends at ", stackPointer, U" instead of 1.");
9521 /*
9522 Move the result from the stack to `result`.
9523 */
9524 result -> reset();
9525 if (theExpressionType [theLevel] == kFormula_EXPRESSION_TYPE_NUMERIC) {
9526 if (theStack [1]. which == Stackel_STRING)
9527 Melder_throw (U"Found a string expression instead of a numeric expression.");
9528 if (theStack [1]. which == Stackel_NUMERIC_VECTOR)
9529 Melder_throw (U"Found a vector expression instead of a numeric expression.");
9530 if (theStack [1]. which == Stackel_NUMERIC_MATRIX)
9531 Melder_throw (U"Found a matrix expression instead of a numeric expression.");
9532 if (theStack [1]. which == Stackel_STRING_ARRAY)
9533 Melder_throw (U"Found a string vector expression instead of a numeric expression.");
9534 Melder_assert (theStack [1]. which == Stackel_NUMBER);
9535 result -> expressionType = kFormula_EXPRESSION_TYPE_NUMERIC;
9536 result -> numericResult = theStack [1]. number;
9537 } else if (theExpressionType [theLevel] == kFormula_EXPRESSION_TYPE_STRING) {
9538 if (theStack [1]. which == Stackel_NUMBER)
9539 Melder_throw (U"Found a numeric expression (value ", theStack [1]. number, U") instead of a string expression.");
9540 if (theStack [1]. which == Stackel_NUMERIC_VECTOR)
9541 Melder_throw (U"Found a vector expression instead of a string expression.");
9542 if (theStack [1]. which == Stackel_NUMERIC_MATRIX)
9543 Melder_throw (U"Found a matrix expression instead of a string expression.");
9544 if (theStack [1]. which == Stackel_STRING_ARRAY)
9545 Melder_throw (U"Found a string vector expression instead of a string expression.");
9546 Melder_assert (theStack [1]. which == Stackel_STRING);
9547 result -> expressionType = kFormula_EXPRESSION_TYPE_STRING;
9548 Melder_assert (! result -> stringResult);
9549 result -> stringResult = theStack [1]. moveString();
9550 Melder_assert (theStack [1]. which == Stackel_STRING);
9551 Melder_assert (! theStack [1]. getString());
9552 } else if (theExpressionType [theLevel] == kFormula_EXPRESSION_TYPE_NUMERIC_VECTOR) {
9553 if (theStack [1]. which == Stackel_NUMBER)
9554 Melder_throw (U"Found a numeric expression instead of a vector expression.");
9555 if (theStack [1]. which == Stackel_STRING)
9556 Melder_throw (U"Found a string expression instead of a vector expression.");
9557 if (theStack [1]. which == Stackel_NUMERIC_MATRIX)
9558 Melder_throw (U"Found a matrix expression instead of a vector expression.");
9559 if (theStack [1]. which == Stackel_STRING_ARRAY)
9560 Melder_throw (U"Found a string vector expression instead of a numeric vector expression.");
9561 Melder_assert (theStack [1]. which == Stackel_NUMERIC_VECTOR);
9562 result -> expressionType = kFormula_EXPRESSION_TYPE_NUMERIC_VECTOR;
9563 result -> numericVectorResult = theStack [1]. numericVector;
9564 result -> owned = theStack [1]. owned;
9565 theStack [1]. owned = false;
9566 } else if (theExpressionType [theLevel] == kFormula_EXPRESSION_TYPE_NUMERIC_MATRIX) {
9567 if (theStack [1]. which == Stackel_NUMBER)
9568 Melder_throw (U"Found a numeric expression instead of a matrix expression.");
9569 if (theStack [1]. which == Stackel_STRING)
9570 Melder_throw (U"Found a string expression instead of a matrix expression.");
9571 if (theStack [1]. which == Stackel_NUMERIC_VECTOR)
9572 Melder_throw (U"Found a vector expression instead of a matrix expression.");
9573 if (theStack [1]. which == Stackel_STRING_ARRAY)
9574 Melder_throw (U"Found a string vector expression instead of a numeric matrix expression.");
9575 Melder_assert (theStack [1]. which == Stackel_NUMERIC_MATRIX);
9576 result -> expressionType = kFormula_EXPRESSION_TYPE_NUMERIC_MATRIX;
9577 result -> numericMatrixResult = theStack [1]. numericMatrix;
9578 result -> owned = theStack [1]. owned;
9579 theStack [1]. owned = false;
9580 } else if (theExpressionType [theLevel] == kFormula_EXPRESSION_TYPE_STRING_ARRAY) {
9581 if (theStack [1]. which == Stackel_NUMBER)
9582 Melder_throw (U"Found a numeric expression instead of a string vector expression.");
9583 if (theStack [1]. which == Stackel_STRING)
9584 Melder_throw (U"Found a string expression instead of a string vector expression.");
9585 if (theStack [1]. which == Stackel_NUMERIC_VECTOR)
9586 Melder_throw (U"Found a vector expression instead of a string vector expression.");
9587 if (theStack [1]. which == Stackel_NUMERIC_MATRIX)
9588 Melder_throw (U"Found a matrix expression instead of a string vector expression.");
9589 Melder_assert (theStack [1]. which == Stackel_STRING_ARRAY);
9590 result -> expressionType = kFormula_EXPRESSION_TYPE_STRING_ARRAY;
9591 result -> stringArrayResult = theStack [1]. stringArray;
9592 result -> owned = theStack [1]. owned;
9593 theStack [1]. owned = false;
9594 } else {
9595 Melder_assert (theExpressionType [theLevel] == kFormula_EXPRESSION_TYPE_UNKNOWN);
9596 if (theStack [1]. which == Stackel_NUMBER) {
9597 result -> expressionType = kFormula_EXPRESSION_TYPE_NUMERIC;
9598 result -> numericResult = theStack [1]. number;
9599 } else if (theStack [1]. which == Stackel_STRING) {
9600 result -> expressionType = kFormula_EXPRESSION_TYPE_STRING;
9601 Melder_assert (! result -> stringResult);
9602 result -> stringResult = theStack [1]. moveString();
9603 Melder_assert (theStack [1]. which == Stackel_STRING);
9604 Melder_assert (! theStack [1]. getString());
9605 } else if (theStack [1]. which == Stackel_NUMERIC_VECTOR) {
9606 result -> expressionType = kFormula_EXPRESSION_TYPE_NUMERIC_VECTOR;
9607 result -> numericVectorResult = theStack [1]. numericVector;
9608 result -> owned = theStack [1]. owned;
9609 theStack [1]. owned = false;
9610 } else if (theStack [1]. which == Stackel_NUMERIC_MATRIX) {
9611 result -> expressionType = kFormula_EXPRESSION_TYPE_NUMERIC_MATRIX;
9612 result -> numericMatrixResult = theStack [1]. numericMatrix;
9613 result -> owned = theStack [1]. owned;
9614 theStack [1]. owned = false;
9615 } else if (theStack [1]. which == Stackel_STRING_ARRAY) {
9616 result -> expressionType = kFormula_EXPRESSION_TYPE_STRING_ARRAY;
9617 result -> stringArrayResult = theStack [1]. stringArray;
9618 result -> owned = theStack [1]. owned;
9619 theStack [1]. owned = false;
9620 } else {
9621 Melder_throw (U"Don't know yet how to write ", theStack [1]. whichText(), U".");
9622 }
9623 }
9624 /*
9625 Clean up the stack (theStack [1] has probably been disowned).
9626 */
9627 for (stackPointer = stackPointerMax; stackPointer > 0; stackPointer --)
9628 theStack [stackPointer]. reset();
9629 } catch (MelderError) {
9630 /*
9631 Clean up the stack (theStack [1] has probably not been disowned).
9632 */
9633 for (stackPointer = stackPointerMax; stackPointer > 0; stackPointer --)
9634 theStack [stackPointer]. reset();
9635 if (Melder_hasError (U"Script exited.")) {
9636 throw;
9637 } else {
9638 Melder_throw (U"Formula not run.");
9639 }
9640 }
9641 }
9642
9643 /* End of file Formula.cpp */