CTABLES weird special formats
[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 #include <errno.h>
21
22 #include "data/casereader.h"
23 #include "data/casewriter.h"
24 #include "data/data-out.h"
25 #include "data/dataset.h"
26 #include "data/dictionary.h"
27 #include "data/mrset.h"
28 #include "data/subcase.h"
29 #include "data/value-labels.h"
30 #include "language/command.h"
31 #include "language/lexer/format-parser.h"
32 #include "language/lexer/lexer.h"
33 #include "language/lexer/variable-parser.h"
34 #include "libpspp/array.h"
35 #include "libpspp/assertion.h"
36 #include "libpspp/hash-functions.h"
37 #include "libpspp/hmap.h"
38 #include "libpspp/i18n.h"
39 #include "libpspp/message.h"
40 #include "libpspp/string-array.h"
41 #include "math/mode.h"
42 #include "math/moments.h"
43 #include "math/percentiles.h"
44 #include "math/sort.h"
45 #include "output/pivot-table.h"
46
47 #include "gl/minmax.h"
48 #include "gl/xalloc.h"
49
50 #include "gettext.h"
51 #define _(msgid) gettext (msgid)
52 #define N_(msgid) (msgid)
53
54 enum ctables_vlabel
55   {
56     CTVL_NONE = SETTINGS_VALUE_SHOW_DEFAULT,
57     CTVL_NAME = SETTINGS_VALUE_SHOW_VALUE,
58     CTVL_LABEL = SETTINGS_VALUE_SHOW_LABEL,
59     CTVL_BOTH = SETTINGS_VALUE_SHOW_BOTH,
60   };
61
62 /* XXX:
63    - unweighted summaries (U*)
64    - lower confidence limits (*.LCL)
65    - upper confidence limits (*.UCL)
66    - standard error (*.SE)
67  */
68 #define SUMMARIES                                                       \
69     /* All variables. */                                                \
70     S(CTSF_COUNT, "COUNT", N_("Count"), CTF_COUNT, CTFA_ALL)            \
71     S(CTSF_ECOUNT, "ECOUNT", N_("Adjusted Count"), CTF_COUNT, CTFA_ALL) \
72     S(CTSF_ROWPCT_COUNT, "ROWPCT.COUNT", N_("Row %"), CTF_PERCENT, CTFA_ALL) \
73     S(CTSF_COLPCT_COUNT, "COLPCT.COUNT", N_("Column %"), CTF_PERCENT, CTFA_ALL) \
74     S(CTSF_TABLEPCT_COUNT, "TABLEPCT.COUNT", N_("Table %"), CTF_PERCENT, CTFA_ALL) \
75     S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT.COUNT", N_("Subtable %"), CTF_PERCENT, CTFA_ALL) \
76     S(CTSF_LAYERPCT_COUNT, "LAYERPCT.COUNT", N_("Layer %"), CTF_PERCENT, CTFA_ALL) \
77     S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT.COUNT", N_("Layer Row %"), CTF_PERCENT, CTFA_ALL) \
78     S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT.COUNT", N_("Layer Column %"), CTF_PERCENT, CTFA_ALL) \
79     S(CTSF_ROWPCT_VALIDN, "ROWPCT.VALIDN", N_("Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
80     S(CTSF_COLPCT_VALIDN, "COLPCT.VALIDN", N_("Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
81     S(CTSF_TABLEPCT_VALIDN, "TABLEPCT.VALIDN", N_("Table Valid N %"), CTF_PERCENT, CTFA_ALL) \
82     S(CTSF_SUBTABLEPCT_VALIDN, "SUBTABLEPCT.VALIDN", N_("Subtable Valid N %"), CTF_PERCENT, CTFA_ALL) \
83     S(CTSF_LAYERPCT_VALIDN, "LAYERPCT.VALIDN", N_("Layer Valid N %"), CTF_PERCENT, CTFA_ALL) \
84     S(CTSF_LAYERROWPCT_VALIDN, "LAYERROWPCT.VALIDN", N_("Layer Row Valid N %"), CTF_PERCENT, CTFA_ALL) \
85     S(CTSF_LAYERCOLPCT_VALIDN, "LAYERCOLPCT.VALIDN", N_("Layer Column Valid N %"), CTF_PERCENT, CTFA_ALL) \
86     S(CTSF_ROWPCT_TOTALN, "ROWPCT.TOTALN", N_("Row Total N %"), CTF_PERCENT, CTFA_ALL) \
87     S(CTSF_COLPCT_TOTALN, "COLPCT.TOTALN", N_("Column Total N %"), CTF_PERCENT, CTFA_ALL) \
88     S(CTSF_TABLEPCT_TOTALN, "TABLEPCT.TOTALN", N_("Table Total N %"), CTF_PERCENT, CTFA_ALL) \
89     S(CTSF_SUBTABLEPCT_TOTALN, "SUBTABLEPCT.TOTALN", N_("Subtable Total N %"), CTF_PERCENT, CTFA_ALL) \
90     S(CTSF_LAYERPCT_TOTALN, "LAYERPCT.TOTALN", N_("Layer Total N %"), CTF_PERCENT, CTFA_ALL) \
91     S(CTSF_LAYERROWPCT_TOTALN, "LAYERROWPCT.TOTALN", N_("Layer Row Total N %"), CTF_PERCENT, CTFA_ALL) \
92     S(CTSF_LAYERCOLPCT_TOTALN, "LAYERCOLPCT.TOTALN", N_("Layer Column Total N %"), CTF_PERCENT, CTFA_ALL) \
93                                                                         \
94     /* Scale variables, totals, and subtotals. */                       \
95     S(CTSF_MAXIMUM, "MAXIMUM", N_("Maximum"), CTF_GENERAL, CTFA_SCALE)  \
96     S(CTSF_MEAN, "MEAN", N_("Mean"), CTF_GENERAL, CTFA_SCALE)           \
97     S(CTSF_MEDIAN, "MEDIAN", N_("Median"), CTF_GENERAL, CTFA_SCALE)     \
98     S(CTSF_MINIMUM, "MINIMUM", N_("Minimum"), CTF_GENERAL, CTFA_SCALE)  \
99     S(CTSF_MISSING, "MISSING", N_("Missing"), CTF_GENERAL, CTFA_SCALE)  \
100     S(CTSF_MODE, "MODE", N_("Mode"), CTF_GENERAL, CTFA_SCALE)           \
101     S(CTSF_PTILE, "PTILE", N_("Percentile"), CTF_GENERAL, CTFA_SCALE)   \
102     S(CTSF_RANGE, "RANGE", N_("Range"), CTF_GENERAL, CTFA_SCALE)        \
103     S(CTSF_SEMEAN, "SEMEAN", N_("Std Error of Mean"), CTF_GENERAL, CTFA_SCALE) \
104     S(CTSF_STDDEV, "STDDEV", N_("Std Deviation"), CTF_GENERAL, CTFA_SCALE) \
105     S(CTSF_SUM, "SUM", N_("Sum"), CTF_GENERAL, CTFA_SCALE)              \
106     S(CSTF_TOTALN, "TOTALN", N_("Total N"), CTF_COUNT, CTFA_SCALE)      \
107     S(CTSF_ETOTALN, "ETOTALN", N_("Adjusted Total N"), CTF_COUNT, CTFA_SCALE) \
108     S(CTSF_VALIDN, "VALIDN", N_("Valid N"), CTF_COUNT, CTFA_SCALE)      \
109     S(CTSF_EVALIDN, "EVALIDN", N_("Adjusted Valid N"), CTF_COUNT, CTFA_SCALE) \
110     S(CTSF_VARIANCE, "VARIANCE", N_("Variance"), CTF_GENERAL, CTFA_SCALE) \
111     S(CTSF_ROWPCT_SUM, "ROWPCT.SUM", N_("Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
112     S(CTSF_COLPCT_SUM, "COLPCT.SUM", N_("Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
113     S(CTSF_TABLEPCT_SUM, "TABLEPCT.SUM", N_("Table Sum %"), CTF_PERCENT, CTFA_SCALE) \
114     S(CTSF_SUBTABLEPCT_SUM, "SUBTABLEPCT.SUM", N_("Subtable Sum %"), CTF_PERCENT, CTFA_SCALE) \
115     S(CTSF_LAYERPCT_SUM, "LAYERPCT.SUM", N_("Layer Sum %"), CTF_PERCENT, CTFA_SCALE) \
116     S(CTSF_LAYERROWPCT_SUM, "LAYERROWPCT.SUM", N_("Layer Row Sum %"), CTF_PERCENT, CTFA_SCALE) \
117     S(CTSF_LAYERCOLPCT_SUM, "LAYERCOLPCT.SUM", N_("Layer Column Sum %"), CTF_PERCENT, CTFA_SCALE) \
118                                                                         \
119     /* Multiple response sets. */                                       \
120   S(CTSF_RESPONSES, "RESPONSES", N_("Responses"), CTF_COUNT, CTFA_MRSETS) \
121     S(CTSF_ROWPCT_RESPONSES, "ROWPCT.RESPONSES", N_("Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
122     S(CTSF_COLPCT_RESPONSES, "COLPCT.RESPONSES", N_("Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
123     S(CTSF_TABLEPCT_RESPONSES, "TABLEPCT.RESPONSES", N_("Table Responses %"), CTF_PERCENT, CTFA_MRSETS) \
124     S(CTSF_SUBTABLEPCT_RESPONSES, "SUBTABLEPCT.RESPONSES", N_("Subtable Responses %"), CTF_PERCENT, CTFA_MRSETS) \
125     S(CTSF_LAYERPCT_RESPONSES, "LAYERPCT.RESPONSES", N_("Layer Responses %"), CTF_PERCENT, CTFA_MRSETS) \
126     S(CTSF_LAYERROWPCT_RESPONSES, "LAYERROWPCT.RESPONSES", N_("Layer Row Responses %"), CTF_PERCENT, CTFA_MRSETS) \
127     S(CTSF_LAYERCOLPCT_RESPONSES, "LAYERCOLPCT.RESPONSES", N_("Layer Column Responses %"), CTF_PERCENT, CTFA_MRSETS) \
128     S(CTSF_ROWPCT_RESPONSES_COUNT, "ROWPCT.RESPONSES.COUNT", N_("Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
129     S(CTSF_COLPCT_RESPONSES_COUNT, "COLPCT.RESPONSES.COUNT", N_("Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
130     S(CTSF_TABLEPCT_RESPONSES_COUNT, "TABLEPCT.RESPONSES.COUNT", N_("Table Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
131     S(CTSF_SUBTABLEPCT_RESPONSES_COUNT, "SUBTABLEPCT.RESPONSES.COUNT", N_("Subtable Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
132     S(CTSF_LAYERPCT_RESPONSES_COUNT, "LAYERPCT.RESPONSES.COUNT", N_("Layer Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
133     S(CTSF_LAYERROWPCT_RESPONSES_COUNT, "LAYERROWPCT.RESPONSES.COUNT", N_("Layer Row Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
134     S(CTSF_LAYERCOLPCT_RESPONSES_COUNT, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Responses % (Base: Count)"), CTF_PERCENT, CTFA_MRSETS) \
135     S(CTSF_ROWPCT_COUNT_RESPONSES, "ROWPCT.COUNT.RESPONSES", N_("Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
136     S(CTSF_COLPCT_COUNT_RESPONSES, "COLPCT.COUNT.RESPONSES", N_("Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
137     S(CTSF_TABLEPCT_COUNT_RESPONSES, "TABLEPCT.COUNT.RESPONSES", N_("Table Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
138     S(CTSF_SUBTABLEPCT_COUNT_RESPONSES, "SUBTABLEPCT.COUNT.RESPONSES", N_("Subtable Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
139     S(CTSF_LAYERPCT_COUNT_RESPONSES, "LAYERPCT.COUNT.RESPONSES", N_("Layer Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
140     S(CTSF_LAYERROWPCT_COUNT_RESPONSES, "LAYERROWPCT.COUNT.RESPONSES", N_("Layer Row Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS) \
141     S(CTSF_LAYERCOLPCT_COUNT_RESPONSES, "LAYERCOLPCT.RESPONSES.COUNT", N_("Layer Column Count % (Base: Responses)"), CTF_PERCENT, CTFA_MRSETS)
142
143 enum ctables_summary_function
144   {
145 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) ENUM,
146     SUMMARIES
147 #undef S
148   };
149
150 enum {
151 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) +1
152   N_CTSF_FUNCTIONS = SUMMARIES
153 #undef S
154 };
155
156 static bool ctables_summary_function_is_count (enum ctables_summary_function);
157
158 enum ctables_domain_type
159   {
160     /* Within a section, where stacked variables divide one section from
161        another. */
162     CTDT_TABLE,                  /* All layers of a whole section. */
163     CTDT_LAYER,                  /* One layer within a section. */
164     CTDT_LAYERROW,               /* Row in one layer within a section. */
165     CTDT_LAYERCOL,               /* Column in one layer within a section. */
166
167     /* Within a subtable, where a subtable pairs an innermost row variable with
168        an innermost column variable within a single layer.  */
169     CTDT_SUBTABLE,               /* Whole subtable. */
170     CTDT_ROW,                    /* Row within a subtable. */
171     CTDT_COL,                    /* Column within a subtable. */
172 #define N_CTDTS 7
173   };
174
175 struct ctables_domain
176   {
177     struct hmap_node node;
178
179     const struct ctables_cell *example;
180
181     double d_valid;             /* Dictionary weight. */
182     double d_missing;
183     double e_valid;             /* Effective weight */
184     double e_missing;
185   };
186
187 enum ctables_summary_variant
188   {
189     CSV_CELL,
190     CSV_TOTAL
191 #define N_CSVS 2
192   };
193
194 struct ctables_cell
195   {
196     /* In struct ctables_section's 'cells' hmap.  Indexed by all the values in
197        all the axes (except the scalar variable, if any). */
198     struct hmap_node node;
199
200     /* The domains that contain this cell. */
201     bool contributes_to_domains;
202     struct ctables_domain *domains[N_CTDTS];
203
204     bool hide;
205     bool postcompute;
206     enum ctables_summary_variant sv;
207
208     struct ctables_cell_axis
209       {
210         struct ctables_cell_value
211           {
212             const struct ctables_category *category;
213             union value value;
214           }
215         *cvs;
216         int leaf;
217       }
218     axes[PIVOT_N_AXES];
219
220     union ctables_summary *summaries;
221   };
222
223 struct ctables
224   {
225     const struct dictionary *dict;
226     struct pivot_table_look *look;
227
228     /* CTABLES has a number of extra formats that we implement via custom
229        currency specifications on an alternate fmt_settings. */
230 #define CTEF_NEGPAREN FMT_CCA
231 #define CTEF_NEQUAL   FMT_CCB
232 #define CTEF_PAREN    FMT_CCC
233 #define CTEF_PCTPAREN FMT_CCD
234     struct fmt_settings ctables_formats;
235
236     /* If this is NULL, zeros are displayed using the normal print format.
237        Otherwise, this string is displayed. */
238     char *zero;
239
240     /* If this is NULL, missing values are displayed using the normal print
241        format.  Otherwise, this string is displayed. */
242     char *missing;
243
244     /* Indexed by variable dictionary index. */
245     enum ctables_vlabel *vlabels;
246
247     struct hmap postcomputes;   /* Contains "struct ctables_postcompute"s. */
248
249     bool mrsets_count_duplicates; /* MRSETS. */
250     bool smissing_listwise;       /* SMISSING. */
251     struct variable *e_weight;    /* WEIGHT. */
252     int hide_threshold;           /* HIDESMALLCOUNTS. */
253
254     struct ctables_table **tables;
255     size_t n_tables;
256   };
257
258 static struct ctables_postcompute *ctables_find_postcompute (struct ctables *,
259                                                              const char *name);
260
261 struct ctables_postcompute
262   {
263     struct hmap_node hmap_node; /* In struct ctables's 'pcompute' hmap. */
264     char *name;                 /* Name, without leading &. */
265
266     struct msg_location *location; /* Location of definition. */
267     struct ctables_pcexpr *expr;
268     char *label;
269     struct ctables_summary_spec_set *specs;
270     bool hide_source_cats;
271   };
272
273 struct ctables_pcexpr
274   {
275     /* Precedence table:
276
277        ()
278        **
279        -
280        * /
281        - +
282     */
283     enum ctables_postcompute_op
284       {
285         /* Terminals. */
286         CTPO_CONSTANT,          /* 5 */
287         CTPO_CAT_NUMBER,        /* [5] */
288         CTPO_CAT_STRING,        /* ["STRING"] */
289         CTPO_CAT_RANGE,         /* [LO THRU 5] */
290         CTPO_CAT_MISSING,       /* MISSING */
291         CTPO_CAT_OTHERNM,       /* OTHERNM */
292         CTPO_CAT_SUBTOTAL,      /* SUBTOTAL */
293         CTPO_CAT_TOTAL,         /* TOTAL */
294
295         /* Nonterminals. */
296         CTPO_ADD,
297         CTPO_SUB,
298         CTPO_MUL,
299         CTPO_DIV,
300         CTPO_POW,
301         CTPO_NEG,
302       }
303     op;
304
305     union
306       {
307         /* CTPO_CAT_NUMBER. */
308         double number;
309
310         /* CTPO_CAT_STRING. */
311         char *string;
312
313         /* CTPO_CAT_RANGE. */
314         double range[2];
315
316         /* CTPO_CAT_SUBTOTAL. */
317         size_t subtotal_index;
318
319         /* Two elements: CTPO_ADD, CTPO_SUB, CTPO_MUL, CTPO_DIV, CTPO_POW.
320            One element: CTPO_NEG. */
321         struct ctables_pcexpr *subs[2];
322       };
323
324     /* Source location. */
325     struct msg_location *location;
326   };
327
328 static void ctables_pcexpr_destroy (struct ctables_pcexpr *);
329 static struct ctables_pcexpr *ctables_pcexpr_allocate_binary (
330   enum ctables_postcompute_op, struct ctables_pcexpr *sub0,
331   struct ctables_pcexpr *sub1);
332
333 struct ctables_summary_spec_set
334   {
335     struct ctables_summary_spec *specs;
336     size_t n;
337     size_t allocated;
338
339     struct variable *var;
340   };
341
342 static void ctables_summary_spec_set_clone (struct ctables_summary_spec_set *,
343                                             const struct ctables_summary_spec_set *);
344 static void ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *);
345
346 /* A nested sequence of variables, e.g. a > b > c. */
347 struct ctables_nest
348   {
349     struct variable **vars;
350     size_t n;
351     size_t scale_idx;
352     size_t *domains[N_CTDTS];
353     size_t n_domains[N_CTDTS];
354
355     struct ctables_summary_spec_set specs[N_CSVS];
356   };
357
358 /* A stack of nestings, e.g. nest1 + nest2 + ... + nestN. */
359 struct ctables_stack
360   {
361     struct ctables_nest *nests;
362     size_t n;
363   };
364
365 struct ctables_value
366   {
367     struct hmap_node node;
368     union value value;
369     int leaf;
370   };
371
372 struct ctables_occurrence
373   {
374     struct hmap_node node;
375     union value value;
376   };
377
378 struct ctables_section
379   {
380     struct ctables_table *table;
381     struct ctables_nest *nests[PIVOT_N_AXES];
382     struct hmap *occurrences[PIVOT_N_AXES];
383     struct hmap cells;            /* Contains "struct ctable_cell"s. */
384     struct hmap domains[N_CTDTS]; /* Contains "struct ctable_domain"s. */
385   };
386
387 struct ctables_table
388   {
389     struct ctables *ctables;
390     struct ctables_axis *axes[PIVOT_N_AXES];
391     struct ctables_stack stacks[PIVOT_N_AXES];
392     struct ctables_section *sections;
393     size_t n_sections;
394     enum pivot_axis_type summary_axis;
395     struct ctables_summary_spec_set summary_specs;
396
397     const struct variable *clabels_example;
398     struct hmap clabels_values_map;
399     struct ctables_value **clabels_values;
400     size_t n_clabels_values;
401
402     enum pivot_axis_type slabels_axis;
403     bool slabels_visible;
404
405     /* The innermost category labels for axis 'a' appear on axis label_axis[a].
406
407        Most commonly, label_axis[a] == a, and in particular we always have
408        label_axis{PIVOT_AXIS_LAYER] == PIVOT_AXIS_LAYER.
409
410        If ROWLABELS or COLLABELS is specified, then one of
411        label_axis[PIVOT_AXIS_ROW] or label_axis[PIVOT_AXIS_COLUMN] can be the
412        opposite axis or PIVOT_AXIS_LAYER.  Only one of them will differ.
413     */
414     enum pivot_axis_type label_axis[PIVOT_N_AXES];
415     enum pivot_axis_type clabels_from_axis;
416
417     /* Indexed by variable dictionary index. */
418     struct ctables_categories **categories;
419     size_t n_categories;
420
421     double cilevel;
422
423     char *caption;
424     char *corner;
425     char *title;
426
427     struct ctables_chisq *chisq;
428     struct ctables_pairwise *pairwise;
429   };
430
431 struct ctables_var
432   {
433     bool is_mrset;
434     union
435       {
436         struct variable *var;
437         const struct mrset *mrset;
438       };
439   };
440
441 static const struct fmt_spec *
442 ctables_var_get_print_format (const struct ctables_var *var)
443 {
444   return (var->is_mrset
445           ? var_get_print_format (var->mrset->vars[0])
446           : var_get_print_format (var->var));
447 }
448
449 static const char *
450 ctables_var_name (const struct ctables_var *var)
451 {
452   return var->is_mrset ? var->mrset->name : var_get_name (var->var);
453 }
454
455 struct ctables_categories
456   {
457     size_t n_refs;
458     struct ctables_category *cats;
459     size_t n_cats;
460     bool show_empty;
461   };
462
463 struct ctables_category
464   {
465     enum ctables_category_type
466       {
467         /* Explicit category lists. */
468         CCT_NUMBER,
469         CCT_STRING,
470         CCT_RANGE,
471         CCT_MISSING,
472         CCT_OTHERNM,
473         CCT_POSTCOMPUTE,
474
475         /* Totals and subtotals. */
476         CCT_SUBTOTAL,
477         CCT_TOTAL,
478
479         /* Implicit category lists. */
480         CCT_VALUE,
481         CCT_LABEL,
482         CCT_FUNCTION,
483       }
484     type;
485
486     struct ctables_category *subtotal;
487
488     bool hide;
489
490     union
491       {
492         double number;          /* CCT_NUMBER. */
493         char *string;           /* CCT_STRING. */
494         double range[2];        /* CCT_RANGE. */
495
496         struct
497           {
498             char *total_label;      /* CCT_SUBTOTAL, CCT_TOTAL. */
499             bool hide_subcategories; /* CCT_SUBTOTAL. */
500           };
501
502         const struct ctables_postcompute *pc; /* CCT_POSTCOMPUTE. */
503
504         /* CCT_VALUE, CCT_LABEL, CCT_FUNCTION. */
505         struct
506           {
507             bool include_missing;
508             bool sort_ascending;
509
510             /* CCT_FUNCTION. */
511             enum ctables_summary_function sort_function;
512             struct variable *sort_var;
513             double percentile;
514           };
515       };
516
517     /* Source location.  This is null for CCT_TOTAL, CCT_VALUE, CCT_LABEL,
518        CCT_FUNCTION. */
519     struct msg_location *location;
520   };
521
522 static void
523 ctables_category_uninit (struct ctables_category *cat)
524 {
525   if (!cat)
526     return;
527
528   switch (cat->type)
529     {
530     case CCT_NUMBER:
531     case CCT_RANGE:
532     case CCT_MISSING:
533     case CCT_OTHERNM:
534     case CCT_POSTCOMPUTE:
535       break;
536
537     case CCT_STRING:
538       free (cat->string);
539       break;
540
541     case CCT_SUBTOTAL:
542     case CCT_TOTAL:
543       free (cat->total_label);
544       break;
545
546     case CCT_VALUE:
547     case CCT_LABEL:
548     case CCT_FUNCTION:
549       break;
550     }
551 }
552
553 static bool
554 ctables_category_equal (const struct ctables_category *a,
555                         const struct ctables_category *b)
556 {
557   if (a->type != b->type)
558     return false;
559
560   switch (a->type)
561     {
562     case CCT_NUMBER:
563       return a->number == b->number;
564
565     case CCT_STRING:
566       return strcmp (a->string, b->string);
567
568     case CCT_RANGE:
569       return a->range[0] == b->range[0] && a->range[1] == b->range[1];
570
571     case CCT_MISSING:
572     case CCT_OTHERNM:
573       return true;
574
575     case CCT_POSTCOMPUTE:
576       return a->pc == b->pc;
577
578     case CCT_SUBTOTAL:
579     case CCT_TOTAL:
580       return !strcmp (a->total_label, b->total_label);
581
582     case CCT_VALUE:
583     case CCT_LABEL:
584     case CCT_FUNCTION:
585       return (a->include_missing == b->include_missing
586               && a->sort_ascending == b->sort_ascending
587               && a->sort_function == b->sort_function
588               && a->sort_var == b->sort_var
589               && a->percentile == b->percentile);
590     }
591
592   NOT_REACHED ();
593 }
594
595 static void
596 ctables_categories_unref (struct ctables_categories *c)
597 {
598   if (!c)
599     return;
600
601   assert (c->n_refs > 0);
602   if (--c->n_refs)
603     return;
604
605   for (size_t i = 0; i < c->n_cats; i++)
606     ctables_category_uninit (&c->cats[i]);
607   free (c->cats);
608   free (c);
609 }
610
611 static bool
612 ctables_categories_equal (const struct ctables_categories *a,
613                           const struct ctables_categories *b)
614 {
615   if (a->n_cats != b->n_cats || a->show_empty != b->show_empty)
616     return false;
617
618   for (size_t i = 0; i < a->n_cats; i++)
619     if (!ctables_category_equal (&a->cats[i], &b->cats[i]))
620       return false;
621
622   return true;
623 }
624
625 /* Chi-square test (SIGTEST). */
626 struct ctables_chisq
627   {
628     double alpha;
629     bool include_mrsets;
630     bool all_visible;
631   };
632
633 /* Pairwise comparison test (COMPARETEST). */
634 struct ctables_pairwise
635   {
636     enum { PROP, MEAN } type;
637     double alpha[2];
638     bool include_mrsets;
639     bool meansvariance_allcats;
640     bool all_visible;
641     enum { BONFERRONI = 1, BH } adjust;
642     bool merge;
643     bool apa_style;
644     bool show_sig;
645   };
646
647 struct ctables_axis
648   {
649     enum ctables_axis_op
650       {
651         /* Terminals. */
652         CTAO_VAR,
653
654         /* Nonterminals. */
655         CTAO_STACK,             /* + */
656         CTAO_NEST,              /* > */
657       }
658     op;
659
660     union
661       {
662         /* Terminals. */
663         struct
664           {
665             struct ctables_var var;
666             bool scale;
667             struct ctables_summary_spec_set specs[N_CSVS];
668           };
669
670         /* Nonterminals. */
671         struct ctables_axis *subs[2];
672       };
673
674     struct msg_location *loc;
675   };
676
677 static void ctables_axis_destroy (struct ctables_axis *);
678
679 enum ctables_format
680   {
681     CTF_COUNT,
682     CTF_PERCENT,
683     CTF_GENERAL
684   };
685
686 enum ctables_function_availability
687   {
688     CTFA_ALL,                /* Any variables. */
689     CTFA_SCALE,              /* Only scale variables, totals, and subtotals. */
690     CTFA_MRSETS,             /* Only multiple-response sets */
691   };
692
693 struct ctables_summary_spec
694   {
695     enum ctables_summary_function function;
696     double percentile;          /* CTSF_PTILE only. */
697     char *label;
698
699     struct fmt_spec format;
700     bool is_ctables_format;       /* Is 'format' one of CTEF_*? */
701
702     size_t axis_idx;
703   };
704
705 static void
706 ctables_summary_spec_clone (struct ctables_summary_spec *dst,
707                             const struct ctables_summary_spec *src)
708 {
709   *dst = *src;
710   dst->label = xstrdup (src->label);
711 }
712
713 static void
714 ctables_summary_spec_uninit (struct ctables_summary_spec *s)
715 {
716   if (s)
717     free (s->label);
718 }
719
720 static void
721 ctables_summary_spec_set_clone (struct ctables_summary_spec_set *dst,
722                                 const struct ctables_summary_spec_set *src)
723 {
724   struct ctables_summary_spec *specs = xnmalloc (src->n, sizeof *specs);
725   for (size_t i = 0; i < src->n; i++)
726     ctables_summary_spec_clone (&specs[i], &src->specs[i]);
727
728   *dst = (struct ctables_summary_spec_set) {
729     .specs = specs,
730     .n = src->n,
731     .allocated = src->n,
732     .var = src->var
733   };
734 }
735
736 static void
737 ctables_summary_spec_set_uninit (struct ctables_summary_spec_set *set)
738 {
739   for (size_t i = 0; i < set->n; i++)
740     ctables_summary_spec_uninit (&set->specs[i]);
741   free (set->specs);
742 }
743
744 static bool
745 parse_col_width (struct lexer *lexer, const char *name, double *width)
746 {
747   lex_match (lexer, T_EQUALS);
748   if (lex_match_id (lexer, "DEFAULT"))
749     *width = SYSMIS;
750   else if (lex_force_num_range_closed (lexer, name, 0, DBL_MAX))
751     {
752       *width = lex_number (lexer);
753       lex_get (lexer);
754     }
755   else
756     return false;
757
758   return true;
759 }
760
761 static bool
762 parse_bool (struct lexer *lexer, bool *b)
763 {
764   if (lex_match_id (lexer, "NO"))
765     *b = false;
766   else if (lex_match_id (lexer, "YES"))
767     *b = true;
768   else
769     {
770       lex_error_expecting (lexer, "YES", "NO");
771       return false;
772     }
773   return true;
774 }
775
776 static enum ctables_function_availability
777 ctables_function_availability (enum ctables_summary_function f)
778 {
779   static enum ctables_function_availability availability[] = {
780 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = AVAILABILITY,
781     SUMMARIES
782 #undef S
783   };
784
785   return availability[f];
786 }
787
788 static bool
789 ctables_summary_function_is_count (enum ctables_summary_function f)
790 {
791   static const bool is_count[N_CTSF_FUNCTIONS] = {
792     [CTSF_COUNT] = true,
793     [CTSF_ECOUNT] = true,
794     [CTSF_ROWPCT_COUNT] = true,
795     [CTSF_COLPCT_COUNT] = true,
796     [CTSF_TABLEPCT_COUNT] = true,
797     [CTSF_SUBTABLEPCT_COUNT] = true,
798     [CTSF_LAYERPCT_COUNT] = true,
799     [CTSF_LAYERROWPCT_COUNT] = true,
800     [CTSF_LAYERCOLPCT_COUNT] = true,
801     [CTSF_ROWPCT_RESPONSES_COUNT] = true,
802     [CTSF_COLPCT_RESPONSES_COUNT] = true,
803     [CTSF_TABLEPCT_RESPONSES_COUNT] = true,
804     [CTSF_SUBTABLEPCT_RESPONSES_COUNT] = true,
805     [CTSF_LAYERPCT_RESPONSES_COUNT] = true,
806     [CTSF_LAYERROWPCT_RESPONSES_COUNT] = true,
807     [CTSF_LAYERCOLPCT_RESPONSES_COUNT] = true,
808     [CTSF_ROWPCT_COUNT_RESPONSES] = true,
809     [CTSF_COLPCT_COUNT_RESPONSES] = true,
810     [CTSF_TABLEPCT_COUNT_RESPONSES] = true,
811     [CTSF_SUBTABLEPCT_COUNT_RESPONSES] = true,
812     [CTSF_LAYERPCT_COUNT_RESPONSES] = true,
813     [CTSF_LAYERROWPCT_COUNT_RESPONSES] = true,
814     [CTSF_LAYERCOLPCT_COUNT_RESPONSES] = true,
815   };
816   return is_count[f];
817 }
818
819
820 static bool
821 parse_ctables_summary_function (struct lexer *lexer,
822                                 enum ctables_summary_function *f)
823 {
824   struct pair
825     {
826       enum ctables_summary_function function;
827       struct substring name;
828     };
829   static struct pair names[] = {
830 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) \
831     { ENUM, SS_LITERAL_INITIALIZER (NAME) },
832     SUMMARIES
833
834     /* The .COUNT suffix may be omitted. */
835     S(CTSF_ROWPCT_COUNT, "ROWPCT", _, _, _)
836     S(CTSF_COLPCT_COUNT, "COLPCT", _, _, _)
837     S(CTSF_TABLEPCT_COUNT, "TABLEPCT", _, _, _)
838     S(CTSF_SUBTABLEPCT_COUNT, "SUBTABLEPCT", _, _, _)
839     S(CTSF_LAYERPCT_COUNT, "LAYERPCT", _, _, _)
840     S(CTSF_LAYERROWPCT_COUNT, "LAYERROWPCT", _, _, _)
841     S(CTSF_LAYERCOLPCT_COUNT, "LAYERCOLPCT", _, _, _)
842 #undef S
843   };
844
845   if (!lex_force_id (lexer))
846     return false;
847
848   for (size_t i = 0; i < sizeof names / sizeof *names; i++)
849     if (ss_equals_case (names[i].name, lex_tokss (lexer)))
850       {
851         *f = names[i].function;
852         lex_get (lexer);
853         return true;
854       }
855
856   lex_error (lexer, _("Expecting summary function name."));
857   return false;
858 }
859
860 static void
861 ctables_axis_destroy (struct ctables_axis *axis)
862 {
863   if (!axis)
864     return;
865
866   switch (axis->op)
867     {
868     case CTAO_VAR:
869       for (size_t i = 0; i < N_CSVS; i++)
870         ctables_summary_spec_set_uninit (&axis->specs[i]);
871       break;
872
873     case CTAO_STACK:
874     case CTAO_NEST:
875       ctables_axis_destroy (axis->subs[0]);
876       ctables_axis_destroy (axis->subs[1]);
877       break;
878     }
879   msg_location_destroy (axis->loc);
880   free (axis);
881 }
882
883 static struct ctables_axis *
884 ctables_axis_new_nonterminal (enum ctables_axis_op op,
885                               struct ctables_axis *sub0,
886                               struct ctables_axis *sub1,
887                               struct lexer *lexer, int start_ofs)
888 {
889   struct ctables_axis *axis = xmalloc (sizeof *axis);
890   *axis = (struct ctables_axis) {
891     .op = op,
892     .subs = { sub0, sub1 },
893     .loc = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
894   };
895   return axis;
896 }
897
898 struct ctables_axis_parse_ctx
899   {
900     struct lexer *lexer;
901     struct dictionary *dict;
902     struct ctables *ct;
903     struct ctables_table *t;
904   };
905
906 static struct fmt_spec
907 ctables_summary_default_format (enum ctables_summary_function function,
908                                 const struct ctables_var *var)
909 {
910   static const enum ctables_format default_formats[] = {
911 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = FORMAT,
912     SUMMARIES
913 #undef S
914   };
915   switch (default_formats[function])
916     {
917     case CTF_COUNT:
918       return (struct fmt_spec) { .type = FMT_F, .w = 40 };
919
920     case CTF_PERCENT:
921       return (struct fmt_spec) { .type = FMT_PCT, .w = 40, .d = 1 };
922
923     case CTF_GENERAL:
924       return *ctables_var_get_print_format (var);
925
926     default:
927       NOT_REACHED ();
928     }
929 }
930
931 static char *
932 ctables_summary_default_label (enum ctables_summary_function function,
933                                double percentile)
934 {
935   static const char *default_labels[] = {
936 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = LABEL,
937     SUMMARIES
938 #undef S
939   };
940
941   return (function == CTSF_PTILE
942           ? xasprintf (_("Percentile %.2f"), percentile)
943           : xstrdup (gettext (default_labels[function])));
944 }
945
946 static const char *
947 ctables_summary_function_name (enum ctables_summary_function function)
948 {
949   static const char *names[] = {
950 #define S(ENUM, NAME, LABEL, FORMAT, AVAILABILITY) [ENUM] = NAME,
951     SUMMARIES
952 #undef S
953   };
954   return names[function];
955 }
956
957 static bool
958 add_summary_spec (struct ctables_axis *axis,
959                   enum ctables_summary_function function, double percentile,
960                   const char *label, const struct fmt_spec *format,
961                   bool is_ctables_format, const struct msg_location *loc,
962                   enum ctables_summary_variant sv)
963 {
964   if (axis->op == CTAO_VAR)
965     {
966       const char *function_name = ctables_summary_function_name (function);
967       const char *var_name = ctables_var_name (&axis->var);
968       switch (ctables_function_availability (function))
969         {
970         case CTFA_MRSETS:
971           if (!axis->var.is_mrset)
972             {
973               msg_at (SE, loc, _("Summary function %s applies only to multiple "
974                                  "response sets."), function_name);
975               msg_at (SN, axis->loc, _("'%s' is not a multiple response set."),
976                       var_name);
977               return false;
978             }
979           break;
980
981         case CTFA_SCALE:
982           if (!axis->scale)
983             {
984               msg_at (SE, loc,
985                       _("Summary function %s applies only to scale variables."),
986                       function_name);
987               msg_at (SN, axis->loc, _("'%s' is not a scale variable."),
988                       var_name);
989               return false;
990             }
991           break;
992
993         case CTFA_ALL:
994           break;
995         }
996
997       struct ctables_summary_spec_set *set = &axis->specs[sv];
998       if (set->n >= set->allocated)
999         set->specs = x2nrealloc (set->specs, &set->allocated,
1000                                  sizeof *set->specs);
1001
1002       struct ctables_summary_spec *dst = &set->specs[set->n++];
1003       *dst = (struct ctables_summary_spec) {
1004         .function = function,
1005         .percentile = percentile,
1006         .label = xstrdup (label),
1007         .format = (format ? *format
1008                    : ctables_summary_default_format (function, &axis->var)),
1009         .is_ctables_format = is_ctables_format,
1010       };
1011       return true;
1012     }
1013   else
1014     {
1015       for (size_t i = 0; i < 2; i++)
1016         if (!add_summary_spec (axis->subs[i], function, percentile, label,
1017                                format, is_ctables_format, loc, sv))
1018           return false;
1019       return true;
1020     }
1021 }
1022
1023 static struct ctables_axis *ctables_axis_parse_stack (
1024   struct ctables_axis_parse_ctx *);
1025
1026 static bool
1027 ctables_var_parse (struct lexer *lexer, struct dictionary *dict,
1028                    struct ctables_var *var)
1029 {
1030   if (ss_starts_with (lex_tokss (lexer), ss_cstr ("$")))
1031     {
1032       *var = (struct ctables_var) {
1033         .is_mrset = true,
1034         .mrset = dict_lookup_mrset (dict, lex_tokcstr (lexer))
1035       };
1036       if (!var->mrset)
1037         {
1038           lex_error (lexer, _("'%s' does not name a multiple-response set "
1039                               "in the active file dictionary."),
1040                      lex_tokcstr (lexer));
1041           return false;
1042         }
1043       lex_get (lexer);
1044       return true;
1045     }
1046   else
1047     {
1048       *var = (struct ctables_var) {
1049         .is_mrset = false,
1050         .var = parse_variable (lexer, dict),
1051       };
1052       return var->var != NULL;
1053     }
1054 }
1055
1056 static struct ctables_axis *
1057 ctables_axis_parse_primary (struct ctables_axis_parse_ctx *ctx)
1058 {
1059   if (lex_match (ctx->lexer, T_LPAREN))
1060     {
1061       struct ctables_axis *sub = ctables_axis_parse_stack (ctx);
1062       if (!sub || !lex_force_match (ctx->lexer, T_RPAREN))
1063         {
1064           ctables_axis_destroy (sub);
1065           return NULL;
1066         }
1067       return sub;
1068     }
1069
1070   if (!lex_force_id (ctx->lexer))
1071     return NULL;
1072
1073   int start_ofs = lex_ofs (ctx->lexer);
1074   struct ctables_var var;
1075   if (!ctables_var_parse (ctx->lexer, ctx->dict, &var))
1076     return NULL;
1077
1078   struct ctables_axis *axis = xmalloc (sizeof *axis);
1079   *axis = (struct ctables_axis) { .op = CTAO_VAR, .var = var };
1080
1081   /* XXX should figure out default measures by reading data */
1082   axis->scale = (var.is_mrset ? false
1083                  : lex_match_phrase (ctx->lexer, "[S]") ? true
1084                  : lex_match_phrase (ctx->lexer, "[C]") ? false
1085                  : var_get_measure (var.var) == MEASURE_SCALE);
1086   axis->loc = lex_ofs_location (ctx->lexer, start_ofs,
1087                                 lex_ofs (ctx->lexer) - 1);
1088   return axis;
1089 }
1090
1091 static bool
1092 has_digit (const char *s)
1093 {
1094   return s[strcspn (s, "0123456789")] != '\0';
1095 }
1096
1097 static bool
1098 parse_ctables_format_specifier (struct lexer *lexer, struct fmt_spec *format,
1099                                 bool *is_ctables_format)
1100 {
1101   char type[FMT_TYPE_LEN_MAX + 1];
1102   if (!parse_abstract_format_specifier__ (lexer, type, &format->w, &format->d))
1103     return false;
1104
1105   if (!strcasecmp (type, "NEGPAREN"))
1106     format->type = CTEF_NEGPAREN;
1107   else if (!strcasecmp (type, "NEQUAL"))
1108     format->type = CTEF_NEQUAL;
1109   else if (!strcasecmp (type, "PAREN"))
1110     format->type = CTEF_PAREN;
1111   else if (!strcasecmp (type, "PCTPAREN"))
1112     format->type = CTEF_PCTPAREN;
1113   else
1114     {
1115       *is_ctables_format = false;
1116       return (parse_format_specifier (lexer, format)
1117               && fmt_check_output (format)
1118               && fmt_check_type_compat (format, VAL_NUMERIC));
1119     }
1120
1121   if (format->w < 2)
1122     {
1123       msg (SE, _("Output format %s requires width 2 or greater."), type);
1124       return false;
1125     }
1126   else if (format->d > format->w - 1)
1127     {
1128       msg (SE, _("Output format %s requires width greater than decimals."),
1129            type);
1130       return false;
1131     }
1132   else
1133     {
1134       *is_ctables_format = true;
1135       return true;
1136     }
1137 }
1138
1139 static struct ctables_axis *
1140 ctables_axis_parse_postfix (struct ctables_axis_parse_ctx *ctx)
1141 {
1142   struct ctables_axis *sub = ctables_axis_parse_primary (ctx);
1143   if (!sub || !lex_match (ctx->lexer, T_LBRACK))
1144     return sub;
1145
1146   enum ctables_summary_variant sv = CSV_CELL;
1147   for (;;)
1148     {
1149       int start_ofs = lex_ofs (ctx->lexer);
1150
1151       /* Parse function. */
1152       enum ctables_summary_function function;
1153       if (!parse_ctables_summary_function (ctx->lexer, &function))
1154         goto error;
1155
1156       /* Parse percentile. */
1157       double percentile = 0;
1158       if (function == CTSF_PTILE)
1159         {
1160           if (!lex_force_num_range_closed (ctx->lexer, "PTILE", 0, 100))
1161             goto error;
1162           percentile = lex_number (ctx->lexer);
1163           lex_get (ctx->lexer);
1164         }
1165
1166       /* Parse label. */
1167       char *label;
1168       if (lex_is_string (ctx->lexer))
1169         {
1170           label = ss_xstrdup (lex_tokss (ctx->lexer));
1171           lex_get (ctx->lexer);
1172         }
1173       else
1174         label = ctables_summary_default_label (function, percentile);
1175
1176       /* Parse format. */
1177       struct fmt_spec format;
1178       const struct fmt_spec *formatp;
1179       bool is_ctables_format = false;
1180       if (lex_token (ctx->lexer) == T_ID
1181           && has_digit (lex_tokcstr (ctx->lexer)))
1182         {
1183           if (!parse_ctables_format_specifier (ctx->lexer, &format,
1184                                                &is_ctables_format))
1185             {
1186               free (label);
1187               goto error;
1188             }
1189           formatp = &format;
1190         }
1191       else
1192         formatp = NULL;
1193
1194       struct msg_location *loc = lex_ofs_location (ctx->lexer, start_ofs,
1195                                                    lex_ofs (ctx->lexer) - 1);
1196       add_summary_spec (sub, function, percentile, label, formatp,
1197                         is_ctables_format, loc, sv);
1198       free (label);
1199       msg_location_destroy (loc);
1200
1201       lex_match (ctx->lexer, T_COMMA);
1202       if (sv == CSV_CELL && lex_match_id (ctx->lexer, "TOTALS"))
1203         {
1204           if (!lex_force_match (ctx->lexer, T_LBRACK))
1205             goto error;
1206           sv = CSV_TOTAL;
1207         }
1208       else if (lex_match (ctx->lexer, T_RBRACK))
1209         {
1210           if (sv == CSV_TOTAL && !lex_force_match (ctx->lexer, T_RBRACK))
1211             goto error;
1212           return sub;
1213         }
1214     }
1215
1216 error:
1217   ctables_axis_destroy (sub);
1218   return NULL;
1219 }
1220
1221 static const struct ctables_axis *
1222 find_scale (const struct ctables_axis *axis)
1223 {
1224   if (!axis)
1225     return NULL;
1226   else if (axis->op == CTAO_VAR)
1227     {
1228       if (axis->scale)
1229         {
1230           assert (!axis->var.is_mrset);
1231           return axis;
1232         }
1233       else
1234         return NULL;
1235     }
1236   else
1237     {
1238       for (size_t i = 0; i < 2; i++)
1239         {
1240           const struct ctables_axis *scale = find_scale (axis->subs[i]);
1241           if (scale)
1242             return scale;
1243         }
1244       return NULL;
1245     }
1246 }
1247
1248 static const struct ctables_axis *
1249 find_categorical_summary_spec (const struct ctables_axis *axis)
1250 {
1251   if (!axis)
1252     return NULL;
1253   else if (axis->op == CTAO_VAR)
1254     return !axis->scale && axis->specs[CSV_CELL].n ? axis : NULL;
1255   else
1256     {
1257       for (size_t i = 0; i < 2; i++)
1258         {
1259           const struct ctables_axis *sum
1260             = find_categorical_summary_spec (axis->subs[i]);
1261           if (sum)
1262             return sum;
1263         }
1264       return NULL;
1265     }
1266 }
1267
1268 static struct ctables_axis *
1269 ctables_axis_parse_nest (struct ctables_axis_parse_ctx *ctx)
1270 {
1271   int start_ofs = lex_ofs (ctx->lexer);
1272   struct ctables_axis *lhs = ctables_axis_parse_postfix (ctx);
1273   if (!lhs)
1274     return NULL;
1275
1276   while (lex_match (ctx->lexer, T_GT))
1277     {
1278       struct ctables_axis *rhs = ctables_axis_parse_postfix (ctx);
1279       if (!rhs)
1280         return NULL;
1281
1282       struct ctables_axis *nest = ctables_axis_new_nonterminal (
1283         CTAO_NEST, lhs, rhs, ctx->lexer, start_ofs);
1284
1285       const struct ctables_axis *outer_scale = find_scale (lhs);
1286       const struct ctables_axis *inner_scale = find_scale (rhs);
1287       if (outer_scale && inner_scale)
1288         {
1289           msg_at (SE, nest->loc, _("Cannot nest scale variables."));
1290           msg_at (SN, outer_scale->loc, _("This is an outer scale variable."));
1291           msg_at (SN, inner_scale->loc, _("This is an inner scale variable."));
1292           ctables_axis_destroy (nest);
1293           return NULL;
1294         }
1295
1296       const struct ctables_axis *outer_sum = find_categorical_summary_spec (lhs);
1297       if (outer_sum)
1298         {
1299           msg_at (SE, nest->loc,
1300                   _("Summaries may only be requested for categorical variables "
1301                     "at the innermost nesting level."));
1302           msg_at (SN, outer_sum->loc,
1303                   _("This outer categorical variable has a summary."));
1304           ctables_axis_destroy (nest);
1305           return NULL;
1306         }
1307
1308       lhs = nest;
1309     }
1310
1311   return lhs;
1312 }
1313
1314 static struct ctables_axis *
1315 ctables_axis_parse_stack (struct ctables_axis_parse_ctx *ctx)
1316 {
1317   int start_ofs = lex_ofs (ctx->lexer);
1318   struct ctables_axis *lhs = ctables_axis_parse_nest (ctx);
1319   if (!lhs)
1320     return NULL;
1321
1322   while (lex_match (ctx->lexer, T_PLUS))
1323     {
1324       struct ctables_axis *rhs = ctables_axis_parse_nest (ctx);
1325       if (!rhs)
1326         return NULL;
1327
1328       lhs = ctables_axis_new_nonterminal (CTAO_STACK, lhs, rhs,
1329                                           ctx->lexer, start_ofs);
1330     }
1331
1332   return lhs;
1333 }
1334
1335 static bool
1336 ctables_axis_parse (struct lexer *lexer, struct dictionary *dict,
1337                     struct ctables *ct, struct ctables_table *t,
1338                     enum pivot_axis_type a)
1339 {
1340   if (lex_token (lexer) == T_BY
1341       || lex_token (lexer) == T_SLASH
1342       || lex_token (lexer) == T_ENDCMD)
1343     return true;
1344
1345   struct ctables_axis_parse_ctx ctx = {
1346     .lexer = lexer,
1347     .dict = dict,
1348     .ct = ct,
1349     .t = t
1350   };
1351   t->axes[a] = ctables_axis_parse_stack (&ctx);
1352   return t->axes[a] != NULL;
1353 }
1354
1355 static void
1356 ctables_chisq_destroy (struct ctables_chisq *chisq)
1357 {
1358   free (chisq);
1359 }
1360
1361 static void
1362 ctables_pairwise_destroy (struct ctables_pairwise *pairwise)
1363 {
1364   free (pairwise);
1365 }
1366
1367 static void
1368 ctables_table_destroy (struct ctables_table *t)
1369 {
1370   if (!t)
1371     return;
1372
1373   for (size_t i = 0; i < t->n_categories; i++)
1374     ctables_categories_unref (t->categories[i]);
1375   free (t->categories);
1376
1377   ctables_axis_destroy (t->axes[PIVOT_AXIS_COLUMN]);
1378   ctables_axis_destroy (t->axes[PIVOT_AXIS_ROW]);
1379   ctables_axis_destroy (t->axes[PIVOT_AXIS_LAYER]);
1380   free (t->caption);
1381   free (t->corner);
1382   free (t->title);
1383   ctables_chisq_destroy (t->chisq);
1384   ctables_pairwise_destroy (t->pairwise);
1385   free (t);
1386 }
1387
1388 static void
1389 ctables_destroy (struct ctables *ct)
1390 {
1391   if (!ct)
1392     return;
1393
1394   pivot_table_look_unref (ct->look);
1395   free (ct->zero);
1396   free (ct->missing);
1397   free (ct->vlabels);
1398   for (size_t i = 0; i < ct->n_tables; i++)
1399     ctables_table_destroy (ct->tables[i]);
1400   free (ct->tables);
1401   free (ct);
1402 }
1403
1404 static struct ctables_category
1405 cct_range (double low, double high)
1406 {
1407   return (struct ctables_category) {
1408     .type = CCT_RANGE,
1409     .range = { low, high }
1410   };
1411 }
1412
1413 static bool
1414 ctables_table_parse_subtotal (struct lexer *lexer, bool hide_subcategories,
1415                               struct ctables_category *cat)
1416 {
1417   char *total_label;
1418   if (lex_match (lexer, T_EQUALS))
1419     {
1420       if (!lex_force_string (lexer))
1421         return false;
1422
1423       total_label = ss_xstrdup (lex_tokss (lexer));
1424       lex_get (lexer);
1425     }
1426   else
1427     total_label = xstrdup (_("Subtotal"));
1428
1429   *cat = (struct ctables_category) {
1430     .type = CCT_SUBTOTAL,
1431     .hide_subcategories = hide_subcategories,
1432     .total_label = total_label
1433   };
1434   return true;
1435 }
1436
1437 static bool
1438 ctables_table_parse_explicit_category (struct lexer *lexer, struct ctables *ct,
1439                                        struct ctables_category *cat)
1440 {
1441   if (lex_match_id (lexer, "OTHERNM"))
1442     *cat = (struct ctables_category) { .type = CCT_OTHERNM };
1443   else if (lex_match_id (lexer, "MISSING"))
1444     *cat = (struct ctables_category) { .type = CCT_MISSING };
1445   else if (lex_match_id (lexer, "SUBTOTAL"))
1446     return ctables_table_parse_subtotal (lexer, false, cat);
1447   else if (lex_match_id (lexer, "HSUBTOTAL"))
1448     return ctables_table_parse_subtotal (lexer, true, cat);
1449   else if (lex_match_id (lexer, "LO"))
1450     {
1451       if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
1452         return false;
1453       *cat = cct_range (-DBL_MAX, lex_number (lexer));
1454       lex_get (lexer);
1455     }
1456   else if (lex_is_number (lexer))
1457     {
1458       double number = lex_number (lexer);
1459       lex_get (lexer);
1460       if (lex_match_id (lexer, "THRU"))
1461         {
1462           if (lex_match_id (lexer, "HI"))
1463             *cat = cct_range (number, DBL_MAX);
1464           else
1465             {
1466               if (!lex_force_num (lexer))
1467                 return false;
1468               *cat = cct_range (number, lex_number (lexer));
1469               lex_get (lexer);
1470             }
1471         }
1472       else
1473         *cat = (struct ctables_category) {
1474           .type = CCT_NUMBER,
1475           .number = number
1476         };
1477     }
1478   else if (lex_is_string (lexer))
1479     {
1480       *cat = (struct ctables_category) {
1481         .type = CCT_STRING,
1482         .string = ss_xstrdup (lex_tokss (lexer)),
1483       };
1484       lex_get (lexer);
1485     }
1486   else if (lex_match (lexer, T_AND))
1487     {
1488       if (!lex_force_id (lexer))
1489         return false;
1490       struct ctables_postcompute *pc = ctables_find_postcompute (
1491         ct, lex_tokcstr (lexer));
1492       if (!pc)
1493         {
1494           struct msg_location *loc = lex_get_location (lexer, -1, 0);
1495           msg_at (SE, loc, _("Unknown postcompute &%s."),
1496                   lex_tokcstr (lexer));
1497           msg_location_destroy (loc);
1498           return false;
1499         }
1500       lex_get (lexer);
1501
1502       *cat = (struct ctables_category) { .type = CCT_POSTCOMPUTE, .pc = pc };
1503     }
1504   else
1505     {
1506       lex_error (lexer, NULL);
1507       return false;
1508     }
1509
1510   return true;
1511 }
1512
1513 static struct ctables_category *
1514 ctables_find_category_for_postcompute (const struct ctables_categories *cats,
1515                                        const struct ctables_pcexpr *e)
1516 {
1517   struct ctables_category *best = NULL;
1518   size_t n_subtotals = 0;
1519   for (size_t i = 0; i < cats->n_cats; i++)
1520     {
1521       struct ctables_category *cat = &cats->cats[i];
1522       switch (e->op)
1523         {
1524         case CTPO_CAT_NUMBER:
1525           if (cat->type == CCT_NUMBER && cat->number == e->number)
1526             best = cat;
1527           break;
1528
1529         case CTPO_CAT_STRING:
1530           if (cat->type == CCT_STRING && !strcmp (cat->string, e->string))
1531             best = cat;
1532           break;
1533
1534         case CTPO_CAT_RANGE:
1535           if (cat->type == CCT_RANGE
1536               && cat->range[0] == e->range[0]
1537               && cat->range[1] == e->range[1])
1538             best = cat;
1539           break;
1540
1541         case CTPO_CAT_MISSING:
1542           if (cat->type == CCT_MISSING)
1543             best = cat;
1544           break;
1545
1546         case CTPO_CAT_OTHERNM:
1547           if (cat->type == CCT_OTHERNM)
1548             best = cat;
1549           break;
1550
1551         case CTPO_CAT_SUBTOTAL:
1552           if (cat->type == CCT_SUBTOTAL)
1553             {
1554               n_subtotals++;
1555               if (e->subtotal_index == n_subtotals)
1556                 return cat;
1557               else if (e->subtotal_index == 0)
1558                 best = cat;
1559             }
1560           break;
1561
1562         case CTPO_CAT_TOTAL:
1563           if (cat->type == CCT_TOTAL)
1564             return cat;
1565           break;
1566
1567         case CTPO_CONSTANT:
1568         case CTPO_ADD:
1569         case CTPO_SUB:
1570         case CTPO_MUL:
1571         case CTPO_DIV:
1572         case CTPO_POW:
1573         case CTPO_NEG:
1574           NOT_REACHED ();
1575         }
1576     }
1577   if (e->op == CTPO_CAT_SUBTOTAL && e->subtotal_index == 0 && n_subtotals > 1)
1578     return NULL;
1579   return best;
1580 }
1581
1582 static bool
1583 ctables_recursive_check_postcompute (const struct ctables_pcexpr *e,
1584                                      struct ctables_category *pc_cat,
1585                                      const struct ctables_categories *cats,
1586                                      const struct msg_location *cats_location)
1587 {
1588   switch (e->op)
1589     {
1590     case CTPO_CAT_NUMBER:
1591     case CTPO_CAT_STRING:
1592     case CTPO_CAT_RANGE:
1593     case CTPO_CAT_MISSING:
1594     case CTPO_CAT_OTHERNM:
1595     case CTPO_CAT_SUBTOTAL:
1596     case CTPO_CAT_TOTAL:
1597       {
1598         struct ctables_category *cat = ctables_find_category_for_postcompute (
1599           cats, e);
1600         if (!cat)
1601           {
1602             if (e->op == CTPO_CAT_SUBTOTAL && e->subtotal_index == 0)
1603               {
1604                 size_t n_subtotals = 0;
1605                 for (size_t i = 0; i < cats->n_cats; i++)
1606                   n_subtotals += cats->cats[i].type == CCT_SUBTOTAL;
1607                 if (n_subtotals > 1)
1608                   {
1609                     msg_at (SE, cats_location,
1610                             ngettext ("These categories include %zu instance "
1611                                       "of SUBTOTAL or HSUBTOTAL, so references "
1612                                       "from computed categories must refer to "
1613                                       "subtotals by position.",
1614                                       "These categories include %zu instances "
1615                                       "of SUBTOTAL or HSUBTOTAL, so references "
1616                                       "from computed categories must refer to "
1617                                       "subtotals by position.",
1618                                       n_subtotals),
1619                             n_subtotals);
1620                     msg_at (SN, e->location,
1621                             _("This is the reference that lacks a position."));
1622                     return NULL;
1623                   }
1624               }
1625
1626             msg_at (SE, pc_cat->location,
1627                     _("Computed category &%s references a category not included "
1628                       "in the category list."),
1629                     pc_cat->pc->name);
1630             msg_at (SN, e->location, _("This is the missing category."));
1631             msg_at (SN, cats_location,
1632                     _("To fix the problem, add the missing category to the "
1633                       "list of categories here."));
1634             return false;
1635           }
1636         if (pc_cat->pc->hide_source_cats)
1637           cat->hide = true;
1638         return true;
1639       }
1640
1641     case CTPO_CONSTANT:
1642       return true;
1643
1644     case CTPO_ADD:
1645     case CTPO_SUB:
1646     case CTPO_MUL:
1647     case CTPO_DIV:
1648     case CTPO_POW:
1649     case CTPO_NEG:
1650       for (size_t i = 0; i < 2; i++)
1651         if (e->subs[i] && !ctables_recursive_check_postcompute (
1652               e->subs[i], pc_cat, cats, cats_location))
1653           return false;
1654       return true;
1655
1656     default:
1657       NOT_REACHED ();
1658     }
1659 }
1660
1661 static bool
1662 ctables_table_parse_categories (struct lexer *lexer, struct dictionary *dict,
1663                                 struct ctables *ct, struct ctables_table *t)
1664 {
1665   if (!lex_match_id (lexer, "VARIABLES"))
1666     return false;
1667   lex_match (lexer, T_EQUALS);
1668
1669   struct variable **vars;
1670   size_t n_vars;
1671   if (!parse_variables (lexer, dict, &vars, &n_vars, PV_NO_SCRATCH))
1672     return false;
1673
1674   struct ctables_categories *c = xmalloc (sizeof *c);
1675   *c = (struct ctables_categories) { .n_refs = n_vars, .show_empty = true };
1676   for (size_t i = 0; i < n_vars; i++)
1677     {
1678       struct ctables_categories **cp
1679         = &t->categories[var_get_dict_index (vars[i])];
1680       ctables_categories_unref (*cp);
1681       *cp = c;
1682     }
1683   free (vars);
1684
1685   size_t allocated_cats = 0;
1686   if (lex_match (lexer, T_LBRACK))
1687     {
1688       int cats_start_ofs = lex_ofs (lexer);
1689       do
1690         {
1691           if (c->n_cats >= allocated_cats)
1692             c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1693
1694           int start_ofs = lex_ofs (lexer);
1695           struct ctables_category *cat = &c->cats[c->n_cats];
1696           if (!ctables_table_parse_explicit_category (lexer, ct, cat))
1697             return false;
1698           cat->location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1);
1699           c->n_cats++;
1700
1701           lex_match (lexer, T_COMMA);
1702         }
1703       while (!lex_match (lexer, T_RBRACK));
1704
1705       struct msg_location *cats_location
1706         = lex_ofs_location (lexer, cats_start_ofs, lex_ofs (lexer) - 1);
1707       for (size_t i = 0; i < c->n_cats; i++)
1708         {
1709           struct ctables_category *cat = &c->cats[i];
1710           if (cat->type == CCT_POSTCOMPUTE
1711               && !ctables_recursive_check_postcompute (cat->pc->expr, cat,
1712                                                        c, cats_location))
1713             return false;
1714         }
1715     }
1716
1717   struct ctables_category cat = {
1718     .type = CCT_VALUE,
1719     .include_missing = false,
1720     .sort_ascending = true,
1721   };
1722   bool show_totals = false;
1723   char *total_label = NULL;
1724   bool totals_before = false;
1725   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
1726     {
1727       if (!c->n_cats && lex_match_id (lexer, "ORDER"))
1728         {
1729           lex_match (lexer, T_EQUALS);
1730           if (lex_match_id (lexer, "A"))
1731             cat.sort_ascending = true;
1732           else if (lex_match_id (lexer, "D"))
1733             cat.sort_ascending = false;
1734           else
1735             {
1736               lex_error_expecting (lexer, "A", "D");
1737               return false;
1738             }
1739         }
1740       else if (!c->n_cats && lex_match_id (lexer, "KEY"))
1741         {
1742           lex_match (lexer, T_EQUALS);
1743           if (lex_match_id (lexer, "VALUE"))
1744             cat.type = CCT_VALUE;
1745           else if (lex_match_id (lexer, "LABEL"))
1746             cat.type = CCT_LABEL;
1747           else
1748             {
1749               cat.type = CCT_FUNCTION;
1750               if (!parse_ctables_summary_function (lexer, &cat.sort_function))
1751                 return false;
1752
1753               if (lex_match (lexer, T_LPAREN))
1754                 {
1755                   cat.sort_var = parse_variable (lexer, dict);
1756                   if (!cat.sort_var)
1757                     return false;
1758
1759                   if (cat.sort_function == CTSF_PTILE)
1760                     {
1761                       lex_match (lexer, T_COMMA);
1762                       if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
1763                         return false;
1764                       cat.percentile = lex_number (lexer);
1765                       lex_get (lexer);
1766                     }
1767
1768                   if (!lex_force_match (lexer, T_RPAREN))
1769                     return false;
1770                 }
1771               else if (ctables_function_availability (cat.sort_function)
1772                        == CTFA_SCALE)
1773                 {
1774                   bool UNUSED b = lex_force_match (lexer, T_LPAREN);
1775                   return false;
1776                 }
1777             }
1778         }
1779       else if (!c->n_cats && lex_match_id (lexer, "MISSING"))
1780         {
1781           lex_match (lexer, T_EQUALS);
1782           if (lex_match_id (lexer, "INCLUDE"))
1783             cat.include_missing = true;
1784           else if (lex_match_id (lexer, "EXCLUDE"))
1785             cat.include_missing = false;
1786           else
1787             {
1788               lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1789               return false;
1790             }
1791         }
1792       else if (lex_match_id (lexer, "TOTAL"))
1793         {
1794           lex_match (lexer, T_EQUALS);
1795           if (!parse_bool (lexer, &show_totals))
1796             return false;
1797         }
1798       else if (lex_match_id (lexer, "LABEL"))
1799         {
1800           lex_match (lexer, T_EQUALS);
1801           if (!lex_force_string (lexer))
1802             return false;
1803           free (total_label);
1804           total_label = ss_xstrdup (lex_tokss (lexer));
1805           lex_get (lexer);
1806         }
1807       else if (lex_match_id (lexer, "POSITION"))
1808         {
1809           lex_match (lexer, T_EQUALS);
1810           if (lex_match_id (lexer, "BEFORE"))
1811             totals_before = true;
1812           else if (lex_match_id (lexer, "AFTER"))
1813             totals_before = false;
1814           else
1815             {
1816               lex_error_expecting (lexer, "BEFORE", "AFTER");
1817               return false;
1818             }
1819         }
1820       else if (lex_match_id (lexer, "EMPTY"))
1821         {
1822           lex_match (lexer, T_EQUALS);
1823           if (lex_match_id (lexer, "INCLUDE"))
1824             c->show_empty = true;
1825           else if (lex_match_id (lexer, "EXCLUDE"))
1826             c->show_empty = false;
1827           else
1828             {
1829               lex_error_expecting (lexer, "INCLUDE", "EXCLUDE");
1830               return false;
1831             }
1832         }
1833       else
1834         {
1835           if (!c->n_cats)
1836             lex_error_expecting (lexer, "ORDER", "KEY", "MISSING",
1837                                  "TOTAL", "LABEL", "POSITION", "EMPTY");
1838           else
1839             lex_error_expecting (lexer, "TOTAL", "LABEL", "POSITION", "EMPTY");
1840           return false;
1841         }
1842     }
1843
1844   if (!c->n_cats)
1845     {
1846       if (c->n_cats >= allocated_cats)
1847         c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1848       c->cats[c->n_cats++] = cat;
1849     }
1850
1851   if (show_totals)
1852     {
1853       if (c->n_cats >= allocated_cats)
1854         c->cats = x2nrealloc (c->cats, &allocated_cats, sizeof *c->cats);
1855
1856       struct ctables_category *totals;
1857       if (totals_before)
1858         {
1859           insert_element (c->cats, c->n_cats, sizeof *c->cats, 0);
1860           totals = &c->cats[0];
1861         }
1862       else
1863         totals = &c->cats[c->n_cats];
1864       c->n_cats++;
1865
1866       *totals = (struct ctables_category) {
1867         .type = CCT_TOTAL,
1868         .total_label = total_label ? total_label : xstrdup (_("Total")),
1869       };
1870     }
1871
1872   struct ctables_category *subtotal = NULL;
1873   for (size_t i = totals_before ? 0 : c->n_cats;
1874        totals_before ? i < c->n_cats : i-- > 0;
1875        totals_before ? i++ : 0)
1876     {
1877       struct ctables_category *cat = &c->cats[i];
1878       switch (cat->type)
1879         {
1880         case CCT_NUMBER:
1881         case CCT_STRING:
1882         case CCT_RANGE:
1883         case CCT_MISSING:
1884         case CCT_OTHERNM:
1885           cat->subtotal = subtotal;
1886           break;
1887
1888         case CCT_POSTCOMPUTE:
1889           break;
1890
1891         case CCT_SUBTOTAL:
1892           subtotal = cat;
1893           break;
1894
1895         case CCT_TOTAL:
1896         case CCT_VALUE:
1897         case CCT_LABEL:
1898         case CCT_FUNCTION:
1899           break;
1900         }
1901     }
1902
1903   return true;
1904 }
1905
1906 static void
1907 ctables_nest_uninit (struct ctables_nest *nest)
1908 {
1909   if (nest)
1910     free (nest->vars);
1911 }
1912
1913 static void
1914 ctables_stack_uninit (struct ctables_stack *stack)
1915 {
1916   if (stack)
1917     {
1918       for (size_t i = 0; i < stack->n; i++)
1919         ctables_nest_uninit (&stack->nests[i]);
1920       free (stack->nests);
1921     }
1922 }
1923
1924 static struct ctables_stack
1925 nest_fts (struct ctables_stack s0, struct ctables_stack s1)
1926 {
1927   if (!s0.n)
1928     return s1;
1929   else if (!s1.n)
1930     return s0;
1931
1932   struct ctables_stack stack = { .nests = xnmalloc (s0.n, s1.n * sizeof *stack.nests) };
1933   for (size_t i = 0; i < s0.n; i++)
1934     for (size_t j = 0; j < s1.n; j++)
1935       {
1936         const struct ctables_nest *a = &s0.nests[i];
1937         const struct ctables_nest *b = &s1.nests[j];
1938
1939         size_t allocate = a->n + b->n;
1940         struct variable **vars = xnmalloc (allocate, sizeof *vars);
1941         enum pivot_axis_type *axes = xnmalloc (allocate, sizeof *axes);
1942         size_t n = 0;
1943         for (size_t k = 0; k < a->n; k++)
1944           vars[n++] = a->vars[k];
1945         for (size_t k = 0; k < b->n; k++)
1946           vars[n++] = b->vars[k];
1947         assert (n == allocate);
1948
1949         const struct ctables_nest *summary_src;
1950         if (!a->specs[CSV_CELL].var)
1951           summary_src = b;
1952         else if (!b->specs[CSV_CELL].var)
1953           summary_src = a;
1954         else
1955           NOT_REACHED ();
1956
1957         struct ctables_nest *new = &stack.nests[stack.n++];
1958         *new = (struct ctables_nest) {
1959           .vars = vars,
1960           .scale_idx = (a->scale_idx != SIZE_MAX ? a->scale_idx
1961                         : b->scale_idx != SIZE_MAX ? a->n + b->scale_idx
1962                         : SIZE_MAX),
1963           .n = n,
1964         };
1965         for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
1966           ctables_summary_spec_set_clone (&new->specs[sv], &summary_src->specs[sv]);
1967       }
1968   ctables_stack_uninit (&s0);
1969   ctables_stack_uninit (&s1);
1970   return stack;
1971 }
1972
1973 static struct ctables_stack
1974 stack_fts (struct ctables_stack s0, struct ctables_stack s1)
1975 {
1976   struct ctables_stack stack = { .nests = xnmalloc (s0.n + s1.n, sizeof *stack.nests) };
1977   for (size_t i = 0; i < s0.n; i++)
1978     stack.nests[stack.n++] = s0.nests[i];
1979   for (size_t i = 0; i < s1.n; i++)
1980     stack.nests[stack.n++] = s1.nests[i];
1981   assert (stack.n == s0.n + s1.n);
1982   free (s0.nests);
1983   free (s1.nests);
1984   return stack;
1985 }
1986
1987 static struct ctables_stack
1988 enumerate_fts (enum pivot_axis_type axis_type, const struct ctables_axis *a)
1989 {
1990   if (!a)
1991     return (struct ctables_stack) { .n = 0 };
1992
1993   switch (a->op)
1994     {
1995     case CTAO_VAR:
1996       assert (!a->var.is_mrset);
1997
1998       struct variable **vars = xmalloc (sizeof *vars);
1999       *vars = a->var.var;
2000
2001       struct ctables_nest *nest = xmalloc (sizeof *nest);
2002       *nest = (struct ctables_nest) {
2003         .vars = vars,
2004         .n = 1,
2005         .scale_idx = a->scale ? 0 : SIZE_MAX,
2006       };
2007       if (a->specs[CSV_CELL].n || a->scale)
2008         for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
2009           {
2010             ctables_summary_spec_set_clone (&nest->specs[sv], &a->specs[sv]);
2011             nest->specs[sv].var = a->var.var;
2012           }
2013       return (struct ctables_stack) { .nests = nest, .n = 1 };
2014
2015     case CTAO_STACK:
2016       return stack_fts (enumerate_fts (axis_type, a->subs[0]),
2017                         enumerate_fts (axis_type, a->subs[1]));
2018
2019     case CTAO_NEST:
2020       return nest_fts (enumerate_fts (axis_type, a->subs[0]),
2021                        enumerate_fts (axis_type, a->subs[1]));
2022     }
2023
2024   NOT_REACHED ();
2025 }
2026
2027 union ctables_summary
2028   {
2029     /* COUNT, VALIDN, TOTALN. */
2030     struct
2031       {
2032         double valid;
2033         double missing;
2034       };
2035
2036     /* MINIMUM, MAXIMUM, RANGE. */
2037     struct
2038       {
2039         double min;
2040         double max;
2041       };
2042
2043     /* MEAN, SEMEAN, STDDEV, SUM, VARIANCE, *.SUM. */
2044     struct moments1 *moments;
2045
2046     /* MEDIAN, MODE, PTILE. */
2047     struct
2048       {
2049         struct casewriter *writer;
2050         double ovalid;
2051         double ovalue;
2052       };
2053
2054     /* XXX multiple response */
2055   };
2056
2057 static void
2058 ctables_summary_init (union ctables_summary *s,
2059                       const struct ctables_summary_spec *ss)
2060 {
2061   switch (ss->function)
2062     {
2063     case CTSF_COUNT:
2064     case CTSF_ECOUNT:
2065     case CTSF_ROWPCT_COUNT:
2066     case CTSF_COLPCT_COUNT:
2067     case CTSF_TABLEPCT_COUNT:
2068     case CTSF_SUBTABLEPCT_COUNT:
2069     case CTSF_LAYERPCT_COUNT:
2070     case CTSF_LAYERROWPCT_COUNT:
2071     case CTSF_LAYERCOLPCT_COUNT:
2072     case CTSF_ROWPCT_VALIDN:
2073     case CTSF_COLPCT_VALIDN:
2074     case CTSF_TABLEPCT_VALIDN:
2075     case CTSF_SUBTABLEPCT_VALIDN:
2076     case CTSF_LAYERPCT_VALIDN:
2077     case CTSF_LAYERROWPCT_VALIDN:
2078     case CTSF_LAYERCOLPCT_VALIDN:
2079     case CTSF_ROWPCT_TOTALN:
2080     case CTSF_COLPCT_TOTALN:
2081     case CTSF_TABLEPCT_TOTALN:
2082     case CTSF_SUBTABLEPCT_TOTALN:
2083     case CTSF_LAYERPCT_TOTALN:
2084     case CTSF_LAYERROWPCT_TOTALN:
2085     case CTSF_LAYERCOLPCT_TOTALN:
2086     case CTSF_MISSING:
2087     case CSTF_TOTALN:
2088     case CTSF_ETOTALN:
2089     case CTSF_VALIDN:
2090     case CTSF_EVALIDN:
2091       s->missing = s->valid = 0;
2092       break;
2093
2094     case CTSF_MAXIMUM:
2095     case CTSF_MINIMUM:
2096     case CTSF_RANGE:
2097       s->min = s->max = SYSMIS;
2098       break;
2099
2100     case CTSF_MEAN:
2101     case CTSF_SEMEAN:
2102     case CTSF_STDDEV:
2103     case CTSF_SUM:
2104     case CTSF_VARIANCE:
2105     case CTSF_ROWPCT_SUM:
2106     case CTSF_COLPCT_SUM:
2107     case CTSF_TABLEPCT_SUM:
2108     case CTSF_SUBTABLEPCT_SUM:
2109     case CTSF_LAYERPCT_SUM:
2110     case CTSF_LAYERROWPCT_SUM:
2111     case CTSF_LAYERCOLPCT_SUM:
2112       s->moments = moments1_create (MOMENT_VARIANCE);
2113       break;
2114
2115     case CTSF_MEDIAN:
2116     case CTSF_MODE:
2117     case CTSF_PTILE:
2118       {
2119         struct caseproto *proto = caseproto_create ();
2120         proto = caseproto_add_width (proto, 0);
2121         proto = caseproto_add_width (proto, 0);
2122
2123         struct subcase ordering;
2124         subcase_init (&ordering, 0, 0, SC_ASCEND);
2125         s->writer = sort_create_writer (&ordering, proto);
2126         subcase_uninit (&ordering);
2127         caseproto_unref (proto);
2128
2129         s->ovalid = 0;
2130         s->ovalue = SYSMIS;
2131       }
2132       break;
2133
2134     case CTSF_RESPONSES:
2135     case CTSF_ROWPCT_RESPONSES:
2136     case CTSF_COLPCT_RESPONSES:
2137     case CTSF_TABLEPCT_RESPONSES:
2138     case CTSF_SUBTABLEPCT_RESPONSES:
2139     case CTSF_LAYERPCT_RESPONSES:
2140     case CTSF_LAYERROWPCT_RESPONSES:
2141     case CTSF_LAYERCOLPCT_RESPONSES:
2142     case CTSF_ROWPCT_RESPONSES_COUNT:
2143     case CTSF_COLPCT_RESPONSES_COUNT:
2144     case CTSF_TABLEPCT_RESPONSES_COUNT:
2145     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2146     case CTSF_LAYERPCT_RESPONSES_COUNT:
2147     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2148     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2149     case CTSF_ROWPCT_COUNT_RESPONSES:
2150     case CTSF_COLPCT_COUNT_RESPONSES:
2151     case CTSF_TABLEPCT_COUNT_RESPONSES:
2152     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2153     case CTSF_LAYERPCT_COUNT_RESPONSES:
2154     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2155     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2156       NOT_REACHED ();
2157     }
2158 }
2159
2160 static void UNUSED
2161 ctables_summary_uninit (union ctables_summary *s,
2162                         const struct ctables_summary_spec *ss)
2163 {
2164   switch (ss->function)
2165     {
2166     case CTSF_COUNT:
2167     case CTSF_ECOUNT:
2168     case CTSF_ROWPCT_COUNT:
2169     case CTSF_COLPCT_COUNT:
2170     case CTSF_TABLEPCT_COUNT:
2171     case CTSF_SUBTABLEPCT_COUNT:
2172     case CTSF_LAYERPCT_COUNT:
2173     case CTSF_LAYERROWPCT_COUNT:
2174     case CTSF_LAYERCOLPCT_COUNT:
2175     case CTSF_ROWPCT_VALIDN:
2176     case CTSF_COLPCT_VALIDN:
2177     case CTSF_TABLEPCT_VALIDN:
2178     case CTSF_SUBTABLEPCT_VALIDN:
2179     case CTSF_LAYERPCT_VALIDN:
2180     case CTSF_LAYERROWPCT_VALIDN:
2181     case CTSF_LAYERCOLPCT_VALIDN:
2182     case CTSF_ROWPCT_TOTALN:
2183     case CTSF_COLPCT_TOTALN:
2184     case CTSF_TABLEPCT_TOTALN:
2185     case CTSF_SUBTABLEPCT_TOTALN:
2186     case CTSF_LAYERPCT_TOTALN:
2187     case CTSF_LAYERROWPCT_TOTALN:
2188     case CTSF_LAYERCOLPCT_TOTALN:
2189     case CTSF_MISSING:
2190     case CSTF_TOTALN:
2191     case CTSF_ETOTALN:
2192     case CTSF_VALIDN:
2193     case CTSF_EVALIDN:
2194       break;
2195
2196     case CTSF_MAXIMUM:
2197     case CTSF_MINIMUM:
2198     case CTSF_RANGE:
2199       break;
2200
2201     case CTSF_MEAN:
2202     case CTSF_SEMEAN:
2203     case CTSF_STDDEV:
2204     case CTSF_SUM:
2205     case CTSF_VARIANCE:
2206     case CTSF_ROWPCT_SUM:
2207     case CTSF_COLPCT_SUM:
2208     case CTSF_TABLEPCT_SUM:
2209     case CTSF_SUBTABLEPCT_SUM:
2210     case CTSF_LAYERPCT_SUM:
2211     case CTSF_LAYERROWPCT_SUM:
2212     case CTSF_LAYERCOLPCT_SUM:
2213       moments1_destroy (s->moments);
2214       break;
2215
2216     case CTSF_MEDIAN:
2217     case CTSF_MODE:
2218     case CTSF_PTILE:
2219       casewriter_destroy (s->writer);
2220       break;
2221
2222     case CTSF_RESPONSES:
2223     case CTSF_ROWPCT_RESPONSES:
2224     case CTSF_COLPCT_RESPONSES:
2225     case CTSF_TABLEPCT_RESPONSES:
2226     case CTSF_SUBTABLEPCT_RESPONSES:
2227     case CTSF_LAYERPCT_RESPONSES:
2228     case CTSF_LAYERROWPCT_RESPONSES:
2229     case CTSF_LAYERCOLPCT_RESPONSES:
2230     case CTSF_ROWPCT_RESPONSES_COUNT:
2231     case CTSF_COLPCT_RESPONSES_COUNT:
2232     case CTSF_TABLEPCT_RESPONSES_COUNT:
2233     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2234     case CTSF_LAYERPCT_RESPONSES_COUNT:
2235     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2236     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2237     case CTSF_ROWPCT_COUNT_RESPONSES:
2238     case CTSF_COLPCT_COUNT_RESPONSES:
2239     case CTSF_TABLEPCT_COUNT_RESPONSES:
2240     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2241     case CTSF_LAYERPCT_COUNT_RESPONSES:
2242     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2243     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2244       NOT_REACHED ();
2245     }
2246 }
2247
2248 static void
2249 ctables_summary_add (union ctables_summary *s,
2250                      const struct ctables_summary_spec *ss,
2251                      const struct variable *var, const union value *value,
2252                      double d_weight, double e_weight)
2253 {
2254   switch (ss->function)
2255     {
2256     case CTSF_COUNT:
2257     case CSTF_TOTALN:
2258     case CTSF_VALIDN:
2259       if (var_is_value_missing (var, value))
2260         s->missing += d_weight;
2261       else
2262         s->valid += d_weight;
2263       break;
2264
2265     case CTSF_ECOUNT:
2266     case CTSF_ROWPCT_COUNT:
2267     case CTSF_COLPCT_COUNT:
2268     case CTSF_TABLEPCT_COUNT:
2269     case CTSF_SUBTABLEPCT_COUNT:
2270     case CTSF_LAYERPCT_COUNT:
2271     case CTSF_LAYERROWPCT_COUNT:
2272     case CTSF_LAYERCOLPCT_COUNT:
2273     case CTSF_ROWPCT_VALIDN:
2274     case CTSF_COLPCT_VALIDN:
2275     case CTSF_TABLEPCT_VALIDN:
2276     case CTSF_SUBTABLEPCT_VALIDN:
2277     case CTSF_LAYERPCT_VALIDN:
2278     case CTSF_LAYERROWPCT_VALIDN:
2279     case CTSF_LAYERCOLPCT_VALIDN:
2280     case CTSF_ROWPCT_TOTALN:
2281     case CTSF_COLPCT_TOTALN:
2282     case CTSF_TABLEPCT_TOTALN:
2283     case CTSF_SUBTABLEPCT_TOTALN:
2284     case CTSF_LAYERPCT_TOTALN:
2285     case CTSF_LAYERROWPCT_TOTALN:
2286     case CTSF_LAYERCOLPCT_TOTALN:
2287     case CTSF_MISSING:
2288     case CTSF_ETOTALN:
2289     case CTSF_EVALIDN:
2290       if (var_is_value_missing (var, value))
2291         s->missing += e_weight;
2292       else
2293         s->valid += e_weight;
2294       break;
2295
2296     case CTSF_MAXIMUM:
2297     case CTSF_MINIMUM:
2298     case CTSF_RANGE:
2299       if (!var_is_value_missing (var, value))
2300         {
2301           assert (!var_is_alpha (var)); /* XXX? */
2302           if (s->min == SYSMIS || value->f < s->min)
2303             s->min = value->f;
2304           if (s->max == SYSMIS || value->f > s->max)
2305             s->max = value->f;
2306         }
2307       break;
2308
2309     case CTSF_MEAN:
2310     case CTSF_SEMEAN:
2311     case CTSF_STDDEV:
2312     case CTSF_SUM:
2313     case CTSF_VARIANCE:
2314     case CTSF_ROWPCT_SUM:
2315     case CTSF_COLPCT_SUM:
2316     case CTSF_TABLEPCT_SUM:
2317     case CTSF_SUBTABLEPCT_SUM:
2318     case CTSF_LAYERPCT_SUM:
2319     case CTSF_LAYERROWPCT_SUM:
2320     case CTSF_LAYERCOLPCT_SUM:
2321       if (!var_is_value_missing (var, value))
2322         moments1_add (s->moments, value->f, e_weight);
2323       break;
2324
2325     case CTSF_MEDIAN:
2326     case CTSF_MODE:
2327     case CTSF_PTILE:
2328       if (var_is_value_missing (var, value))
2329         {
2330           s->ovalid += e_weight;
2331
2332           struct ccase *c = case_create (casewriter_get_proto (s->writer));
2333           *case_num_rw_idx (c, 0) = value->f;
2334           *case_num_rw_idx (c, 1) = e_weight;
2335           casewriter_write (s->writer, c);
2336         }
2337       break;
2338
2339     case CTSF_RESPONSES:
2340     case CTSF_ROWPCT_RESPONSES:
2341     case CTSF_COLPCT_RESPONSES:
2342     case CTSF_TABLEPCT_RESPONSES:
2343     case CTSF_SUBTABLEPCT_RESPONSES:
2344     case CTSF_LAYERPCT_RESPONSES:
2345     case CTSF_LAYERROWPCT_RESPONSES:
2346     case CTSF_LAYERCOLPCT_RESPONSES:
2347     case CTSF_ROWPCT_RESPONSES_COUNT:
2348     case CTSF_COLPCT_RESPONSES_COUNT:
2349     case CTSF_TABLEPCT_RESPONSES_COUNT:
2350     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2351     case CTSF_LAYERPCT_RESPONSES_COUNT:
2352     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2353     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2354     case CTSF_ROWPCT_COUNT_RESPONSES:
2355     case CTSF_COLPCT_COUNT_RESPONSES:
2356     case CTSF_TABLEPCT_COUNT_RESPONSES:
2357     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2358     case CTSF_LAYERPCT_COUNT_RESPONSES:
2359     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2360     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2361       NOT_REACHED ();
2362     }
2363 }
2364
2365 static enum ctables_domain_type
2366 ctables_function_domain (enum ctables_summary_function function)
2367 {
2368   switch (function)
2369     {
2370     case CTSF_COUNT:
2371     case CTSF_ECOUNT:
2372     case CTSF_MISSING:
2373     case CSTF_TOTALN:
2374     case CTSF_ETOTALN:
2375     case CTSF_VALIDN:
2376     case CTSF_EVALIDN:
2377     case CTSF_MAXIMUM:
2378     case CTSF_MINIMUM:
2379     case CTSF_RANGE:
2380     case CTSF_MEAN:
2381     case CTSF_SEMEAN:
2382     case CTSF_STDDEV:
2383     case CTSF_SUM:
2384     case CTSF_VARIANCE:
2385     case CTSF_MEDIAN:
2386     case CTSF_PTILE:
2387     case CTSF_MODE:
2388     case CTSF_RESPONSES:
2389       NOT_REACHED ();
2390
2391     case CTSF_COLPCT_COUNT:
2392     case CTSF_COLPCT_COUNT_RESPONSES:
2393     case CTSF_COLPCT_RESPONSES:
2394     case CTSF_COLPCT_RESPONSES_COUNT:
2395     case CTSF_COLPCT_SUM:
2396     case CTSF_COLPCT_TOTALN:
2397     case CTSF_COLPCT_VALIDN:
2398       return CTDT_COL;
2399
2400     case CTSF_LAYERCOLPCT_COUNT:
2401     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2402     case CTSF_LAYERCOLPCT_RESPONSES:
2403     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2404     case CTSF_LAYERCOLPCT_SUM:
2405     case CTSF_LAYERCOLPCT_TOTALN:
2406     case CTSF_LAYERCOLPCT_VALIDN:
2407       return CTDT_LAYERCOL;
2408
2409     case CTSF_LAYERPCT_COUNT:
2410     case CTSF_LAYERPCT_COUNT_RESPONSES:
2411     case CTSF_LAYERPCT_RESPONSES:
2412     case CTSF_LAYERPCT_RESPONSES_COUNT:
2413     case CTSF_LAYERPCT_SUM:
2414     case CTSF_LAYERPCT_TOTALN:
2415     case CTSF_LAYERPCT_VALIDN:
2416       return CTDT_LAYER;
2417
2418     case CTSF_LAYERROWPCT_COUNT:
2419     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2420     case CTSF_LAYERROWPCT_RESPONSES:
2421     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2422     case CTSF_LAYERROWPCT_SUM:
2423     case CTSF_LAYERROWPCT_TOTALN:
2424     case CTSF_LAYERROWPCT_VALIDN:
2425       return CTDT_LAYERROW;
2426
2427     case CTSF_ROWPCT_COUNT:
2428     case CTSF_ROWPCT_COUNT_RESPONSES:
2429     case CTSF_ROWPCT_RESPONSES:
2430     case CTSF_ROWPCT_RESPONSES_COUNT:
2431     case CTSF_ROWPCT_SUM:
2432     case CTSF_ROWPCT_TOTALN:
2433     case CTSF_ROWPCT_VALIDN:
2434       return CTDT_ROW;
2435
2436     case CTSF_SUBTABLEPCT_COUNT:
2437     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2438     case CTSF_SUBTABLEPCT_RESPONSES:
2439     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2440     case CTSF_SUBTABLEPCT_SUM:
2441     case CTSF_SUBTABLEPCT_TOTALN:
2442     case CTSF_SUBTABLEPCT_VALIDN:
2443       return CTDT_SUBTABLE;
2444
2445     case CTSF_TABLEPCT_COUNT:
2446     case CTSF_TABLEPCT_COUNT_RESPONSES:
2447     case CTSF_TABLEPCT_RESPONSES:
2448     case CTSF_TABLEPCT_RESPONSES_COUNT:
2449     case CTSF_TABLEPCT_SUM:
2450     case CTSF_TABLEPCT_TOTALN:
2451     case CTSF_TABLEPCT_VALIDN:
2452       return CTDT_TABLE;
2453     }
2454
2455   NOT_REACHED ();
2456 }
2457
2458 static double
2459 ctables_summary_value (const struct ctables_cell *cell,
2460                        union ctables_summary *s,
2461                        const struct ctables_summary_spec *ss)
2462 {
2463   switch (ss->function)
2464     {
2465     case CTSF_COUNT:
2466     case CTSF_ECOUNT:
2467       return s->valid;
2468
2469     case CTSF_ROWPCT_COUNT:
2470     case CTSF_COLPCT_COUNT:
2471     case CTSF_TABLEPCT_COUNT:
2472     case CTSF_SUBTABLEPCT_COUNT:
2473     case CTSF_LAYERPCT_COUNT:
2474     case CTSF_LAYERROWPCT_COUNT:
2475     case CTSF_LAYERCOLPCT_COUNT:
2476       {
2477         enum ctables_domain_type d = ctables_function_domain (ss->function);
2478         return (cell->domains[d]->e_valid
2479                 ? s->valid / cell->domains[d]->e_valid * 100
2480                 : SYSMIS);
2481       }
2482
2483     case CTSF_ROWPCT_VALIDN:
2484     case CTSF_COLPCT_VALIDN:
2485     case CTSF_TABLEPCT_VALIDN:
2486     case CTSF_SUBTABLEPCT_VALIDN:
2487     case CTSF_LAYERPCT_VALIDN:
2488     case CTSF_LAYERROWPCT_VALIDN:
2489     case CTSF_LAYERCOLPCT_VALIDN:
2490     case CTSF_ROWPCT_TOTALN:
2491     case CTSF_COLPCT_TOTALN:
2492     case CTSF_TABLEPCT_TOTALN:
2493     case CTSF_SUBTABLEPCT_TOTALN:
2494     case CTSF_LAYERPCT_TOTALN:
2495     case CTSF_LAYERROWPCT_TOTALN:
2496     case CTSF_LAYERCOLPCT_TOTALN:
2497       NOT_REACHED ();
2498
2499     case CTSF_MISSING:
2500       return s->missing;
2501
2502     case CSTF_TOTALN:
2503     case CTSF_ETOTALN:
2504       return s->valid + s->missing;
2505
2506     case CTSF_VALIDN:
2507     case CTSF_EVALIDN:
2508       return s->valid;
2509
2510     case CTSF_MAXIMUM:
2511       return s->max;
2512
2513     case CTSF_MINIMUM:
2514       return s->min;
2515
2516     case CTSF_RANGE:
2517       return s->max != SYSMIS && s->min != SYSMIS ? s->max - s->min : SYSMIS;
2518
2519     case CTSF_MEAN:
2520       {
2521         double mean;
2522         moments1_calculate (s->moments, NULL, &mean, NULL, NULL, NULL);
2523         return mean;
2524       }
2525
2526     case CTSF_SEMEAN:
2527       {
2528         double weight, variance;
2529         moments1_calculate (s->moments, &weight, NULL, &variance, NULL, NULL);
2530         return calc_semean (variance, weight);
2531       }
2532
2533     case CTSF_STDDEV:
2534       {
2535         double variance;
2536         moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2537         return variance != SYSMIS ? sqrt (variance) : SYSMIS;
2538       }
2539
2540     case CTSF_SUM:
2541       {
2542         double weight, mean;
2543         moments1_calculate (s->moments, &weight, &mean, NULL, NULL, NULL);
2544         return weight != SYSMIS && mean != SYSMIS ? weight * mean : SYSMIS;
2545       }
2546
2547     case CTSF_VARIANCE:
2548       {
2549         double variance;
2550         moments1_calculate (s->moments, NULL, NULL, &variance, NULL, NULL);
2551         return variance;
2552       }
2553
2554     case CTSF_ROWPCT_SUM:
2555     case CTSF_COLPCT_SUM:
2556     case CTSF_TABLEPCT_SUM:
2557     case CTSF_SUBTABLEPCT_SUM:
2558     case CTSF_LAYERPCT_SUM:
2559     case CTSF_LAYERROWPCT_SUM:
2560     case CTSF_LAYERCOLPCT_SUM:
2561       NOT_REACHED ();
2562
2563     case CTSF_MEDIAN:
2564     case CTSF_PTILE:
2565       if (s->writer)
2566         {
2567           struct casereader *reader = casewriter_make_reader (s->writer);
2568           s->writer = NULL;
2569
2570           struct percentile *ptile = percentile_create (
2571             ss->function == CTSF_PTILE ? ss->percentile : 0.5, s->ovalid);
2572           struct order_stats *os = &ptile->parent;
2573           order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2574           s->ovalue = percentile_calculate (ptile, PC_HAVERAGE);
2575           statistic_destroy (&ptile->parent.parent);
2576         }
2577       return s->ovalue;
2578
2579     case CTSF_MODE:
2580       if (s->writer)
2581         {
2582           struct casereader *reader = casewriter_make_reader (s->writer);
2583           s->writer = NULL;
2584
2585           struct mode *mode = mode_create ();
2586           struct order_stats *os = &mode->parent;
2587           order_stats_accumulate_idx (&os, 1, reader, 1, 0);
2588           s->ovalue = mode->mode;
2589           statistic_destroy (&mode->parent.parent);
2590         }
2591       return s->ovalue;
2592
2593     case CTSF_RESPONSES:
2594     case CTSF_ROWPCT_RESPONSES:
2595     case CTSF_COLPCT_RESPONSES:
2596     case CTSF_TABLEPCT_RESPONSES:
2597     case CTSF_SUBTABLEPCT_RESPONSES:
2598     case CTSF_LAYERPCT_RESPONSES:
2599     case CTSF_LAYERROWPCT_RESPONSES:
2600     case CTSF_LAYERCOLPCT_RESPONSES:
2601     case CTSF_ROWPCT_RESPONSES_COUNT:
2602     case CTSF_COLPCT_RESPONSES_COUNT:
2603     case CTSF_TABLEPCT_RESPONSES_COUNT:
2604     case CTSF_SUBTABLEPCT_RESPONSES_COUNT:
2605     case CTSF_LAYERPCT_RESPONSES_COUNT:
2606     case CTSF_LAYERROWPCT_RESPONSES_COUNT:
2607     case CTSF_LAYERCOLPCT_RESPONSES_COUNT:
2608     case CTSF_ROWPCT_COUNT_RESPONSES:
2609     case CTSF_COLPCT_COUNT_RESPONSES:
2610     case CTSF_TABLEPCT_COUNT_RESPONSES:
2611     case CTSF_SUBTABLEPCT_COUNT_RESPONSES:
2612     case CTSF_LAYERPCT_COUNT_RESPONSES:
2613     case CTSF_LAYERROWPCT_COUNT_RESPONSES:
2614     case CTSF_LAYERCOLPCT_COUNT_RESPONSES:
2615       NOT_REACHED ();
2616     }
2617
2618   NOT_REACHED ();
2619 }
2620
2621 struct ctables_cell_sort_aux
2622   {
2623     const struct ctables_nest *nest;
2624     enum pivot_axis_type a;
2625   };
2626
2627 static int
2628 ctables_cell_compare_3way (const void *a_, const void *b_, const void *aux_)
2629 {
2630   const struct ctables_cell_sort_aux *aux = aux_;
2631   struct ctables_cell *const *ap = a_;
2632   struct ctables_cell *const *bp = b_;
2633   const struct ctables_cell *a = *ap;
2634   const struct ctables_cell *b = *bp;
2635
2636   const struct ctables_nest *nest = aux->nest;
2637   for (size_t i = 0; i < nest->n; i++)
2638     if (i != nest->scale_idx)
2639       {
2640         const struct variable *var = nest->vars[i];
2641         const struct ctables_cell_value *a_cv = &a->axes[aux->a].cvs[i];
2642         const struct ctables_cell_value *b_cv = &b->axes[aux->a].cvs[i];
2643         if (a_cv->category != b_cv->category)
2644           return a_cv->category > b_cv->category ? 1 : -1;
2645
2646         const union value *a_val = &a_cv->value;
2647         const union value *b_val = &b_cv->value;
2648         switch (a_cv->category->type)
2649           {
2650           case CCT_NUMBER:
2651           case CCT_STRING:
2652           case CCT_SUBTOTAL:
2653           case CCT_TOTAL:
2654           case CCT_POSTCOMPUTE:
2655             /* Must be equal. */
2656             continue;
2657
2658           case CCT_RANGE:
2659           case CCT_MISSING:
2660           case CCT_OTHERNM:
2661             {
2662               int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2663               if (cmp)
2664                 return cmp;
2665             }
2666             break;
2667
2668           case CCT_VALUE:
2669             {
2670               int cmp = value_compare_3way (a_val, b_val, var_get_width (var));
2671               if (cmp)
2672                 return a_cv->category->sort_ascending ? cmp : -cmp;
2673             }
2674             break;
2675
2676           case CCT_LABEL:
2677             {
2678               const char *a_label = var_lookup_value_label (var, a_val);
2679               const char *b_label = var_lookup_value_label (var, b_val);
2680               int cmp = (a_label
2681                          ? (b_label ? strcmp (a_label, b_label) : 1)
2682                          : (b_label ? -1 : value_compare_3way (
2683                               a_val, b_val, var_get_width (var))));
2684               if (cmp)
2685                 return a_cv->category->sort_ascending ? cmp : -cmp;
2686             }
2687             break;
2688
2689           case CCT_FUNCTION:
2690             NOT_REACHED ();
2691           }
2692       }
2693   return 0;
2694 }
2695
2696 /* Algorithm:
2697
2698    For each row:
2699        For each ctables_table:
2700            For each combination of row vars:
2701                For each combination of column vars:
2702                    For each combination of layer vars:
2703                        Add entry
2704    Make a table of row values:
2705        Sort entries by row values
2706        Assign a 0-based index to each actual value
2707        Construct a dimension
2708    Make a table of column values
2709    Make a table of layer values
2710    For each entry:
2711        Fill the table entry using the indexes from before.
2712  */
2713
2714 static struct ctables_domain *
2715 ctables_domain_insert (struct ctables_section *s, struct ctables_cell *cell,
2716                        enum ctables_domain_type domain)
2717 {
2718   size_t hash = 0;
2719   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2720     {
2721       const struct ctables_nest *nest = s->nests[a];
2722       for (size_t i = 0; i < nest->n_domains[domain]; i++)
2723         {
2724           size_t v_idx = nest->domains[domain][i];
2725           hash = value_hash (&cell->axes[a].cvs[v_idx].value,
2726                              var_get_width (nest->vars[v_idx]), hash);
2727         }
2728     }
2729
2730   struct ctables_domain *d;
2731   HMAP_FOR_EACH_WITH_HASH (d, struct ctables_domain, node, hash, &s->domains[domain])
2732     {
2733       const struct ctables_cell *df = d->example;
2734       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2735         {
2736           const struct ctables_nest *nest = s->nests[a];
2737           for (size_t i = 0; i < nest->n_domains[domain]; i++)
2738             {
2739               size_t v_idx = nest->domains[domain][i];
2740               if (!value_equal (&df->axes[a].cvs[v_idx].value,
2741                                 &cell->axes[a].cvs[v_idx].value,
2742                                 var_get_width (nest->vars[v_idx])))
2743                 goto not_equal;
2744             }
2745         }
2746       return d;
2747
2748     not_equal: ;
2749     }
2750
2751   d = xmalloc (sizeof *d);
2752   *d = (struct ctables_domain) { .example = cell };
2753   hmap_insert (&s->domains[domain], &d->node, hash);
2754   return d;
2755 }
2756
2757 static const struct ctables_category *
2758 ctables_categories_match (const struct ctables_categories *c,
2759                           const union value *v, const struct variable *var)
2760 {
2761   const struct ctables_category *othernm = NULL;
2762   for (size_t i = c->n_cats; i-- > 0; )
2763     {
2764       const struct ctables_category *cat = &c->cats[i];
2765       switch (cat->type)
2766         {
2767         case CCT_NUMBER:
2768           if (cat->number == v->f)
2769             return cat;
2770           break;
2771
2772         case CCT_STRING:
2773           NOT_REACHED ();
2774
2775         case CCT_RANGE:
2776           if ((cat->range[0] == -DBL_MAX || v->f >= cat->range[0])
2777               && (cat->range[1] == DBL_MAX || v->f <= cat->range[1]))
2778             return cat;
2779           break;
2780
2781         case CCT_MISSING:
2782           if (var_is_value_missing (var, v))
2783             return cat;
2784           break;
2785
2786         case CCT_POSTCOMPUTE:
2787           break;
2788
2789         case CCT_OTHERNM:
2790           if (!othernm)
2791             othernm = cat;
2792           break;
2793
2794         case CCT_SUBTOTAL:
2795         case CCT_TOTAL:
2796           break;
2797
2798         case CCT_VALUE:
2799         case CCT_LABEL:
2800         case CCT_FUNCTION:
2801           return (cat->include_missing || !var_is_value_missing (var, v) ? cat
2802                   : NULL);
2803         }
2804     }
2805
2806   return var_is_value_missing (var, v) ? NULL : othernm;
2807 }
2808
2809 static const struct ctables_category *
2810 ctables_categories_total (const struct ctables_categories *c)
2811 {
2812   const struct ctables_category *first = &c->cats[0];
2813   const struct ctables_category *last = &c->cats[c->n_cats - 1];
2814   return (first->type == CCT_TOTAL ? first
2815           : last->type == CCT_TOTAL ? last
2816           : NULL);
2817 }
2818
2819 static struct ctables_cell *
2820 ctables_cell_insert__ (struct ctables_section *s, const struct ccase *c,
2821                        const struct ctables_category *cats[PIVOT_N_AXES][10])
2822 {
2823   size_t hash = 0;
2824   enum ctables_summary_variant sv = CSV_CELL;
2825   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2826     {
2827       const struct ctables_nest *nest = s->nests[a];
2828       for (size_t i = 0; i < nest->n; i++)
2829         if (i != nest->scale_idx)
2830           {
2831             hash = hash_pointer (cats[a][i], hash);
2832             if (cats[a][i]->type != CCT_TOTAL
2833                 && cats[a][i]->type != CCT_SUBTOTAL
2834                 && cats[a][i]->type != CCT_POSTCOMPUTE)
2835               hash = value_hash (case_data (c, nest->vars[i]),
2836                                  var_get_width (nest->vars[i]), hash);
2837             else
2838               sv = CSV_TOTAL;
2839           }
2840     }
2841
2842   struct ctables_cell *cell;
2843   HMAP_FOR_EACH_WITH_HASH (cell, struct ctables_cell, node, hash, &s->cells)
2844     {
2845       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2846         {
2847           const struct ctables_nest *nest = s->nests[a];
2848           for (size_t i = 0; i < nest->n; i++)
2849             if (i != nest->scale_idx
2850                 && (cats[a][i] != cell->axes[a].cvs[i].category
2851                     || (cats[a][i]->type != CCT_TOTAL
2852                         && cats[a][i]->type != CCT_SUBTOTAL
2853                         && cats[a][i]->type != CCT_POSTCOMPUTE
2854                         && !value_equal (case_data (c, nest->vars[i]),
2855                                          &cell->axes[a].cvs[i].value,
2856                                          var_get_width (nest->vars[i])))))
2857                 goto not_equal;
2858         }
2859
2860       return cell;
2861
2862     not_equal: ;
2863     }
2864
2865   cell = xmalloc (sizeof *cell);
2866   cell->hide = false;
2867   cell->sv = sv;
2868   cell->contributes_to_domains = true;
2869   cell->postcompute = false;
2870   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
2871     {
2872       const struct ctables_nest *nest = s->nests[a];
2873       cell->axes[a].cvs = (nest->n
2874                         ? xnmalloc (nest->n, sizeof *cell->axes[a].cvs)
2875                         : NULL);
2876       for (size_t i = 0; i < nest->n; i++)
2877         {
2878           const struct ctables_category *cat = cats[a][i];
2879           if (i != nest->scale_idx)
2880             {
2881               const struct ctables_category *subtotal = cat->subtotal;
2882               if (cat->hide || (subtotal && subtotal->hide_subcategories))
2883                 cell->hide = true;
2884
2885               if (cat->type == CCT_TOTAL
2886                   || cat->type == CCT_SUBTOTAL
2887                   || cat->type == CCT_POSTCOMPUTE)
2888                 cell->contributes_to_domains = false;
2889               if (cat->type == CCT_POSTCOMPUTE)
2890                 cell->postcompute = true;
2891             }
2892
2893           cell->axes[a].cvs[i].category = cat;
2894           value_clone (&cell->axes[a].cvs[i].value, case_data (c, nest->vars[i]),
2895                        var_get_width (nest->vars[i]));
2896         }
2897     }
2898
2899   const struct ctables_nest *ss = s->nests[s->table->summary_axis];
2900   const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2901   cell->summaries = xmalloc (specs->n * sizeof *cell->summaries);
2902   for (size_t i = 0; i < specs->n; i++)
2903     ctables_summary_init (&cell->summaries[i], &specs->specs[i]);
2904   for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2905     cell->domains[dt] = ctables_domain_insert (s, cell, dt);
2906   hmap_insert (&s->cells, &cell->node, hash);
2907   return cell;
2908 }
2909
2910 static void
2911 ctables_cell_add__ (struct ctables_section *s, const struct ccase *c,
2912                     const struct ctables_category *cats[PIVOT_N_AXES][10],
2913                     double d_weight, double e_weight)
2914 {
2915   struct ctables_cell *cell = ctables_cell_insert__ (s, c, cats);
2916   const struct ctables_nest *ss = s->nests[s->table->summary_axis];
2917
2918   const struct ctables_summary_spec_set *specs = &ss->specs[cell->sv];
2919   for (size_t i = 0; i < specs->n; i++)
2920     ctables_summary_add (&cell->summaries[i], &specs->specs[i], specs->var,
2921                          case_data (c, specs->var), d_weight, e_weight);
2922   if (cell->contributes_to_domains)
2923     {
2924       for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
2925         {
2926           cell->domains[dt]->d_valid += d_weight;
2927           cell->domains[dt]->e_valid += e_weight;
2928         }
2929     }
2930 }
2931
2932 static void
2933 recurse_totals (struct ctables_section *s, const struct ccase *c,
2934                 const struct ctables_category *cats[PIVOT_N_AXES][10],
2935                 double d_weight, double e_weight,
2936                 enum pivot_axis_type start_axis, size_t start_nest)
2937 {
2938   for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2939     {
2940       const struct ctables_nest *nest = s->nests[a];
2941       for (size_t i = start_nest; i < nest->n; i++)
2942         {
2943           if (i == nest->scale_idx)
2944             continue;
2945
2946           const struct variable *var = nest->vars[i];
2947
2948           const struct ctables_category *total = ctables_categories_total (
2949             s->table->categories[var_get_dict_index (var)]);
2950           if (total)
2951             {
2952               const struct ctables_category *save = cats[a][i];
2953               cats[a][i] = total;
2954               ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2955               recurse_totals (s, c, cats, d_weight, e_weight, a, i + 1);
2956               cats[a][i] = save;
2957             }
2958         }
2959       start_nest = 0;
2960     }
2961 }
2962
2963 static void
2964 recurse_subtotals (struct ctables_section *s, const struct ccase *c,
2965                    const struct ctables_category *cats[PIVOT_N_AXES][10],
2966                    double d_weight, double e_weight,
2967                    enum pivot_axis_type start_axis, size_t start_nest)
2968 {
2969   for (enum pivot_axis_type a = start_axis; a < PIVOT_N_AXES; a++)
2970     {
2971       const struct ctables_nest *nest = s->nests[a];
2972       for (size_t i = start_nest; i < nest->n; i++)
2973         {
2974           if (i == nest->scale_idx)
2975             continue;
2976
2977           const struct ctables_category *save = cats[a][i];
2978           if (save->subtotal)
2979             {
2980               cats[a][i] = save->subtotal;
2981               ctables_cell_add__ (s, c, cats, d_weight, e_weight);
2982               recurse_subtotals (s, c, cats, d_weight, e_weight, a, i + 1);
2983               cats[a][i] = save;
2984             }
2985         }
2986       start_nest = 0;
2987     }
2988 }
2989
2990 static void
2991 ctables_add_occurrence (const struct variable *var,
2992                         const union value *value,
2993                         struct hmap *occurrences)
2994 {
2995   int width = var_get_width (var);
2996   unsigned int hash = value_hash (value, width, 0);
2997
2998   struct ctables_occurrence *o;
2999   HMAP_FOR_EACH_WITH_HASH (o, struct ctables_occurrence, node, hash,
3000                            occurrences)
3001     if (value_equal (value, &o->value, width))
3002       return;
3003
3004   o = xmalloc (sizeof *o);
3005   value_clone (&o->value, value, width);
3006   hmap_insert (occurrences, &o->node, hash);
3007 }
3008
3009 static void
3010 ctables_cell_insert (struct ctables_section *s,
3011                      const struct ccase *c,
3012                      double d_weight, double e_weight)
3013 {
3014   const struct ctables_category *cats[PIVOT_N_AXES][10]; /* XXX */
3015   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3016     {
3017       const struct ctables_nest *nest = s->nests[a];
3018       for (size_t i = 0; i < nest->n; i++)
3019         {
3020           if (i == nest->scale_idx)
3021             continue;
3022
3023           const struct variable *var = nest->vars[i];
3024           const union value *value = case_data (c, var);
3025
3026           if (var_is_numeric (var) && value->f == SYSMIS)
3027             return;
3028
3029           cats[a][i] = ctables_categories_match (
3030             s->table->categories[var_get_dict_index (var)], value, var);
3031           if (!cats[a][i])
3032             return;
3033         }
3034     }
3035
3036   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3037     {
3038       const struct ctables_nest *nest = s->nests[a];
3039       for (size_t i = 0; i < nest->n; i++)
3040         if (i != nest->scale_idx)
3041           {
3042             const struct variable *var = nest->vars[i];
3043             const union value *value = case_data (c, var);
3044             ctables_add_occurrence (var, value, &s->occurrences[a][i]);
3045           }
3046     }
3047
3048   ctables_cell_add__ (s, c, cats, d_weight, e_weight);
3049
3050   recurse_totals (s, c, cats, d_weight, e_weight, 0, 0);
3051   recurse_subtotals (s, c, cats, d_weight, e_weight, 0, 0);
3052 }
3053
3054 struct merge_item
3055   {
3056     const struct ctables_summary_spec_set *set;
3057     size_t ofs;
3058   };
3059
3060 static int
3061 merge_item_compare_3way (const struct merge_item *a, const struct merge_item *b)
3062 {
3063   const struct ctables_summary_spec *as = &a->set->specs[a->ofs];
3064   const struct ctables_summary_spec *bs = &b->set->specs[b->ofs];
3065   if (as->function != bs->function)
3066     return as->function > bs->function ? 1 : -1;
3067   else if (as->percentile != bs->percentile)
3068     return as->percentile < bs->percentile ? 1 : -1;
3069   return strcmp (as->label, bs->label);
3070 }
3071
3072 static struct pivot_value *
3073 ctables_category_create_label (const struct ctables_category *cat,
3074                                const struct variable *var,
3075                                const union value *value)
3076 {
3077   return (cat->type == CCT_TOTAL || cat->type == CCT_SUBTOTAL
3078           ? pivot_value_new_user_text (cat->total_label, SIZE_MAX)
3079           : cat->type == CCT_POSTCOMPUTE && cat->pc->label
3080           ? pivot_value_new_user_text (cat->pc->label, SIZE_MAX)
3081           : pivot_value_new_var_value (var, value));
3082 }
3083
3084 static struct ctables_value *
3085 ctables_value_find__ (struct ctables_table *t, const union value *value,
3086                       int width, unsigned int hash)
3087 {
3088   struct ctables_value *clv;
3089   HMAP_FOR_EACH_WITH_HASH (clv, struct ctables_value, node,
3090                            hash, &t->clabels_values_map)
3091     if (value_equal (value, &clv->value, width))
3092       return clv;
3093   return NULL;
3094 }
3095
3096 static void
3097 ctables_value_insert (struct ctables_table *t, const union value *value,
3098                       int width)
3099 {
3100   unsigned int hash = value_hash (value, width, 0);
3101   struct ctables_value *clv = ctables_value_find__ (t, value, width, hash);
3102   if (!clv)
3103     {
3104       clv = xmalloc (sizeof *clv);
3105       value_clone (&clv->value, value, width);
3106       hmap_insert (&t->clabels_values_map, &clv->node, hash);
3107     }
3108 }
3109
3110 static struct ctables_value *
3111 ctables_value_find (struct ctables_table *t,
3112                     const union value *value, int width)
3113 {
3114   return ctables_value_find__ (t, value, width,
3115                                value_hash (value, width, 0));
3116 }
3117
3118 static void
3119 ctables_table_add_section (struct ctables_table *t, enum pivot_axis_type a,
3120                            size_t ix[PIVOT_N_AXES])
3121 {
3122   if (a < PIVOT_N_AXES)
3123     {
3124       size_t limit = MAX (t->stacks[a].n, 1);
3125       for (ix[a] = 0; ix[a] < limit; ix[a]++)
3126         ctables_table_add_section (t, a + 1, ix);
3127     }
3128   else
3129     {
3130       struct ctables_section *s = &t->sections[t->n_sections++];
3131       *s = (struct ctables_section) {
3132         .table = t,
3133         .cells = HMAP_INITIALIZER (s->cells),
3134       };
3135       for (a = 0; a < PIVOT_N_AXES; a++)
3136         if (t->stacks[a].n)
3137           {
3138             struct ctables_nest *nest = &t->stacks[a].nests[ix[a]];
3139             s->nests[a] = nest;
3140             s->occurrences[a] = xnmalloc (nest->n, sizeof *s->occurrences[a]);
3141             for (size_t i = 0; i < nest->n; i++)
3142               hmap_init (&s->occurrences[a][i]);
3143         }
3144       for (size_t i = 0; i < N_CTDTS; i++)
3145         hmap_init (&s->domains[i]);
3146     }
3147 }
3148
3149 static double
3150 ctpo_add (double a, double b)
3151 {
3152   return a + b;
3153 }
3154
3155 static double
3156 ctpo_sub (double a, double b)
3157 {
3158   return a - b;
3159 }
3160
3161 static double
3162 ctpo_mul (double a, double b)
3163 {
3164   return a * b;
3165 }
3166
3167 static double
3168 ctpo_div (double a, double b)
3169 {
3170   return b ? a / b : SYSMIS;
3171 }
3172
3173 static double
3174 ctpo_pow (double a, double b)
3175 {
3176   int save_errno = errno;
3177   errno = 0;
3178   double result = pow (a, b);
3179   if (errno)
3180     result = SYSMIS;
3181   errno = save_errno;
3182   return result;
3183 }
3184
3185 static double
3186 ctpo_neg (double a, double b UNUSED)
3187 {
3188   return -a;
3189 }
3190
3191 struct ctables_pcexpr_evaluate_ctx
3192   {
3193     const struct ctables_cell *cell;
3194     const struct ctables_section *section;
3195     const struct ctables_categories *cats;
3196     enum pivot_axis_type pc_a;
3197     size_t pc_a_idx;
3198   };
3199
3200 static double ctables_pcexpr_evaluate (
3201   const struct ctables_pcexpr_evaluate_ctx *, const struct ctables_pcexpr *);
3202
3203 static double
3204 ctables_pcexpr_evaluate_nonterminal (
3205   const struct ctables_pcexpr_evaluate_ctx *ctx,
3206   const struct ctables_pcexpr *e, size_t n_args,
3207   double evaluate (double, double))
3208 {
3209   double args[2] = { 0, 0 };
3210   for (size_t i = 0; i < n_args; i++)
3211     {
3212       args[i] = ctables_pcexpr_evaluate (ctx, e->subs[i]);
3213       if (!isfinite (args[i]) || args[i] == SYSMIS)
3214         return SYSMIS;
3215     }
3216   return evaluate (args[0], args[1]);
3217 }
3218
3219 static double
3220 ctables_pcexpr_evaluate_category (const struct ctables_pcexpr_evaluate_ctx *ctx,
3221                                   const struct ctables_cell_value *pc_cv)
3222 {
3223   const struct ctables_section *s = ctx->section;
3224
3225   size_t hash = 0;
3226   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3227     {
3228       const struct ctables_nest *nest = s->nests[a];
3229       for (size_t i = 0; i < nest->n; i++)
3230         if (i != nest->scale_idx)
3231           {
3232             const struct ctables_cell_value *cv
3233               = (a == ctx->pc_a && i == ctx->pc_a_idx ? pc_cv
3234                  : &ctx->cell->axes[a].cvs[i]);
3235             hash = hash_pointer (cv->category, hash);
3236             if (cv->category->type != CCT_TOTAL
3237                 && cv->category->type != CCT_SUBTOTAL
3238                 && cv->category->type != CCT_POSTCOMPUTE)
3239               hash = value_hash (&cv->value,
3240                                  var_get_width (nest->vars[i]), hash);
3241           }
3242     }
3243
3244   struct ctables_cell *tc;
3245   HMAP_FOR_EACH_WITH_HASH (tc, struct ctables_cell, node, hash, &s->cells)
3246     {
3247       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3248         {
3249           const struct ctables_nest *nest = s->nests[a];
3250           for (size_t i = 0; i < nest->n; i++)
3251             if (i != nest->scale_idx)
3252               {
3253                 const struct ctables_cell_value *p_cv
3254                   = (a == ctx->pc_a && i == ctx->pc_a_idx ? pc_cv
3255                      : &ctx->cell->axes[a].cvs[i]);
3256                 const struct ctables_cell_value *t_cv = &tc->axes[a].cvs[i];
3257                 if (p_cv->category != t_cv->category
3258                     || (p_cv->category->type != CCT_TOTAL
3259                         && p_cv->category->type != CCT_SUBTOTAL
3260                         && p_cv->category->type != CCT_POSTCOMPUTE
3261                         && !value_equal (&p_cv->value,
3262                                          &t_cv->value,
3263                                          var_get_width (nest->vars[i]))))
3264                   goto not_equal;
3265               }
3266         }
3267
3268       goto found;
3269
3270     not_equal: ;
3271     }
3272   return 0;
3273
3274 found: ;
3275   const struct ctables_table *t = s->table;
3276   const struct ctables_nest *specs_nest = s->nests[t->summary_axis];
3277   const struct ctables_summary_spec_set *specs = &specs_nest->specs[tc->sv];
3278   size_t j = 0 /* XXX */;
3279   return ctables_summary_value (tc, &tc->summaries[j], &specs->specs[j]);
3280 }
3281
3282 static double
3283 ctables_pcexpr_evaluate (const struct ctables_pcexpr_evaluate_ctx *ctx,
3284                          const struct ctables_pcexpr *e)
3285 {
3286   switch (e->op)
3287     {
3288     case CTPO_CONSTANT:
3289       return e->number;
3290
3291     case CTPO_CAT_RANGE:
3292       {
3293         struct ctables_cell_value cv = {
3294           .category = ctables_find_category_for_postcompute (ctx->cats, e)
3295         };
3296         assert (cv.category != NULL);
3297
3298         struct hmap *occurrences = &ctx->section->occurrences[ctx->pc_a][ctx->pc_a_idx];
3299         const struct ctables_occurrence *o;
3300
3301         double sum = 0.0;
3302         const struct variable *var = ctx->section->nests[ctx->pc_a]->vars[ctx->pc_a_idx];
3303         HMAP_FOR_EACH (o, struct ctables_occurrence, node, occurrences)
3304           if (ctables_categories_match (ctx->cats, &o->value, var) == cv.category)
3305             {
3306               cv.value = o->value;
3307               sum += ctables_pcexpr_evaluate_category (ctx, &cv);
3308             }
3309         return sum;
3310       }
3311
3312     case CTPO_CAT_NUMBER:
3313     case CTPO_CAT_STRING:
3314     case CTPO_CAT_MISSING:
3315     case CTPO_CAT_OTHERNM:
3316     case CTPO_CAT_SUBTOTAL:
3317     case CTPO_CAT_TOTAL:
3318       {
3319         struct ctables_cell_value cv = {
3320           .category = ctables_find_category_for_postcompute (ctx->cats, e),
3321           .value = { .f = e->number },
3322         };
3323         assert (cv.category != NULL);
3324         return ctables_pcexpr_evaluate_category (ctx, &cv);
3325       }
3326
3327     case CTPO_ADD:
3328       return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_add);
3329
3330     case CTPO_SUB:
3331       return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_sub);
3332
3333     case CTPO_MUL:
3334       return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_mul);
3335
3336     case CTPO_DIV:
3337       return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_div);
3338
3339     case CTPO_POW:
3340       return ctables_pcexpr_evaluate_nonterminal (ctx, e, 2, ctpo_pow);
3341
3342     case CTPO_NEG:
3343       return ctables_pcexpr_evaluate_nonterminal (ctx, e, 1, ctpo_neg);
3344     }
3345
3346   NOT_REACHED ();
3347 }
3348
3349 static double
3350 ctables_cell_calculate_postcompute (const struct ctables_section *s,
3351                                     const struct ctables_cell *cell)
3352 {
3353   enum pivot_axis_type pc_a;
3354   size_t pc_a_idx;
3355   const struct ctables_postcompute *pc;
3356   for (pc_a = 0; ; pc_a++)
3357     {
3358       assert (pc_a < PIVOT_N_AXES);
3359       for (pc_a_idx = 0; pc_a_idx < s->nests[pc_a]->n; pc_a_idx++)
3360         {
3361           const struct ctables_cell_value *cv = &cell->axes[pc_a].cvs[pc_a_idx];
3362           if (cv->category->type == CCT_POSTCOMPUTE)
3363             {
3364               pc = cv->category->pc;
3365               goto found;
3366             }
3367         }
3368     }
3369 found: ;
3370
3371   const struct variable *var = s->nests[pc_a]->vars[pc_a_idx];
3372   const struct ctables_categories *cats = s->table->categories[
3373     var_get_dict_index (var)];
3374   struct ctables_pcexpr_evaluate_ctx ctx = {
3375     .cell = cell,
3376     .section = s,
3377     .cats = cats,
3378     .pc_a = pc_a,
3379     .pc_a_idx = pc_a_idx,
3380   };
3381   return ctables_pcexpr_evaluate (&ctx, pc->expr);
3382 }
3383
3384 static void
3385 ctables_table_output (struct ctables *ct, struct ctables_table *t)
3386 {
3387   struct pivot_table *pt = pivot_table_create__ (
3388     (t->title
3389      ? pivot_value_new_user_text (t->title, SIZE_MAX)
3390      : pivot_value_new_text (N_("Custom Tables"))),
3391     "Custom Tables");
3392   if (t->caption)
3393     pivot_table_set_caption (
3394       pt, pivot_value_new_user_text (t->caption, SIZE_MAX));
3395   if (t->corner)
3396     pivot_table_set_caption (
3397       pt, pivot_value_new_user_text (t->corner, SIZE_MAX));
3398
3399   bool summary_dimension = (t->summary_axis != t->slabels_axis
3400                             || (!t->slabels_visible
3401                                 && t->summary_specs.n > 1));
3402   if (summary_dimension)
3403     {
3404       struct pivot_dimension *d = pivot_dimension_create (
3405         pt, t->slabels_axis, N_("Statistics"));
3406       const struct ctables_summary_spec_set *specs = &t->summary_specs;
3407       if (!t->slabels_visible)
3408         d->hide_all_labels = true;
3409       for (size_t i = 0; i < specs->n; i++)
3410         pivot_category_create_leaf (
3411           d->root, pivot_value_new_text (specs->specs[i].label));
3412     }
3413
3414   bool categories_dimension = t->clabels_example != NULL;
3415   if (categories_dimension)
3416     {
3417       struct pivot_dimension *d = pivot_dimension_create (
3418         pt, t->label_axis[t->clabels_from_axis],
3419         t->clabels_from_axis == PIVOT_AXIS_ROW
3420         ? N_("Row Categories")
3421         : N_("Column Categories"));
3422       const struct variable *var = t->clabels_example;
3423       const struct ctables_categories *c = t->categories[var_get_dict_index (var)];
3424       for (size_t i = 0; i < t->n_clabels_values; i++)
3425         {
3426           const struct ctables_value *value = t->clabels_values[i];
3427           const struct ctables_category *cat = ctables_categories_match (c, &value->value, var);
3428           assert (cat != NULL);
3429           pivot_category_create_leaf (d->root, ctables_category_create_label (
3430                                         cat, t->clabels_example, &value->value));
3431         }
3432     }
3433
3434   pivot_table_set_look (pt, ct->look);
3435   struct pivot_dimension *d[PIVOT_N_AXES];
3436   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3437     {
3438       static const char *names[] = {
3439         [PIVOT_AXIS_ROW] = N_("Rows"),
3440         [PIVOT_AXIS_COLUMN] = N_("Columns"),
3441         [PIVOT_AXIS_LAYER] = N_("Layers"),
3442       };
3443       d[a] = (t->axes[a] || a == t->summary_axis
3444               ? pivot_dimension_create (pt, a, names[a])
3445               : NULL);
3446       if (!d[a])
3447         continue;
3448
3449       assert (t->axes[a]);
3450
3451       for (size_t i = 0; i < t->stacks[a].n; i++)
3452         {
3453           struct ctables_nest *nest = &t->stacks[a].nests[i];
3454           struct ctables_section **sections = xnmalloc (t->n_sections,
3455                                                         sizeof *sections);
3456           size_t n_sections = 0;
3457
3458           size_t n_total_cells = 0;
3459           size_t max_depth = 0;
3460           for (size_t j = 0; j < t->n_sections; j++)
3461             if (t->sections[j].nests[a] == nest)
3462               {
3463                 struct ctables_section *s = &t->sections[j];
3464                 sections[n_sections++] = s;
3465                 n_total_cells += s->cells.count;
3466
3467                 size_t depth = s->nests[a]->n;
3468                 max_depth = MAX (depth, max_depth);
3469               }
3470
3471           struct ctables_cell **sorted = xnmalloc (n_total_cells,
3472                                                    sizeof *sorted);
3473           size_t n_sorted = 0;
3474
3475           for (size_t j = 0; j < n_sections; j++)
3476             {
3477               struct ctables_section *s = sections[j];
3478
3479               struct ctables_cell *cell;
3480               HMAP_FOR_EACH (cell, struct ctables_cell, node, &s->cells)
3481                 if (!cell->hide)
3482                   sorted[n_sorted++] = cell;
3483               assert (n_sorted <= n_total_cells);
3484             }
3485
3486           struct ctables_cell_sort_aux aux = { .nest = nest, .a = a };
3487           sort (sorted, n_sorted, sizeof *sorted, ctables_cell_compare_3way, &aux);
3488
3489           struct ctables_level
3490             {
3491               enum ctables_level_type
3492                 {
3493                   CTL_VAR,          /* Variable label for nest->vars[var_idx]. */
3494                   CTL_CATEGORY,     /* Category for nest->vars[var_idx]. */
3495                   CTL_SUMMARY,      /* Summary functions. */
3496                 }
3497                 type;
3498
3499               enum settings_value_show vlabel; /* CTL_VAR only. */
3500               size_t var_idx;
3501             };
3502           struct ctables_level *levels = xnmalloc (1 + 2 * max_depth, sizeof *levels);
3503           size_t n_levels = 0;
3504           for (size_t k = 0; k < nest->n; k++)
3505             {
3506               enum ctables_vlabel vlabel = ct->vlabels[var_get_dict_index (nest->vars[k])];
3507               if (vlabel != CTVL_NONE)
3508                 {
3509                   levels[n_levels++] = (struct ctables_level) {
3510                     .type = CTL_VAR,
3511                     .vlabel = (enum settings_value_show) vlabel,
3512                     .var_idx = k,
3513                   };
3514                 }
3515
3516               if (nest->scale_idx != k
3517                   && (k != nest->n - 1 || t->label_axis[a] == a))
3518                 {
3519                   levels[n_levels++] = (struct ctables_level) {
3520                     .type = CTL_CATEGORY,
3521                     .var_idx = k,
3522                   };
3523                 }
3524             }
3525
3526           if (!summary_dimension && a == t->slabels_axis)
3527             {
3528               levels[n_levels++] = (struct ctables_level) {
3529                 .type = CTL_SUMMARY,
3530                 .var_idx = SIZE_MAX,
3531               };
3532             }
3533
3534           /* Pivot categories:
3535
3536              - variable label for nest->vars[0], if vlabel != CTVL_NONE
3537              - category for nest->vars[0], if nest->scale_idx != 0
3538              - variable label for nest->vars[1], if vlabel != CTVL_NONE
3539              - category for nest->vars[1], if nest->scale_idx != 1
3540              ...
3541              - variable label for nest->vars[n - 1], if vlabel != CTVL_NONE
3542              - category for nest->vars[n - 1], if t->label_axis[a] == a && nest->scale_idx != n - 1.
3543              - summary function, if 'a == t->slabels_axis && a ==
3544              t->summary_axis'.
3545
3546              Additional dimensions:
3547
3548              - If 'a == t->slabels_axis && a != t->summary_axis', add a summary
3549              dimension.
3550              - If 't->label_axis[b] == a' for some 'b != a', add a category
3551              dimension to 'a'.
3552           */
3553
3554
3555           struct pivot_category **groups = xnmalloc (1 + 2 * max_depth, sizeof *groups);
3556           int prev_leaf = 0;
3557           for (size_t j = 0; j < n_sorted; j++)
3558             {
3559               struct ctables_cell *cell = sorted[j];
3560               struct ctables_cell *prev = j > 0 ? sorted[j - 1] : NULL;
3561
3562               size_t n_common = 0;
3563               if (j > 0)
3564                 {
3565                   for (; n_common < n_levels; n_common++)
3566                     {
3567                       const struct ctables_level *level = &levels[n_common];
3568                       if (level->type == CTL_CATEGORY)
3569                         {
3570                           size_t var_idx = level->var_idx;
3571                           const struct ctables_category *c = cell->axes[a].cvs[var_idx].category;
3572                           if (prev->axes[a].cvs[var_idx].category != c)
3573                             break;
3574                           else if (c->type != CCT_SUBTOTAL
3575                                    && c->type != CCT_TOTAL
3576                                    && c->type != CCT_POSTCOMPUTE
3577                                    && !value_equal (&prev->axes[a].cvs[var_idx].value,
3578                                                     &cell->axes[a].cvs[var_idx].value,
3579                                                     var_get_type (nest->vars[var_idx])))
3580                             break;
3581                         }
3582                     }
3583                 }
3584
3585               for (size_t k = n_common; k < n_levels; k++)
3586                 {
3587                   const struct ctables_level *level = &levels[k];
3588                   struct pivot_category *parent = k ? groups[k - 1] : d[a]->root;
3589                   if (level->type == CTL_SUMMARY)
3590                     {
3591                       assert (k == n_levels - 1);
3592
3593                       const struct ctables_summary_spec_set *specs = &t->summary_specs;
3594                       for (size_t m = 0; m < specs->n; m++)
3595                         {
3596                           int leaf = pivot_category_create_leaf (
3597                             parent, pivot_value_new_text (specs->specs[m].label));
3598                           if (!m)
3599                             prev_leaf = leaf;
3600                         }
3601                     }
3602                   else
3603                     {
3604                       const struct variable *var = nest->vars[level->var_idx];
3605                       struct pivot_value *label;
3606                       if (level->type == CTL_VAR)
3607                         {
3608                           label = pivot_value_new_variable (var);
3609                           label->variable.show = level->vlabel;
3610                         }
3611                       else if (level->type == CTL_CATEGORY)
3612                         {
3613                           const struct ctables_cell_value *cv = &cell->axes[a].cvs[level->var_idx];
3614                           label = ctables_category_create_label (cv->category,
3615                                                                  var, &cv->value);
3616                         }
3617                       else
3618                         NOT_REACHED ();
3619
3620                       if (k == n_levels - 1)
3621                         prev_leaf = pivot_category_create_leaf (parent, label);
3622                       else
3623                         groups[k] = pivot_category_create_group__ (parent, label);
3624                     }
3625                 }
3626
3627               cell->axes[a].leaf = prev_leaf;
3628             }
3629           free (sorted);
3630           free (groups);
3631         }
3632     }
3633
3634   for (size_t i = 0; i < t->n_sections; i++)
3635     {
3636       struct ctables_section *s = &t->sections[i];
3637
3638       struct ctables_cell *cell;
3639       HMAP_FOR_EACH (cell, struct ctables_cell, node, &s->cells)
3640         {
3641           if (cell->hide)
3642             continue;
3643
3644           const struct ctables_nest *specs_nest = s->nests[t->summary_axis];
3645           const struct ctables_summary_spec_set *specs = &specs_nest->specs[cell->sv];
3646           for (size_t j = 0; j < specs->n; j++)
3647             {
3648               size_t dindexes[5];
3649               size_t n_dindexes = 0;
3650
3651               if (summary_dimension)
3652                 dindexes[n_dindexes++] = specs->specs[j].axis_idx;
3653
3654               if (categories_dimension)
3655                 {
3656                   const struct ctables_nest *clabels_nest = s->nests[t->clabels_from_axis];
3657                   const struct variable *var = clabels_nest->vars[clabels_nest->n - 1];
3658                   const union value *value = &cell->axes[t->clabels_from_axis].cvs[clabels_nest->n - 1].value;
3659                   const struct ctables_value *ctv = ctables_value_find (t, value, var_get_width (var));
3660                   if (!ctv)
3661                     continue;
3662                   dindexes[n_dindexes++] = ctv->leaf;
3663                 }
3664
3665               for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3666                 if (d[a])
3667                   {
3668                     int leaf = cell->axes[a].leaf;
3669                     if (a == t->summary_axis && !summary_dimension)
3670                       leaf += j;
3671                     dindexes[n_dindexes++] = leaf;
3672                   }
3673
3674               const struct ctables_summary_spec *ss = &specs->specs[j];
3675
3676               double d = (cell->postcompute
3677                           ? ctables_cell_calculate_postcompute (s, cell)
3678                           : ctables_summary_value (cell, &cell->summaries[j], ss));
3679               struct pivot_value *value;
3680               if (ct->hide_threshold != 0
3681                   && d < ct->hide_threshold
3682                   && (cell->postcompute
3683                       ? false /* XXX */
3684                       : ctables_summary_function_is_count (ss->function)))
3685                 {
3686                   value = pivot_value_new_user_text_nocopy (
3687                     xasprintf ("<%d", ct->hide_threshold));
3688                 }
3689               else if (d == 0 && ct->zero)
3690                 value = pivot_value_new_user_text (ct->zero, SIZE_MAX);
3691               else if (d == SYSMIS && ct->missing)
3692                 value = pivot_value_new_user_text (ct->missing, SIZE_MAX);
3693               else if (specs->specs[j].is_ctables_format)
3694                 {
3695                   char *s = data_out_stretchy (&(union value) { .f = d },
3696                                                "UTF-8",
3697                                                &specs->specs[j].format,
3698                                                &ct->ctables_formats, NULL);
3699                   value = pivot_value_new_user_text_nocopy (s);
3700                 }
3701               else
3702                 {
3703                   value = pivot_value_new_number (d);
3704                   value->numeric.format = specs->specs[j].format;
3705                 }
3706               pivot_table_put (pt, dindexes, n_dindexes, value);
3707             }
3708         }
3709     }
3710
3711   pivot_table_submit (pt);
3712 }
3713
3714 static bool
3715 ctables_check_label_position (struct ctables_table *t, enum pivot_axis_type a)
3716 {
3717   enum pivot_axis_type label_pos = t->label_axis[a];
3718   if (label_pos == a)
3719     return true;
3720
3721   t->clabels_from_axis = a;
3722
3723   const char *subcommand_name = a == PIVOT_AXIS_ROW ? "ROWLABELS" : "COLLABELS";
3724   const char *pos_name = label_pos == PIVOT_AXIS_LAYER ? "LAYER" : "OPPOSITE";
3725
3726   const struct ctables_stack *stack = &t->stacks[a];
3727   if (!stack->n)
3728     return true;
3729
3730   const struct ctables_nest *n0 = &stack->nests[0];
3731   assert (n0->n > 0);
3732   const struct variable *v0 = n0->vars[n0->n - 1];
3733   struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
3734   t->clabels_example = v0;
3735
3736   for (size_t i = 0; i < c0->n_cats; i++)
3737     if (c0->cats[i].type == CCT_FUNCTION)
3738       {
3739         msg (SE, _("%s=%s is not allowed with sorting based "
3740                    "on a summary function."),
3741              subcommand_name, pos_name);
3742         return false;
3743       }
3744   if (n0->n - 1 == n0->scale_idx)
3745     {
3746       msg (SE, _("%s=%s requires the variables to be moved to be categorical, "
3747                  "but %s is a scale variable."),
3748            subcommand_name, pos_name, var_get_name (v0));
3749       return false;
3750     }
3751
3752   for (size_t i = 1; i < stack->n; i++)
3753     {
3754       const struct ctables_nest *ni = &stack->nests[i];
3755       assert (ni->n > 0);
3756       const struct variable *vi = ni->vars[ni->n - 1];
3757       struct ctables_categories *ci = t->categories[var_get_dict_index (vi)];
3758
3759       if (ni->n - 1 == ni->scale_idx)
3760         {
3761           msg (SE, _("%s=%s requires the variables to be moved to be "
3762                      "categorical, but %s is a scale variable."),
3763                subcommand_name, pos_name, var_get_name (vi));
3764           return false;
3765         }
3766       if (var_get_width (v0) != var_get_width (vi))
3767         {
3768           msg (SE, _("%s=%s requires the variables to be "
3769                      "moved to have the same width, but %s has "
3770                      "width %d and %s has width %d."),
3771                subcommand_name, pos_name,
3772                var_get_name (v0), var_get_width (v0),
3773                var_get_name (vi), var_get_width (vi));
3774           return false;
3775         }
3776       if (!val_labs_equal (var_get_value_labels (v0),
3777                            var_get_value_labels (vi)))
3778         {
3779           msg (SE, _("%s=%s requires the variables to be "
3780                      "moved to have the same value labels, but %s "
3781                      "and %s have different value labels."),
3782                subcommand_name, pos_name,
3783                var_get_name (v0), var_get_name (vi));
3784           return false;
3785         }
3786       if (!ctables_categories_equal (c0, ci))
3787         {
3788           msg (SE, _("%s=%s requires the variables to be "
3789                      "moved to have the same category "
3790                      "specifications, but %s and %s have different "
3791                      "category specifications."),
3792                subcommand_name, pos_name,
3793                var_get_name (v0), var_get_name (vi));
3794           return false;
3795         }
3796     }
3797
3798   return true;
3799 }
3800
3801 static bool
3802 ctables_prepare_table (struct ctables_table *t)
3803 {
3804   for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
3805     if (t->axes[a])
3806       {
3807         t->stacks[a] = enumerate_fts (a, t->axes[a]);
3808
3809         for (size_t j = 0; j < t->stacks[a].n; j++)
3810           {
3811             struct ctables_nest *nest = &t->stacks[a].nests[j];
3812             for (enum ctables_domain_type dt = 0; dt < N_CTDTS; dt++)
3813               {
3814                 nest->domains[dt] = xmalloc (nest->n * sizeof *nest->domains[dt]);
3815                 nest->n_domains[dt] = 0;
3816
3817                 for (size_t k = 0; k < nest->n; k++)
3818                   {
3819                     if (k == nest->scale_idx)
3820                       continue;
3821
3822                     switch (dt)
3823                       {
3824                       case CTDT_TABLE:
3825                         continue;
3826
3827                       case CTDT_LAYER:
3828                         if (a != PIVOT_AXIS_LAYER)
3829                           continue;
3830                         break;
3831
3832                       case CTDT_SUBTABLE:
3833                       case CTDT_ROW:
3834                       case CTDT_COL:
3835                         if (dt == CTDT_SUBTABLE ? a != PIVOT_AXIS_LAYER
3836                             : dt == CTDT_ROW ? a == PIVOT_AXIS_COLUMN
3837                             : a == PIVOT_AXIS_ROW)
3838                           {
3839                             if (k == nest->n - 1
3840                                 || (nest->scale_idx == nest->n - 1
3841                                     && k == nest->n - 2))
3842                               continue;
3843                           }
3844                         break;
3845
3846                       case CTDT_LAYERROW:
3847                         if (a == PIVOT_AXIS_COLUMN)
3848                           continue;
3849                         break;
3850
3851                       case CTDT_LAYERCOL:
3852                         if (a == PIVOT_AXIS_ROW)
3853                           continue;
3854                         break;
3855                       }
3856
3857                     nest->domains[dt][nest->n_domains[dt]++] = k;
3858                   }
3859               }
3860           }
3861       }
3862     else
3863       {
3864         struct ctables_nest *nest = xmalloc (sizeof *nest);
3865         *nest = (struct ctables_nest) { .n = 0 };
3866         t->stacks[a] = (struct ctables_stack) { .nests = nest, .n = 1 };
3867       }
3868
3869   struct ctables_stack *stack = &t->stacks[t->summary_axis];
3870   for (size_t i = 0; i < stack->n; i++)
3871     {
3872       struct ctables_nest *nest = &stack->nests[i];
3873       if (!nest->specs[CSV_CELL].n)
3874         {
3875           struct ctables_summary_spec_set *specs = &nest->specs[CSV_CELL];
3876           specs->specs = xmalloc (sizeof *specs->specs);
3877           specs->n = 1;
3878
3879           enum ctables_summary_function function
3880             = specs->var ? CTSF_MEAN : CTSF_COUNT;
3881           struct ctables_var var = { .is_mrset = false, .var = specs->var };
3882
3883           *specs->specs = (struct ctables_summary_spec) {
3884             .function = function,
3885             .format = ctables_summary_default_format (function, &var),
3886             .label = ctables_summary_default_label (function, 0),
3887           };
3888           if (!specs->var)
3889             specs->var = nest->vars[0];
3890
3891           ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3892                                           &nest->specs[CSV_CELL]);
3893         }
3894       else if (!nest->specs[CSV_TOTAL].n)
3895         ctables_summary_spec_set_clone (&nest->specs[CSV_TOTAL],
3896                                         &nest->specs[CSV_CELL]);
3897     }
3898
3899   struct ctables_summary_spec_set *merged = &t->summary_specs;
3900   struct merge_item *items = xnmalloc (2 * stack->n, sizeof *items);
3901   size_t n_left = 0;
3902   for (size_t j = 0; j < stack->n; j++)
3903     {
3904       const struct ctables_nest *nest = &stack->nests[j];
3905       if (nest->n)
3906         for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3907           items[n_left++] = (struct merge_item) { .set = &nest->specs[sv] };
3908     }
3909
3910   while (n_left > 0)
3911     {
3912       struct merge_item min = items[0];
3913       for (size_t j = 1; j < n_left; j++)
3914         if (merge_item_compare_3way (&items[j], &min) < 0)
3915           min = items[j];
3916
3917       if (merged->n >= merged->allocated)
3918         merged->specs = x2nrealloc (merged->specs, &merged->allocated,
3919                                     sizeof *merged->specs);
3920       merged->specs[merged->n++] = min.set->specs[min.ofs];
3921
3922       for (size_t j = 0; j < n_left; )
3923         {
3924           if (merge_item_compare_3way (&items[j], &min) == 0)
3925             {
3926               struct merge_item *item = &items[j];
3927               item->set->specs[item->ofs].axis_idx = merged->n - 1;
3928               if (++item->ofs >= item->set->n)
3929                 {
3930                   items[j] = items[--n_left];
3931                   continue;
3932                 }
3933             }
3934           j++;
3935         }
3936     }
3937
3938 #if 0
3939   for (size_t j = 0; j < merged->n; j++)
3940     printf ("%s\n", ctables_summary_function_name (merged->specs[j].function));
3941
3942   for (size_t j = 0; j < stack->n; j++)
3943     {
3944       const struct ctables_nest *nest = &stack->nests[j];
3945       for (enum ctables_summary_variant sv = 0; sv < N_CSVS; sv++)
3946         {
3947           const struct ctables_summary_spec_set *specs = &nest->specs[sv];
3948           for (size_t k = 0; k < specs->n; k++)
3949             printf ("(%s, %zu) ", ctables_summary_function_name (specs->specs[k].function),
3950                     specs->specs[k].axis_idx);
3951           printf ("\n");
3952         }
3953     }
3954 #endif
3955
3956   return (ctables_check_label_position (t, PIVOT_AXIS_ROW)
3957           && ctables_check_label_position (t, PIVOT_AXIS_COLUMN));
3958 }
3959
3960 static void
3961 ctables_insert_clabels_values (struct ctables_table *t, const struct ccase *c,
3962                                enum pivot_axis_type a)
3963 {
3964   struct ctables_stack *stack = &t->stacks[a];
3965   for (size_t i = 0; i < stack->n; i++)
3966     {
3967       const struct ctables_nest *nest = &stack->nests[i];
3968       const struct variable *var = nest->vars[nest->n - 1];
3969       const union value *value = case_data (c, var);
3970
3971       if (var_is_numeric (var) && value->f == SYSMIS)
3972         continue;
3973
3974       if (ctables_categories_match (t->categories [var_get_dict_index (var)],
3975                                     value, var))
3976         ctables_value_insert (t, value, var_get_width (var));
3977     }
3978 }
3979
3980 static int
3981 compare_clabels_values_3way (const void *a_, const void *b_, const void *width_)
3982 {
3983   const struct ctables_value *const *ap = a_;
3984   const struct ctables_value *const *bp = b_;
3985   const struct ctables_value *a = *ap;
3986   const struct ctables_value *b = *bp;
3987   const int *width = width_;
3988   return value_compare_3way (&a->value, &b->value, *width);
3989 }
3990
3991 static void
3992 ctables_sort_clabels_values (struct ctables_table *t)
3993 {
3994   const struct variable *v0 = t->clabels_example;
3995   int width = var_get_width (v0);
3996
3997   struct ctables_categories *c0 = t->categories[var_get_dict_index (v0)];
3998   if (c0->show_empty)
3999     {
4000       const struct val_labs *val_labs = var_get_value_labels (v0);
4001       for (const struct val_lab *vl = val_labs_first (val_labs); vl;
4002            vl = val_labs_next (val_labs, vl))
4003         if (ctables_categories_match (c0, &vl->value, v0))
4004           ctables_value_insert (t, &vl->value, width);
4005     }
4006
4007   size_t n = hmap_count (&t->clabels_values_map);
4008   t->clabels_values = xnmalloc (n, sizeof *t->clabels_values);
4009
4010   struct ctables_value *clv;
4011   size_t i = 0;
4012   HMAP_FOR_EACH (clv, struct ctables_value, node, &t->clabels_values_map)
4013     t->clabels_values[i++] = clv;
4014   t->n_clabels_values = n;
4015   assert (i == n);
4016
4017   sort (t->clabels_values, n, sizeof *t->clabels_values,
4018         compare_clabels_values_3way, &width);
4019
4020   for (size_t i = 0; i < n; i++)
4021     t->clabels_values[i]->leaf = i;
4022 }
4023
4024 static void
4025 ctables_add_category_occurrences (const struct variable *var,
4026                                   struct hmap *occurrences,
4027                                   const struct ctables_categories *cats)
4028 {
4029   const struct val_labs *val_labs = var_get_value_labels (var);
4030
4031   for (size_t i = 0; i < cats->n_cats; i++)
4032     {
4033       const struct ctables_category *c = &cats->cats[i];
4034       switch (c->type)
4035         {
4036         case CCT_NUMBER:
4037           ctables_add_occurrence (var, &(const union value) { .f = c->number },
4038                                   occurrences);
4039           break;
4040
4041         case CCT_STRING:
4042           abort ();             /* XXX */
4043
4044         case CCT_RANGE:
4045           assert (var_is_numeric (var));
4046           for (const struct val_lab *vl = val_labs_first (val_labs); vl;
4047                vl = val_labs_next (val_labs, vl))
4048             if (vl->value.f >= c->range[0] && vl->value.f <= c->range[1])
4049               ctables_add_occurrence (var, &vl->value, occurrences);
4050           break;
4051
4052         case CCT_MISSING:
4053           for (const struct val_lab *vl = val_labs_first (val_labs); vl;
4054                vl = val_labs_next (val_labs, vl))
4055             if (var_is_value_missing (var, &vl->value))
4056               ctables_add_occurrence (var, &vl->value, occurrences);
4057           break;
4058
4059         case CCT_OTHERNM:
4060           for (const struct val_lab *vl = val_labs_first (val_labs); vl;
4061                vl = val_labs_next (val_labs, vl))
4062             ctables_add_occurrence (var, &vl->value, occurrences);
4063           break;
4064
4065         case CCT_POSTCOMPUTE:
4066           break;
4067
4068         case CCT_SUBTOTAL:
4069         case CCT_TOTAL:
4070           break;
4071
4072         case CCT_VALUE:
4073         case CCT_LABEL:
4074         case CCT_FUNCTION:
4075           for (const struct val_lab *vl = val_labs_first (val_labs); vl;
4076                vl = val_labs_next (val_labs, vl))
4077             if (c->include_missing || !var_is_value_missing (var, &vl->value))
4078               ctables_add_occurrence (var, &vl->value, occurrences);
4079           break;
4080         }
4081     }
4082 }
4083
4084 static void
4085 ctables_section_recurse_add_empty_categories (
4086   struct ctables_section *s,
4087   const struct ctables_category *cats[PIVOT_N_AXES][10], struct ccase *c,
4088   enum pivot_axis_type a, size_t a_idx)
4089 {
4090   if (a >= PIVOT_N_AXES)
4091     ctables_cell_insert__ (s, c, cats);
4092   else if (!s->nests[a] || a_idx >= s->nests[a]->n)
4093     ctables_section_recurse_add_empty_categories (s, cats, c, a + 1, 0);
4094   else
4095     {
4096       const struct variable *var = s->nests[a]->vars[a_idx];
4097       const struct ctables_categories *categories = s->table->categories[
4098         var_get_dict_index (var)];
4099       int width = var_get_width (var);
4100       const struct hmap *occurrences = &s->occurrences[a][a_idx];
4101       const struct ctables_occurrence *o;
4102       HMAP_FOR_EACH (o, struct ctables_occurrence, node, occurrences)
4103         {
4104           union value *value = case_data_rw (c, var);
4105           value_destroy (value, width);
4106           value_clone (value, &o->value, width);
4107           cats[a][a_idx] = ctables_categories_match (categories, value, var);
4108           assert (cats[a][a_idx] != NULL);
4109           ctables_section_recurse_add_empty_categories (s, cats, c, a, a_idx + 1);
4110         }
4111
4112       for (size_t i = 0; i < categories->n_cats; i++)
4113         {
4114           const struct ctables_category *cat = &categories->cats[i];
4115           if (cat->type == CCT_POSTCOMPUTE)
4116             {
4117               cats[a][a_idx] = cat;
4118               ctables_section_recurse_add_empty_categories (s, cats, c, a, a_idx + 1);
4119             }
4120         }
4121     }
4122 }
4123
4124 static void
4125 ctables_section_add_empty_categories (struct ctables_section *s)
4126 {
4127   bool show_empty = false;
4128   for (size_t a = 0; a < PIVOT_N_AXES; a++)
4129     if (s->nests[a])
4130       for (size_t k = 0; k < s->nests[a]->n; k++)
4131         if (k != s->nests[a]->scale_idx)
4132           {
4133             const struct variable *var = s->nests[a]->vars[k];
4134             const struct ctables_categories *cats = s->table->categories[
4135               var_get_dict_index (var)];
4136             if (cats->show_empty)
4137               {
4138                 show_empty = true;
4139                 ctables_add_category_occurrences (var, &s->occurrences[a][k], cats);
4140               }
4141           }
4142   if (!show_empty)
4143     return;
4144
4145   const struct ctables_category *cats[PIVOT_N_AXES][10]; /* XXX */
4146   struct ccase *c = case_create (dict_get_proto (s->table->ctables->dict));
4147   ctables_section_recurse_add_empty_categories (s, cats, c, 0, 0);
4148   case_unref (c);
4149 }
4150
4151 static bool
4152 ctables_execute (struct dataset *ds, struct ctables *ct)
4153 {
4154   for (size_t i = 0; i < ct->n_tables; i++)
4155     {
4156       struct ctables_table *t = ct->tables[i];
4157       t->sections = xnmalloc (MAX (1, t->stacks[PIVOT_AXIS_ROW].n) *
4158                               MAX (1, t->stacks[PIVOT_AXIS_COLUMN].n) *
4159                               MAX (1, t->stacks[PIVOT_AXIS_LAYER].n),
4160                               sizeof *t->sections);
4161       size_t ix[PIVOT_N_AXES];
4162       ctables_table_add_section (t, 0, ix);
4163     }
4164
4165   struct casereader *input = proc_open (ds);
4166   bool warn_on_invalid = true;
4167   for (struct ccase *c = casereader_read (input); c;
4168        case_unref (c), c = casereader_read (input))
4169     {
4170       double d_weight = dict_get_case_weight (dataset_dict (ds), c,
4171                                               &warn_on_invalid);
4172       double e_weight = (ct->e_weight
4173                          ? var_force_valid_weight (ct->e_weight,
4174                                                    case_num (c, ct->e_weight),
4175                                                    &warn_on_invalid)
4176                          : d_weight);
4177
4178       for (size_t i = 0; i < ct->n_tables; i++)
4179         {
4180           struct ctables_table *t = ct->tables[i];
4181
4182           for (size_t j = 0; j < t->n_sections; j++)
4183             ctables_cell_insert (&t->sections[j], c, d_weight, e_weight);
4184
4185           for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
4186             if (t->label_axis[a] != a)
4187               ctables_insert_clabels_values (t, c, a);
4188         }
4189     }
4190   casereader_destroy (input);
4191
4192   for (size_t i = 0; i < ct->n_tables; i++)
4193     {
4194       struct ctables_table *t = ct->tables[i];
4195
4196       if (t->clabels_example)
4197         ctables_sort_clabels_values (t);
4198
4199       for (size_t j = 0; j < t->n_sections; j++)
4200         ctables_section_add_empty_categories (&t->sections[j]);
4201
4202       ctables_table_output (ct, ct->tables[i]);
4203     }
4204   return proc_commit (ds);
4205 }
4206 \f
4207 /* Postcomputes. */
4208
4209 typedef struct ctables_pcexpr *parse_recursively_func (struct lexer *);
4210
4211 static void
4212 ctables_pcexpr_destroy (struct ctables_pcexpr *e)
4213 {
4214   if (e)
4215     {
4216       switch (e->op)
4217         {
4218         case CTPO_CAT_STRING:
4219           free (e->string);
4220           break;
4221
4222         case CTPO_ADD:
4223         case CTPO_SUB:
4224         case CTPO_MUL:
4225         case CTPO_DIV:
4226         case CTPO_POW:
4227         case CTPO_NEG:
4228           for (size_t i = 0; i < 2; i++)
4229             ctables_pcexpr_destroy (e->subs[i]);
4230           break;
4231
4232         case CTPO_CONSTANT:
4233         case CTPO_CAT_NUMBER:
4234         case CTPO_CAT_RANGE:
4235         case CTPO_CAT_MISSING:
4236         case CTPO_CAT_OTHERNM:
4237         case CTPO_CAT_SUBTOTAL:
4238         case CTPO_CAT_TOTAL:
4239           break;
4240         }
4241
4242       msg_location_destroy (e->location);
4243       free (e);
4244     }
4245 }
4246
4247 static struct ctables_pcexpr *
4248 ctables_pcexpr_allocate_binary (enum ctables_postcompute_op op,
4249                                 struct ctables_pcexpr *sub0,
4250                                 struct ctables_pcexpr *sub1)
4251 {
4252   struct ctables_pcexpr *e = xmalloc (sizeof *e);
4253   *e = (struct ctables_pcexpr) {
4254     .op = op,
4255     .subs = { sub0, sub1 },
4256     .location = msg_location_merged (sub0->location, sub1->location),
4257   };
4258   return e;
4259 }
4260
4261 /* How to parse an operator. */
4262 struct operator
4263   {
4264     enum token_type token;
4265     enum ctables_postcompute_op op;
4266   };
4267
4268 static const struct operator *
4269 match_operator (struct lexer *lexer, const struct operator ops[], size_t n_ops)
4270 {
4271   for (const struct operator *op = ops; op < ops + n_ops; op++)
4272     if (lex_token (lexer) == op->token)
4273       {
4274         if (op->token != T_NEG_NUM)
4275           lex_get (lexer);
4276
4277         return op;
4278       }
4279
4280   return NULL;
4281 }
4282
4283 static struct ctables_pcexpr *
4284 parse_binary_operators__ (struct lexer *lexer,
4285                           const struct operator ops[], size_t n_ops,
4286                           parse_recursively_func *parse_next_level,
4287                           const char *chain_warning,
4288                           struct ctables_pcexpr *lhs)
4289 {
4290   for (int op_count = 0; ; op_count++)
4291     {
4292       const struct operator *op = match_operator (lexer, ops, n_ops);
4293       if (!op)
4294         {
4295           if (op_count > 1 && chain_warning)
4296             msg_at (SW, lhs->location, "%s", chain_warning);
4297
4298           return lhs;
4299         }
4300
4301       struct ctables_pcexpr *rhs = parse_next_level (lexer);
4302       if (!rhs)
4303         {
4304           ctables_pcexpr_destroy (lhs);
4305           return NULL;
4306         }
4307
4308       lhs = ctables_pcexpr_allocate_binary (op->op, lhs, rhs);
4309     }
4310 }
4311
4312 static struct ctables_pcexpr *
4313 parse_binary_operators (struct lexer *lexer,
4314                         const struct operator ops[], size_t n_ops,
4315                         parse_recursively_func *parse_next_level,
4316                         const char *chain_warning)
4317 {
4318   struct ctables_pcexpr *lhs = parse_next_level (lexer);
4319   if (!lhs)
4320     return NULL;
4321
4322   return parse_binary_operators__ (lexer, ops, n_ops, parse_next_level,
4323                                    chain_warning, lhs);
4324 }
4325
4326 static struct ctables_pcexpr *parse_add (struct lexer *);
4327
4328 static struct ctables_pcexpr
4329 ctpo_cat_range (double low, double high)
4330 {
4331   return (struct ctables_pcexpr) {
4332     .op = CTPO_CAT_RANGE,
4333     .range = { low, high },
4334   };
4335 }
4336
4337 static struct ctables_pcexpr *
4338 parse_primary (struct lexer *lexer)
4339 {
4340   int start_ofs = lex_ofs (lexer);
4341   struct ctables_pcexpr e;
4342   if (lex_is_number (lexer))
4343     {
4344       e = (struct ctables_pcexpr) { .op = CTPO_CONSTANT,
4345                                     .number = lex_number (lexer) };
4346       lex_get (lexer);
4347     }
4348   else if (lex_match_id (lexer, "MISSING"))
4349     e = (struct ctables_pcexpr) { .op = CTPO_CAT_MISSING };
4350   else if (lex_match_id (lexer, "OTHERNM"))
4351     e = (struct ctables_pcexpr) { .op = CTPO_CAT_OTHERNM };
4352   else if (lex_match_id (lexer, "TOTAL"))
4353     e = (struct ctables_pcexpr) { .op = CTPO_CAT_TOTAL };
4354   else if (lex_match_id (lexer, "SUBTOTAL"))
4355     {
4356       size_t subtotal_index = 0;
4357       if (lex_match (lexer, T_LBRACK))
4358         {
4359           if (!lex_force_int_range (lexer, "SUBTOTAL", 1, LONG_MAX))
4360             return NULL;
4361           subtotal_index = lex_integer (lexer);
4362           lex_get (lexer);
4363           if (!lex_force_match (lexer, T_RBRACK))
4364             return NULL;
4365         }
4366       e = (struct ctables_pcexpr) { .op = CTPO_CAT_SUBTOTAL,
4367                                     .subtotal_index = subtotal_index };
4368     }
4369   else if (lex_match (lexer, T_LBRACK))
4370     {
4371       if (lex_match_id (lexer, "LO"))
4372         {
4373           if (!lex_force_match_id (lexer, "THRU") || lex_force_num (lexer))
4374             return false;
4375           e = ctpo_cat_range (-DBL_MAX, lex_number (lexer));
4376           lex_get (lexer);
4377         }
4378       else if (lex_is_number (lexer))
4379         {
4380           double number = lex_number (lexer);
4381           lex_get (lexer);
4382           if (lex_match_id (lexer, "THRU"))
4383             {
4384               if (lex_match_id (lexer, "HI"))
4385                 e = ctpo_cat_range (number, DBL_MAX);
4386               else
4387                 {
4388                   if (!lex_force_num (lexer))
4389                     return false;
4390                   e = ctpo_cat_range (number, lex_number (lexer));
4391                   lex_get (lexer);
4392                 }
4393             }
4394           else
4395             e = (struct ctables_pcexpr) { .op = CTPO_CAT_NUMBER,
4396                                           .number = number };
4397         }
4398       else if (lex_is_string (lexer))
4399         {
4400           e = (struct ctables_pcexpr) {
4401             .op = CTPO_CAT_STRING,
4402             .string = ss_xstrdup (lex_tokss (lexer)),
4403           };
4404           lex_get (lexer);
4405         }
4406       else
4407         {
4408           lex_error (lexer, NULL);
4409           return NULL;
4410         }
4411
4412       if (!lex_force_match (lexer, T_RBRACK))
4413         {
4414           if (e.op == CTPO_CAT_STRING)
4415             free (e.string);
4416           return NULL;
4417         }
4418     }
4419   else if (lex_match (lexer, T_LPAREN))
4420     {
4421       struct ctables_pcexpr *ep = parse_add (lexer);
4422       if (!ep)
4423         return NULL;
4424       if (!lex_force_match (lexer, T_RPAREN))
4425         {
4426           ctables_pcexpr_destroy (ep);
4427           return NULL;
4428         }
4429       return ep;
4430     }
4431   else
4432     {
4433       lex_error (lexer, NULL);
4434       return NULL;
4435     }
4436
4437   e.location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1);
4438   return xmemdup (&e, sizeof e);
4439 }
4440
4441 static struct ctables_pcexpr *
4442 ctables_pcexpr_allocate_neg (struct ctables_pcexpr *sub,
4443                              struct lexer *lexer, int start_ofs)
4444 {
4445   struct ctables_pcexpr *e = xmalloc (sizeof *e);
4446   *e = (struct ctables_pcexpr) {
4447     .op = CTPO_NEG,
4448     .subs = { sub },
4449     .location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1),
4450   };
4451   return e;
4452 }
4453
4454 static struct ctables_pcexpr *
4455 parse_exp (struct lexer *lexer)
4456 {
4457   static const struct operator op = { T_EXP, CTPO_POW };
4458
4459   const char *chain_warning =
4460     _("The exponentiation operator (`**') is left-associative: "
4461       "`a**b**c' equals `(a**b)**c', not `a**(b**c)'.  "
4462       "To disable this warning, insert parentheses.");
4463
4464   if (lex_token (lexer) != T_NEG_NUM || lex_next_token (lexer, 1) != T_EXP)
4465     return parse_binary_operators (lexer, &op, 1,
4466                                    parse_primary, chain_warning);
4467
4468   /* Special case for situations like "-5**6", which must be parsed as
4469      -(5**6). */
4470
4471   int start_ofs = lex_ofs (lexer);
4472   struct ctables_pcexpr *lhs = xmalloc (sizeof *lhs);
4473   *lhs = (struct ctables_pcexpr) {
4474     .op = CTPO_CONSTANT,
4475     .number = -lex_tokval (lexer),
4476     .location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer)),
4477   };
4478   lex_get (lexer);
4479
4480   struct ctables_pcexpr *node = parse_binary_operators__ (
4481     lexer, &op, 1, parse_primary, chain_warning, lhs);
4482   if (!node)
4483     return NULL;
4484
4485   return ctables_pcexpr_allocate_neg (node, lexer, start_ofs);
4486 }
4487
4488 /* Parses the unary minus level. */
4489 static struct ctables_pcexpr *
4490 parse_neg (struct lexer *lexer)
4491 {
4492   int start_ofs = lex_ofs (lexer);
4493   if (!lex_match (lexer, T_DASH))
4494     return parse_exp (lexer);
4495
4496   struct ctables_pcexpr *inner = parse_neg (lexer);
4497   if (!inner)
4498     return NULL;
4499
4500   return ctables_pcexpr_allocate_neg (inner, lexer, start_ofs);
4501 }
4502
4503 /* Parses the multiplication and division level. */
4504 static struct ctables_pcexpr *
4505 parse_mul (struct lexer *lexer)
4506 {
4507   static const struct operator ops[] =
4508     {
4509       { T_ASTERISK, CTPO_MUL },
4510       { T_SLASH, CTPO_DIV },
4511     };
4512
4513   return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
4514                                  parse_neg, NULL);
4515 }
4516
4517 /* Parses the addition and subtraction level. */
4518 static struct ctables_pcexpr *
4519 parse_add (struct lexer *lexer)
4520 {
4521   static const struct operator ops[] =
4522     {
4523       { T_PLUS, CTPO_ADD },
4524       { T_DASH, CTPO_SUB },
4525       { T_NEG_NUM, CTPO_ADD },
4526     };
4527
4528   return parse_binary_operators (lexer, ops, sizeof ops / sizeof *ops,
4529                                  parse_mul, NULL);
4530 }
4531
4532 static struct ctables_postcompute *
4533 ctables_find_postcompute (struct ctables *ct, const char *name)
4534 {
4535   struct ctables_postcompute *pc;
4536   HMAP_FOR_EACH_WITH_HASH (pc, struct ctables_postcompute, hmap_node,
4537                            utf8_hash_case_string (name, 0), &ct->postcomputes)
4538     if (!utf8_strcasecmp (pc->name, name))
4539       return pc;
4540   return NULL;
4541 }
4542
4543 static bool
4544 ctables_parse_pcompute (struct lexer *lexer, struct ctables *ct)
4545 {
4546   int pcompute_start = lex_ofs (lexer) - 1;
4547
4548   if (!lex_force_match (lexer, T_AND) || !lex_force_id (lexer))
4549     return false;
4550
4551   char *name = ss_xstrdup (lex_tokss (lexer));
4552
4553   lex_get (lexer);
4554   if (!lex_force_match (lexer, T_EQUALS)
4555       || !lex_force_match_id (lexer, "EXPR")
4556       || !lex_force_match (lexer, T_LPAREN))
4557     {
4558       free (name);
4559       return false;
4560     }
4561
4562   int expr_start = lex_ofs (lexer);
4563   struct ctables_pcexpr *expr = parse_add (lexer);
4564   int expr_end = lex_ofs (lexer) - 1;
4565   if (!expr || !lex_force_match (lexer, T_RPAREN))
4566     {
4567       free (name);
4568       return false;
4569     }
4570   int pcompute_end = lex_ofs (lexer) - 1;
4571
4572   struct msg_location *location = lex_ofs_location (lexer, pcompute_start,
4573                                                     pcompute_end);
4574
4575   struct ctables_postcompute *pc = ctables_find_postcompute (ct, name);
4576   if (pc)
4577     {
4578       msg_at (SW, location, _("New definition of &%s will override the "
4579                               "previous definition."),
4580               pc->name);
4581       msg_at (SN, pc->location, _("This is the previous definition."));
4582
4583       ctables_pcexpr_destroy (pc->expr);
4584       msg_location_destroy (pc->location);
4585       free (name);
4586     }
4587   else
4588     {
4589       pc = xmalloc (sizeof *pc);
4590       *pc = (struct ctables_postcompute) { .name = name };
4591       hmap_insert (&ct->postcomputes, &pc->hmap_node,
4592                    utf8_hash_case_string (pc->name, 0));
4593     }
4594   pc->expr = expr;
4595   pc->location = location;
4596   if (!pc->label)
4597     pc->label = lex_ofs_representation (lexer, expr_start, expr_end);
4598   return true;
4599 }
4600
4601 static bool
4602 ctables_parse_pproperties_format (struct lexer *lexer,
4603                                   struct ctables_summary_spec_set *sss)
4604 {
4605   *sss = (struct ctables_summary_spec_set) { .n = 0 };
4606
4607   while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH
4608          && !(lex_token (lexer) == T_ID
4609               && (lex_id_match (ss_cstr ("LABEL"), lex_tokss (lexer))
4610                   || lex_id_match (ss_cstr ("HIDESOURCECATS"),
4611                                    lex_tokss (lexer)))))
4612     {
4613       /* Parse function. */
4614       enum ctables_summary_function function;
4615       if (!parse_ctables_summary_function (lexer, &function))
4616         goto error;
4617
4618       /* Parse percentile. */
4619       double percentile = 0;
4620       if (function == CTSF_PTILE)
4621         {
4622           if (!lex_force_num_range_closed (lexer, "PTILE", 0, 100))
4623             goto error;
4624           percentile = lex_number (lexer);
4625           lex_get (lexer);
4626         }
4627
4628       /* Parse format. */
4629       struct fmt_spec format;
4630       if (!parse_format_specifier (lexer, &format)
4631           || !fmt_check_output (&format)
4632           || !fmt_check_type_compat (&format, VAL_NUMERIC))
4633         goto error;
4634
4635       if (sss->n >= sss->allocated)
4636         sss->specs = x2nrealloc (sss->specs, &sss->allocated,
4637                                  sizeof *sss->specs);
4638       sss->specs[sss->n++] = (struct ctables_summary_spec) {
4639         .function = function,
4640         .percentile = percentile,
4641         .format = format,
4642       };
4643     }
4644   return true;
4645
4646 error:
4647   ctables_summary_spec_set_uninit (sss);
4648   return false;
4649 }
4650
4651 static bool
4652 ctables_parse_pproperties (struct lexer *lexer, struct ctables *ct)
4653 {
4654   struct ctables_postcompute **pcs = NULL;
4655   size_t n_pcs = 0;
4656   size_t allocated_pcs = 0;
4657
4658   while (lex_match (lexer, T_AND))
4659     {
4660       if (!lex_force_id (lexer))
4661         goto error;
4662       struct ctables_postcompute *pc
4663         = ctables_find_postcompute (ct, lex_tokcstr (lexer));
4664       if (!pc)
4665         {
4666           msg (SE, _("Unknown computed category &%s."), lex_tokcstr (lexer));
4667           goto error;
4668         }
4669       lex_get (lexer);
4670
4671       if (n_pcs >= allocated_pcs)
4672         pcs = x2nrealloc (pcs, &allocated_pcs, sizeof *pcs);
4673       pcs[n_pcs++] = pc;
4674     }
4675
4676   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
4677     {
4678       if (lex_match_id (lexer, "LABEL"))
4679         {
4680           lex_match (lexer, T_EQUALS);
4681           if (!lex_force_string (lexer))
4682             goto error;
4683
4684           for (size_t i = 0; i < n_pcs; i++)
4685             {
4686               free (pcs[i]->label);
4687               pcs[i]->label = ss_xstrdup (lex_tokss (lexer));
4688             }
4689
4690           lex_get (lexer);
4691         }
4692       else if (lex_match_id (lexer, "FORMAT"))
4693         {
4694           lex_match (lexer, T_EQUALS);
4695
4696           struct ctables_summary_spec_set sss;
4697           if (!ctables_parse_pproperties_format (lexer, &sss))
4698             goto error;
4699
4700           for (size_t i = 0; i < n_pcs; i++)
4701             {
4702               if (pcs[i]->specs)
4703                 ctables_summary_spec_set_uninit (pcs[i]->specs);
4704               else
4705                 pcs[i]->specs = xmalloc (sizeof *pcs[i]->specs);
4706               ctables_summary_spec_set_clone (pcs[i]->specs, &sss);
4707             }
4708           ctables_summary_spec_set_uninit (&sss);
4709         }
4710       else if (lex_match_id (lexer, "HIDESOURCECATS"))
4711         {
4712           lex_match (lexer, T_EQUALS);
4713           bool hide_source_cats;
4714           if (!parse_bool (lexer, &hide_source_cats))
4715             goto error;
4716           for (size_t i = 0; i < n_pcs; i++)
4717             pcs[i]->hide_source_cats = hide_source_cats;
4718         }
4719       else
4720         {
4721           lex_error_expecting (lexer, "LABEL", "FORMAT", "HIDESOURCECATS");
4722           goto error;
4723         }
4724     }
4725   free (pcs);
4726   return true;
4727
4728 error:
4729   free (pcs);
4730   return false;
4731 }
4732
4733 int
4734 cmd_ctables (struct lexer *lexer, struct dataset *ds)
4735 {
4736   size_t n_vars = dict_get_n_vars (dataset_dict (ds));
4737   enum ctables_vlabel *vlabels = xnmalloc (n_vars, sizeof *vlabels);
4738   enum settings_value_show tvars = settings_get_show_variables ();
4739   for (size_t i = 0; i < n_vars; i++)
4740     vlabels[i] = (enum ctables_vlabel) tvars;
4741
4742   struct pivot_table_look *look = pivot_table_look_unshare (
4743     pivot_table_look_ref (pivot_table_look_get_default ()));
4744   look->omit_empty = false;
4745
4746   struct ctables *ct = xmalloc (sizeof *ct);
4747   *ct = (struct ctables) {
4748     .dict = dataset_dict (ds),
4749     .look = look,
4750     .ctables_formats = FMT_SETTINGS_INIT,
4751     .vlabels = vlabels,
4752     .postcomputes = HMAP_INITIALIZER (ct->postcomputes),
4753   };
4754
4755   struct ctf
4756     {
4757       enum fmt_type type;
4758       const char *dot_string;
4759       const char *comma_string;
4760     };
4761   static const struct ctf ctfs[4] = {
4762     { CTEF_NEGPAREN, "(,,,)",   "(...)" },
4763     { CTEF_NEQUAL,   "-,N=,,",  "-.N=.." },
4764     { CTEF_PAREN,    "-,(,),",  "-.(.)." },
4765     { CTEF_PCTPAREN, "-,(,%),", "-.(.%)." },
4766   };
4767   bool is_dot = settings_get_fmt_settings ()->decimal == '.';
4768   for (size_t i = 0; i < 4; i++)
4769     {
4770       const char *s = is_dot ? ctfs[i].dot_string : ctfs[i].comma_string;
4771       fmt_settings_set_cc (&ct->ctables_formats, ctfs[i].type,
4772                            fmt_number_style_from_string (s));
4773     }
4774
4775   if (!lex_force_match (lexer, T_SLASH))
4776     goto error;
4777
4778   while (!lex_match_id (lexer, "TABLE"))
4779     {
4780       if (lex_match_id (lexer, "FORMAT"))
4781         {
4782           double widths[2] = { SYSMIS, SYSMIS };
4783           double units_per_inch = 72.0;
4784
4785           while (lex_token (lexer) != T_SLASH)
4786             {
4787               if (lex_match_id (lexer, "MINCOLWIDTH"))
4788                 {
4789                   if (!parse_col_width (lexer, "MINCOLWIDTH", &widths[0]))
4790                     goto error;
4791                 }
4792               else if (lex_match_id (lexer, "MAXCOLWIDTH"))
4793                 {
4794                   if (!parse_col_width (lexer, "MAXCOLWIDTH", &widths[1]))
4795                     goto error;
4796                 }
4797               else if (lex_match_id (lexer, "UNITS"))
4798                 {
4799                   lex_match (lexer, T_EQUALS);
4800                   if (lex_match_id (lexer, "POINTS"))
4801                     units_per_inch = 72.0;
4802                   else if (lex_match_id (lexer, "INCHES"))
4803                     units_per_inch = 1.0;
4804                   else if (lex_match_id (lexer, "CM"))
4805                     units_per_inch = 2.54;
4806                   else
4807                     {
4808                       lex_error_expecting (lexer, "POINTS", "INCHES", "CM");
4809                       goto error;
4810                     }
4811                 }
4812               else if (lex_match_id (lexer, "EMPTY"))
4813                 {
4814                   free (ct->zero);
4815                   ct->zero = NULL;
4816
4817                   lex_match (lexer, T_EQUALS);
4818                   if (lex_match_id (lexer, "ZERO"))
4819                     {
4820                       /* Nothing to do. */
4821                     }
4822                   else if (lex_match_id (lexer, "BLANK"))
4823                     ct->zero = xstrdup ("");
4824                   else if (lex_force_string (lexer))
4825                     {
4826                       ct->zero = ss_xstrdup (lex_tokss (lexer));
4827                       lex_get (lexer);
4828                     }
4829                   else
4830                     goto error;
4831                 }
4832               else if (lex_match_id (lexer, "MISSING"))
4833                 {
4834                   lex_match (lexer, T_EQUALS);
4835                   if (!lex_force_string (lexer))
4836                     goto error;
4837
4838                   free (ct->missing);
4839                   ct->missing = (strcmp (lex_tokcstr (lexer), ".")
4840                                  ? ss_xstrdup (lex_tokss (lexer))
4841                                  : NULL);
4842                   lex_get (lexer);
4843                 }
4844               else
4845                 {
4846                   lex_error_expecting (lexer, "MINCOLWIDTH", "MAXCOLWIDTH",
4847                                        "UNITS", "EMPTY", "MISSING");
4848                   goto error;
4849                 }
4850             }
4851
4852           if (widths[0] != SYSMIS && widths[1] != SYSMIS
4853               && widths[0] > widths[1])
4854             {
4855               msg (SE, _("MINCOLWIDTH must not be greater than MAXCOLWIDTH."));
4856               goto error;
4857             }
4858
4859           for (size_t i = 0; i < 2; i++)
4860             if (widths[i] != SYSMIS)
4861               {
4862                 int *wr = ct->look->width_ranges[TABLE_HORZ];
4863                 wr[i] = widths[i] / units_per_inch * 96.0;
4864                 if (wr[0] > wr[1])
4865                   wr[!i] = wr[i];
4866               }
4867         }
4868       else if (lex_match_id (lexer, "VLABELS"))
4869         {
4870           if (!lex_force_match_id (lexer, "VARIABLES"))
4871             goto error;
4872           lex_match (lexer, T_EQUALS);
4873
4874           struct variable **vars;
4875           size_t n_vars;
4876           if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
4877                                 PV_NO_SCRATCH))
4878             goto error;
4879
4880           if (!lex_force_match_id (lexer, "DISPLAY"))
4881             {
4882               free (vars);
4883               goto error;
4884             }
4885           lex_match (lexer, T_EQUALS);
4886
4887           enum ctables_vlabel vlabel;
4888           if (lex_match_id (lexer, "DEFAULT"))
4889             vlabel = (enum ctables_vlabel) settings_get_show_variables ();
4890           else if (lex_match_id (lexer, "NAME"))
4891             vlabel = CTVL_NAME;
4892           else if (lex_match_id (lexer, "LABEL"))
4893             vlabel = CTVL_LABEL;
4894           else if (lex_match_id (lexer, "BOTH"))
4895             vlabel = CTVL_BOTH;
4896           else if (lex_match_id (lexer, "NONE"))
4897             vlabel = CTVL_NONE;
4898           else
4899             {
4900               lex_error_expecting (lexer, "DEFAULT", "NAME", "LABEL",
4901                                    "BOTH", "NONE");
4902               free (vars);
4903               goto error;
4904             }
4905
4906           for (size_t i = 0; i < n_vars; i++)
4907             ct->vlabels[var_get_dict_index (vars[i])] = vlabel;
4908           free (vars);
4909         }
4910       else if (lex_match_id (lexer, "MRSETS"))
4911         {
4912           if (!lex_force_match_id (lexer, "COUNTDUPLICATES"))
4913             goto error;
4914           lex_match (lexer, T_EQUALS);
4915           if (!parse_bool (lexer, &ct->mrsets_count_duplicates))
4916             goto error;
4917         }
4918       else if (lex_match_id (lexer, "SMISSING"))
4919         {
4920           if (lex_match_id (lexer, "VARIABLE"))
4921             ct->smissing_listwise = false;
4922           else if (lex_match_id (lexer, "LISTWISE"))
4923             ct->smissing_listwise = true;
4924           else
4925             {
4926               lex_error_expecting (lexer, "VARIABLE", "LISTWISE");
4927               goto error;
4928             }
4929         }
4930       else if (lex_match_id (lexer, "PCOMPUTE"))
4931         {
4932           if (!ctables_parse_pcompute (lexer, ct))
4933             goto error;
4934         }
4935       else if (lex_match_id (lexer, "PPROPERTIES"))
4936         {
4937           if (!ctables_parse_pproperties (lexer, ct))
4938             goto error;
4939         }
4940       else if (lex_match_id (lexer, "WEIGHT"))
4941         {
4942           if (!lex_force_match_id (lexer, "VARIABLE"))
4943             goto error;
4944           lex_match (lexer, T_EQUALS);
4945           ct->e_weight = parse_variable (lexer, dataset_dict (ds));
4946           if (!ct->e_weight)
4947             goto error;
4948         }
4949       else if (lex_match_id (lexer, " HIDESMALLCOUNTS"))
4950         {
4951           if (lex_match_id (lexer, "COUNT"))
4952             {
4953               lex_match (lexer, T_EQUALS);
4954               if (!lex_force_int_range (lexer, "HIDESMALLCOUNTS COUNT",
4955                                         2, INT_MAX))
4956                 goto error;
4957               ct->hide_threshold = lex_integer (lexer);
4958               lex_get (lexer);
4959             }
4960           else if (ct->hide_threshold == 0)
4961             ct->hide_threshold = 5;
4962         }
4963       else
4964         {
4965           lex_error_expecting (lexer, "FORMAT", "VLABELS", "MRSETS",
4966                                "SMISSING", "PCOMPUTE", "PPROPERTIES",
4967                                "WEIGHT", "HIDESMALLCOUNTS", "TABLE");
4968           goto error;
4969         }
4970
4971       if (!lex_force_match (lexer, T_SLASH))
4972         goto error;
4973     }
4974
4975   size_t allocated_tables = 0;
4976   do
4977     {
4978       if (ct->n_tables >= allocated_tables)
4979         ct->tables = x2nrealloc (ct->tables, &allocated_tables,
4980                                  sizeof *ct->tables);
4981
4982       struct ctables_category *cat = xmalloc (sizeof *cat);
4983       *cat = (struct ctables_category) {
4984         .type = CCT_VALUE,
4985         .include_missing = false,
4986         .sort_ascending = true,
4987       };
4988
4989       struct ctables_categories *c = xmalloc (sizeof *c);
4990       size_t n_vars = dict_get_n_vars (dataset_dict (ds));
4991       *c = (struct ctables_categories) {
4992         .n_refs = n_vars,
4993         .cats = cat,
4994         .n_cats = 1,
4995         .show_empty = true,
4996       };
4997
4998       struct ctables_categories **categories = xnmalloc (n_vars,
4999                                                          sizeof *categories);
5000       for (size_t i = 0; i < n_vars; i++)
5001         categories[i] = c;
5002
5003       struct ctables_table *t = xmalloc (sizeof *t);
5004       *t = (struct ctables_table) {
5005         .ctables = ct,
5006         .slabels_axis = PIVOT_AXIS_COLUMN,
5007         .slabels_visible = true,
5008         .clabels_values_map = HMAP_INITIALIZER (t->clabels_values_map),
5009         .label_axis = {
5010           [PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW,
5011           [PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN,
5012           [PIVOT_AXIS_LAYER] = PIVOT_AXIS_LAYER,
5013         },
5014         .clabels_from_axis = PIVOT_AXIS_LAYER,
5015         .categories = categories,
5016         .n_categories = n_vars,
5017         .cilevel = 95,
5018       };
5019       ct->tables[ct->n_tables++] = t;
5020
5021       lex_match (lexer, T_EQUALS);
5022       if (!ctables_axis_parse (lexer, dataset_dict (ds), ct, t, PIVOT_AXIS_ROW))
5023         goto error;
5024       if (lex_match (lexer, T_BY))
5025         {
5026           if (!ctables_axis_parse (lexer, dataset_dict (ds),
5027                                    ct, t, PIVOT_AXIS_COLUMN))
5028             goto error;
5029
5030           if (lex_match (lexer, T_BY))
5031             {
5032               if (!ctables_axis_parse (lexer, dataset_dict (ds),
5033                                        ct, t, PIVOT_AXIS_LAYER))
5034                 goto error;
5035             }
5036         }
5037
5038       if (!t->axes[PIVOT_AXIS_ROW] && !t->axes[PIVOT_AXIS_COLUMN]
5039           && !t->axes[PIVOT_AXIS_LAYER])
5040         {
5041           lex_error (lexer, _("At least one variable must be specified."));
5042           goto error;
5043         }
5044
5045       const struct ctables_axis *scales[PIVOT_N_AXES];
5046       size_t n_scales = 0;
5047       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
5048         {
5049           scales[a] = find_scale (t->axes[a]);
5050           if (scales[a])
5051             n_scales++;
5052         }
5053       if (n_scales > 1)
5054         {
5055           msg (SE, _("Scale variables may appear only on one axis."));
5056           if (scales[PIVOT_AXIS_ROW])
5057             msg_at (SN, scales[PIVOT_AXIS_ROW]->loc,
5058                     _("This scale variable appears on the rows axis."));
5059           if (scales[PIVOT_AXIS_COLUMN])
5060             msg_at (SN, scales[PIVOT_AXIS_COLUMN]->loc,
5061                     _("This scale variable appears on the columns axis."));
5062           if (scales[PIVOT_AXIS_LAYER])
5063             msg_at (SN, scales[PIVOT_AXIS_LAYER]->loc,
5064                     _("This scale variable appears on the layer axis."));
5065           goto error;
5066         }
5067
5068       const struct ctables_axis *summaries[PIVOT_N_AXES];
5069       size_t n_summaries = 0;
5070       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
5071         {
5072           summaries[a] = (scales[a]
5073                           ? scales[a]
5074                           : find_categorical_summary_spec (t->axes[a]));
5075           if (summaries[a])
5076             n_summaries++;
5077         }
5078       if (n_summaries > 1)
5079         {
5080           msg (SE, _("Summaries may appear only on one axis."));
5081           if (summaries[PIVOT_AXIS_ROW])
5082             msg_at (SN, summaries[PIVOT_AXIS_ROW]->loc,
5083                     _("This variable on the rows axis has a summary."));
5084           if (summaries[PIVOT_AXIS_COLUMN])
5085             msg_at (SN, summaries[PIVOT_AXIS_COLUMN]->loc,
5086                     _("This variable on the columns axis has a summary."));
5087           if (summaries[PIVOT_AXIS_LAYER])
5088             msg_at (SN, summaries[PIVOT_AXIS_LAYER]->loc,
5089                     _("This variable on the layers axis has a summary."));
5090           goto error;
5091         }
5092       for (enum pivot_axis_type a = 0; a < PIVOT_N_AXES; a++)
5093         if (n_summaries ? summaries[a] : t->axes[a])
5094           {
5095             t->summary_axis = a;
5096             break;
5097           }
5098
5099       if (lex_token (lexer) == T_ENDCMD)
5100         {
5101           if (!ctables_prepare_table (t))
5102             goto error;
5103           break;
5104         }
5105       if (!lex_force_match (lexer, T_SLASH))
5106         break;
5107
5108       while (!lex_match_id (lexer, "TABLE") && lex_token (lexer) != T_ENDCMD)
5109         {
5110           if (lex_match_id (lexer, "SLABELS"))
5111             {
5112               while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
5113                 {
5114                   if (lex_match_id (lexer, "POSITION"))
5115                     {
5116                       lex_match (lexer, T_EQUALS);
5117                       if (lex_match_id (lexer, "COLUMN"))
5118                         t->slabels_axis = PIVOT_AXIS_COLUMN;
5119                       else if (lex_match_id (lexer, "ROW"))
5120                         t->slabels_axis = PIVOT_AXIS_ROW;
5121                       else if (lex_match_id (lexer, "LAYER"))
5122                         t->slabels_axis = PIVOT_AXIS_LAYER;
5123                       else
5124                         {
5125                           lex_error_expecting (lexer, "COLUMN", "ROW", "LAYER");
5126                           goto error;
5127                         }
5128                     }
5129                   else if (lex_match_id (lexer, "VISIBLE"))
5130                     {
5131                       lex_match (lexer, T_EQUALS);
5132                       if (!parse_bool (lexer, &t->slabels_visible))
5133                         goto error;
5134                     }
5135                   else
5136                     {
5137                       lex_error_expecting (lexer, "POSITION", "VISIBLE");
5138                       goto error;
5139                     }
5140                 }
5141             }
5142           else if (lex_match_id (lexer, "CLABELS"))
5143             {
5144               while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
5145                 {
5146                   if (lex_match_id (lexer, "AUTO"))
5147                     {
5148                       t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_ROW;
5149                       t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_COLUMN;
5150                     }
5151                   else if (lex_match_id (lexer, "ROWLABELS"))
5152                     {
5153                       lex_match (lexer, T_EQUALS);
5154                       if (lex_match_id (lexer, "OPPOSITE"))
5155                         t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_COLUMN;
5156                       else if (lex_match_id (lexer, "LAYER"))
5157                         t->label_axis[PIVOT_AXIS_ROW] = PIVOT_AXIS_LAYER;
5158                       else
5159                         {
5160                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
5161                           goto error;
5162                         }
5163                     }
5164                   else if (lex_match_id (lexer, "COLLABELS"))
5165                     {
5166                       lex_match (lexer, T_EQUALS);
5167                       if (lex_match_id (lexer, "OPPOSITE"))
5168                         t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_ROW;
5169                       else if (lex_match_id (lexer, "LAYER"))
5170                         t->label_axis[PIVOT_AXIS_COLUMN] = PIVOT_AXIS_LAYER;
5171                       else
5172                         {
5173                           lex_error_expecting (lexer, "OPPOSITE", "LAYER");
5174                           goto error;
5175                         }
5176                     }
5177                   else
5178                     {
5179                       lex_error_expecting (lexer, "AUTO", "ROWLABELS",
5180                                            "COLLABELS");
5181                       goto error;
5182                     }
5183                 }
5184             }
5185           else if (lex_match_id (lexer, "CRITERIA"))
5186             {
5187               if (!lex_force_match_id (lexer, "CILEVEL"))
5188                 goto error;
5189               lex_match (lexer, T_EQUALS);
5190
5191               if (!lex_force_num_range_halfopen (lexer, "CILEVEL", 0, 100))
5192                 goto error;
5193               t->cilevel = lex_number (lexer);
5194               lex_get (lexer);
5195             }
5196           else if (lex_match_id (lexer, "CATEGORIES"))
5197             {
5198               if (!ctables_table_parse_categories (lexer, dataset_dict (ds),
5199                                                    ct, t))
5200                 goto error;
5201             }
5202           else if (lex_match_id (lexer, "TITLES"))
5203             {
5204               do
5205                 {
5206                   char **textp;
5207                   if (lex_match_id (lexer, "CAPTION"))
5208                     textp = &t->caption;
5209                   else if (lex_match_id (lexer, "CORNER"))
5210                     textp = &t->corner;
5211                   else if (lex_match_id (lexer, "TITLE"))
5212                     textp = &t->title;
5213                   else
5214                     {
5215                       lex_error_expecting (lexer, "CAPTION", "CORNER", "TITLE");
5216                       goto error;
5217                     }
5218                   lex_match (lexer, T_EQUALS);
5219
5220                   struct string s = DS_EMPTY_INITIALIZER;
5221                   while (lex_is_string (lexer))
5222                     {
5223                       if (!ds_is_empty (&s))
5224                         ds_put_byte (&s, ' ');
5225                       ds_put_substring (&s, lex_tokss (lexer));
5226                       lex_get (lexer);
5227                     }
5228                   free (*textp);
5229                   *textp = ds_steal_cstr (&s);
5230                 }
5231               while (lex_token (lexer) != T_SLASH
5232                      && lex_token (lexer) != T_ENDCMD);
5233             }
5234           else if (lex_match_id (lexer, "SIGTEST"))
5235             {
5236               if (!t->chisq)
5237                 {
5238                   t->chisq = xmalloc (sizeof *t->chisq);
5239                   *t->chisq = (struct ctables_chisq) {
5240                     .alpha = .05,
5241                     .include_mrsets = true,
5242                     .all_visible = true,
5243                   };
5244                 }
5245
5246               do
5247                 {
5248                   if (lex_match_id (lexer, "TYPE"))
5249                     {
5250                       lex_match (lexer, T_EQUALS);
5251                       if (!lex_force_match_id (lexer, "CHISQUARE"))
5252                         goto error;
5253                     }
5254                   else if (lex_match_id (lexer, "ALPHA"))
5255                     {
5256                       lex_match (lexer, T_EQUALS);
5257                       if (!lex_force_num_range_halfopen (lexer, "ALPHA", 0, 1))
5258                         goto error;
5259                       t->chisq->alpha = lex_number (lexer);
5260                       lex_get (lexer);
5261                     }
5262                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
5263                     {
5264                       lex_match (lexer, T_EQUALS);
5265                       if (parse_bool (lexer, &t->chisq->include_mrsets))
5266                         goto error;
5267                     }
5268                   else if (lex_match_id (lexer, "CATEGORIES"))
5269                     {
5270                       lex_match (lexer, T_EQUALS);
5271                       if (lex_match_id (lexer, "ALLVISIBLE"))
5272                         t->chisq->all_visible = true;
5273                       else if (lex_match_id (lexer, "SUBTOTALS"))
5274                         t->chisq->all_visible = false;
5275                       else
5276                         {
5277                           lex_error_expecting (lexer,
5278                                                "ALLVISIBLE", "SUBTOTALS");
5279                           goto error;
5280                         }
5281                     }
5282                   else
5283                     {
5284                       lex_error_expecting (lexer, "TYPE", "ALPHA",
5285                                            "INCLUDEMRSETS", "CATEGORIES");
5286                       goto error;
5287                     }
5288                 }
5289               while (lex_token (lexer) != T_SLASH
5290                      && lex_token (lexer) != T_ENDCMD);
5291             }
5292           else if (lex_match_id (lexer, "COMPARETEST"))
5293             {
5294               if (!t->pairwise)
5295                 {
5296                   t->pairwise = xmalloc (sizeof *t->pairwise);
5297                   *t->pairwise = (struct ctables_pairwise) {
5298                     .type = PROP,
5299                     .alpha = { .05, .05 },
5300                     .adjust = BONFERRONI,
5301                     .include_mrsets = true,
5302                     .meansvariance_allcats = true,
5303                     .all_visible = true,
5304                     .merge = false,
5305                     .apa_style = true,
5306                     .show_sig = false,
5307                   };
5308                 }
5309
5310               do
5311                 {
5312                   if (lex_match_id (lexer, "TYPE"))
5313                     {
5314                       lex_match (lexer, T_EQUALS);
5315                       if (lex_match_id (lexer, "PROP"))
5316                         t->pairwise->type = PROP;
5317                       else if (lex_match_id (lexer, "MEAN"))
5318                         t->pairwise->type = MEAN;
5319                       else
5320                         {
5321                           lex_error_expecting (lexer, "PROP", "MEAN");
5322                           goto error;
5323                         }
5324                     }
5325                   else if (lex_match_id (lexer, "ALPHA"))
5326                     {
5327                       lex_match (lexer, T_EQUALS);
5328
5329                       if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
5330                         goto error;
5331                       double a0 = lex_number (lexer);
5332                       lex_get (lexer);
5333
5334                       lex_match (lexer, T_COMMA);
5335                       if (lex_is_number (lexer))
5336                         {
5337                           if (!lex_force_num_range_open (lexer, "ALPHA", 0, 1))
5338                             goto error;
5339                           double a1 = lex_number (lexer);
5340                           lex_get (lexer);
5341
5342                           t->pairwise->alpha[0] = MIN (a0, a1);
5343                           t->pairwise->alpha[1] = MAX (a0, a1);
5344                         }
5345                       else
5346                         t->pairwise->alpha[0] = t->pairwise->alpha[1] = a0;
5347                     }
5348                   else if (lex_match_id (lexer, "ADJUST"))
5349                     {
5350                       lex_match (lexer, T_EQUALS);
5351                       if (lex_match_id (lexer, "BONFERRONI"))
5352                         t->pairwise->adjust = BONFERRONI;
5353                       else if (lex_match_id (lexer, "BH"))
5354                         t->pairwise->adjust = BH;
5355                       else if (lex_match_id (lexer, "NONE"))
5356                         t->pairwise->adjust = 0;
5357                       else
5358                         {
5359                           lex_error_expecting (lexer, "BONFERRONI", "BH",
5360                                                "NONE");
5361                           goto error;
5362                         }
5363                     }
5364                   else if (lex_match_id (lexer, "INCLUDEMRSETS"))
5365                     {
5366                       lex_match (lexer, T_EQUALS);
5367                       if (!parse_bool (lexer, &t->pairwise->include_mrsets))
5368                         goto error;
5369                     }
5370                   else if (lex_match_id (lexer, "MEANSVARIANCE"))
5371                     {
5372                       lex_match (lexer, T_EQUALS);
5373                       if (lex_match_id (lexer, "ALLCATS"))
5374                         t->pairwise->meansvariance_allcats = true;
5375                       else if (lex_match_id (lexer, "TESTEDCATS"))
5376                         t->pairwise->meansvariance_allcats = false;
5377                       else
5378                         {
5379                           lex_error_expecting (lexer, "ALLCATS", "TESTEDCATS");
5380                           goto error;
5381                         }
5382                     }
5383                   else if (lex_match_id (lexer, "CATEGORIES"))
5384                     {
5385                       lex_match (lexer, T_EQUALS);
5386                       if (lex_match_id (lexer, "ALLVISIBLE"))
5387                         t->pairwise->all_visible = true;
5388                       else if (lex_match_id (lexer, "SUBTOTALS"))
5389                         t->pairwise->all_visible = false;
5390                       else
5391                         {
5392                           lex_error_expecting (lexer, "ALLVISIBLE",
5393                                                "SUBTOTALS");
5394                           goto error;
5395                         }
5396                     }
5397                   else if (lex_match_id (lexer, "MERGE"))
5398                     {
5399                       lex_match (lexer, T_EQUALS);
5400                       if (!parse_bool (lexer, &t->pairwise->merge))
5401                         goto error;
5402                     }
5403                   else if (lex_match_id (lexer, "STYLE"))
5404                     {
5405                       lex_match (lexer, T_EQUALS);
5406                       if (lex_match_id (lexer, "APA"))
5407                         t->pairwise->apa_style = true;
5408                       else if (lex_match_id (lexer, "SIMPLE"))
5409                         t->pairwise->apa_style = false;
5410                       else
5411                         {
5412                           lex_error_expecting (lexer, "APA", "SIMPLE");
5413                           goto error;
5414                         }
5415                     }
5416                   else if (lex_match_id (lexer, "SHOWSIG"))
5417                     {
5418                       lex_match (lexer, T_EQUALS);
5419                       if (!parse_bool (lexer, &t->pairwise->show_sig))
5420                         goto error;
5421                     }
5422                   else
5423                     {
5424                       lex_error_expecting (lexer, "TYPE", "ALPHA", "ADJUST",
5425                                            "INCLUDEMRSETS", "MEANSVARIANCE",
5426                                            "CATEGORIES", "MERGE", "STYLE",
5427                                            "SHOWSIG");
5428                       goto error;
5429                     }
5430                 }
5431               while (lex_token (lexer) != T_SLASH
5432                      && lex_token (lexer) != T_ENDCMD);
5433             }
5434           else
5435             {
5436               lex_error_expecting (lexer, "TABLE", "SLABELS", "CLABELS",
5437                                    "CRITERIA", "CATEGORIES", "TITLES",
5438                                    "SIGTEST", "COMPARETEST");
5439               goto error;
5440             }
5441
5442           if (!lex_match (lexer, T_SLASH))
5443             break;
5444         }
5445
5446       if (t->label_axis[PIVOT_AXIS_ROW] != PIVOT_AXIS_ROW
5447           && t->label_axis[PIVOT_AXIS_COLUMN] != PIVOT_AXIS_COLUMN)
5448         {
5449           msg (SE, _("ROWLABELS and COLLABELS may not both be specified."));
5450           goto error;
5451         }
5452
5453       if (!ctables_prepare_table (t))
5454         goto error;
5455     }
5456   while (lex_token (lexer) != T_ENDCMD);
5457
5458   bool ok = ctables_execute (ds, ct);
5459   ctables_destroy (ct);
5460   return ok ? CMD_SUCCESS : CMD_FAILURE;
5461
5462 error:
5463   ctables_destroy (ct);
5464   return CMD_FAILURE;
5465 }
5466