88c326c8d0c4576f216159b5f0671a43054f80c9
[pspp] / src / language / stats / ctables.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2021 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <math.h>
20
21 #include "data/casereader.h"
22 #include "data/dataset.h"
23 #include "data/dictionary.h"
24 #include "data/mrset.h"
25 #include "language/command.h"
26 #include "language/lexer/format-parser.h"
27 #include "language/lexer/lexer.h"
28 #include "language/lexer/variable-parser.h"
29 #include "libpspp/array.h"
30 #include "libpspp/assertion.h"
31 #include "libpspp/hash-functions.h"
32 #include "libpspp/hmap.h"
33 #include "libpspp/message.h"
34 #include "libpspp/string-array.h"
35 #include "math/moments.h"
36 #include "output/pivot-table.h"
37
38 #include "gl/minmax.h"
39 #include "gl/xalloc.h"
40
41 #include "gettext.h"
42 #define _(msgid) gettext (msgid)
43 #define N_(msgid) (msgid)
44
45 enum ctables_vlabel
46   {
47     CTVL_NONE = SETTINGS_VALUE_SHOW_DEFAULT,
48     CTVL_NAME = SETTINGS_VALUE_SHOW_VALUE,
49     CTVL_LABEL = SETTINGS_VALUE_SHOW_LABEL,
50     CTVL_BOTH = SETTINGS_VALUE_SHOW_BOTH,
51   };
52
53 /* XXX:
54    - unweighted summaries (U*)
55    - lower confidence limits (*.LCL)
56    - upper confidence limits (*.UCL)
57    - standard error (*.SE)
58  */
59 #define SUMMARIES                                                       \
60     /* All variables. */                                                \
61     S(CTSF_COUNT, "COUNT", N_("Count"), CTF_COUNT, CTFA_ALL)            \
62     S(CTSF_ECOUNT, "ECOUNT", N_("Adjusted Count"), CTF_COUNT, CTFA_ALL) \
63     S(CTSF_ROWPCT_COUNT, "ROWPCT.COUNT", N_("Row %"), CTF_PERCENT, CTFA_ALL) \
64     S(CTSF_COLPCT_COUNT, "COLPCT.COUNT", N_("Column %"), CTF_PERCENT, CTFA_ALL) \
65     S(CTSF_TABLEPCT_COUNT, "TABLEPCT.COUNT", N_("Table %"), CTF_PERCENT, CTFA_ALL) \
66     S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT.COUNT", N_("Subtable %"), CTF_PERCENT, CTFA_ALL) \
67     S(CTSF_LAYERPCT_COUNT, "LAYERPCT.COUNT", N_("Layer %"), CTF_PERCENT, CTFA_ALL) \
68     S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT.COUNT", N_("Layer Row %"), CTF_PERCENT, CTFA_ALL) \
69     S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT.COUNT", N_("Layer Column %"), CTF_PERCENT, CTFA_ALL) \
70     S(CTSF_ROWPCT_VALIDN, "ROWPCT.VALIDN", N_("Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
71     S(CTSF_COLPCT_VALIDN, "COLPCT.VALIDN", N_("Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
72     S(CTSF_TABLEPCT_VALIDN, "TABLEPCT.VALIDN", N_("Table Valid N %"), CTF_PERCENT, CTFA_ALL) \
73     S(CTSF_SUBTABLEPCT_VALIDN, "SUBTABLEPCT.VALIDN", N_("Subtable Valid N %"), CTF_PERCENT, CTFA_ALL) \
74     S(CTSF_LAYERPCT_VALIDN, "LAYERPCT.VALIDN", N_("Layer Valid N %"), CTF_PERCENT, CTFA_ALL) \
75     S(CTSF_LAYERROWPCT_VALIDN, "LAYERROWPCT.VALIDN", N_("Layer Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
76     S(CTSF_LAYERCOLPCT_VALIDN, "LAYERCOLPCT.VALIDN", N_("Layer Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
77     S(CTSF_ROWPCT_TOTALN, "ROWPCT.TOTALN", N_("Row Total N %"), CTF_PERCENT, CTFA_ALL) \
78     S(CTSF_COLPCT_TOTALN, "COLPCT.TOTALN", N_("Column Total N %"), CTF_PERCENT, CTFA_ALL) \
79     S(CTSF_TABLEPCT_TOTALN, "TABLEPCT.TOTALN", N_("Table Total N %"), CTF_PERCENT, CTFA_ALL) \
80     S(CTSF_SUBTABLEPCT_TOTALN, "SUBTABLEPCT.TOTALN", N_("Subtable Total N %"), CTF_PERCENT, CTFA_ALL) \
81     S(CTSF_LAYERPCT_TOTALN, "LAYERPCT.TOTALN", N_("Layer Total N %"), CTF_PERCENT, CTFA_ALL) \
82     S(CTSF_LAYERROWPCT_TOTALN, "LAYERROWPCT.TOTALN", N_("Layer Row Total N %"), CTF_PERCENT, CTFA_ALL) \
83     S(CTSF_LAYERCOLPCT_TOTALN, "LAYERCOLPCT.TOTALN", N_("Layer Column Total N %"), CTF_PERCENT, CTFA_ALL) \
84                                                                         \
85     /* Scale variables, totals, and subtotals. */                       \
86     S(CTSF_MAXIMUM, "MAXIMUM", N_("Maximum"), CTF_GENERAL, CTFA_SCALE)  \
87     S(CTSF_MEAN, "MEAN", N_("Mean"), CTF_GENERAL, CTFA_SCALE)           \
88     S(CTSF_MEDIAN, "MEDIAN", N_("Median"), CTF_GENERAL, CTFA_SCALE)     \
89     S(CTSF_MINIMUM, "MINIMUM", N_("Minimum"), CTF_GENERAL, CTFA_SCALE)  \
90     S(CTSF_MISSING, "MISSING", N_("Missing"), CTF_GENERAL, CTFA_SCALE)  \
91     S(CTSF_MODE, "MODE", N_("Mode"), CTF_GENERAL, CTFA_SCALE)           \
92     S(CTSF_PTILE, "PTILE", N_("Percentile"), CTF_GENERAL, CTFA_SCALE)   \
93     S(CTSF_RANGE, "RANGE", N_("Range"), CTF_GENERAL, CTFA_SCALE)        \
94     S(CTSF_SEMEAN, "SEMEAN", N_("Std Error of Mean"), CTF_GENERAL, CTFA_SCALE) \
95     S(CTSF_STDDEV, "STDDEV", N_("Std Deviation"), CTF_GENERAL, CTFA_SCALE) \
96     S(CTSF_SUM, "SUM", N_("Sum"), CTF_GENERAL, CTFA_SCALE)              \
97     S(CSTF_TOTALN, "TOTALN", N_("Total N"), CTF_COUNT, CTFA_SCALE)      \
98     S(CTSF_ETOTALN, "ETOTALN", N_("Adjusted Total N"), CTF_COUNT, CTFA_SCALE) \
99     S(CTSF_VALIDN, "VALIDN", N_("Valid N"), CTF_COUNT, CTFA_SCALE)      \
100     S(CTSF_EVALIDN, "EVALIDN", N_("Adjusted Valid N"), CTF_COUNT, CTFA_SCALE) \
101     S(CTSF_VARIANCE, "VARIANCE", N_("Variance"), CTF_GENERAL, CTFA_SCALE) \
102     S(CTSF_ROWPCT_SUM, "ROWPCT.SUM", N_("Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
103     S(CTSF_COLPCT_SUM, "COLPCT.SUM", N_("Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
104     S(CTSF_TABLEPCT_SUM, "TABLEPCT.SUM", N_("Table Sum %"), CTF_PERCENT, CTFA_SCALE) \
105     S(CTSF_SUBTABLEPCT_SUM, "SUBTABLEPCT.SUM", N_("Subtable Sum %"), CTF_PERCENT, CTFA_SCALE) \
106     S(CTSF_LAYERPCT_SUM, "LAYERPCT.SUM", N_("Layer Sum %"), CTF_PERCENT, CTFA_SCALE) \
107     S(CTSF_LAYERROWPCT_SUM, "LAYERROWPCT.SUM", N_("Layer Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
108     S(CTSF_LAYERCOLPCT_SUM, "LAYERCOLPCT.SUM", N_("Layer Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
109                                                                         \
110     /* Multiple response sets. */                                       \
111   S(CTSF_RESPONSES, "RESPONSES", N_("Responses"), CTF_COUNT, CTFA_MRSETS) \
112     S(CTSF_ROWPCT_RESPONSES, "ROWPCT.RESPONSES", N_("Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
113     S(CTSF_COLPCT_RESPONSES, "COLPCT.RESPONSES", N_("Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
114     S(CTSF_TABLEPCT_RESPONSES, "TABLEPCT.RESPONSES", N_("Table Responses %"), CTF_PERCENT, CTFA_MRSETS) \
115     S(CTSF_SUBTABLEPCT_RESPONSES, "SUBTABLEPCT.RESPONSES", N_("Subtable Responses %"), CTF_PERCENT, CTFA_MRSETS) \
116     S(CTSF_LAYERPCT_RESPONSES, "LAYERPCT.RESPONSES", N_("Layer Responses %"), CTF_PERCENT, CTFA_MRSETS) \
117     S(CTSF_LAYERROWPCT_RESPONSES, "LAYERROWPCT.RESPONSES", N_("Layer Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
118     S(CTSF_LAYERCOLPCT_RESPONSES, "LAYERCOLPCT.RESPONSES", N_("Layer Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
119     S(CTSF_ROWPCT_RESPONSES_COUNT, "ROWPCT.RESPONSES.COUNT", N_("Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
120     S(CTSF_COLPCT_RESPONSES_COUNT, "COLPCT.RESPONSES.COUNT", N_("Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
121     S(CTSF_TABLEPCT_RESPONSES_COUNT, "TABLEPCT.RESPONSES.COUNT", N_("Table Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
122     S(CTSF_SUBTABLEPCT_RESPONSES_COUNT, "SUBTABLEPCT.RESPONSES.COUNT", N_("Subtable Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
123     S(CTSF_LAYERPCT_RESPONSES_COUNT, "LAYERPCT.RESPONSES.COUNT", N_("Layer Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
124     S(CTSF_LAYERROWPCT_RESPONSES_COUNT, "LAYERROWPCT.RESPONSES.COUNT", N_("Layer Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
125     S(CTSF_LAYERCOLPCT_RESPONSES_COUNT, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
126     S(CTSF_ROWPCT_COUNT_RESPONSES, "ROWPCT.COUNT.RESPONSES", N_("Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
127     S(CTSF_COLPCT_COUNT_RESPONSES, "COLPCT.COUNT.RESPONSES", N_("Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
128     S(CTSF_TABLEPCT_COUNT_RESPONSES, "TABLEPCT.COUNT.RESPONSES", N_("Table Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
129     S(CTSF_SUBTABLEPCT_COUNT_RESPONSES, "SUBTABLEPCT.COUNT.RESPONSES", N_("Subtable Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
130     S(CTSF_LAYERPCT_COUNT_RESPONSES, "LAYERPCT.COUNT.RESPONSES", N_("Layer Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
131     S(CTSF_LAYERROWPCT_COUNT_RESPONSES, "LAYERROWPCT.COUNT.RESPONSES", N_("Layer Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
132     S(CTSF_LAYERCOLPCT_COUNT_RESPONSES, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS)
133
134 enum ctables_summary_function
135   {
136 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) ENUM,
137     SUMMARIES
138 #undef S
139   };
140
141 enum {
142 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) +1
143   N_CTSF_FUNCTIONS = SUMMARIES
144 #undef S
145 };
146
147 enum ctables_domain_type
148   {
149     CTDT_TABLE,                  /* Entire table. */
150     CTDT_SUBTABLE,               /* Innermost variable in a single layer. */
151     CTDT_ROW,                    /* Row within a subtable. */
152     CTDT_COL,                    /* Column within a subtable. */
153     CTDT_LAYER,                  /* Entire layer. */
154     CTDT_LAYERROW,               /* Row within a layer. */
155     CTDT_LAYERCOL,               /* Column within a layer. */
156 #define N_CTDTS 7
157   };
158
159 struct ctables_domain
160   {
161     struct hmap_node node;
162
163     const struct ctables_freq *example;
164
165     double valid;
166     double missing;
167   };
168
169 struct ctables_freq
170   {
171     /* In struct ctables's 'ft' hmap.  Indexed by all the values in all the
172        axes (except the scalar variable, if any). */
173     struct hmap_node node;
174
175     /* The domains that contains this cell. */
176     struct ctables_domain *domains[N_CTDTS];
177
178     struct
179       {
180         size_t vaa_idx;
181         union value *values;
182         int leaf;
183       }
184     axes[PIVOT_N_AXES];
185
186     union ctables_summary *summaries;
187   };
188
189 struct ctables
190   {
191     struct pivot_table_look *look;
192
193     /* If this is NULL, zeros are displayed using the normal print format.
194        Otherwise, this string is displayed. */
195     char *zero;
196
197     /* If this is NULL, missing values are displayed using the normal print
198        format.  Otherwise, this string is displayed. */
199     char *missing;
200
201     /* Indexed by variable dictionary index. */
202     enum ctables_vlabel *vlabels;
203
204     bool mrsets_count_duplicates; /* MRSETS. */
205     bool smissing_listwise;       /* SMISSING. */
206     struct variable *base_weight; /* WEIGHT. */
207     int hide_threshold;           /* HIDESMALLCOUNTS. */
208
209     struct ctables_table **tables;
210     size_t n_tables;
211   };
212
213 struct ctables_postcompute
214   {
215     struct hmap_node hmap_node; /* In struct ctables's 'pcompute' hmap. */
216     const char *name;           /* Name, without leading &. */
217
218     struct ctables_postcompute_expr *expr;
219     char *label;
220     /* XXX FORMAT */
221     bool hide_source_cats;
222   };
223
224 struct ctables_postcompute_expr
225   {
226     enum ctables_postcompute_op
227       {
228         /* Terminals. */
229         CTPO_CAT_NUMBER,
230         CTPO_CAT_STRING,
231         CTPO_CAT_RANGE,
232         CTPO_CAT_MISSING,
233         /* XXX OTHERNM */
234         /* XXX SUBTOTAL and HSUBTOTAL */
235
236         /* Nonterminals. */
237         CTPO_ADD,
238         CTPO_SUB,
239         CTPO_MUL,
240         CTPO_DIV,
241         CTPO_POW,
242       }
243     op;
244
245     union
246       {
247         /* CTPO_CAT_NUMBER, CTPO_NUMBER. */
248         double number;
249
250         /* CTPO_CAT_RANGE.
251
252            XXX what about string ranges? */
253         double range[2];
254
255         /* CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW. */
256         struct ctables_postcompute_expr *subs[2];
257       };
258   };
259
260 enum ctables_label_position
261   {
262     CTLP_NORMAL,
263     CTLP_OPPOSITE,
264     CTLP_LAYER,
265   };
266
267 struct var_array
268   {
269     struct variable **vars;
270     size_t n;
271     size_t scale_idx;
272     size_t *domains[N_CTDTS];
273     size_t n_domains[N_CTDTS];
274
275     struct ctables_summary_spec *summaries;
276     size_t n_summaries;
277     struct variable *summary_var;
278   };
279
280 struct var_array2
281   {
282     struct var_array *vas;
283     size_t n;
284   };
285
286 struct ctables_table
287   {
288     struct ctables_axis *axes[PIVOT_N_AXES];
289     struct var_array2 vaas[PIVOT_N_AXES];
290     enum pivot_axis_type summary_axis;
291     struct hmap ft;
292     struct hmap domains[N_CTDTS];
293
294     enum pivot_axis_type slabels_position;
295     bool slabels_visible;
296
297     enum ctables_label_position row_labels;
298     enum ctables_label_position col_labels;
299
300     /* Indexed by variable dictionary index. */
301     struct ctables_categories **categories;
302     size_t n_categories;
303
304     double cilevel;
305
306     char *caption;
307     char *corner;
308     char *title;
309
310     struct ctables_chisq *chisq;
311     struct ctables_pairwise *pairwise;
312
313   };
314
315 struct ctables_var
316   {
317     bool is_mrset;
318     union
319       {
320         struct variable *var;
321         const struct mrset *mrset;
322       };
323   };
324
325 static const struct fmt_spec *
326 ctables_var_get_print_format (const struct ctables_var *var)
327 {
328   return (var->is_mrset
329           ? var_get_print_format (var->mrset->vars[0])
330           : var_get_print_format (var->var));
331 }
332
333 static const char *
334 ctables_var_name (const struct ctables_var *var)
335 {
336   return var->is_mrset ? var->mrset->name : var_get_name (var->var);
337 }
338
339 struct ctables_categories
340   {
341     size_t n_refs;
342
343     /* Explicit categories. */
344     struct ctables_cat_value *values;
345     size_t n_values;
346
347     /* Implicit categories. */
348     bool sort_ascending;
349     bool include_missing;
350     enum { CTCS_VALUE, CTCS_LABEL, CTCS_FUNCTION } key;
351     enum ctables_summary_function sort_func;
352     struct variable *sort_func_var;
353     double percentile;
354
355     /* Totals. */
356     bool show_totals;
357     bool totals_before;
358     char *total_label;
359
360     /* Empty categories. */
361     bool show_empty;
362   };
363
364 struct ctables_cat_value
365   {
366     enum ctables_cat_value_type
367       {
368         CCVT_NUMBER,
369         CCVT_STRING,
370         CCVT_RANGE,
371         CCVT_MISSING,
372         CCVT_OTHERNM,
373         CCVT_SUBTOTAL,
374         CCVT_HSUBTOTAL,
375       }
376     type;
377
378     union
379       {
380         double number;          /* CCVT_NUMBER. */
381         char *string;           /* CCVT_STRING. */
382         double range[2];        /* CCVT_RANGE. */
383         char *subtotal_label;   /* CCVT_SUBTOTAL, CCVT_HSUBTOTAL. */
384       };
385   };
386
387 static void
388 ctables_cat_value_uninit (struct ctables_cat_value *cv)
389 {
390   if (!cv)
391     return;
392
393   switch (cv->type)
394     {
395     case CCVT_NUMBER:
396     case CCVT_RANGE:
397     case CCVT_MISSING:
398     case CCVT_OTHERNM:
399       break;
400
401     case CCVT_STRING:
402       free (cv->string);
403       break;
404
405     case CCVT_SUBTOTAL:
406     case CCVT_HSUBTOTAL:
407       free (cv->subtotal_label);
408     }
409 }
410
411 static void
412 ctables_categories_unref (struct ctables_categories *c)
413 {
414   if (!c)
415     return;
416
417   assert (c->n_refs > 0);
418   if (--c->n_refs)
419     return;
420
421   for (size_t i = 0; i < c->n_values; i++)
422     ctables_cat_value_uninit (&c->values[i]);
423   free (c->values);
424   free (c->total_label);
425   free (c);
426 }
427
428 /* Chi-square test (SIGTEST). */
429 struct ctables_chisq
430   {
431     double alpha;
432     bool include_mrsets;
433     bool all_visible;
434   };
435
436 /* Pairwise comparison test (COMPARETEST). */
437 struct ctables_pairwise
438   {
439     enum { PROP, MEAN } type;
440     double alpha[2];
441     bool include_mrsets;
442     bool meansvariance_allcats;
443     bool all_visible;
444     enum { BONFERRONI = 1, BH } adjust;
445     bool merge;
446     bool apa_style;
447     bool show_sig;
448   };
449
450 struct ctables_axis
451   {
452     enum ctables_axis_op
453       {
454         /* Terminals. */
455         CTAO_VAR,
456
457         /* Nonterminals. */
458         CTAO_STACK,             /* + */
459         CTAO_NEST,              /* > */
460       }
461     op;
462
463     union
464       {
465         /* Terminals. */
466         struct
467           {
468             struct ctables_var var;
469             bool scale;
470             struct ctables_summary_spec *summaries;
471             size_t n_summaries;
472             size_t allocated_summaries;
473           };
474
475         /* Nonterminals. */
476         struct ctables_axis *subs[2];
477       };
478
479     struct msg_location *loc;
480   };
481
482 static void ctables_axis_destroy (struct ctables_axis *);
483
484 enum ctables_format
485   {
486     CTF_COUNT,
487     CTF_PERCENT,
488     CTF_GENERAL
489   };
490
491 enum ctables_function_availability
492   {
493     CTFA_ALL,                /* Any variables. */
494     CTFA_SCALE,              /* Only scale variables, totals, and subtotals. */
495     CTFA_MRSETS,             /* Only multiple-response sets */
496   };
497
498 struct ctables_summary_spec
499   {
500     enum ctables_summary_function function;
501     double percentile;          /* CTSF_PTILE only. */
502     char *label;
503     struct fmt_spec format;     /* XXX extra CTABLES formats */
504   };
505
506 static void
507 ctables_summary_spec_uninit (struct ctables_summary_spec *s)
508 {
509   if (s)
510     free (s->label);
511 }
512
513 static bool
514 parse_col_width (struct lexer *lexer, const char *name, double *width)
515 {
516   lex_match (lexer, T_EQUALS);
517   if (lex_match_id (lexer, "DEFAULT"))
518     *width = SYSMIS;
519   else if (lex_force_num_range_closed (lexer, name, 0, DBL_MAX))
520     {
521       *width = lex_number (lexer);
522       lex_get (lexer);
523     }
524   else
525     return false;
526
527   return true;
528 }
529
530 static bool
531 parse_bool (struct lexer *lexer, bool *b)
532 {
533   if (lex_match_id (lexer, "NO"))
534     *b = false;
535   else if (lex_match_id (lexer, "YES"))
536     *b = true;
537   else
538     {
539       lex_error_expecting (lexer, "YES", "NO");
540       return false;
541     }
542   return true;
543 }
544
545 static enum ctables_function_availability
546 ctables_function_availability (enum ctables_summary_function f)
547 {
548   static enum ctables_function_availability availability[] = {
549 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
550     SUMMARIES
551 #undef S
552   };
553
554   return availability[f];
555 }
556
557 static bool
558 parse_ctables_summary_function (struct lexer *lexer,
559                                 enum ctables_summary_function *f)
560 {
561   struct pair
562     {
563       enum ctables_summary_function function;
564       struct substring name;
565     };
566   static struct pair names[] = {
567 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
568     { ENUM, SS_LITERAL_INITIALIZER (NAME) },
569     SUMMARIES
570
571     /* The .COUNT suffix may be omitted. */
572     S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
573     S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
574     S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
575     S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
576     S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
577     S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
578     S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
579 #undef S
580   };
581
582   if (!lex_force_id (lexer))
583     return false;
584
585   for (size_t i = 0; i < sizeof names / sizeof *names; i++)
586     if (ss_equals_case (names[i].name, lex_tokss (lexer)))
587       {
588         *f = names[i].function;
589         lex_get (lexer);
590         return true;
591       }
592
593   lex_error (lexer, _("Expecting summary function name."));
594   return false;
595 }
596
597 static void
598 ctables_axis_destroy (struct ctables_axis *axis)
599 {
600   if (!axis)
601     return;
602
603   switch (axis->op)
604     {
605     case CTAO_VAR:
606       for (size_t i = 0; i < axis->n_summaries; i++)
607         ctables_summary_spec_uninit (&axis->summaries[i]);
608       free (axis->summaries);
609       break;
610
611     case CTAO_STACK:
612     case CTAO_NEST:
613       ctables_axis_destroy (axis->subs[0]);
614       ctables_axis_destroy (axis->subs[1]);
615       break;
616     }
617   msg_location_destroy (axis->loc);
618   free (axis);
619 }
620
621 static struct ctables_axis *
622 ctables_axis_new_nonterminal (enum ctables_axis_op op,
623                               struct ctables_axis *sub0,
624                               struct ctables_axis *sub1,
625                               struct lexer *lexer, int start_ofs)
626 {
627   struct ctables_axis *axis = xmalloc (sizeof *axis);
628   *axis = (struct ctables_axis) {
629     .op = op,
630     .subs = { sub0, sub1 },
631     .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
632   };
633   return axis;
634 }
635
636 struct ctables_axis_parse_ctx
637   {
638     struct lexer *lexer;
639     struct dictionary *dict;
640     struct ctables *ct;
641     struct ctables_table *t;
642   };
643
644 static struct fmt_spec
645 ctables_summary_default_format (enum ctables_summary_function function,
646                                 const struct ctables_var *var)
647 {
648   static const enum ctables_format default_formats[] = {
649 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
650     SUMMARIES
651 #undef S
652   };
653   switch (default_formats[function])
654     {
655     case CTF_COUNT:
656       return (struct fmt_spec) { .type = FMT_F, .w = 40 };
657
658     case CTF_PERCENT:
659       return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
660
661     case CTF_GENERAL:
662       return *ctables_var_get_print_format (var);
663
664     default:
665       NOT_REACHED ();
666     }
667 }
668
669 static char *
670 ctables_summary_default_label (enum ctables_summary_function function,
671                                double percentile)
672 {
673   static const char *default_labels[] = {
674 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
675     SUMMARIES
676 #undef S
677   };
678
679   return (function == CTSF_PTILE
680           ? xasprintf (_("Percentile %.2f"), percentile)
681           : xstrdup (gettext (default_labels[function])));
682 }
683
684 static const char *
685 ctables_summary_function_name (enum ctables_summary_function function)
686 {
687   static const char *names[] = {
688 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
689     SUMMARIES
690 #undef S
691   };
692   return names[function];
693 }
694
695 static bool
696 add_summary_spec (struct ctables_axis *axis,
697                   enum ctables_summary_function function, double percentile,
698                   const char *label, const struct fmt_spec *format,
699                   const struct msg_location *loc)
700 {
701   if (axis->op == CTAO_VAR)
702     {
703       if (axis->n_summaries >= axis->allocated_summaries)
704         axis->summaries = x2nrealloc (axis->summaries,
705                                       &axis->allocated_summaries,
706                                       sizeof *axis->summaries);
707
708       const char *function_name = ctables_summary_function_name (function);
709       const char *var_name = ctables_var_name (&axis->var);
710       switch (ctables_function_availability (function))
711         {
712         case CTFA_MRSETS:
713           if (!axis->var.is_mrset)
714             {
715               msg_at (SE, loc, _("Summary function %s applies only to multiple "
716                                  "response sets."), function_name);
717               msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
718                       var_name);
719               return false;
720             }
721           break;
722
723         case CTFA_SCALE:
724           if (!axis->scale)
725             {
726               msg_at (SE, loc,
727                       _("Summary function %s applies only to scale variables."),
728                       function_name);
729               msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
730                       var_name);
731               return false;
732             }
733           break;
734
735         case CTFA_ALL:
736           break;
737         }
738
739       struct ctables_summary_spec *dst = &axis->summaries[axis->n_summaries++];
740       *dst = (struct ctables_summary_spec) {
741         .function = function,
742         .percentile = percentile,
743         .label = xstrdup (label),
744         .format = (format ? *format
745                    : ctables_summary_default_format (function, &axis->var)),
746       };
747       return true;
748     }
749   else
750     {
751       for (size_t i = 0; i < 2; i++)
752         if (!add_summary_spec (axis->subs[i], function, percentile, label,
753                                format, loc))
754           return false;
755       return true;
756     }
757 }
758
759 static struct ctables_axis *ctables_axis_parse_stack (
760   struct ctables_axis_parse_ctx *);
761
762 static bool
763 ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
764                    struct ctables_var *var)
765 {
766   if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
767     {
768       *var = (struct ctables_var) {
769         .is_mrset = true,
770         .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
771       };
772       if (!var->mrset)
773         {
774           lex_error (lexer, _("'%s' does not name a multiple-response set "
775                               "in the active file dictionary."),
776                      lex_tokcstr (lexer));
777           return false;
778         }
779       lex_get (lexer);
780       return true;
781     }
782   else
783     {
784       *var = (struct ctables_var) {
785         .is_mrset = false,
786         .var = parse_variable (lexer, dict),
787       };
788       return var->var != NULL;
789     }
790 }
791
792 static struct ctables_axis *
793 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
794 {
795   if (lex_match (ctx->lexer, T_LPAREN))
796     {
797       struct ctables_axis *sub = ctables_axis_parse_stack (ctx);
798       if (!sub || !lex_force_match (ctx->lexer, T_RPAREN))
799         {
800           ctables_axis_destroy (sub);
801           return NULL;
802         }
803       return sub;
804     }
805
806   if (!lex_force_id (ctx->lexer))
807     return NULL;
808
809   int start_ofs = lex_ofs (ctx->lexer);
810   struct ctables_var var;
811   if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
812     return NULL;
813
814   struct ctables_axis *axis = xmalloc (sizeof *axis);
815   *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
816
817   /* XXX should figure out default measures by reading data */
818   axis->scale = (var.is_mrset ? false
819                  : lex_match_phrase (ctx->lexer, "[S]") ? true
820                  : lex_match_phrase (ctx->lexer, "[C]") ? false
821                  : var_get_measure (var.var) == MEASURE_SCALE);
822   axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
823                                 lex_ofs (ctx->lexer) - 1);
824   return axis;
825 }
826
827 static struct ctables_axis *
828 ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
829 {
830   struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
831   if (!sub || !lex_match (ctx->lexer, T_LBRACK))
832     return sub;
833
834   do
835     {
836       int start_ofs = lex_ofs (ctx->lexer);
837
838       /* Parse function. */
839       enum ctables_summary_function function;
840       if (!parse_ctables_summary_function (ctx->lexer, &function))
841         goto error;
842
843       /* Parse percentile. */
844       double percentile = 0;
845       if (function == CTSF_PTILE)
846         {
847           if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
848             goto error;
849           percentile = lex_number (ctx->lexer);
850           lex_get (ctx->lexer);
851         }
852
853       /* Parse label. */
854       char *label;
855       if (lex_is_string (ctx->lexer))
856         {
857           label = ss_xstrdup (lex_tokss (ctx->lexer));
858           lex_get (ctx->lexer);
859         }
860       else
861         label = ctables_summary_default_label (function, percentile);
862
863       /* Parse format. */
864       struct fmt_spec format;
865       const struct fmt_spec *formatp;
866       if (lex_token (ctx->lexer) == T_ID)
867         {
868           if (!parse_format_specifier (ctx->lexer, &format)
869               || !fmt_check_output (&format)
870               || !fmt_check_type_compat (&format, VAL_NUMERIC))
871             {
872               free (label);
873               goto error;
874             }
875           formatp = &format;
876         }
877       else
878         formatp = NULL;
879
880       struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
881                                                    lex_ofs (ctx->lexer) - 1);
882       add_summary_spec (sub, function, percentile, label, formatp, loc);
883       free (label);
884       msg_location_destroy (loc);
885
886       lex_match (ctx->lexer, T_COMMA);
887     }
888   while (!lex_match (ctx->lexer, T_RBRACK));
889
890   return sub;
891
892 error:
893   ctables_axis_destroy (sub);
894   return NULL;
895 }
896
897 static const struct ctables_axis *
898 find_scale (const struct ctables_axis *axis)
899 {
900   if (!axis)
901     return NULL;
902   else if (axis->op == CTAO_VAR)
903     {
904       if (axis->scale)
905         {
906           assert (!axis->var.is_mrset);
907           return axis;
908         }
909       else
910         return NULL;
911     }
912   else
913     {
914       for (size_t i = 0; i < 2; i++)
915         {
916           const struct ctables_axis *scale = find_scale (axis->subs[i]);
917           if (scale)
918             return scale;
919         }
920       return NULL;
921     }
922 }
923
924 static const struct ctables_axis *
925 find_categorical_summary_spec (const struct ctables_axis *axis)
926 {
927   if (!axis)
928     return NULL;
929   else if (axis->op == CTAO_VAR)
930     return !axis->scale && axis->n_summaries ? axis : NULL;
931   else
932     {
933       for (size_t i = 0; i < 2; i++)
934         {
935           const struct ctables_axis *sum
936             = find_categorical_summary_spec (axis->subs[i]);
937           if (sum)
938             return sum;
939         }
940       return NULL;
941     }
942 }
943
944 static struct ctables_axis *
945 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
946 {
947   int start_ofs = lex_ofs (ctx->lexer);
948   struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
949   if (!lhs)
950     return NULL;
951
952   while (lex_match (ctx->lexer, T_GT))
953     {
954       struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
955       if (!rhs)
956         return NULL;
957
958       struct ctables_axis *nest = ctables_axis_new_nonterminal (
959         CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
960
961       const struct ctables_axis *outer_scale = find_scale (lhs);
962       const struct ctables_axis *inner_scale = find_scale (rhs);
963       if (outer_scale && inner_scale)
964         {
965           msg_at (SE, nest->loc, _("Cannot nest scale variables."));
966           msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
967           msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
968           ctables_axis_destroy (nest);
969           return NULL;
970         }
971
972       const struct ctables_axis *outer_sum = find_categorical_summary_spec (lhs);
973       if (outer_sum)
974         {
975           msg_at (SE, nest->loc,
976                   _("Summaries may only be requested for categorical variables "
977                     "at the innermost nesting level."));
978           msg_at (SN, outer_sum->loc,
979                   _("This outer categorical variable has a summary."));
980           ctables_axis_destroy (nest);
981           return NULL;
982         }
983
984       lhs = nest;
985     }
986
987   return lhs;
988 }
989
990 static struct ctables_axis *
991 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
992 {
993   int start_ofs = lex_ofs (ctx->lexer);
994   struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
995   if (!lhs)
996     return NULL;
997
998   while (lex_match (ctx->lexer, T_PLUS))
999     {
1000       struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
1001       if (!rhs)
1002         return NULL;
1003
1004       lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
1005                                           ctx->lexer, start_ofs);
1006     }
1007
1008   return lhs;
1009 }
1010
1011 static bool
1012 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
1013                     struct ctables *ct, struct ctables_table *t,
1014                     enum pivot_axis_type a)
1015 {
1016   if (lex_token (lexer) == T_BY
1017       || lex_token (lexer) == T_SLASH
1018       || lex_token (lexer) == T_ENDCMD)
1019     return true;
1020
1021   struct ctables_axis_parse_ctx ctx = {
1022     .lexer = lexer,
1023     .dict = dict,
1024     .ct = ct,
1025     .t = t
1026   };
1027   t->axes[a] = ctables_axis_parse_stack (&ctx);
1028   return t->axes[a] != NULL;
1029 }
1030
1031 static void
1032 ctables_chisq_destroy (struct ctables_chisq *chisq)
1033 {
1034   free (chisq);
1035 }
1036
1037 static void
1038 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
1039 {
1040   free (pairwise);
1041 }
1042
1043 static void
1044 ctables_table_destroy (struct ctables_table *t)
1045 {
1046   if (!t)
1047     return;
1048
1049   for (size_t i = 0; i < t->n_categories; i++)
1050     ctables_categories_unref (t->categories[i]);
1051   free (t->categories);
1052
1053   ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
1054   ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
1055   ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
1056   free (t->caption);
1057   free (t->corner);
1058   free (t->title);
1059   ctables_chisq_destroy (t->chisq);
1060   ctables_pairwise_destroy (t->pairwise);
1061   free (t);
1062 }
1063
1064 static void
1065 ctables_destroy (struct ctables *ct)
1066 {
1067   if (!ct)
1068     return;
1069
1070   pivot_table_look_unref (ct->look);
1071   free (ct->zero);
1072   free (ct->missing);
1073   free (ct->vlabels);
1074   for (size_t i = 0; i < ct->n_tables; i++)
1075     ctables_table_destroy (ct->tables[i]);
1076   free (ct->tables);
1077   free (ct);
1078 }
1079
1080 static struct ctables_cat_value
1081 ccvt_range (double low, double high)
1082 {
1083   return (struct ctables_cat_value) {
1084     .type = CCVT_RANGE,
1085     .range = { low, high }
1086   };
1087 }
1088
1089 static bool
1090 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1091                                 struct ctables_table *t)
1092 {
1093   if (!lex_match_id (lexer, "VARIABLES"))
1094     return false;
1095   lex_match (lexer, T_EQUALS);
1096
1097   struct variable **vars;
1098   size_t n_vars;
1099   if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1100     return false;
1101
1102   struct ctables_categories *c = xmalloc (sizeof *c);
1103   *c = (struct ctables_categories) { .n_refs = n_vars };
1104   for (size_t i = 0; i < n_vars; i++)
1105     {
1106       struct ctables_categories **cp
1107         = &t->categories[var_get_dict_index (vars[i])];
1108       ctables_categories_unref (*cp);
1109       *cp = c;
1110     }
1111   free (vars);
1112
1113   if (lex_match (lexer, T_LBRACK))
1114     {
1115       size_t allocated_values = 0;
1116       do
1117         {
1118           if (c->n_values >= allocated_values)
1119             c->values = x2nrealloc (c->values, &allocated_values,
1120                                     sizeof *c->values);
1121
1122           struct ctables_cat_value *v = &c->values[c->n_values];
1123           if (lex_match_id (lexer, "OTHERNM"))
1124             v->type = CCVT_OTHERNM;
1125           else if (lex_match_id (lexer, "MISSING"))
1126             v->type = CCVT_MISSING;
1127           else if (lex_match_id (lexer, "SUBTOTAL"))
1128             *v = (struct ctables_cat_value)
1129               { .type = CCVT_SUBTOTAL, .subtotal_label = NULL };
1130           else if (lex_match_id (lexer, "HSUBTOTAL"))
1131             *v = (struct ctables_cat_value)
1132               { .type = CCVT_HSUBTOTAL, .subtotal_label = NULL };
1133           else if (lex_match_id (lexer, "LO"))
1134             {
1135               if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1136                 return false;
1137               *v = ccvt_range (-DBL_MAX, lex_number (lexer));
1138               lex_get (lexer);
1139             }
1140           else if (lex_is_number (lexer))
1141             {
1142               double number = lex_number (lexer);
1143               lex_get (lexer);
1144               if (lex_match_id (lexer, "THRU"))
1145                 {
1146                   v->type = CCVT_RANGE;
1147                   v->range[0] = number;
1148                   if (lex_match_id (lexer, "HI"))
1149                     *v = ccvt_range (number, DBL_MAX);
1150                   else
1151                     {
1152                       if (!lex_force_num (lexer))
1153                         return false;
1154                       *v = ccvt_range (number, lex_number (lexer));
1155                       lex_get (lexer);
1156                     }
1157                 }
1158               else
1159                 *v = (struct ctables_cat_value) {
1160                   .type = CCVT_NUMBER,
1161                   .number = number
1162                 };
1163             }
1164           else if (lex_is_string (lexer))
1165             {
1166               *v = (struct ctables_cat_value) {
1167                 .type = CCVT_STRING,
1168                 .string = ss_xstrdup (lex_tokss (lexer)),
1169               };
1170               lex_get (lexer);
1171             }
1172           else
1173             {
1174               lex_error (lexer, NULL);
1175               return false;
1176             }
1177
1178           if ((v->type == CCVT_SUBTOTAL || v->type == CCVT_HSUBTOTAL)
1179               && lex_match (lexer, T_EQUALS))
1180             {
1181               if (!lex_force_string (lexer))
1182                 return false;
1183
1184               v->subtotal_label = ss_xstrdup (lex_tokss (lexer));
1185               lex_get (lexer);
1186             }
1187
1188           c->n_values++;
1189           lex_match (lexer, T_COMMA);
1190         }
1191       while (!lex_match (lexer, T_RBRACK));
1192     }
1193
1194   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1195     {
1196       if (!c->n_values && lex_match_id (lexer, "ORDER"))
1197         {
1198           lex_match (lexer, T_EQUALS);
1199           if (lex_match_id (lexer, "A"))
1200             c->sort_ascending = true;
1201           else if (lex_match_id (lexer, "D"))
1202             c->sort_ascending = false;
1203           else
1204             {
1205               lex_error_expecting (lexer, "A", "D");
1206               return false;
1207             }
1208         }
1209       else if (!c->n_values && lex_match_id (lexer, "KEY"))
1210         {
1211           lex_match (lexer, T_EQUALS);
1212           if (lex_match_id (lexer, "VALUE"))
1213             c->key = CTCS_VALUE;
1214           else if (lex_match_id (lexer, "LABEL"))
1215             c->key = CTCS_LABEL;
1216           else
1217             {
1218               c->key = CTCS_FUNCTION;
1219               if (!parse_ctables_summary_function (lexer, &c->sort_func))
1220                 return false;
1221
1222               if (lex_match (lexer, T_LPAREN))
1223                 {
1224                   c->sort_func_var = parse_variable (lexer, dict);
1225                   if (!c->sort_func_var)
1226                     return false;
1227
1228                   if (c->sort_func == CTSF_PTILE)
1229                     {
1230                       lex_match (lexer, T_COMMA);
1231                       if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1232                         return false;
1233                       c->percentile = lex_number (lexer);
1234                       lex_get (lexer);
1235                     }
1236
1237                   if (!lex_force_match (lexer, T_RPAREN))
1238                     return false;
1239                 }
1240               else if (ctables_function_availability (c->sort_func)
1241                        == CTFA_SCALE)
1242                 {
1243                   bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1244                   return false;
1245                 }
1246             }
1247         }
1248       else if (!c->n_values && lex_match_id (lexer, "MISSING"))
1249         {
1250           lex_match (lexer, T_EQUALS);
1251           if (lex_match_id (lexer, "INCLUDE"))
1252             c->include_missing = true;
1253           else if (lex_match_id (lexer, "EXCLUDE"))
1254             c->include_missing = false;
1255           else
1256             {
1257               lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1258               return false;
1259             }
1260         }
1261       else if (lex_match_id (lexer, "TOTAL"))
1262         {
1263           lex_match (lexer, T_EQUALS);
1264           if (!parse_bool (lexer, &c->show_totals))
1265             return false;
1266         }
1267       else if (lex_match_id (lexer, "LABEL"))
1268         {
1269           lex_match (lexer, T_EQUALS);
1270           if (!lex_force_string (lexer))
1271             return false;
1272           free (c->total_label);
1273           c->total_label = ss_xstrdup (lex_tokss (lexer));
1274           lex_get (lexer);
1275         }
1276       else if (lex_match_id (lexer, "POSITION"))
1277         {
1278           lex_match (lexer, T_EQUALS);
1279           if (lex_match_id (lexer, "BEFORE"))
1280             c->totals_before = true;
1281           else if (lex_match_id (lexer, "AFTER"))
1282             c->totals_before = false;
1283           else
1284             {
1285               lex_error_expecting (lexer, "BEFORE", "AFTER");
1286               return false;
1287             }
1288         }
1289       else if (lex_match_id (lexer, "EMPTY"))
1290         {
1291           lex_match (lexer, T_EQUALS);
1292           if (lex_match_id (lexer, "INCLUDE"))
1293             c->show_empty = true;
1294           else if (lex_match_id (lexer, "EXCLUDE"))
1295             c->show_empty = false;
1296           else
1297             {
1298               lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1299               return false;
1300             }
1301         }
1302       else
1303         {
1304           if (!c->n_values)
1305             lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1306                                  "TOTAL", "LABEL", "POSITION", "EMPTY");
1307           else
1308             lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1309           return false;
1310         }
1311     }
1312   return true;
1313 }
1314
1315 static void
1316 var_array_uninit (struct var_array *va)
1317 {
1318   if (va)
1319     free (va->vars);
1320 }
1321
1322 static void
1323 var_array2_uninit (struct var_array2 *vaa)
1324 {
1325   if (vaa)
1326     {
1327       for (size_t i = 0; i < vaa->n; i++)
1328         var_array_uninit (&vaa->vas[i]);
1329       free (vaa->vas);
1330     }
1331 }
1332
1333 static struct var_array2
1334 nest_fts (struct var_array2 va0, struct var_array2 va1)
1335 {
1336   if (!va0.n)
1337     return va1;
1338   else if (!va1.n)
1339     return va0;
1340
1341   struct var_array2 vaa = { .vas = xnmalloc (va0.n, va1.n * sizeof *vaa.vas) };
1342   for (size_t i = 0; i < va0.n; i++)
1343     for (size_t j = 0; j < va1.n; j++)
1344       {
1345         const struct var_array *a = &va0.vas[i];
1346         const struct var_array *b = &va1.vas[j];
1347
1348         size_t allocate = a->n + b->n;
1349         struct variable **vars = xnmalloc (allocate, sizeof *vars);
1350         enum pivot_axis_type *axes = xnmalloc (allocate, sizeof *axes);
1351         size_t n = 0;
1352         for (size_t k = 0; k < a->n; k++)
1353           vars[n++] = a->vars[k];
1354         for (size_t k = 0; k < b->n; k++)
1355           vars[n++] = b->vars[k];
1356         assert (n == allocate);
1357
1358         const struct var_array *summary_src;
1359         if (!a->summary_var)
1360           summary_src = b;
1361         else if (!b->summary_var)
1362           summary_src = a;
1363         else
1364           NOT_REACHED ();
1365         vaa.vas[vaa.n++] = (struct var_array) {
1366           .vars = vars,
1367           .scale_idx = (a->scale_idx != SIZE_MAX ? a->scale_idx
1368                         : b->scale_idx != SIZE_MAX ? a->n + b->scale_idx
1369                         : SIZE_MAX),
1370           .n = n,
1371           .summaries = summary_src->summaries,
1372           .n_summaries = summary_src->n_summaries,
1373           .summary_var = summary_src->summary_var,
1374         };
1375       }
1376   var_array2_uninit (&va0);
1377   var_array2_uninit (&va1);
1378   return vaa;
1379 }
1380
1381 static struct var_array2
1382 stack_fts (struct var_array2 va0, struct var_array2 va1)
1383 {
1384   struct var_array2 vaa = { .vas = xnmalloc (va0.n + va1.n, sizeof *vaa.vas) };
1385   for (size_t i = 0; i < va0.n; i++)
1386     vaa.vas[vaa.n++] = va0.vas[i];
1387   for (size_t i = 0; i < va1.n; i++)
1388     vaa.vas[vaa.n++] = va1.vas[i];
1389   assert (vaa.n == va0.n + va1.n);
1390   free (va0.vas);
1391   free (va1.vas);
1392   return vaa;
1393 }
1394
1395 static struct var_array2
1396 enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
1397 {
1398   if (!a)
1399     return (struct var_array2) { .n = 0 };
1400
1401   switch (a->op)
1402     {
1403     case CTAO_VAR:
1404       assert (!a->var.is_mrset);
1405
1406       struct variable **vars = xmalloc (sizeof *vars);
1407       *vars = a->var.var;
1408
1409       struct var_array *va = xmalloc (sizeof *va);
1410       *va = (struct var_array) {
1411         .vars = vars,
1412         .n = 1,
1413         .scale_idx = a->scale ? 0 : SIZE_MAX,
1414       };
1415       if (a->n_summaries || a->scale)
1416         {
1417           va->summaries = a->summaries;
1418           va->n_summaries = a->n_summaries;
1419           va->summary_var = a->var.var;
1420         }
1421       return (struct var_array2) { .vas = va, .n = 1 };
1422
1423     case CTAO_STACK:
1424       return stack_fts (enumerate_fts (axis_type, a->subs[0]),
1425                         enumerate_fts (axis_type, a->subs[1]));
1426
1427     case CTAO_NEST:
1428       return nest_fts (enumerate_fts (axis_type, a->subs[0]),
1429                        enumerate_fts (axis_type, a->subs[1]));
1430     }
1431
1432   NOT_REACHED ();
1433 }
1434
1435 union ctables_summary
1436   {
1437     /* COUNT, VALIDN, TOTALN. */
1438     struct
1439       {
1440         double valid;
1441         double missing;
1442       };
1443
1444     /* MINIMUM, MAXIMUM, RANGE. */
1445     struct
1446       {
1447         double min;
1448         double max;
1449       };
1450
1451     /* MEAN, SEMEAN, STDDEV, SUM, VARIANCE, *.SUM. */
1452     struct moments1 *moments;
1453
1454     /* XXX percentiles, median, mode, multiple response */
1455   };
1456
1457 static void
1458 ctables_summary_init (union ctables_summary *s,
1459                       const struct ctables_summary_spec *ss)
1460 {
1461   switch (ss->function)
1462     {
1463     case CTSF_COUNT:
1464     case CTSF_ECOUNT:
1465     case CTSF_ROWPCT_COUNT:
1466     case CTSF_COLPCT_COUNT:
1467     case CTSF_TABLEPCT_COUNT:
1468     case CTSF_SUBTABLEPCT_COUNT:
1469     case CTSF_LAYERPCT_COUNT:
1470     case CTSF_LAYERROWPCT_COUNT:
1471     case CTSF_LAYERCOLPCT_COUNT:
1472     case CTSF_ROWPCT_VALIDN:
1473     case CTSF_COLPCT_VALIDN:
1474     case CTSF_TABLEPCT_VALIDN:
1475     case CTSF_SUBTABLEPCT_VALIDN:
1476     case CTSF_LAYERPCT_VALIDN:
1477     case CTSF_LAYERROWPCT_VALIDN:
1478     case CTSF_LAYERCOLPCT_VALIDN:
1479     case CTSF_ROWPCT_TOTALN:
1480     case CTSF_COLPCT_TOTALN:
1481     case CTSF_TABLEPCT_TOTALN:
1482     case CTSF_SUBTABLEPCT_TOTALN:
1483     case CTSF_LAYERPCT_TOTALN:
1484     case CTSF_LAYERROWPCT_TOTALN:
1485     case CTSF_LAYERCOLPCT_TOTALN:
1486     case CSTF_TOTALN:
1487     case CTSF_ETOTALN:
1488     case CTSF_VALIDN:
1489     case CTSF_EVALIDN:
1490       s->missing = s->valid = 0;
1491       break;
1492
1493     case CTSF_MAXIMUM:
1494     case CTSF_MINIMUM:
1495     case CTSF_RANGE:
1496       s->min = s->max = SYSMIS;
1497       break;
1498
1499     case CTSF_MEAN:
1500     case CTSF_SEMEAN:
1501     case CTSF_STDDEV:
1502     case CTSF_SUM:
1503     case CTSF_VARIANCE:
1504     case CTSF_ROWPCT_SUM:
1505     case CTSF_COLPCT_SUM:
1506     case CTSF_TABLEPCT_SUM:
1507     case CTSF_SUBTABLEPCT_SUM:
1508     case CTSF_LAYERPCT_SUM:
1509     case CTSF_LAYERROWPCT_SUM:
1510     case CTSF_LAYERCOLPCT_SUM:
1511       s->moments = moments1_create (MOMENT_VARIANCE);
1512       break;
1513
1514     case CTSF_MEDIAN:
1515     case CTSF_MISSING:
1516     case CTSF_MODE:
1517     case CTSF_PTILE:
1518       NOT_REACHED ();
1519
1520     case CTSF_RESPONSES:
1521     case CTSF_ROWPCT_RESPONSES:
1522     case CTSF_COLPCT_RESPONSES:
1523     case CTSF_TABLEPCT_RESPONSES:
1524     case CTSF_SUBTABLEPCT_RESPONSES:
1525     case CTSF_LAYERPCT_RESPONSES:
1526     case CTSF_LAYERROWPCT_RESPONSES:
1527     case CTSF_LAYERCOLPCT_RESPONSES:
1528     case CTSF_ROWPCT_RESPONSES_COUNT:
1529     case CTSF_COLPCT_RESPONSES_COUNT:
1530     case CTSF_TABLEPCT_RESPONSES_COUNT:
1531     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1532     case CTSF_LAYERPCT_RESPONSES_COUNT:
1533     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1534     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1535     case CTSF_ROWPCT_COUNT_RESPONSES:
1536     case CTSF_COLPCT_COUNT_RESPONSES:
1537     case CTSF_TABLEPCT_COUNT_RESPONSES:
1538     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1539     case CTSF_LAYERPCT_COUNT_RESPONSES:
1540     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1541     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1542       NOT_REACHED ();
1543     }
1544 }
1545
1546 static void UNUSED
1547 ctables_summary_uninit (union ctables_summary *s,
1548                         const struct ctables_summary_spec *ss)
1549 {
1550   switch (ss->function)
1551     {
1552     case CTSF_COUNT:
1553     case CTSF_ECOUNT:
1554     case CTSF_ROWPCT_COUNT:
1555     case CTSF_COLPCT_COUNT:
1556     case CTSF_TABLEPCT_COUNT:
1557     case CTSF_SUBTABLEPCT_COUNT:
1558     case CTSF_LAYERPCT_COUNT:
1559     case CTSF_LAYERROWPCT_COUNT:
1560     case CTSF_LAYERCOLPCT_COUNT:
1561     case CTSF_ROWPCT_VALIDN:
1562     case CTSF_COLPCT_VALIDN:
1563     case CTSF_TABLEPCT_VALIDN:
1564     case CTSF_SUBTABLEPCT_VALIDN:
1565     case CTSF_LAYERPCT_VALIDN:
1566     case CTSF_LAYERROWPCT_VALIDN:
1567     case CTSF_LAYERCOLPCT_VALIDN:
1568     case CTSF_ROWPCT_TOTALN:
1569     case CTSF_COLPCT_TOTALN:
1570     case CTSF_TABLEPCT_TOTALN:
1571     case CTSF_SUBTABLEPCT_TOTALN:
1572     case CTSF_LAYERPCT_TOTALN:
1573     case CTSF_LAYERROWPCT_TOTALN:
1574     case CTSF_LAYERCOLPCT_TOTALN:
1575     case CSTF_TOTALN:
1576     case CTSF_ETOTALN:
1577     case CTSF_VALIDN:
1578     case CTSF_EVALIDN:
1579       break;
1580
1581     case CTSF_MAXIMUM:
1582     case CTSF_MINIMUM:
1583     case CTSF_RANGE:
1584       break;
1585
1586     case CTSF_MEAN:
1587     case CTSF_SEMEAN:
1588     case CTSF_STDDEV:
1589     case CTSF_SUM:
1590     case CTSF_VARIANCE:
1591     case CTSF_ROWPCT_SUM:
1592     case CTSF_COLPCT_SUM:
1593     case CTSF_TABLEPCT_SUM:
1594     case CTSF_SUBTABLEPCT_SUM:
1595     case CTSF_LAYERPCT_SUM:
1596     case CTSF_LAYERROWPCT_SUM:
1597     case CTSF_LAYERCOLPCT_SUM:
1598       moments1_destroy (s->moments);
1599       break;
1600
1601     case CTSF_MEDIAN:
1602     case CTSF_MISSING:
1603     case CTSF_MODE:
1604     case CTSF_PTILE:
1605       NOT_REACHED ();
1606
1607     case CTSF_RESPONSES:
1608     case CTSF_ROWPCT_RESPONSES:
1609     case CTSF_COLPCT_RESPONSES:
1610     case CTSF_TABLEPCT_RESPONSES:
1611     case CTSF_SUBTABLEPCT_RESPONSES:
1612     case CTSF_LAYERPCT_RESPONSES:
1613     case CTSF_LAYERROWPCT_RESPONSES:
1614     case CTSF_LAYERCOLPCT_RESPONSES:
1615     case CTSF_ROWPCT_RESPONSES_COUNT:
1616     case CTSF_COLPCT_RESPONSES_COUNT:
1617     case CTSF_TABLEPCT_RESPONSES_COUNT:
1618     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1619     case CTSF_LAYERPCT_RESPONSES_COUNT:
1620     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1621     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1622     case CTSF_ROWPCT_COUNT_RESPONSES:
1623     case CTSF_COLPCT_COUNT_RESPONSES:
1624     case CTSF_TABLEPCT_COUNT_RESPONSES:
1625     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1626     case CTSF_LAYERPCT_COUNT_RESPONSES:
1627     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1628     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1629       NOT_REACHED ();
1630     }
1631 }
1632
1633 static void
1634 ctables_summary_add (union ctables_summary *s,
1635                      const struct ctables_summary_spec *ss,
1636                      const struct variable *var, const union value *value,
1637                      double weight)
1638 {
1639   switch (ss->function)
1640     {
1641     case CTSF_COUNT:
1642     case CTSF_ECOUNT:
1643     case CTSF_ROWPCT_COUNT:
1644     case CTSF_COLPCT_COUNT:
1645     case CTSF_TABLEPCT_COUNT:
1646     case CTSF_SUBTABLEPCT_COUNT:
1647     case CTSF_LAYERPCT_COUNT:
1648     case CTSF_LAYERROWPCT_COUNT:
1649     case CTSF_LAYERCOLPCT_COUNT:
1650     case CTSF_ROWPCT_VALIDN:
1651     case CTSF_COLPCT_VALIDN:
1652     case CTSF_TABLEPCT_VALIDN:
1653     case CTSF_SUBTABLEPCT_VALIDN:
1654     case CTSF_LAYERPCT_VALIDN:
1655     case CTSF_LAYERROWPCT_VALIDN:
1656     case CTSF_LAYERCOLPCT_VALIDN:
1657     case CTSF_ROWPCT_TOTALN:
1658     case CTSF_COLPCT_TOTALN:
1659     case CTSF_TABLEPCT_TOTALN:
1660     case CTSF_SUBTABLEPCT_TOTALN:
1661     case CTSF_LAYERPCT_TOTALN:
1662     case CTSF_LAYERROWPCT_TOTALN:
1663     case CTSF_LAYERCOLPCT_TOTALN:
1664     case CSTF_TOTALN:
1665     case CTSF_ETOTALN:
1666     case CTSF_VALIDN:
1667     case CTSF_EVALIDN:
1668       if (var_is_value_missing (var, value))
1669         s->missing += weight;
1670       else
1671         s->valid += weight;
1672       break;
1673
1674     case CTSF_MAXIMUM:
1675     case CTSF_MINIMUM:
1676     case CTSF_RANGE:
1677       if (!var_is_value_missing (var, value))
1678         {
1679           assert (!var_is_alpha (var)); /* XXX? */
1680           if (s->min == SYSMIS || value->f < s->min)
1681             s->min = value->f;
1682           if (s->max == SYSMIS || value->f > s->max)
1683             s->max = value->f;
1684         }
1685       break;
1686
1687     case CTSF_MEAN:
1688     case CTSF_SEMEAN:
1689     case CTSF_STDDEV:
1690     case CTSF_SUM:
1691     case CTSF_VARIANCE:
1692     case CTSF_ROWPCT_SUM:
1693     case CTSF_COLPCT_SUM:
1694     case CTSF_TABLEPCT_SUM:
1695     case CTSF_SUBTABLEPCT_SUM:
1696     case CTSF_LAYERPCT_SUM:
1697     case CTSF_LAYERROWPCT_SUM:
1698     case CTSF_LAYERCOLPCT_SUM:
1699       moments1_add (s->moments, value->f, weight);
1700       break;
1701
1702     case CTSF_MEDIAN:
1703     case CTSF_MISSING:
1704     case CTSF_MODE:
1705     case CTSF_PTILE:
1706       NOT_REACHED ();
1707
1708     case CTSF_RESPONSES:
1709     case CTSF_ROWPCT_RESPONSES:
1710     case CTSF_COLPCT_RESPONSES:
1711     case CTSF_TABLEPCT_RESPONSES:
1712     case CTSF_SUBTABLEPCT_RESPONSES:
1713     case CTSF_LAYERPCT_RESPONSES:
1714     case CTSF_LAYERROWPCT_RESPONSES:
1715     case CTSF_LAYERCOLPCT_RESPONSES:
1716     case CTSF_ROWPCT_RESPONSES_COUNT:
1717     case CTSF_COLPCT_RESPONSES_COUNT:
1718     case CTSF_TABLEPCT_RESPONSES_COUNT:
1719     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1720     case CTSF_LAYERPCT_RESPONSES_COUNT:
1721     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1722     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1723     case CTSF_ROWPCT_COUNT_RESPONSES:
1724     case CTSF_COLPCT_COUNT_RESPONSES:
1725     case CTSF_TABLEPCT_COUNT_RESPONSES:
1726     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1727     case CTSF_LAYERPCT_COUNT_RESPONSES:
1728     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1729     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1730       NOT_REACHED ();
1731     }
1732 }
1733
1734 static double
1735 ctables_summary_value (const struct ctables_freq *f,
1736                        union ctables_summary *s,
1737                        const struct ctables_summary_spec *ss)
1738 {
1739   switch (ss->function)
1740     {
1741     case CTSF_COUNT:
1742     case CTSF_ECOUNT:
1743       return s->valid;
1744
1745     case CTSF_SUBTABLEPCT_COUNT:
1746       return f->domains[CTDT_SUBTABLE]->valid ? s->valid / f->domains[CTDT_SUBTABLE]->valid * 100 : SYSMIS;
1747
1748     case CTSF_ROWPCT_COUNT:
1749       return f->domains[CTDT_ROW]->valid ? s->valid / f->domains[CTDT_ROW]->valid * 100 : SYSMIS;
1750
1751     case CTSF_COLPCT_COUNT:
1752       return f->domains[CTDT_COL]->valid ? s->valid / f->domains[CTDT_COL]->valid * 100 : SYSMIS;
1753
1754     case CTSF_TABLEPCT_COUNT:
1755       return f->domains[CTDT_TABLE]->valid ? s->valid / f->domains[CTDT_TABLE]->valid * 100 : SYSMIS;
1756
1757     case CTSF_LAYERPCT_COUNT:
1758       return f->domains[CTDT_LAYER]->valid ? s->valid / f->domains[CTDT_LAYER]->valid * 100 : SYSMIS;
1759
1760     case CTSF_LAYERROWPCT_COUNT:
1761       return f->domains[CTDT_LAYERROW]->valid ? s->valid / f->domains[CTDT_LAYERROW]->valid * 100 : SYSMIS;
1762
1763     case CTSF_LAYERCOLPCT_COUNT:
1764       return f->domains[CTDT_LAYERCOL]->valid ? s->valid / f->domains[CTDT_LAYERCOL]->valid * 100 : SYSMIS;
1765
1766     case CTSF_ROWPCT_VALIDN:
1767     case CTSF_COLPCT_VALIDN:
1768     case CTSF_TABLEPCT_VALIDN:
1769     case CTSF_SUBTABLEPCT_VALIDN:
1770     case CTSF_LAYERPCT_VALIDN:
1771     case CTSF_LAYERROWPCT_VALIDN:
1772     case CTSF_LAYERCOLPCT_VALIDN:
1773     case CTSF_ROWPCT_TOTALN:
1774     case CTSF_COLPCT_TOTALN:
1775     case CTSF_TABLEPCT_TOTALN:
1776     case CTSF_SUBTABLEPCT_TOTALN:
1777     case CTSF_LAYERPCT_TOTALN:
1778     case CTSF_LAYERROWPCT_TOTALN:
1779     case CTSF_LAYERCOLPCT_TOTALN:
1780       NOT_REACHED ();
1781
1782     case CSTF_TOTALN:
1783     case CTSF_ETOTALN:
1784       return s->valid + s->missing;
1785
1786     case CTSF_VALIDN:
1787     case CTSF_EVALIDN:
1788       return s->valid;
1789
1790     case CTSF_MAXIMUM:
1791       return s->max;
1792
1793     case CTSF_MINIMUM:
1794       return s->min;
1795
1796     case CTSF_RANGE:
1797       return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
1798
1799     case CTSF_MEAN:
1800       {
1801         double mean;
1802         moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
1803         return mean;
1804       }
1805
1806     case CTSF_SEMEAN:
1807       {
1808         double weight, variance;
1809         moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
1810         return calc_semean (variance, weight);
1811       }
1812
1813     case CTSF_STDDEV:
1814       {
1815         double variance;
1816         moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
1817         return variance != SYSMIS ? sqrt (variance) : SYSMIS;
1818       }
1819
1820     case CTSF_SUM:
1821       {
1822         double weight, mean;
1823         moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
1824         return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
1825       }
1826
1827     case CTSF_VARIANCE:
1828       {
1829         double variance;
1830         moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
1831         return variance;
1832       }
1833
1834     case CTSF_ROWPCT_SUM:
1835     case CTSF_COLPCT_SUM:
1836     case CTSF_TABLEPCT_SUM:
1837     case CTSF_SUBTABLEPCT_SUM:
1838     case CTSF_LAYERPCT_SUM:
1839     case CTSF_LAYERROWPCT_SUM:
1840     case CTSF_LAYERCOLPCT_SUM:
1841       NOT_REACHED ();
1842
1843     case CTSF_MEDIAN:
1844     case CTSF_MISSING:
1845     case CTSF_MODE:
1846     case CTSF_PTILE:
1847       NOT_REACHED ();
1848
1849     case CTSF_RESPONSES:
1850     case CTSF_ROWPCT_RESPONSES:
1851     case CTSF_COLPCT_RESPONSES:
1852     case CTSF_TABLEPCT_RESPONSES:
1853     case CTSF_SUBTABLEPCT_RESPONSES:
1854     case CTSF_LAYERPCT_RESPONSES:
1855     case CTSF_LAYERROWPCT_RESPONSES:
1856     case CTSF_LAYERCOLPCT_RESPONSES:
1857     case CTSF_ROWPCT_RESPONSES_COUNT:
1858     case CTSF_COLPCT_RESPONSES_COUNT:
1859     case CTSF_TABLEPCT_RESPONSES_COUNT:
1860     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
1861     case CTSF_LAYERPCT_RESPONSES_COUNT:
1862     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
1863     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
1864     case CTSF_ROWPCT_COUNT_RESPONSES:
1865     case CTSF_COLPCT_COUNT_RESPONSES:
1866     case CTSF_TABLEPCT_COUNT_RESPONSES:
1867     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
1868     case CTSF_LAYERPCT_COUNT_RESPONSES:
1869     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
1870     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
1871       NOT_REACHED ();
1872     }
1873
1874   NOT_REACHED ();
1875 }
1876
1877 struct ctables_freq_sort_aux
1878   {
1879     const struct ctables_table *t;
1880     enum pivot_axis_type a;
1881   };
1882
1883 static int
1884 ctables_freq_compare_3way (const void *a_, const void *b_, const void *aux_)
1885 {
1886   const struct ctables_freq_sort_aux *aux = aux_;
1887   struct ctables_freq *const *ap = a_;
1888   struct ctables_freq *const *bp = b_;
1889   const struct ctables_freq *a = *ap;
1890   const struct ctables_freq *b = *bp;
1891
1892   size_t a_idx = a->axes[aux->a].vaa_idx;
1893   size_t b_idx = b->axes[aux->a].vaa_idx;
1894   if (a_idx != b_idx)
1895     return a_idx < b_idx ? -1 : 1;
1896
1897   const struct var_array *va = &aux->t->vaas[aux->a].vas[a_idx];
1898   for (size_t i = 0; i < va->n; i++)
1899     if (i != va->scale_idx)
1900       {
1901         int cmp = value_compare_3way (&a->axes[aux->a].values[i],
1902                                       &b->axes[aux->a].values[i],
1903                                       var_get_width (va->vars[i]));
1904         if (cmp)
1905           return cmp;
1906       }
1907   return 0;
1908 }
1909
1910 /* Algorithm:
1911
1912    For each row:
1913        For each ctables_table:
1914            For each combination of row vars:
1915                For each combination of column vars:
1916                    For each combination of layer vars:
1917                        Add entry
1918    Make a table of row values:
1919        Sort entries by row values
1920        Assign a 0-based index to each actual value
1921        Construct a dimension
1922    Make a table of column values
1923    Make a table of layer values
1924    For each entry:
1925        Fill the table entry using the indexes from before.
1926  */
1927
1928 static struct ctables_domain *
1929 ctables_domain_insert (struct ctables_table *t, struct ctables_freq *f,
1930                        enum ctables_domain_type domain)
1931 {
1932   /* XXX how can we handle CTDT_LAYERROW and CTDT_LAYERCOL?  Crossing subtables
1933      is hard.  */
1934   size_t hash = 0;
1935   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
1936     {
1937       size_t idx = f->axes[a].vaa_idx;
1938       const struct var_array *va = &t->vaas[a].vas[idx];
1939       hash = hash_int (idx, hash);
1940       for (size_t i = 0; i < va->n_domains[domain]; i++)
1941         {
1942           size_t v_idx = va->domains[domain][i];
1943           hash = value_hash (&f->axes[a].values[v_idx],
1944                              var_get_width (va->vars[v_idx]), hash);
1945         }
1946     }
1947
1948   struct ctables_domain *d;
1949   HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &t->domains[domain])
1950     {
1951       const struct ctables_freq *df = d->example;
1952       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
1953         {
1954           size_t idx = f->axes[a].vaa_idx;
1955           if (idx != df->axes[a].vaa_idx)
1956             goto not_equal;
1957
1958           const struct var_array *va = &t->vaas[a].vas[idx];
1959           for (size_t i = 0; i < va->n_domains[domain]; i++)
1960             {
1961               size_t v_idx = va->domains[domain][i];
1962               if (!value_equal (&df->axes[a].values[v_idx],
1963                                 &f->axes[a].values[v_idx],
1964                                 var_get_width (va->vars[v_idx])))
1965                 goto not_equal;
1966             }
1967         }
1968       return d;
1969
1970     not_equal: ;
1971     }
1972
1973   d = xmalloc (sizeof *d);
1974   *d = (struct ctables_domain) { .example = f };
1975   hmap_insert (&t->domains[domain], &d->node, hash);
1976   return d;
1977 }
1978
1979 static void
1980 ctables_freqtab_insert (struct ctables_table *t,
1981                         const struct ccase *c,
1982                         size_t ir, size_t ic, size_t il,
1983                         double weight)
1984 {
1985   size_t ix[PIVOT_N_AXES] = {
1986     [PIVOT_AXIS_ROW] = ir,
1987     [PIVOT_AXIS_COLUMN] = ic,
1988     [PIVOT_AXIS_LAYER] = il,
1989   };
1990   const struct var_array *ss = &t->vaas[t->summary_axis].vas[ix[t->summary_axis]];
1991
1992   size_t hash = 0;
1993   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
1994     {
1995       const struct var_array *va = &t->vaas[a].vas[ix[a]];
1996       hash = hash_int (ix[a], hash);
1997       for (size_t i = 0; i < va->n; i++)
1998         if (i != va->scale_idx)
1999           hash = value_hash (case_data (c, va->vars[i]),
2000                              var_get_width (va->vars[i]), hash);
2001     }
2002
2003   struct ctables_freq *f;
2004   HMAP_FOR_EACH_WITH_HASH (f, struct ctables_freq, node, hash, &t->ft)
2005     {
2006       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2007         {
2008           const struct var_array *va = &t->vaas[a].vas[ix[a]];
2009           if (f->axes[a].vaa_idx != ix[a])
2010             goto not_equal;
2011           for (size_t i = 0; i < va->n; i++)
2012             if (i != va->scale_idx
2013                 && !value_equal (case_data (c, va->vars[i]),
2014                                  &f->axes[a].values[i],
2015                                  var_get_width (va->vars[i])))
2016                 goto not_equal;
2017         }
2018
2019       goto summarize;
2020
2021     not_equal: ;
2022     }
2023
2024   f = xmalloc (sizeof *f);
2025   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2026     {
2027       const struct var_array *va = &t->vaas[a].vas[ix[a]];
2028       f->axes[a].vaa_idx = ix[a];
2029       f->axes[a].values = (va->n
2030                            ? xnmalloc (va->n, sizeof *f->axes[a].values)
2031                            : NULL);
2032       for (size_t i = 0; i < va->n; i++)
2033         value_clone (&f->axes[a].values[i], case_data (c, va->vars[i]),
2034                      var_get_width (va->vars[i]));
2035     }
2036   f->summaries = xmalloc (ss->n_summaries * sizeof *f->summaries);
2037   for (size_t i = 0; i < ss->n_summaries; i++)
2038     ctables_summary_init (&f->summaries[i], &ss->summaries[i]);
2039   for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2040     f->domains[dt] = ctables_domain_insert (t, f, dt);
2041   hmap_insert (&t->ft, &f->node, hash);
2042
2043 summarize:
2044   for (size_t i = 0; i < ss->n_summaries; i++)
2045     ctables_summary_add (&f->summaries[i], &ss->summaries[i], ss->summary_var,
2046                          case_data (c, ss->summary_var), weight);
2047   for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2048     f->domains[dt]->valid += weight;
2049 }
2050
2051 static bool
2052 ctables_execute (struct dataset *ds, struct ctables *ct)
2053 {
2054   for (size_t i = 0; i < ct->n_tables; i++)
2055     {
2056       struct ctables_table *t = ct->tables[i];
2057       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2058         if (t->axes[a])
2059           {
2060             t->vaas[a] = enumerate_fts (a, t->axes[a]);
2061
2062             for (size_t j = 0; j < t->vaas[a].n; j++)
2063               {
2064                 struct var_array *va = &t->vaas[a].vas[j];
2065                 for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2066                   {
2067                     va->domains[dt] = xmalloc (va->n * sizeof *va->domains[dt]);
2068                     va->n_domains[dt] = 0;
2069
2070                     for (size_t k = 0; k < va->n; k++)
2071                       {
2072                         if (k == va->scale_idx)
2073                           continue;
2074
2075                         switch (dt)
2076                           {
2077                           case CTDT_TABLE:
2078                             continue;
2079
2080                           case CTDT_LAYER:
2081                             if (a != PIVOT_AXIS_LAYER)
2082                               continue;
2083                             break;
2084
2085                           case CTDT_SUBTABLE:
2086                           case CTDT_ROW:
2087                           case CTDT_COL:
2088                             if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
2089                                 : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
2090                                 : a == PIVOT_AXIS_ROW)
2091                               {
2092                                 if (k == va->n - 1
2093                                     || (va->scale_idx == va->n - 1
2094                                         && k == va->n - 2))
2095                                   continue;
2096                               }
2097                             break;
2098
2099                           case CTDT_LAYERROW:
2100                             if (a == PIVOT_AXIS_COLUMN)
2101                               continue;
2102                             break;
2103
2104                           case CTDT_LAYERCOL:
2105                             if (a == PIVOT_AXIS_ROW)
2106                               continue;
2107                             break;
2108                           }
2109
2110                         va->domains[dt][va->n_domains[dt]++] = k;
2111                       }
2112                   }
2113               }
2114           }
2115         else
2116           {
2117             struct var_array *va = xmalloc (sizeof *va);
2118             *va = (struct var_array) { .n = 0 };
2119             t->vaas[a] = (struct var_array2) { .vas = va, .n = 1 };
2120           }
2121
2122       for (size_t i = 0; i < t->vaas[t->summary_axis].n; i++)
2123         {
2124           struct var_array *va = &t->vaas[t->summary_axis].vas[i];
2125           if (!va->n_summaries)
2126             {
2127               va->summaries = xmalloc (sizeof *va->summaries);
2128               va->n_summaries = 1;
2129
2130               enum ctables_summary_function function
2131                 = va->summary_var ? CTSF_MEAN : CTSF_COUNT;
2132               struct ctables_var var = { .is_mrset = false, .var = va->summary_var };
2133
2134               *va->summaries = (struct ctables_summary_spec) {
2135                 .function = function,
2136                 .format = ctables_summary_default_format (function, &var),
2137                 .label = ctables_summary_default_label (function, 0),
2138               };
2139               if (!va->summary_var)
2140                 va->summary_var = va->vars[0];
2141             }
2142         }
2143     }
2144
2145   struct casereader *input = casereader_create_filter_weight (proc_open (ds),
2146                                                               dataset_dict (ds),
2147                                                               NULL, NULL);
2148   bool warn_on_invalid = true;
2149   double total_weight = 0;
2150   for (struct ccase *c = casereader_read (input); c;
2151        case_unref (c), c = casereader_read (input))
2152     {
2153       double weight = dict_get_case_weight (dataset_dict (ds), c,
2154                                             &warn_on_invalid);
2155       total_weight += weight;
2156
2157       for (size_t i = 0; i < ct->n_tables; i++)
2158         {
2159           struct ctables_table *t = ct->tables[i];
2160
2161           for (size_t ir = 0; ir < t->vaas[PIVOT_AXIS_ROW].n; ir++)
2162             for (size_t ic = 0; ic < t->vaas[PIVOT_AXIS_COLUMN].n; ic++)
2163               for (size_t il = 0; il < t->vaas[PIVOT_AXIS_LAYER].n; il++)
2164                 ctables_freqtab_insert (t, c, ir, ic, il, weight);
2165         }
2166     }
2167   casereader_destroy (input);
2168
2169   for (size_t i = 0; i < ct->n_tables; i++)
2170     {
2171       struct ctables_table *t = ct->tables[i];
2172
2173       struct pivot_table *pt = pivot_table_create__ (
2174         (t->title
2175          ? pivot_value_new_user_text (t->title, SIZE_MAX)
2176          : pivot_value_new_text (N_("Custom Tables"))),
2177         NULL);
2178       if (t->caption)
2179         pivot_table_set_caption (
2180           pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
2181       if (t->corner)
2182         pivot_table_set_caption (
2183           pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
2184
2185       pivot_table_set_look (pt, ct->look);
2186       struct pivot_dimension *d[PIVOT_N_AXES];
2187       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2188         {
2189           static const char *names[] = {
2190             [PIVOT_AXIS_ROW] = N_("Rows"),
2191             [PIVOT_AXIS_COLUMN] = N_("Columns"),
2192             [PIVOT_AXIS_LAYER] = N_("Layers"),
2193           };
2194           d[a] = (t->axes[a] || a == t->summary_axis
2195                   ? pivot_dimension_create (pt, a, names[a])
2196                   : NULL);
2197           if (!d[a])
2198             continue;
2199
2200           assert (t->axes[a]);
2201
2202           struct ctables_freq **sorted = xnmalloc (t->ft.count, sizeof *sorted);
2203
2204           struct ctables_freq *f;
2205           size_t n = 0;
2206           HMAP_FOR_EACH (f, struct ctables_freq, node, &t->ft)
2207             sorted[n++] = f;
2208           assert (n == t->ft.count);
2209
2210           struct ctables_freq_sort_aux aux = { .t = t, .a = a };
2211           sort (sorted, n, sizeof *sorted, ctables_freq_compare_3way, &aux);
2212
2213           size_t max_depth = 0;
2214           for (size_t j = 0; j < t->vaas[a].n; j++)
2215             if (t->vaas[a].vas[j].n > max_depth)
2216               max_depth = t->vaas[a].vas[j].n;
2217
2218           struct pivot_category **groups = xnmalloc (max_depth, sizeof *groups);
2219           struct pivot_category *top = NULL;
2220           int prev_leaf = 0;
2221           for (size_t j = 0; j < n; j++)
2222             {
2223               struct ctables_freq *f = sorted[j];
2224               const struct var_array *va = &t->vaas[a].vas[f->axes[a].vaa_idx];
2225
2226               size_t n_common = 0;
2227               bool new_subtable = false;
2228               if (j > 0)
2229                 {
2230                   struct ctables_freq *prev = sorted[j - 1];
2231                   if (prev->axes[a].vaa_idx == f->axes[a].vaa_idx)
2232                     {
2233                       for (; n_common < va->n; n_common++)
2234                         if (n_common != va->scale_idx
2235                             && !value_equal (&prev->axes[a].values[n_common],
2236                                              &f->axes[a].values[n_common],
2237                                              var_get_type (va->vars[n_common])))
2238                           break;
2239                     }
2240                   else
2241                     new_subtable = true;
2242                 }
2243               else
2244                 new_subtable = true;
2245
2246               if (new_subtable)
2247                 {
2248                   enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (va->vars[0])];
2249                   top = d[a]->root;
2250                   if (vlabel != CTVL_NONE)
2251                     top = pivot_category_create_group__ (
2252                       top, pivot_value_new_variable (va->vars[0]));
2253                 }
2254               if (n_common == va->n)
2255                 {
2256                   f->axes[a].leaf = prev_leaf;
2257                   continue;
2258                 }
2259
2260               for (size_t k = n_common; k < va->n; k++)
2261                 {
2262                   struct pivot_category *parent = k > 0 ? groups[k - 1] : top;
2263
2264                   struct pivot_value *label
2265                     = (k != va->scale_idx
2266                        ? pivot_value_new_var_value (va->vars[k],
2267                                                     &f->axes[a].values[k])
2268                        : NULL);
2269                   if (k == va->n - 1)
2270                     {
2271                       if (a == t->summary_axis)
2272                         {
2273                           if (label)
2274                             parent = pivot_category_create_group__ (parent, label);
2275                           for (size_t m = 0; m < va->n_summaries; m++)
2276                             {
2277                               int leaf = pivot_category_create_leaf (
2278                                 parent, pivot_value_new_text (va->summaries[m].label));
2279                               if (m == 0)
2280                                 prev_leaf = leaf;
2281                             }
2282                         }
2283                       else
2284                         {
2285                           /* This assertion is true as long as the summary axis
2286                              is the axis where the summaries are displayed. */
2287                           assert (label);
2288
2289                           prev_leaf = pivot_category_create_leaf (parent, label);
2290                         }
2291                       break;
2292                     }
2293
2294                   if (label)
2295                     parent = pivot_category_create_group__ (parent, label);
2296
2297                   enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (va->vars[k + 1])];
2298                   if (vlabel != CTVL_NONE)
2299                     parent = pivot_category_create_group__ (
2300                       parent, pivot_value_new_variable (va->vars[k + 1]));
2301                   groups[k] = parent;
2302                 }
2303
2304               f->axes[a].leaf = prev_leaf;
2305             }
2306           free (sorted);
2307           free (groups);
2308         }
2309       struct ctables_freq *f;
2310       HMAP_FOR_EACH (f, struct ctables_freq, node, &t->ft)
2311         {
2312           const struct var_array *ss = &t->vaas[t->summary_axis].vas[f->axes[t->summary_axis].vaa_idx];
2313           for (size_t j = 0; j < ss->n_summaries; j++)
2314             {
2315               size_t dindexes[3];
2316               size_t n_dindexes = 0;
2317
2318               for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2319                 if (d[a])
2320                   {
2321                     int leaf = f->axes[a].leaf;
2322                     if (a == t->summary_axis)
2323                       leaf += j;
2324                     dindexes[n_dindexes++] = leaf;
2325                   }
2326
2327               double d = ctables_summary_value (f, &f->summaries[j], &ss->summaries[j]);
2328               struct pivot_value *value = pivot_value_new_number (d);
2329               value->numeric.format = ss->summaries[j].format;
2330               pivot_table_put (pt, dindexes, n_dindexes, value);
2331             }
2332         }
2333
2334       pivot_table_submit (pt);
2335     }
2336
2337 #if 0
2338   for (size_t i = 0; i < ct->n_tables; i++)
2339     {
2340       struct ctables_table *t = ct->tables[i];
2341
2342       for (size_t j = 0; j < t->n_fts; j++)
2343         {
2344           struct ctables_freqtab *ft = t->fts[j];
2345           struct ctables_freq *f, *next;
2346           HMAP_FOR_EACH_SAFE (f, next, struct ctables_freq, node, &ft->data)
2347             {
2348               hmap_delete (&ft->data, &f->node);
2349               for (size_t k = 0; k < ft->n_summaries; k++)
2350                 ctables_summary_uninit (&f->summaries[k], &ft->summaries[k]);
2351               free (f->summaries);
2352               for (size_t k = 0; k < ft->vars.n; k++)
2353                 {
2354                   const struct variable *var = ft->vars.vars[k];
2355                   value_destroy (&f->values[k], var_get_width (var));
2356                 }
2357               free (f);
2358             }
2359           hmap_destroy (&ft->data);
2360           var_array_uninit (&ft->vars);
2361           free (ft);
2362         }
2363       free (t->fts);
2364     }
2365 #endif
2366   
2367   return proc_commit (ds);
2368 }
2369
2370 int
2371 cmd_ctables (struct lexer *lexer, struct dataset *ds)
2372 {
2373   size_t n_vars = dict_get_n_vars (dataset_dict (ds));
2374   enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
2375   enum settings_value_show tvars = settings_get_show_variables ();
2376   for (size_t i = 0; i < n_vars; i++)
2377     vlabels[i] = (enum ctables_vlabel) tvars;
2378
2379   struct ctables *ct = xmalloc (sizeof *ct);
2380   *ct = (struct ctables) {
2381     .look = pivot_table_look_unshare (pivot_table_look_ref (
2382                                         pivot_table_look_get_default ())),
2383     .vlabels = vlabels,
2384     .hide_threshold = 5,
2385   };
2386   ct->look->omit_empty = false;
2387
2388   if (!lex_force_match (lexer, T_SLASH))
2389     goto error;
2390
2391   while (!lex_match_id (lexer, "TABLE"))
2392     {
2393       if (lex_match_id (lexer, "FORMAT"))
2394         {
2395           double widths[2] = { SYSMIS, SYSMIS };
2396           double units_per_inch = 72.0;
2397
2398           while (lex_token (lexer) != T_SLASH)
2399             {
2400               if (lex_match_id (lexer, "MINCOLWIDTH"))
2401                 {
2402                   if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
2403                     goto error;
2404                 }
2405               else if (lex_match_id (lexer, "MAXCOLWIDTH"))
2406                 {
2407                   if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
2408                     goto error;
2409                 }
2410               else if (lex_match_id (lexer, "UNITS"))
2411                 {
2412                   lex_match (lexer, T_EQUALS);
2413                   if (lex_match_id (lexer, "POINTS"))
2414                     units_per_inch = 72.0;
2415                   else if (lex_match_id (lexer, "INCHES"))
2416                     units_per_inch = 1.0;
2417                   else if (lex_match_id (lexer, "CM"))
2418                     units_per_inch = 2.54;
2419                   else
2420                     {
2421                       lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
2422                       goto error;
2423                     }
2424                 }
2425               else if (lex_match_id (lexer, "EMPTY"))
2426                 {
2427                   free (ct->zero);
2428                   ct->zero = NULL;
2429
2430                   lex_match (lexer, T_EQUALS);
2431                   if (lex_match_id (lexer, "ZERO"))
2432                     {
2433                       /* Nothing to do. */
2434                     }
2435                   else if (lex_match_id (lexer, "BLANK"))
2436                     ct->zero = xstrdup ("");
2437                   else if (lex_force_string (lexer))
2438                     {
2439                       ct->zero = ss_xstrdup (lex_tokss (lexer));
2440                       lex_get (lexer);
2441                     }
2442                   else
2443                     goto error;
2444                 }
2445               else if (lex_match_id (lexer, "MISSING"))
2446                 {
2447                   lex_match (lexer, T_EQUALS);
2448                   if (!lex_force_string (lexer))
2449                     goto error;
2450
2451                   free (ct->missing);
2452                   ct->missing = (strcmp (lex_tokcstr (lexer), ".")
2453                                  ? ss_xstrdup (lex_tokss (lexer))
2454                                  : NULL);
2455                   lex_get (lexer);
2456                 }
2457               else
2458                 {
2459                   lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
2460                                        "UNITS", "EMPTY", "MISSING");
2461                   goto error;
2462                 }
2463             }
2464
2465           if (widths[0] != SYSMIS && widths[1] != SYSMIS
2466               && widths[0] > widths[1])
2467             {
2468               msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
2469               goto error;
2470             }
2471
2472           for (size_t i = 0; i < 2; i++)
2473             if (widths[i] != SYSMIS)
2474               {
2475                 int *wr = ct->look->width_ranges[TABLE_HORZ];
2476                 wr[i] = widths[i] / units_per_inch * 96.0;
2477                 if (wr[0] > wr[1])
2478                   wr[!i] = wr[i];
2479               }
2480         }
2481       else if (lex_match_id (lexer, "VLABELS"))
2482         {
2483           if (!lex_force_match_id (lexer, "VARIABLES"))
2484             goto error;
2485           lex_match (lexer, T_EQUALS);
2486
2487           struct variable **vars;
2488           size_t n_vars;
2489           if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
2490                                 PV_NO_SCRATCH))
2491             goto error;
2492
2493           if (!lex_force_match_id (lexer, "DISPLAY"))
2494             {
2495               free (vars);
2496               goto error;
2497             }
2498           lex_match (lexer, T_EQUALS);
2499
2500           enum ctables_vlabel vlabel;
2501           if (lex_match_id (lexer, "DEFAULT"))
2502             vlabel = (enum ctables_vlabel) settings_get_show_variables ();
2503           else if (lex_match_id (lexer, "NAME"))
2504             vlabel = CTVL_NAME;
2505           else if (lex_match_id (lexer, "LABEL"))
2506             vlabel = CTVL_LABEL;
2507           else if (lex_match_id (lexer, "BOTH"))
2508             vlabel = CTVL_BOTH;
2509           else if (lex_match_id (lexer, "NONE"))
2510             vlabel = CTVL_NONE;
2511           else
2512             {
2513               lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
2514                                    "BOTH", "NONE");
2515               free (vars);
2516               goto error;
2517             }
2518
2519           for (size_t i = 0; i < n_vars; i++)
2520             ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
2521           free (vars);
2522         }
2523       else if (lex_match_id (lexer, "MRSETS"))
2524         {
2525           if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
2526             goto error;
2527           lex_match (lexer, T_EQUALS);
2528           if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
2529             goto error;
2530         }
2531       else if (lex_match_id (lexer, "SMISSING"))
2532         {
2533           if (lex_match_id (lexer, "VARIABLE"))
2534             ct->smissing_listwise = false;
2535           else if (lex_match_id (lexer, "LISTWISE"))
2536             ct->smissing_listwise = true;
2537           else
2538             {
2539               lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
2540               goto error;
2541             }
2542         }
2543       /* XXX PCOMPUTE */
2544       else if (lex_match_id (lexer, "WEIGHT"))
2545         {
2546           if (!lex_force_match_id (lexer, "VARIABLE"))
2547             goto error;
2548           lex_match (lexer, T_EQUALS);
2549           ct->base_weight = parse_variable (lexer, dataset_dict (ds));
2550           if (!ct->base_weight)
2551             goto error;
2552         }
2553       else if (lex_match_id (lexer, "HIDESMALLCOUNTS"))
2554         {
2555           if (!lex_force_match_id (lexer, "COUNT"))
2556             goto error;
2557           lex_match (lexer, T_EQUALS);
2558           if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT", 2, INT_MAX))
2559             goto error;
2560           ct->hide_threshold = lex_integer (lexer);
2561           lex_get (lexer);
2562         }
2563       else
2564         {
2565           lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
2566                                "SMISSING", "PCOMPUTE", "PPROPERTIES",
2567                                "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
2568           goto error;
2569         }
2570
2571       if (!lex_force_match (lexer, T_SLASH))
2572         goto error;
2573     }
2574
2575   size_t allocated_tables = 0;
2576   do
2577     {
2578       if (ct->n_tables >= allocated_tables)
2579         ct->tables = x2nrealloc (ct->tables, &allocated_tables,
2580                                  sizeof *ct->tables);
2581
2582       struct ctables_table *t = xmalloc (sizeof *t);
2583       *t = (struct ctables_table) {
2584         .ft = HMAP_INITIALIZER (t->ft),
2585         .slabels_position = PIVOT_AXIS_COLUMN,
2586         .slabels_visible = true,
2587         .row_labels = CTLP_NORMAL,
2588         .col_labels = CTLP_NORMAL,
2589         .categories = xcalloc (dict_get_n_vars (dataset_dict (ds)),
2590                                sizeof *t->categories),
2591         .n_categories = dict_get_n_vars (dataset_dict (ds)),
2592         .cilevel = 95,
2593       };
2594       for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2595         hmap_init (&t->domains[dt]);
2596       ct->tables[ct->n_tables++] = t;
2597
2598       lex_match (lexer, T_EQUALS);
2599       if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
2600         goto error;
2601       if (lex_match (lexer, T_BY))
2602         {
2603           if (!ctables_axis_parse (lexer, dataset_dict (ds),
2604                                    ct, t, PIVOT_AXIS_COLUMN))
2605             goto error;
2606
2607           if (lex_match (lexer, T_BY))
2608             {
2609               if (!ctables_axis_parse (lexer, dataset_dict (ds),
2610                                        ct, t, PIVOT_AXIS_LAYER))
2611                 goto error;
2612             }
2613         }
2614
2615       if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
2616           && !t->axes[PIVOT_AXIS_LAYER])
2617         {
2618           lex_error (lexer, _("At least one variable must be specified."));
2619           goto error;
2620         }
2621
2622       const struct ctables_axis *scales[PIVOT_N_AXES];
2623       size_t n_scales = 0;
2624       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2625         {
2626           scales[a] = find_scale (t->axes[a]);
2627           if (scales[a])
2628             n_scales++;
2629         }
2630       if (n_scales > 1)
2631         {
2632           msg (SE, _("Scale variables may appear only on one axis."));
2633           if (scales[PIVOT_AXIS_ROW])
2634             msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
2635                     _("This scale variable appears on the rows axis."));
2636           if (scales[PIVOT_AXIS_COLUMN])
2637             msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
2638                     _("This scale variable appears on the columns axis."));
2639           if (scales[PIVOT_AXIS_LAYER])
2640             msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
2641                     _("This scale variable appears on the layer axis."));
2642           goto error;
2643         }
2644
2645       const struct ctables_axis *summaries[PIVOT_N_AXES];
2646       size_t n_summaries = 0;
2647       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2648         {
2649           summaries[a] = (scales[a]
2650                           ? scales[a]
2651                           : find_categorical_summary_spec (t->axes[a]));
2652           if (summaries[a])
2653             n_summaries++;
2654         }
2655       if (n_summaries > 1)
2656         {
2657           msg (SE, _("Summaries may appear only on one axis."));
2658           if (summaries[PIVOT_AXIS_ROW])
2659             msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
2660                     _("This variable on the rows axis has a summary."));
2661           if (summaries[PIVOT_AXIS_COLUMN])
2662             msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
2663                     _("This variable on the columns axis has a summary."));
2664           if (summaries[PIVOT_AXIS_LAYER])
2665             msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
2666                     _("This variable on the layers axis has a summary."));
2667           goto error;
2668         }
2669       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2670         if (n_summaries ? summaries[a] : t->axes[a])
2671           {
2672             t->summary_axis = a;
2673             break;
2674           }
2675
2676       if (lex_token (lexer) == T_ENDCMD)
2677         break;
2678       if (!lex_force_match (lexer, T_SLASH))
2679         break;
2680
2681       while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
2682         {
2683           if (lex_match_id (lexer, "SLABELS"))
2684             {
2685               while (lex_token (lexer) != T_SLASH)
2686                 {
2687                   if (lex_match_id (lexer, "POSITION"))
2688                     {
2689                       lex_match (lexer, T_EQUALS);
2690                       if (lex_match_id (lexer, "COLUMN"))
2691                         t->slabels_position = PIVOT_AXIS_COLUMN;
2692                       else if (lex_match_id (lexer, "ROW"))
2693                         t->slabels_position = PIVOT_AXIS_ROW;
2694                       else if (lex_match_id (lexer, "LAYER"))
2695                         t->slabels_position = PIVOT_AXIS_LAYER;
2696                       else
2697                         {
2698                           lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
2699                           goto error;
2700                         }
2701                     }
2702                   else if (lex_match_id (lexer, "VISIBLE"))
2703                     {
2704                       lex_match (lexer, T_EQUALS);
2705                       if (!parse_bool (lexer, &t->slabels_visible))
2706                         goto error;
2707                     }
2708                   else
2709                     {
2710                       lex_error_expecting (lexer, "POSITION", "VISIBLE");
2711                       goto error;
2712                     }
2713                 }
2714             }
2715           else if (lex_match_id (lexer, "CLABELS"))
2716             {
2717               while (lex_token (lexer) != T_SLASH)
2718                 {
2719                   if (lex_match_id (lexer, "AUTO"))
2720                     t->row_labels = t->col_labels = CTLP_NORMAL;
2721                   else if (lex_match_id (lexer, "ROWLABELS"))
2722                     {
2723                       lex_match (lexer, T_EQUALS);
2724                       if (lex_match_id (lexer, "OPPOSITE"))
2725                         t->row_labels = CTLP_OPPOSITE;
2726                       else if (lex_match_id (lexer, "LAYER"))
2727                         t->row_labels = CTLP_LAYER;
2728                       else
2729                         {
2730                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
2731                           goto error;
2732                         }
2733                     }
2734                   else if (lex_match_id (lexer, "COLLABELS"))
2735                     {
2736                       lex_match (lexer, T_EQUALS);
2737                       if (lex_match_id (lexer, "OPPOSITE"))
2738                         t->col_labels = CTLP_OPPOSITE;
2739                       else if (lex_match_id (lexer, "LAYER"))
2740                         t->col_labels = CTLP_LAYER;
2741                       else
2742                         {
2743                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
2744                           goto error;
2745                         }
2746                     }
2747                   else
2748                     {
2749                       lex_error_expecting (lexer, "AUTO", "ROWLABELS",
2750                                            "COLLABELS");
2751                       goto error;
2752                     }
2753                 }
2754             }
2755           else if (lex_match_id (lexer, "CRITERIA"))
2756             {
2757               if (!lex_force_match_id (lexer, "CILEVEL"))
2758                 goto error;
2759               lex_match (lexer, T_EQUALS);
2760
2761               if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
2762                 goto error;
2763               t->cilevel = lex_number (lexer);
2764               lex_get (lexer);
2765             }
2766           else if (lex_match_id (lexer, "CATEGORIES"))
2767             {
2768               if (!ctables_table_parse_categories (lexer, dataset_dict (ds), t))
2769                 goto error;
2770             }
2771           else if (lex_match_id (lexer, "TITLES"))
2772             {
2773               do
2774                 {
2775                   char **textp;
2776                   if (lex_match_id (lexer, "CAPTION"))
2777                     textp = &t->caption;
2778                   else if (lex_match_id (lexer, "CORNER"))
2779                     textp = &t->corner;
2780                   else if (lex_match_id (lexer, "TITLE"))
2781                     textp = &t->title;
2782                   else
2783                     {
2784                       lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
2785                       goto error;
2786                     }
2787                   lex_match (lexer, T_EQUALS);
2788
2789                   struct string s = DS_EMPTY_INITIALIZER;
2790                   while (lex_is_string (lexer))
2791                     {
2792                       if (!ds_is_empty (&s))
2793                         ds_put_byte (&s, ' ');
2794                       ds_put_substring (&s, lex_tokss (lexer));
2795                       lex_get (lexer);
2796                     }
2797                   free (*textp);
2798                   *textp = ds_steal_cstr (&s);
2799                 }
2800               while (lex_token (lexer) != T_SLASH
2801                      && lex_token (lexer) != T_ENDCMD);
2802             }
2803           else if (lex_match_id (lexer, "SIGTEST"))
2804             {
2805               if (!t->chisq)
2806                 {
2807                   t->chisq = xmalloc (sizeof *t->chisq);
2808                   *t->chisq = (struct ctables_chisq) {
2809                     .alpha = .05,
2810                     .include_mrsets = true,
2811                     .all_visible = true,
2812                   };
2813                 }
2814
2815               do
2816                 {
2817                   if (lex_match_id (lexer, "TYPE"))
2818                     {
2819                       lex_match (lexer, T_EQUALS);
2820                       if (!lex_force_match_id (lexer, "CHISQUARE"))
2821                         goto error;
2822                     }
2823                   else if (lex_match_id (lexer, "ALPHA"))
2824                     {
2825                       lex_match (lexer, T_EQUALS);
2826                       if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
2827                         goto error;
2828                       t->chisq->alpha = lex_number (lexer);
2829                       lex_get (lexer);
2830                     }
2831                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
2832                     {
2833                       lex_match (lexer, T_EQUALS);
2834                       if (parse_bool (lexer, &t->chisq->include_mrsets))
2835                         goto error;
2836                     }
2837                   else if (lex_match_id (lexer, "CATEGORIES"))
2838                     {
2839                       lex_match (lexer, T_EQUALS);
2840                       if (lex_match_id (lexer, "ALLVISIBLE"))
2841                         t->chisq->all_visible = true;
2842                       else if (lex_match_id (lexer, "SUBTOTALS"))
2843                         t->chisq->all_visible = false;
2844                       else
2845                         {
2846                           lex_error_expecting (lexer,
2847                                                "ALLVISIBLE", "SUBTOTALS");
2848                           goto error;
2849                         }
2850                     }
2851                   else
2852                     {
2853                       lex_error_expecting (lexer, "TYPE", "ALPHA",
2854                                            "INCLUDEMRSETS", "CATEGORIES");
2855                       goto error;
2856                     }
2857                 }
2858               while (lex_token (lexer) != T_SLASH
2859                      && lex_token (lexer) != T_ENDCMD);
2860             }
2861           else if (lex_match_id (lexer, "COMPARETEST"))
2862             {
2863               if (!t->pairwise)
2864                 {
2865                   t->pairwise = xmalloc (sizeof *t->pairwise);
2866                   *t->pairwise = (struct ctables_pairwise) {
2867                     .type = PROP,
2868                     .alpha = { .05, .05 },
2869                     .adjust = BONFERRONI,
2870                     .include_mrsets = true,
2871                     .meansvariance_allcats = true,
2872                     .all_visible = true,
2873                     .merge = false,
2874                     .apa_style = true,
2875                     .show_sig = false,
2876                   };
2877                 }
2878
2879               do
2880                 {
2881                   if (lex_match_id (lexer, "TYPE"))
2882                     {
2883                       lex_match (lexer, T_EQUALS);
2884                       if (lex_match_id (lexer, "PROP"))
2885                         t->pairwise->type = PROP;
2886                       else if (lex_match_id (lexer, "MEAN"))
2887                         t->pairwise->type = MEAN;
2888                       else
2889                         {
2890                           lex_error_expecting (lexer, "PROP", "MEAN");
2891                           goto error;
2892                         }
2893                     }
2894                   else if (lex_match_id (lexer, "ALPHA"))
2895                     {
2896                       lex_match (lexer, T_EQUALS);
2897
2898                       if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
2899                         goto error;
2900                       double a0 = lex_number (lexer);
2901                       lex_get (lexer);
2902
2903                       lex_match (lexer, T_COMMA);
2904                       if (lex_is_number (lexer))
2905                         {
2906                           if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
2907                             goto error;
2908                           double a1 = lex_number (lexer);
2909                           lex_get (lexer);
2910
2911                           t->pairwise->alpha[0] = MIN (a0, a1);
2912                           t->pairwise->alpha[1] = MAX (a0, a1);
2913                         }
2914                       else
2915                         t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
2916                     }
2917                   else if (lex_match_id (lexer, "ADJUST"))
2918                     {
2919                       lex_match (lexer, T_EQUALS);
2920                       if (lex_match_id (lexer, "BONFERRONI"))
2921                         t->pairwise->adjust = BONFERRONI;
2922                       else if (lex_match_id (lexer, "BH"))
2923                         t->pairwise->adjust = BH;
2924                       else if (lex_match_id (lexer, "NONE"))
2925                         t->pairwise->adjust = 0;
2926                       else
2927                         {
2928                           lex_error_expecting (lexer, "BONFERRONI", "BH",
2929                                                "NONE");
2930                           goto error;
2931                         }
2932                     }
2933                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
2934                     {
2935                       lex_match (lexer, T_EQUALS);
2936                       if (!parse_bool (lexer, &t->pairwise->include_mrsets))
2937                         goto error;
2938                     }
2939                   else if (lex_match_id (lexer, "MEANSVARIANCE"))
2940                     {
2941                       lex_match (lexer, T_EQUALS);
2942                       if (lex_match_id (lexer, "ALLCATS"))
2943                         t->pairwise->meansvariance_allcats = true;
2944                       else if (lex_match_id (lexer, "TESTEDCATS"))
2945                         t->pairwise->meansvariance_allcats = false;
2946                       else
2947                         {
2948                           lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
2949                           goto error;
2950                         }
2951                     }
2952                   else if (lex_match_id (lexer, "CATEGORIES"))
2953                     {
2954                       lex_match (lexer, T_EQUALS);
2955                       if (lex_match_id (lexer, "ALLVISIBLE"))
2956                         t->pairwise->all_visible = true;
2957                       else if (lex_match_id (lexer, "SUBTOTALS"))
2958                         t->pairwise->all_visible = false;
2959                       else
2960                         {
2961                           lex_error_expecting (lexer, "ALLVISIBLE",
2962                                                "SUBTOTALS");
2963                           goto error;
2964                         }
2965                     }
2966                   else if (lex_match_id (lexer, "MERGE"))
2967                     {
2968                       lex_match (lexer, T_EQUALS);
2969                       if (!parse_bool (lexer, &t->pairwise->merge))
2970                         goto error;
2971                     }
2972                   else if (lex_match_id (lexer, "STYLE"))
2973                     {
2974                       lex_match (lexer, T_EQUALS);
2975                       if (lex_match_id (lexer, "APA"))
2976                         t->pairwise->apa_style = true;
2977                       else if (lex_match_id (lexer, "SIMPLE"))
2978                         t->pairwise->apa_style = false;
2979                       else
2980                         {
2981                           lex_error_expecting (lexer, "APA", "SIMPLE");
2982                           goto error;
2983                         }
2984                     }
2985                   else if (lex_match_id (lexer, "SHOWSIG"))
2986                     {
2987                       lex_match (lexer, T_EQUALS);
2988                       if (!parse_bool (lexer, &t->pairwise->show_sig))
2989                         goto error;
2990                     }
2991                   else
2992                     {
2993                       lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
2994                                            "INCLUDEMRSETS", "MEANSVARIANCE",
2995                                            "CATEGORIES", "MERGE", "STYLE",
2996                                            "SHOWSIG");
2997                       goto error;
2998                     }
2999                 }
3000               while (lex_token (lexer) != T_SLASH
3001                      && lex_token (lexer) != T_ENDCMD);
3002             }
3003           else
3004             {
3005               lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
3006                                    "CRITERIA", "CATEGORIES", "TITLES",
3007                                    "SIGTEST", "COMPARETEST");
3008               goto error;
3009             }
3010         }
3011
3012       if (t->row_labels != CTLP_NORMAL && t->col_labels != CTLP_NORMAL)
3013         {
3014           msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
3015           goto error;
3016         }
3017
3018     }
3019   while (lex_token (lexer) != T_ENDCMD);
3020
3021   bool ok = ctables_execute (ds, ct);
3022   ctables_destroy (ct);
3023   return ok ? CMD_SUCCESS : CMD_FAILURE;
3024
3025 error:
3026   ctables_destroy (ct);
3027   return CMD_FAILURE;
3028 }
3029