better tests
[pspp] / src / language / expressions / operations.def
1 // -*- c -*-
2 //
3 // PSPP - a program for statistical analysis.
4 // Copyright (C) 2005, 2006, 2009, 2010, 2011, 2012, 2015, 2016 Free Software Foundation, Inc.
5 //
6 // This program is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19 operator NEG (x) = -x;
20
21 operator ADD (a, b) = a + b;
22 operator SUB (a, b) = a - b;
23
24 absorb_miss operator MUL (a, b)
25 = (a == 0. || b == 0. ? 0.
26    : a == SYSMIS || b == SYSMIS ? SYSMIS
27    : a * b);
28
29 absorb_miss operator DIV (a, b)
30 = (a == 0. ? 0.
31    : a == SYSMIS || b == SYSMIS ? SYSMIS
32    : a / b);
33
34 absorb_miss operator POW (a, b)
35 = (a == SYSMIS ? (b == 0. ? 1. : a)
36    : b == SYSMIS ? (a == 0. ? 0. : SYSMIS)
37    : a == 0. && b <= 0. ? SYSMIS
38    : pow (a, b));
39
40 absorb_miss boolean operator AND (boolean a, boolean b)
41 = (a == 0. ? 0.
42    : b == 0. ? 0.
43    : b == SYSMIS ? SYSMIS
44    : a);
45
46 absorb_miss boolean operator OR (boolean a, boolean b)
47 = (a == 1. ? 1.
48    : b == 1. ? 1.
49    : b == SYSMIS ? SYSMIS
50    : a);
51
52 boolean operator NOT (boolean a)
53 = (a == 0. ? 1.
54    : a == 1. ? 0.
55    : SYSMIS);
56
57 // Numeric relational operators.
58 boolean operator EQ (a, b) = a == b;
59 boolean operator GE (a, b) = a >= b;
60 boolean operator GT (a, b) = a > b;
61 boolean operator LE (a, b) = a <= b;
62 boolean operator LT (a, b) = a < b;
63 boolean operator NE (a, b) = a != b;
64
65 // String relational operators.
66 boolean operator EQ_STRING (string a, string b) = compare_string_3way (&a, &b) == 0;
67 boolean operator GE_STRING (string a, string b) = compare_string_3way (&a, &b) >= 0;
68 boolean operator GT_STRING (string a, string b) = compare_string_3way (&a, &b) > 0;
69 boolean operator LE_STRING (string a, string b) = compare_string_3way (&a, &b) <= 0;
70 boolean operator LT_STRING (string a, string b) = compare_string_3way (&a, &b) < 0;
71 boolean operator NE_STRING (string a, string b) = compare_string_3way (&a, &b) != 0;
72
73 // Unary functions.
74 function ABS (x) = fabs (x);
75 extension function ACOS (x >= -1 && x <= 1) = acos (x);
76 function ASIN (x >= -1 && x <= 1) = asin (x);
77 function ATAN (x) = atan (x);
78 extension function ARCOS (x >= -1 && x <= 1) = acos (x);
79 function ARSIN (x >= -1 && x <= 1) = asin (x);
80 function ARTAN (x) = atan (x);
81 function COS (x) = cos (x);
82 function EXP (x) = check_errno (exp (x));
83 function LG10(x) = check_errno (log10 (x));
84 function LN (x) = check_errno (log (x));
85 function LNGAMMA (x >= 0) = gsl_sf_lngamma (x);
86 function MOD10 (x) = fmod (x, 10);
87 function RND (x) = round_nearest (x, 1, 0);
88 function RND (x, mult != 0) = round_nearest (x, mult, 0);
89 function RND (x, mult != 0, fuzzbits >= 0) = round_nearest (x, mult, fuzzbits);
90 function SIN (x) = sin (x);
91 function SQRT (x >= 0) = sqrt (x);
92 function TAN (x) = check_errno (tan (x));
93 function TRUNC (x) = round_zero (x, 1, 0);
94 function TRUNC (x, mult != 0) = round_zero (x, mult, 0);
95 function TRUNC (x, mult != 0, fuzzbits >= 0) = round_zero (x, mult, fuzzbits);
96
97 absorb_miss function MOD (n, d)
98 {
99   if (d != SYSMIS)
100     return n != SYSMIS ? fmod (n, d) : SYSMIS;
101   else
102     return n != 0. ? SYSMIS : 0.;
103 }
104
105 // N-ary numeric functions.
106 absorb_miss boolean function ANY (x != SYSMIS, a[n])
107 {
108   int sysmis = 0;
109   size_t i;
110
111   for (i = 0; i < n; i++)
112     if (a[i] == x)
113       return 1.;
114     else if (a[i] == SYSMIS)
115       sysmis = 1;
116
117   return sysmis ? SYSMIS : 0.;
118 }
119
120 boolean function ANY (string x, string a[n])
121 {
122   size_t i;
123
124   for (i = 0; i < n; i++)
125     if (!compare_string_3way (&x, &a[i]))
126       return 1.;
127   return 0.;
128 }
129
130 function CFVAR.2 (a[n])
131 {
132   double mean, variance;
133
134   moments_of_doubles (a, n, NULL, &mean, &variance, NULL, NULL);
135
136   if (mean == SYSMIS || mean == 0 || variance == SYSMIS)
137     return SYSMIS;
138   else
139     return sqrt (variance) / mean;
140 }
141
142 function MAX.1 (a[n])
143 {
144   double max;
145   size_t i;
146
147   max = -DBL_MAX;
148   for (i = 0; i < n; i++)
149     if (a[i] != SYSMIS && a[i] > max)
150       max = a[i];
151   return max;
152 }
153
154 string function MAX (string a[n])
155 {
156   struct substring *max;
157   size_t i;
158
159   max = &a[0];
160   for (i = 1; i < n; i++)
161     if (compare_string_3way (&a[i], max) > 0)
162       max = &a[i];
163   return *max;
164 }
165
166 function MEAN.1 (a[n])
167 {
168   double mean;
169   moments_of_doubles (a, n, NULL, &mean, NULL, NULL, NULL);
170   return mean;
171 }
172
173 function MEDIAN.1 (a[n])
174 {
175   return median (a, n);
176 }
177
178 function MIN.1 (a[n])
179 {
180   double min;
181   size_t i;
182
183   min = DBL_MAX;
184   for (i = 0; i < n; i++)
185     if (a[i] != SYSMIS && a[i] < min)
186       min = a[i];
187   return min;
188 }
189
190 string function MIN (string a[n])
191 {
192   struct substring *min;
193   size_t i;
194
195   min = &a[0];
196   for (i = 1; i < n; i++)
197     if (compare_string_3way (&a[i], min) < 0)
198       min = &a[i];
199   return *min;
200 }
201
202 absorb_miss function NMISS (a[n])
203 {
204   size_t n_missings = 0;
205   for (size_t i = 0; i < n; i++)
206     n_missings += a[i] == SYSMIS;
207   return n_missings;
208 }
209
210 absorb_miss function NVALID (a[n])
211 {
212   size_t n_valids = 0;
213   for (size_t i = 0; i < n; i++)
214     n_valids += a[i] != SYSMIS;
215   return n_valids;
216 }
217
218 absorb_miss boolean function RANGE (x != SYSMIS, a[n*2])
219 {
220   size_t i;
221   int sysmis = 0;
222
223   for (i = 0; i < n; i++)
224     {
225       double w = a[2 * i];
226       double y = a[2 * i + 1];
227       if (w != SYSMIS && y != SYSMIS)
228         {
229           if (w <= x && x <= y)
230             return 1.0;
231         }
232       else
233         sysmis = 1;
234     }
235   return sysmis ? SYSMIS : 0.;
236 }
237
238 boolean function RANGE (string x, string a[n*2])
239 {
240   int i;
241
242   for (i = 0; i < n; i++)
243     {
244       struct substring *w = &a[2 * i];
245       struct substring *y = &a[2 * i + 1];
246       if (compare_string_3way (w, &x) <= 0 && compare_string_3way (&x, y) <= 0)
247         return 1.;
248     }
249   return 0.;
250 }
251
252 function SD.2 (a[n])
253 {
254   double variance;
255   moments_of_doubles (a, n, NULL, NULL, &variance, NULL, NULL);
256   return sqrt (variance);
257 }
258
259 function SUM.1 (a[n])
260 {
261   double sum;
262   size_t i;
263
264   sum = 0.;
265   for (i = 0; i < n; i++)
266     if (a[i] != SYSMIS)
267       sum += a[i];
268   return sum;
269 }
270
271 function VARIANCE.2 (a[n])
272 {
273   double variance;
274   moments_of_doubles (a, n, NULL, NULL, &variance, NULL, NULL);
275   return variance;
276 }
277
278 // Time construction & extraction functions.
279 function TIME.HMS (h, m, s)
280   expression e;
281   expr_node n;
282 {
283   if ((h > 0. || m > 0. || s > 0.) && (h < 0. || m < 0. || s < 0.))
284     {
285       msg_at (SW, expr_location (e, n),
286               _("TIME.HMS cannot accept a mix of positive and negative "
287                 "arguments."));
288       double args[] = { h, m, s };
289       for (size_t i = 0; i < 3; i++)
290         if (args[i] > 0)
291           msg_at (SN, expr_location (e, n->args[i]),
292                   _("This argument has positive value %g."), args[i]);
293         else if (args[i] < 0)
294           msg_at (SN, expr_location (e, n->args[i]),
295                   _("This argument has negative value %g."), args[i]);
296       return SYSMIS;
297     }
298   else
299     return H_S * h + MIN_S * m + s;
300 }
301 function TIME.DAYS (days) = days * DAY_S;
302 function CTIME.DAYS (time) = time / DAY_S;
303 function CTIME.HOURS (time) = time / H_S;
304 function CTIME.MINUTES (time) = time / MIN_S;
305 function CTIME.SECONDS (time) = time;
306
307 // Date construction functions.
308 function DATE.DMY (integer d, integer m, integer y)
309   expression e;
310   expr_node n;
311 = expr_ymd_to_date (y, m, d, e, n, 3, 2, 1);
312
313 function DATE.MDY (integer m, integer d, integer y)
314   expression e;
315   expr_node n;
316 = expr_ymd_to_date (y, m, d, e, n, 3, 1, 2);
317
318 function DATE.MOYR (integer m, integer y)
319   expression e;
320   expr_node n;
321 = expr_ymd_to_date (y, m, 1, e, n, 2, 1, 0);
322
323 function DATE.QYR (integer q, integer y)
324   expression e;
325   expr_node n;
326 {
327   if (q < 1 || q > 4)
328     {
329       msg_at (SW, expr_location (e, n->args[0]),
330               _("Argument 1 to DATE.QYR must be 1, 2, 3, or 4 (not %d)."), q);
331       return SYSMIS;
332     }
333   return expr_ymd_to_date (y, q * 3 - 2, 1, e, n, 2, 0, 0);
334 }
335
336 function DATE.WKYR (integer w, integer y)
337   expression e;
338   expr_node n;
339 {
340   if (w < 1 || w > 53)
341     {
342       msg_at (SE, expr_location (e, n->args[0]),
343               _("The week argument to DATE.WKYR is outside the acceptable "
344                 "range of 1 to 53.  The result will be system-missing."));
345       return SYSMIS;
346     }
347   else
348     {
349       double yr_1_1 = expr_ymd_to_ofs (y, 1, 1, e, n, 2, 0, 0);
350       if (yr_1_1 != SYSMIS)
351         return DAY_S * (yr_1_1 + WEEK_DAY * (w - 1));
352       else
353         return SYSMIS;
354     }
355 }
356
357 function DATE.YRDAY (integer y, integer yd)
358   expression e;
359   expr_node n;
360 {
361   if (yd < 1 || yd > 366)
362     {
363       msg_at (SE, expr_location (e, n->args[1]),
364               _("DATE.YRDAY day argument %d is outside the acceptable "
365                 "range of 1 to 366.  The result will be system-missing."), yd);
366       return SYSMIS;
367     }
368   else
369     {
370       double yr_1_1 = expr_ymd_to_ofs (y, 1, 1, e, n, 1, 0, 0);
371       if (yr_1_1 != SYSMIS)
372         return DAY_S * (yr_1_1 + yd - 1.);
373       else
374         return SYSMIS;
375     }
376 }
377
378 function YRMODA (integer y, integer m, integer d)
379   expression e;
380   expr_node n;
381 {
382   if (y >= 0 && y <= 99)
383     y += 1900;
384   else if (y > 47516)
385     {
386       msg_at (SE, expr_location (e, n->args[0]),
387               _("The year argument to YRMODA is greater than 47516.  "
388                 "The result will be system-missing."));
389       return SYSMIS;
390     }
391
392   return expr_ymd_to_ofs (y, m, d, e, n, 1, 2, 3);
393 }
394
395 // Date extraction functions.
396 function XDATE.TDAY (date) = floor (date / DAY_S);
397 function XDATE.HOUR (date) = fmod (floor (date / H_S), DAY_H);
398 function XDATE.MINUTE (date) = fmod (floor (date / H_MIN), H_MIN);
399 function XDATE.SECOND (date) = fmod (date, MIN_S);
400 function XDATE.DATE (date) = floor (date / DAY_S) * DAY_S;
401 function XDATE.TIME (date) = fmod (date, DAY_S);
402
403 function XDATE.JDAY (date >= DAY_S) = calendar_offset_to_yday (date / DAY_S);
404 function XDATE.MDAY (date >= DAY_S) = calendar_offset_to_mday (date / DAY_S);
405 function XDATE.MONTH (date >= DAY_S)
406      = calendar_offset_to_month (date / DAY_S);
407 function XDATE.QUARTER (date >= DAY_S)
408     = (calendar_offset_to_month (date / DAY_S) - 1) / 3 + 1;
409 function XDATE.WEEK (date >= DAY_S)
410     = (calendar_offset_to_yday (date / DAY_S) - 1) / 7 + 1;
411 function XDATE.WKDAY (date >= DAY_S) = calendar_offset_to_wday (date / DAY_S);
412 function XDATE.YEAR (date >= DAY_S) = calendar_offset_to_year (date / DAY_S);
413
414 // Date arithmetic functions.
415 no_abbrev function DATEDIFF (date2 >= DAY_S, date1 >= DAY_S, string unit)
416   expression e;
417   expr_node n;
418 = expr_date_difference (date1, date2, unit, e, n);
419
420 no_abbrev function DATESUM (date, quantity, string unit)
421   expression e;
422   expr_node n;
423 = expr_date_sum_closest (date, quantity, unit, e, n);
424 no_abbrev function DATESUM (date, quantity, string unit, string method)
425   expression e;
426   expr_node n;
427 = expr_date_sum (date, quantity, unit, method, e, n);
428
429
430 // String functions.
431 string function CONCAT (string a[n])
432      expression e;
433 {
434   struct substring dst;
435   size_t i;
436
437   dst = alloc_string (e, MAX_STRING);
438   dst.length = 0;
439   for (i = 0; i < n; i++)
440     {
441       struct substring *src = &a[i];
442       size_t copy_len;
443
444       copy_len = src->length;
445       if (dst.length + copy_len > MAX_STRING)
446         copy_len = MAX_STRING - dst.length;
447       memcpy (&dst.string[dst.length], src->string, copy_len);
448       dst.length += copy_len;
449     }
450
451   return dst;
452 }
453
454 function INDEX (string haystack, string needle)
455 {
456   if (needle.length == 0)
457     return SYSMIS;
458   else
459     {
460       int limit = haystack.length - needle.length + 1;
461       int i;
462       for (i = 1; i <= limit; i++)
463         if (!memcmp (&haystack.string[i - 1], needle.string, needle.length))
464           return i;
465       return 0;
466     }
467 }
468
469 function INDEX (string haystack, string needles, needle_len_d)
470 {
471   if (needle_len_d <= INT_MIN || needle_len_d >= INT_MAX
472       || (int) needle_len_d != needle_len_d
473       || needles.length == 0)
474     return SYSMIS;
475   else
476     {
477       int needle_len = needle_len_d;
478       if (needle_len < 0 || needle_len > needles.length
479           || needles.length % needle_len != 0)
480         return SYSMIS;
481       else
482         {
483           int limit = haystack.length - needle_len + 1;
484           int i, j;
485           for (i = 1; i <= limit; i++)
486             for (j = 0; j < needles.length; j += needle_len)
487               if (!memcmp (&haystack.string[i - 1], &needles.string[j],
488                            needle_len))
489                 return i;
490           return 0;
491         }
492     }
493 }
494
495 function RINDEX (string haystack, string needle)
496 {
497   if (needle.length == 0)
498     return SYSMIS;
499   else
500     {
501       int limit = haystack.length - needle.length + 1;
502       int i;
503       for (i = limit; i >= 1; i--)
504         if (!memcmp (&haystack.string[i - 1], needle.string, needle.length))
505           return i;
506       return 0;
507     }
508 }
509
510 function RINDEX (string haystack, string needles, needle_len_d)
511 {
512   if (needle_len_d <= 0 || needle_len_d >= INT_MAX
513       || (int) needle_len_d != needle_len_d
514       || needles.length == 0)
515     return SYSMIS;
516   else
517     {
518       int needle_len = needle_len_d;
519       if (needle_len < 0 || needle_len > needles.length
520           || needles.length % needle_len != 0)
521         return SYSMIS;
522       else
523         {
524           int limit = haystack.length - needle_len + 1;
525           int i, j;
526           for (i = limit; i >= 1; i--)
527             for (j = 0; j < needles.length; j += needle_len)
528               if (!memcmp (&haystack.string[i - 1],
529                            &needles.string[j], needle_len))
530                 return i;
531           return 0;
532         }
533     }
534 }
535
536 function LENGTH (string s)
537 {
538   return s.length;
539 }
540
541 string function LOWER (string s)
542 {
543   int i;
544
545   for (i = 0; i < s.length; i++)
546     s.string[i] = tolower ((unsigned char) s.string[i]);
547   return s;
548 }
549
550 function MBLEN.BYTE (string s, idx)
551 {
552   if (idx < 0 || idx >= s.length || (int) idx != idx)
553     return SYSMIS;
554   else
555     return 1;
556 }
557
558 string function UPCASE (string s)
559 {
560   int i;
561
562   for (i = 0; i < s.length; i++)
563     s.string[i] = toupper ((unsigned char) s.string[i]);
564   return s;
565 }
566
567 absorb_miss string function LPAD (string s, n)
568      expression e;
569 {
570   if (n < 0 || n > MAX_STRING || (int) n != n)
571     return empty_string;
572   else if (s.length >= n)
573     return s;
574   else
575     {
576       struct substring t = alloc_string (e, n);
577       memset (t.string, ' ', n - s.length);
578       memcpy (&t.string[(int) n - s.length], s.string, s.length);
579       return t;
580     }
581 }
582
583 absorb_miss string function LPAD (string s, n, string c)
584      expression e;
585 {
586   if (n < 0 || n > MAX_STRING || (int) n != n || c.length != 1)
587     return empty_string;
588   else if (s.length >= n)
589     return s;
590   else
591     {
592       struct substring t = alloc_string (e, n);
593       memset (t.string, c.string[0], n - s.length);
594       memcpy (&t.string[(int) n - s.length], s.string, s.length);
595       return t;
596     }
597 }
598
599 string function REPLACE (string haystack, string needle, string replacement)
600     expression e;
601   = replace_string (e, haystack, needle, replacement, DBL_MAX);
602
603 absorb_miss string function REPLACE (string haystack, string needle,
604                                      string replacement, n)
605     expression e;
606   = replace_string (e, haystack, needle, replacement, n);
607
608 absorb_miss string function RPAD (string s, n)
609      expression e;
610 {
611   if (n < 0 || n > MAX_STRING || (int) n != n)
612     return empty_string;
613   else if (s.length >= n)
614     return s;
615   else
616     {
617       struct substring t = alloc_string (e, n);
618       memcpy (t.string, s.string, s.length);
619       memset (&t.string[s.length], ' ', n - s.length);
620       return t;
621     }
622 }
623
624 absorb_miss string function RPAD (string s, n, string c)
625      expression e;
626 {
627   if (n < 0 || n > MAX_STRING || (int) n != n || c.length != 1)
628     return empty_string;
629   else if (s.length >= n)
630     return s;
631   else
632     {
633       struct substring t = alloc_string (e, n);
634       memcpy (t.string, s.string, s.length);
635       memset (&t.string[s.length], c.string[0], n - s.length);
636       return t;
637     }
638 }
639
640 string function LTRIM (string s)
641 {
642   while (s.length > 0 && s.string[0] == ' ')
643     {
644       s.length--;
645       s.string++;
646     }
647   return s;
648 }
649
650 string function LTRIM (string s, string c)
651 {
652   if (c.length == 1)
653     {
654       while (s.length > 0 && s.string[0] == c.string[0])
655         {
656           s.length--;
657           s.string++;
658         }
659       return s;
660     }
661   else
662     return empty_string;
663 }
664
665 string function RTRIM (string s)
666 {
667   while (s.length > 0 && s.string[s.length - 1] == ' ')
668     s.length--;
669   return s;
670 }
671
672 string function RTRIM (string s, string c)
673 {
674   if (c.length == 1)
675     {
676       while (s.length > 0 && s.string[s.length - 1] == c.string[0])
677         s.length--;
678       return s;
679     }
680   else
681     return empty_string;
682 }
683
684 function NUMBER (string s, ni_format f)
685   expression e;
686   expr_node n;
687 {
688   union value out;
689   char *error;
690
691   if (s.length > f->w)
692     s.length = f->w;
693   error = data_in (s, C_ENCODING, f->type, settings_get_fmt_settings (),
694                    &out, 0, NULL);
695   if (error == NULL)
696     data_in_imply_decimals (s, C_ENCODING, f->type, f->d,
697                             settings_get_fmt_settings (), &out);
698   else
699     {
700       msg_at (SE, expr_location (e, n->args[0]),
701               _("Cannot parse `%.*s' as format %s: %s"),
702               (int) s.length, s.string, fmt_name (f->type), error);
703       free (error);
704     }
705   return out.f;
706 }
707
708 absorb_miss string function STRING (x, no_format f)
709      expression e;
710 {
711   union value v;
712   struct substring dst;
713   char *s;
714
715   v.f = x;
716
717   assert (!fmt_is_string (f->type));
718   s = data_out (&v, C_ENCODING, f, settings_get_fmt_settings ());
719   dst = alloc_string (e, strlen (s));
720   strcpy (dst.string, s);
721   free (s);
722   return dst;
723 }
724
725 absorb_miss string function STRUNC (string s, n)
726 {
727   if (n < 1 || n == SYSMIS)
728     return empty_string;
729
730   if (n < s.length)
731     s.length = n;
732   while (s.length > 0 && s.string[s.length - 1] == ' ')
733     s.length--;
734   return s;
735 }
736
737 absorb_miss string function SUBSTR (string s, ofs)
738      expression e;
739 {
740   if (ofs >= 1 && ofs <= s.length && (int) ofs == ofs)
741     return copy_string (e, &s.string[(int) ofs - 1], s.length - ofs + 1);
742   else
743     return empty_string;
744 }
745
746 absorb_miss string function SUBSTR (string s, ofs, cnt)
747      expression e;
748 {
749   if (ofs >= 1 && ofs <= s.length && (int) ofs == ofs
750       && cnt >= 1 && cnt <= INT_MAX && (int) cnt == cnt)
751     {
752       int cnt_max = s.length - (int) ofs + 1;
753       return copy_string (e, &s.string[(int) ofs - 1],
754                           cnt <= cnt_max ? cnt : cnt_max);
755     }
756   else
757     return empty_string;
758 }
759
760 absorb_miss no_opt no_abbrev string function VALUELABEL (var v)
761      expression e;
762      case c;
763 {
764   const char *label = var_lookup_value_label (v, case_data (c, v));
765   if (label != NULL)
766     return copy_string (e, label, strlen (label));
767   else
768     return empty_string;
769 }
770
771 // Artificial.
772 operator SQUARE (x) = x * x;
773
774 absorb_miss boolean operator OPERAND_TO_BOOLEAN (x, expr_node parent)
775   expression e;
776   expr_node n;
777 {
778   if (x == 0. || x == 1. || x == SYSMIS)
779     return x;
780
781   msg_at (SE, expr_location (e, parent),
782           _("The operands of %s must have value 0 or 1."),
783           operations[parent->type].name);
784   msg_at (SN, expr_location (e, n),
785           _("This operand with unexpected value %g will be treated as 0."), x);
786   return 0.;
787 }
788
789 absorb_miss boolean operator EXPR_TO_BOOLEAN (x)
790   expression e;
791   expr_node n;
792 {
793   if (x == 0. || x == 1. || x == SYSMIS)
794     return x;
795
796   msg_at (SE, expr_location (e, n),
797           _("This expression, which must be 0 or 1, evaluated to %g.  "
798             "It will be treated as 0."), x);
799   return 0.;
800 }
801
802 operator NUM_TO_INTEGER (x)
803   expression e;
804   expr_node n;
805 {
806   if (x == floor (x) && x > INT_MIN && x <= INT_MAX)
807     return x;
808
809   msg_at (SE, expr_location (e, n),
810           _("Treating unexpected non-integer value %g as missing."), x);
811   return SYSMIS;
812 }
813
814 operator BOOLEAN_TO_NUM (boolean x) = x;
815
816 // Beta distribution.
817 function PDF.BETA (x >= 0 && x <= 1, a > 0, b > 0)
818      = gsl_ran_beta_pdf (x, a, b);
819 function CDF.BETA (x >= 0 && x <= 1, a > 0, b > 0) = gsl_cdf_beta_P (x, a, b);
820 function IDF.BETA (P >= 0 && P <= 1, a > 0, b > 0)
821      = gsl_cdf_beta_Pinv (P, a, b);
822 no_opt function RV.BETA (a > 0, b > 0) = gsl_ran_beta (get_rng (), a, b);
823 function NCDF.BETA (x >= 0, a > 0, b > 0, lambda > 0)
824      = ncdf_beta (x, a, b, lambda);
825 function NPDF.BETA (x >= 0, a > 0, b > 0, lambda > 0)
826      = npdf_beta (x, a, b, lambda);
827
828 // Bivariate normal distribution.
829 function CDF.BVNOR (x0, x1, r >= -1 && r <= 1) = cdf_bvnor (x0, x1, r);
830 function PDF.BVNOR (x0, x1, r >= -1 && r <= 1)
831      = gsl_ran_bivariate_gaussian_pdf (x0, x1, 1, 1, r);
832
833 // Cauchy distribution.
834 function CDF.CAUCHY (x, a, b > 0) = gsl_cdf_cauchy_P ((x - a) / b, 1);
835 function IDF.CAUCHY (P > 0 && P < 1, a, b > 0)
836      = a + b * gsl_cdf_cauchy_Pinv (P, 1);
837 function PDF.CAUCHY (x, a, b > 0) = gsl_ran_cauchy_pdf ((x - a) / b, 1) / b;
838 no_opt function RV.CAUCHY (a, b > 0) = a + b * gsl_ran_cauchy (get_rng (), 1);
839
840 // Chi-square distribution.
841 function CDF.CHISQ (x >= 0, df > 0) = gsl_cdf_chisq_P (x, df);
842 function IDF.CHISQ (P >= 0 && P < 1, df > 0) = gsl_cdf_chisq_Pinv (P, df);
843 function PDF.CHISQ (x >= 0, df > 0) = gsl_ran_chisq_pdf (x, df);
844 no_opt function RV.CHISQ (df > 0) = gsl_ran_chisq (get_rng (), df);
845 function NCDF.CHISQ (x >= 0, df > 0, c) = unimplemented;
846 function NPDF.CHISQ (x >= 0, df > 0, c) = unimplemented;
847 function SIG.CHISQ (x >= 0, df > 0) = gsl_cdf_chisq_Q (x, df);
848
849 // Exponential distribution.
850 function CDF.EXP (x >= 0, a > 0) = gsl_cdf_exponential_P (x, 1. / a);
851 function IDF.EXP (P >= 0 && P < 1, a > 0)
852      = gsl_cdf_exponential_Pinv (P, 1. / a);
853 function PDF.EXP (x >= 0, a > 0) = gsl_ran_exponential_pdf (x, 1. / a);
854 no_opt function RV.EXP (a > 0) = gsl_ran_exponential (get_rng (), 1. / a);
855
856 // Exponential power distribution.
857 extension function PDF.XPOWER (x, a > 0, b >= 0)
858      = gsl_ran_exppow_pdf (x, a, b);
859 no_opt extension function RV.XPOWER (a > 0, b >= 0)
860      = gsl_ran_exppow (get_rng (), a, b);
861
862 // F distribution.
863 function CDF.F (x >= 0, df1 > 0, df2 > 0) = gsl_cdf_fdist_P (x, df1, df2);
864 function IDF.F (P >= 0 && P < 1, df1 > 0, df2 > 0) = idf_fdist (P, df1, df2);
865 function PDF.F (x >= 0, df1 > 0, df2 > 0) = gsl_ran_fdist_pdf (x, df1, df2);
866 no_opt function RV.F (df1 > 0, df2 > 0) = gsl_ran_fdist (get_rng (), df1, df2);
867 function NCDF.F (x >= 0, df1 > 0, df2 > 0, lambda >= 0) = unimplemented;
868 function NPDF.F (x >= 0, df1 > 0, df2 > 0, lmabda >= 0) = unimplemented;
869 function SIG.F (x >= 0, df1 > 0, df2 > 0) = gsl_cdf_fdist_Q (x, df1, df2);
870
871 // Gamma distribution.
872 function CDF.GAMMA (x >= 0, a > 0, b > 0) = gsl_cdf_gamma_P (x, a, 1. / b);
873 function IDF.GAMMA (P >= 0 && P <= 1, a > 0, b > 0)
874      = gsl_cdf_gamma_Pinv (P, a, 1. / b);
875 function PDF.GAMMA (x >= 0, a > 0, b > 0) = gsl_ran_gamma_pdf (x, a, 1. / b);
876 no_opt function RV.GAMMA (a > 0, b > 0)
877      = gsl_ran_gamma (get_rng (), a, 1. / b);
878
879 // Half-normal distribution.
880 function CDF.HALFNRM (x, a, b > 0) = unimplemented;
881 function IDF.HALFNRM (P > 0 && P < 1, a, b > 0) = unimplemented;
882 function PDF.HALFNRM (x, a, b > 0) = unimplemented;
883 no_opt function RV.HALFNRM (a, b > 0) = unimplemented;
884
885 // Inverse Gaussian distribution.
886 function CDF.IGAUSS (x > 0, a > 0, b > 0) = unimplemented;
887 function IDF.IGAUSS (P >= 0 && P < 1, a > 0, b > 0) = unimplemented;
888 function PDF.IGAUSS (x > 0, a > 0, b > 0) = unimplemented;
889 no_opt function RV.IGAUSS (a > 0, b > 0) = unimplemented;
890
891 // Landau distribution.
892 extension function PDF.LANDAU (x) = gsl_ran_landau_pdf (x);
893 no_opt extension function RV.LANDAU () = gsl_ran_landau (get_rng ());
894
895 // Laplace distribution.
896 function CDF.LAPLACE (x, a, b > 0) = gsl_cdf_laplace_P ((x - a) / b, 1);
897 function IDF.LAPLACE (P > 0 && P < 1, a, b > 0)
898      = a + b * gsl_cdf_laplace_Pinv (P, 1);
899 function PDF.LAPLACE (x, a, b > 0) = gsl_ran_laplace_pdf ((x - a) / b, 1) / b;
900 no_opt function RV.LAPLACE (a, b > 0)
901      = a + b * gsl_ran_laplace (get_rng (), 1);
902
903 // Levy alpha-stable distribution.
904 no_opt extension function RV.LEVY (c, alpha > 0 && alpha <= 2)
905      = gsl_ran_levy (get_rng (), c, alpha);
906
907 // Levy skew alpha-stable distribution.
908 no_opt extension function RV.LVSKEW (c, alpha > 0 && alpha <= 2,
909                                      beta >= -1 && beta <= 1)
910      = gsl_ran_levy_skew (get_rng (), c, alpha, beta);
911
912 // Logistic distribution.
913 function CDF.LOGISTIC (x, a, b > 0) = gsl_cdf_logistic_P ((x - a) / b, 1);
914 function IDF.LOGISTIC (P > 0 && P < 1, a, b > 0)
915      = a + b * gsl_cdf_logistic_Pinv (P, 1);
916 function PDF.LOGISTIC (x, a, b > 0)
917      = gsl_ran_logistic_pdf ((x - a) / b, 1) / b;
918 no_opt function RV.LOGISTIC (a, b > 0)
919      = a + b * gsl_ran_logistic (get_rng (), 1);
920
921 // Lognormal distribution.
922 function CDF.LNORMAL (x >= 0, m > 0, s > 0)
923      = gsl_cdf_lognormal_P (x, log (m), s);
924 function IDF.LNORMAL (P >= 0 && P < 1, m > 0, s > 0)
925      = gsl_cdf_lognormal_Pinv (P, log (m), s);
926 function PDF.LNORMAL (x >= 0, m > 0, s > 0)
927      = gsl_ran_lognormal_pdf (x, log (m), s);
928 no_opt function RV.LNORMAL (m > 0, s > 0)
929      = gsl_ran_lognormal (get_rng (), log (m), s);
930
931 // Normal distribution.
932 function CDF.NORMAL (x, u, s > 0) = gsl_cdf_gaussian_P (x - u, s);
933 function IDF.NORMAL (P > 0 && P < 1, u, s > 0)
934      = u + gsl_cdf_gaussian_Pinv (P, s);
935 function PDF.NORMAL (x, u, s > 0) = gsl_ran_gaussian_pdf ((x - u) / s, 1) / s;
936 no_opt function RV.NORMAL (u, s > 0) = u + gsl_ran_gaussian (get_rng (), s);
937 function CDFNORM (x) = gsl_cdf_ugaussian_P (x);
938 function PROBIT (P > 0 && P < 1) = gsl_cdf_ugaussian_Pinv (P);
939 no_opt function NORMAL (s > 0) = gsl_ran_gaussian (get_rng (), s);
940
941 // Normal tail distribution.
942 function PDF.NTAIL (x, a > 0, sigma > 0)
943      = gsl_ran_gaussian_tail_pdf (x, a, sigma);
944 no_opt function RV.NTAIL (a > 0, sigma > 0)
945      = gsl_ran_gaussian_tail (get_rng (), a, sigma);
946
947 // Pareto distribution.
948 function CDF.PARETO (x >= a, a > 0, b > 0) = gsl_cdf_pareto_P (x, b, a);
949 function IDF.PARETO (P >= 0 && P < 1, a > 0, b > 0)
950      = gsl_cdf_pareto_Pinv (P, b, a);
951 function PDF.PARETO (x >= a, a > 0, b > 0) = gsl_ran_pareto_pdf (x, b, a);
952 no_opt function RV.PARETO (a > 0, b > 0) = gsl_ran_pareto (get_rng (), b, a);
953
954 // Rayleigh distribution.
955 extension function CDF.RAYLEIGH (x, sigma > 0) = gsl_cdf_rayleigh_P (x, sigma);
956 extension function IDF.RAYLEIGH (P >= 0 && P <= 1, sigma > 0)
957      = gsl_cdf_rayleigh_Pinv (P, sigma);
958 extension function PDF.RAYLEIGH (x, sigma > 0)
959      = gsl_ran_rayleigh_pdf (x, sigma);
960 no_opt extension function RV.RAYLEIGH (sigma > 0)
961      = gsl_ran_rayleigh (get_rng (), sigma);
962
963 // Rayleigh tail distribution.
964 extension function PDF.RTAIL (x, a, sigma)
965      = gsl_ran_rayleigh_tail_pdf (x, a, sigma);
966 no_opt extension function RV.RTAIL (a, sigma)
967      = gsl_ran_rayleigh_tail (get_rng (), a, sigma);
968
969 // Studentized maximum modulus distribution.
970 function CDF.SMOD (x > 0, a >= 1, b >= 1) = unimplemented;
971 function IDF.SMOD (P >= 0 && P < 1, a >= 1, b >= 1) = unimplemented;
972
973 // Studentized range distribution.
974 function CDF.SRANGE (x > 0, a >= 1, b >= 1) = unimplemented;
975 function IDF.SRANGE (P >= 0 && P < 1, a >= 1, b >= 1) = unimplemented;
976
977 // Student t distribution.
978 function CDF.T (x, df > 0) = gsl_cdf_tdist_P (x, df);
979 function IDF.T (P > 0 && P < 1, df > 0) = gsl_cdf_tdist_Pinv (P, df);
980 function PDF.T (x, df > 0) = gsl_ran_tdist_pdf (x, df);
981 no_opt function RV.T (df > 0) = gsl_ran_tdist (get_rng (), df);
982 function NCDF.T (x, df > 0, nc) = unimplemented;
983 function NPDF.T (x, df > 0, nc) = unimplemented;
984
985 // Type-1 Gumbel distribution.
986 extension function CDF.T1G (x, a, b) = gsl_cdf_gumbel1_P (x, a, b);
987 extension function IDF.T1G (P >= 0 && P <= 1, a, b)
988      = gsl_cdf_gumbel1_Pinv (P, a, b);
989 extension function PDF.T1G (x, a, b) = gsl_ran_gumbel1_pdf (x, a, b);
990 no_opt extension function RV.T1G (a, b) = gsl_ran_gumbel1 (get_rng (), a, b);
991
992 // Type-2 Gumbel distribution.
993 extension function CDF.T2G (x, a, b) = gsl_cdf_gumbel2_P (x, a, b);
994 extension function IDF.T2G (P >= 0 && P <= 1, a, b)
995      = gsl_cdf_gumbel2_Pinv (P, a, b);
996 extension function PDF.T2G (x, a, b) = gsl_ran_gumbel2_pdf (x, a, b);
997 no_opt extension function RV.T2G (a, b) = gsl_ran_gumbel2 (get_rng (), a, b);
998
999 // Uniform distribution.
1000 function CDF.UNIFORM (x <= b, a <= x, b) = gsl_cdf_flat_P (x, a, b);
1001 function IDF.UNIFORM (P >= 0 && P <= 1, a <= b, b)
1002      = gsl_cdf_flat_Pinv (P, a, b);
1003 function PDF.UNIFORM (x <= b, a <= x, b) = gsl_ran_flat_pdf (x, a, b);
1004 no_opt function RV.UNIFORM (a <= b, b) = gsl_ran_flat (get_rng (), a, b);
1005 no_opt function UNIFORM (b >= 0) = gsl_ran_flat (get_rng (), 0, b);
1006
1007 // Weibull distribution.
1008 function CDF.WEIBULL (x >= 0, a > 0, b > 0) = gsl_cdf_weibull_P (x, a, b);
1009 function IDF.WEIBULL (P >= 0 && P < 1, a > 0, b > 0)
1010      = gsl_cdf_weibull_Pinv (P, a, b);
1011 function PDF.WEIBULL (x >= 0, a > 0, b > 0) = gsl_ran_weibull_pdf (x, a, b);
1012 no_opt function RV.WEIBULL (a > 0, b > 0) = gsl_ran_weibull (get_rng (), a, b);
1013
1014 // Bernoulli distribution.
1015 function CDF.BERNOULLI (k == 0 || k == 1, p >= 0 && p <= 1)
1016      = k ? 1 : 1 - p;
1017 function PDF.BERNOULLI (k == 0 || k == 1, p >= 0 && p <= 1)
1018      = gsl_ran_bernoulli_pdf (k, p);
1019 no_opt function RV.BERNOULLI (p >= 0 && p <= 1)
1020      = gsl_ran_bernoulli (get_rng (), p);
1021
1022 // Binomial distribution.
1023 function CDF.BINOM (k, n > 0 && n == floor (n), p >= 0 && p <= 1)
1024      = gsl_cdf_binomial_P (k, p, n);
1025 function PDF.BINOM (k >= 0 && k == floor (k) && k <= n,
1026                     n > 0 && n == floor (n),
1027                     p >= 0 && p <= 1)
1028      = gsl_ran_binomial_pdf (k, p, n);
1029 no_opt function RV.BINOM (p > 0 && p == floor (p), n >= 0 && n <= 1)
1030      = gsl_ran_binomial (get_rng (), p, n);
1031
1032 // Geometric distribution.
1033 function CDF.GEOM (k >= 1 && k == floor (k), p >= 0 && p <= 1)
1034      = gsl_cdf_geometric_P (k, p);
1035 function PDF.GEOM (k >= 1 && k == floor (k),
1036                    p >= 0 && p <= 1)
1037      = gsl_ran_geometric_pdf (k, p);
1038 no_opt function RV.GEOM (p >= 0 && p <= 1) = gsl_ran_geometric (get_rng (), p);
1039
1040 // Hypergeometric distribution.
1041 function CDF.HYPER (k >= 0 && k == floor (k) && k <= c,
1042                     a > 0 && a == floor (a),
1043                     b > 0 && b == floor (b) && b <= a,
1044                     c > 0 && c == floor (c) && c <= a)
1045      = gsl_cdf_hypergeometric_P (k, c, a - c, b);
1046 function PDF.HYPER (k >= 0 && k == floor (k) && k <= c,
1047                     a > 0 && a == floor (a),
1048                     b > 0 && b == floor (b) && b <= a,
1049                     c > 0 && c == floor (c) && c <= a)
1050      = gsl_ran_hypergeometric_pdf (k, c, a - c, b);
1051 no_opt function RV.HYPER (a > 0 && a == floor (a),
1052                           b > 0 && b == floor (b) && b <= a,
1053                           c > 0 && c == floor (c) && c <= a)
1054      = gsl_ran_hypergeometric (get_rng (), c, a - c, b);
1055
1056 // Logarithmic distribution.
1057 extension function PDF.LOG (k >= 1, p > 0 && p <= 1)
1058      = gsl_ran_logarithmic_pdf (k, p);
1059 no_opt extension function RV.LOG (p > 0 && p <= 1)
1060      = gsl_ran_logarithmic (get_rng (), p);
1061
1062 // Negative binomial distribution.
1063 function CDF.NEGBIN (k >= 1, n == floor (n), p > 0 && p <= 1)
1064      = gsl_cdf_negative_binomial_P (k, p, n);
1065 function PDF.NEGBIN (k >= 1, n == floor (n), p > 0 && p <= 1)
1066      = gsl_ran_negative_binomial_pdf (k, p, n);
1067 no_opt function RV.NEGBIN (n == floor (n), p > 0 && p <= 1)
1068      = gsl_ran_negative_binomial (get_rng (), p, n);
1069
1070 // Poisson distribution.
1071 function CDF.POISSON (k >= 0 && k == floor (k), mu > 0)
1072      = gsl_cdf_poisson_P (k, mu);
1073 function PDF.POISSON (k >= 0 && k == floor (k), mu > 0)
1074      = gsl_ran_poisson_pdf (k, mu);
1075 no_opt function RV.POISSON (mu > 0) = gsl_ran_poisson (get_rng (), mu);
1076
1077 // Weirdness.
1078 absorb_miss boolean function MISSING (x) = x == SYSMIS || !isfinite (x);
1079 absorb_miss boolean function SYSMIS (x) = x == SYSMIS || !isfinite (x);
1080 no_opt boolean function SYSMIS (num_var v)
1081      case c;
1082 {
1083   return case_num (c, v) == SYSMIS;
1084 }
1085 no_opt boolean function VALUE (num_var v)
1086      case c;
1087 {
1088   return case_num (c, v);
1089 }
1090
1091 no_opt operator VEC_ELEM_NUM (idx)
1092      vector v;
1093      case c;
1094      expression e;
1095      expr_node n;
1096 {
1097   if (idx >= 1 && idx <= vector_get_n_vars (v))
1098     {
1099       const struct variable *var = vector_get_var (v, (size_t) idx - 1);
1100       double value = case_num (c, var);
1101       return !var_is_num_missing (var, value, MV_USER) ? value : SYSMIS;
1102     }
1103   else
1104     {
1105       if (idx == SYSMIS)
1106         msg_at (SE, expr_location (e, n->args[0]),
1107                 _("SYSMIS is not a valid index value for %zu-element vector "
1108                    "%s.  The result will be set to SYSMIS."),
1109                 vector_get_n_vars (v), vector_get_name (v));
1110       else
1111         msg_at (SE, expr_location (e, n->args[0]),
1112                 _("%g is not a valid index value for %zu-element vector %s.  "
1113                   "The result will be set to SYSMIS."),
1114                 idx, vector_get_n_vars (v), vector_get_name (v));
1115       return SYSMIS;
1116     }
1117 }
1118
1119 absorb_miss no_opt string operator VEC_ELEM_STR (idx)
1120      expression e;
1121      vector v;
1122      case c;
1123      expr_node n;
1124 {
1125   if (idx >= 1 && idx <= vector_get_n_vars (v))
1126     {
1127       struct variable *var = vector_get_var (v, (size_t) idx - 1);
1128       return copy_string (e, CHAR_CAST_BUG (char *, case_str (c, var)),
1129                           var_get_width (var));
1130     }
1131   else
1132     {
1133       if (idx == SYSMIS)
1134         msg_at (SE, expr_location (e, n->args[0]),
1135                 _("SYSMIS is not a valid index value for %zu-element vector "
1136                    "%s.  The result will be set to the empty string."),
1137                 vector_get_n_vars (v), vector_get_name (v));
1138       else
1139         msg_at (SE, expr_location (e, n->args[0]),
1140                 _("%g is not a valid index value for %zu-element vector %s.  "
1141                   "The result will be set to the empty string."),
1142                 idx, vector_get_n_vars (v), vector_get_name (v));
1143       return empty_string;
1144     }
1145 }
1146
1147 // Terminals.
1148
1149 no_opt operator NUM_VAR ()
1150      case c;
1151      num_var v;
1152 {
1153   double d = case_num (c, v);
1154   return !var_is_num_missing (v, d, MV_USER) ? d : SYSMIS;
1155 }
1156
1157 no_opt string operator STR_VAR ()
1158      case c;
1159      expression e;
1160      str_var v;
1161 {
1162   struct substring s = alloc_string (e, var_get_width (v));
1163   memcpy (s.string, case_str (c, v), var_get_width (v));
1164   return s;
1165 }
1166
1167 no_opt perm_only function LAG (num_var v, pos_int n_before)
1168     dataset ds;
1169 {
1170   const struct ccase *c = lagged_case (ds, n_before);
1171   if (c != NULL)
1172     {
1173       double x = case_num (c, v);
1174       return !var_is_num_missing (v, x, MV_USER) ? x : SYSMIS;
1175     }
1176   else
1177     return SYSMIS;
1178 }
1179
1180 no_opt perm_only function LAG (num_var v)
1181     dataset ds;
1182 {
1183   const struct ccase *c = lagged_case (ds, 1);
1184   if (c != NULL)
1185     {
1186       double x = case_num (c, v);
1187       return !var_is_num_missing (v, x, MV_USER) ? x : SYSMIS;
1188     }
1189   else
1190     return SYSMIS;
1191 }
1192
1193 no_opt perm_only string function LAG (str_var v, pos_int n_before)
1194      expression e;
1195      dataset ds;
1196 {
1197   const struct ccase *c = lagged_case (ds, n_before);
1198   if (c != NULL)
1199     return copy_string (e, CHAR_CAST_BUG (char *, case_str (c, v)),
1200                         var_get_width (v));
1201   else
1202     return empty_string;
1203 }
1204
1205 no_opt perm_only string function LAG (str_var v)
1206      expression e;
1207      dataset ds;
1208 {
1209   const struct ccase *c = lagged_case (ds, 1);
1210   if (c != NULL)
1211     return copy_string (e, CHAR_CAST_BUG (char *, case_str (c, v)),
1212                         var_get_width (v));
1213   else
1214     return empty_string;
1215 }
1216
1217 no_opt operator NUM_SYS ()
1218      case c;
1219      num_var v;
1220 {
1221   return case_num (c, v) == SYSMIS;
1222 }
1223
1224 no_opt operator NUM_VAL ()
1225      case c;
1226      num_var v;
1227 {
1228   return case_num (c, v);
1229 }
1230
1231 no_opt operator CASENUM ()
1232      case_idx idx;
1233 {
1234   return idx;
1235 }