Improve error messages for format specifiers.
[pspp] / src / language / expressions / evaluate.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2007, 2009, 2010, 2011, 2012 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 "language/expressions/private.h"
20 #include "evaluate.h"
21
22 #include <ctype.h>
23
24 #include "libpspp/assertion.h"
25 #include "libpspp/message.h"
26 #include "language/expressions/helpers.h"
27 #include "language/lexer/format-parser.h"
28 #include "language/lexer/value-parser.h"
29 #include "libpspp/pool.h"
30 #include "output/driver.h"
31
32 #include "xalloc.h"
33
34 static void
35 expr_evaluate (struct expression *e, const struct ccase *c, int case_idx,
36                void *result)
37 {
38   struct dataset *ds = e->ds;
39   union operation_data *op = e->ops;
40
41   double *ns = e->number_stack;
42   struct substring *ss = e->string_stack;
43
44   /* Without a dictionary/dataset, the expression can't refer to variables,
45      and you don't need to specify a case when you evaluate the
46      expression.  With a dictionary/dataset, the expression can refer
47      to variables, so you must specify a case when you evaluate the
48      expression. */
49   assert ((c != NULL) == (e->ds != NULL));
50
51   pool_clear (e->eval_pool);
52
53   for (;;)
54     {
55       assert (op < e->ops + e->n_ops);
56       switch (op++->operation)
57         {
58         case OP_number:
59         case OP_boolean:
60           *ns++ = op++->number;
61           break;
62
63         case OP_string:
64           {
65             const struct substring *s = &op++->string;
66             *ss++ = copy_string (e, s->string, s->length);
67           }
68           break;
69
70         case OP_return_number:
71           *(double *) result = isfinite (ns[-1]) ? ns[-1] : SYSMIS;
72           return;
73
74         case OP_return_string:
75           *(struct substring *) result = ss[-1];
76           return;
77
78 #include "evaluate.inc"
79
80         default:
81           NOT_REACHED ();
82         }
83     }
84 }
85
86 double
87 expr_evaluate_num (struct expression *e, const struct ccase *c, int case_idx)
88 {
89   double d;
90
91   assert (e->type == OP_number || e->type == OP_boolean);
92   expr_evaluate (e, c, case_idx, &d);
93   return d;
94 }
95
96 void
97 expr_evaluate_str (struct expression *e, const struct ccase *c, int case_idx,
98                    char *dst, size_t dst_size)
99 {
100   struct substring s;
101
102   assert (e->type == OP_string);
103   assert ((dst == NULL) == (dst_size == 0));
104   expr_evaluate (e, c, case_idx, &s);
105
106   buf_copy_rpad (dst, dst_size, s.string, s.length, ' ');
107 }
108 \f
109 #include "language/lexer/lexer.h"
110 #include "language/command.h"
111
112 static bool default_optimize = true;
113
114 int
115 cmd_debug_evaluate (struct lexer *lexer, struct dataset *dsother UNUSED)
116 {
117   bool optimize = default_optimize;
118   int retval = CMD_FAILURE;
119   bool dump_postfix = false;
120   bool set_defaults = false;
121
122   struct ccase *c = NULL;
123
124   struct dataset *ds = NULL;
125
126   char *name = NULL;
127   char *title = NULL;
128   struct fmt_spec format;
129   bool has_format = false;
130
131   struct expression *expr;
132
133   struct dictionary *d = NULL;
134
135   for (;;)
136     {
137       if (lex_match_id (lexer, "NOOPTIMIZE"))
138         optimize = false;
139       else if (lex_match_id (lexer, "OPTIMIZE"))
140         optimize = true;
141       else if (lex_match_id (lexer, "POSTFIX"))
142         dump_postfix = 1;
143       else if (lex_match_id (lexer, "SET"))
144         set_defaults = true;
145       else if (lex_match (lexer, T_LPAREN))
146         {
147           struct variable *v;
148
149           if (!lex_force_id (lexer))
150             goto done;
151           int name_ofs = lex_ofs (lexer);
152           name = xstrdup (lex_tokcstr (lexer));
153
154           lex_get (lexer);
155           if (!lex_force_match (lexer, T_EQUALS))
156             goto done;
157
158           union value value;
159           int width;
160           if (lex_is_number (lexer))
161             {
162               width = 0;
163               value.f = lex_number (lexer);
164               lex_get (lexer);
165             }
166           else if (lex_match_id (lexer, "SYSMIS"))
167             {
168               width = 0;
169               value.f = SYSMIS;
170             }
171           else if (lex_is_string (lexer))
172             {
173               width = ss_length (lex_tokss (lexer));
174               value.s = CHAR_CAST (uint8_t *, ss_xstrdup (lex_tokss (lexer)));
175               lex_get (lexer);
176             }
177           else
178             {
179               lex_error (lexer, _("Syntax error expecting number or string."));
180               goto done;
181             }
182
183           if  (ds == NULL)
184             {
185               ds = dataset_create (NULL, "");
186               d = dataset_dict (ds);
187             }
188
189           v = dict_create_var (d, name, width);
190           if (v == NULL)
191             {
192               lex_ofs_error (lexer, name_ofs, name_ofs,
193                              _("Duplicate variable name %s."), name);
194               value_destroy (&value, width);
195               goto done;
196             }
197           free (name);
198           name = NULL;
199
200           if (lex_match_id (lexer, "MISSING"))
201             {
202               struct missing_values mv;
203               mv_init (&mv, width);
204               mv_add_value (&mv, &value);
205               var_set_missing_values (v, &mv);
206               mv_destroy (&mv);
207             }
208
209           if (c == NULL)
210             c = case_create (dict_get_proto (d));
211           else
212             c = case_unshare_and_resize (c, dict_get_proto (d));
213           value_swap (case_data_rw (c, v), &value);
214           value_destroy (&value, width);
215
216           if (!lex_force_match (lexer, T_RPAREN))
217             goto done;
218         }
219       else if (lex_match_id (lexer, "VECTOR"))
220         {
221           struct variable **vars;
222           size_t n;
223           dict_get_vars_mutable (d, &vars, &n, 0);
224           dict_create_vector_assert (d, "V", vars, n);
225           free (vars);
226         }
227       else if (lex_match_id (lexer, "FORMAT"))
228         {
229           lex_match (lexer, T_EQUALS);
230           if (!parse_format_specifier (lexer, &format))
231             goto done;
232           char *error = fmt_check_output__ (&format);
233           if (!error)
234             error = fmt_check_type_compat__ (&format, VAL_NUMERIC);
235           if (error)
236             {
237               lex_next_error (lexer, -1, -1, "%s", error);
238               free (error);
239               goto done;
240             }
241           has_format = true;
242         }
243       else
244         break;
245     }
246
247   if (set_defaults)
248     {
249       retval = CMD_SUCCESS;
250       default_optimize = optimize;
251       goto done;
252     }
253
254   if (!lex_force_match (lexer, T_SLASH))
255     goto done;
256
257   for (size_t i = 1; ; i++)
258     if (lex_next_token (lexer, i) == T_ENDCMD)
259       {
260         title = lex_next_representation (lexer, 0, i - 1);
261         break;
262       }
263
264   expr = expr_parse_any (lexer, ds, optimize);
265   if (!expr || lex_end_of_command (lexer) != CMD_SUCCESS)
266     {
267       if (expr != NULL)
268         expr_free (expr);
269       output_log ("%s => error", title);
270       goto done;
271     }
272
273   if (dump_postfix)
274     expr_debug_print_postfix (expr);
275   else
276     switch (expr->type)
277       {
278       case OP_number:
279       case OP_num_vec_elem:
280         {
281           double d = expr_evaluate_num (expr, c, 0);
282           if (has_format)
283             {
284               char *output = data_out (&(const union value) { .f = d },
285                                        NULL, &format,
286                                        settings_get_fmt_settings ());
287               output_log ("%s => %s", title, output);
288               free (output);
289             }
290           else if (d == SYSMIS)
291             output_log ("%s => sysmis", title);
292           else
293             output_log ("%s => %.2f", title, d);
294         }
295         break;
296
297       case OP_boolean:
298         {
299           double b = expr_evaluate_num (expr, c, 0);
300           output_log ("%s => %s", title,
301                       b == SYSMIS ? "sysmis" : b == 0.0 ? "false" : "true");
302         }
303         break;
304
305       case OP_string:
306         {
307           struct substring out;
308           expr_evaluate (expr, c, 0, &out);
309           output_log ("%s => \"%.*s\"", title, (int) out.length, out.string);
310           break;
311         }
312
313       default:
314         NOT_REACHED ();
315       }
316
317   expr_free (expr);
318   retval = CMD_SUCCESS;
319
320  done:
321   dataset_destroy (ds);
322
323   case_unref (c);
324
325   free (name);
326   free (title);
327
328   return retval;
329 }
330
331 void
332 expr_debug_print_postfix (const struct expression *e)
333 {
334   struct string s = DS_EMPTY_INITIALIZER;
335
336   for (size_t i = 0; i < e->n_ops; i++)
337     {
338       union operation_data *op = &e->ops[i];
339       if (i > 0)
340         ds_put_byte (&s, ' ');
341       switch (e->op_types[i])
342         {
343         case OP_operation:
344           if (op->operation == OP_return_number)
345             ds_put_cstr (&s, "return_number");
346           else if (op->operation == OP_return_string)
347             ds_put_cstr (&s, "return_string");
348           else if (is_function (op->operation))
349             ds_put_format (&s, "%s", operations[op->operation].prototype);
350           else if (is_composite (op->operation))
351             ds_put_format (&s, "%s", operations[op->operation].name);
352           else
353             ds_put_format (&s, "%s:", operations[op->operation].name);
354           break;
355         case OP_number:
356           if (op->number != SYSMIS)
357             ds_put_format (&s, "n<%g>", op->number);
358           else
359             ds_put_cstr (&s, "n<SYSMIS>");
360           break;
361         case OP_string:
362           ds_put_cstr (&s, "s<");
363           ds_put_substring (&s, op->string);
364           ds_put_byte (&s, '>');
365           break;
366         case OP_format:
367           {
368             char str[FMT_STRING_LEN_MAX + 1];
369             fmt_to_string (op->format, str);
370             ds_put_format (&s, "f<%s>", str);
371           }
372           break;
373         case OP_variable:
374           ds_put_format (&s, "v<%s>", var_get_name (op->variable));
375           break;
376         case OP_vector:
377           ds_put_format (&s, "vec<%s>", vector_get_name (op->vector));
378           break;
379         case OP_integer:
380           ds_put_format (&s, "i<%d>", op->integer);
381           break;
382         case OP_expr_node:
383           ds_put_cstr (&s, "expr_node");
384           break;
385         default:
386           NOT_REACHED ();
387         }
388     }
389   output_log_nocopy (ds_steal_cstr (&s));
390 }