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