Make the expression code a little nicer and fix bugs found
[pspp-builds.git] / src / debug.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 2004 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18    02111-1307, USA. */
19
20 #include <config.h>
21 #include <assert.h>
22 #include <stdio.h>
23 #include "command.h"
24 #include "error.h"
25 #include "expr.h"
26 #include "lexer.h"
27 #include "var.h"
28
29 int
30 cmd_debug_evaluate (void)
31 {
32   struct expression *expr;
33   union value value;
34   enum expr_type expr_flags;
35   int dump_postfix = 0;
36
37   discard_variables ();
38
39   expr_flags = 0;
40   if (lex_match_id ("NOOPTIMIZE"))
41     expr_flags |= EXPR_NO_OPTIMIZE;
42   if (lex_match_id ("POSTFIX"))
43     dump_postfix = 1;
44   if (token != '/') 
45     {
46       lex_force_match ('/');
47       return CMD_FAILURE;
48     }
49   fprintf (stderr, "%s => ", lex_rest_of_line (NULL));
50   lex_get ();
51
52   expr = expr_parse (EXPR_ANY | expr_flags);
53   if (!expr || token != '.') 
54     {
55       fprintf (stderr, "error\n");
56       return CMD_FAILURE; 
57     }
58
59   if (dump_postfix) 
60     expr_debug_print_postfix (expr);
61   else 
62     {
63       expr_evaluate (expr, NULL, 0, &value);
64       switch (expr_get_type (expr)) 
65         {
66         case EXPR_NUMERIC:
67           if (value.f == SYSMIS)
68             fprintf (stderr, "sysmis\n");
69           else
70             fprintf (stderr, "%.2f\n", value.f);
71           break;
72       
73         case EXPR_BOOLEAN:
74           if (value.f == SYSMIS)
75             fprintf (stderr, "sysmis\n");
76           else if (value.f == 0.0)
77             fprintf (stderr, "false\n");
78           else
79             fprintf (stderr, "true\n");
80           break;
81
82         case EXPR_STRING:
83           fputc ('"', stderr);
84           fwrite (value.c + 1, value.c[0], 1, stderr);
85           fputs ("\"\n", stderr);
86           break;
87
88         default:
89           assert (0);
90         }
91     }
92   
93   expr_free (expr);
94   return CMD_SUCCESS;
95 }