Implement DATASET commands.
[pspp-builds.git] / src / language / command.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009, 2010, 2011 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/command.h"
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <ctype.h>
24 #include <errno.h>
25
26 #include "data/casereader.h"
27 #include "data/dataset.h"
28 #include "data/dictionary.h"
29 #include "data/session.h"
30 #include "data/settings.h"
31 #include "data/variable.h"
32 #include "language/lexer/command-name.h"
33 #include "language/lexer/lexer.h"
34 #include "libpspp/assertion.h"
35 #include "libpspp/compiler.h"
36 #include "libpspp/i18n.h"
37 #include "libpspp/message.h"
38 #include "libpspp/str.h"
39 #include "output/text-item.h"
40
41 #include "xalloc.h"
42 #include "xmalloca.h"
43
44 #include "gettext.h"
45 #define _(msgid) gettext (msgid)
46 #define N_(msgid) msgid
47 \f
48 /* Returns true if RESULT is a valid "enum cmd_result",
49    false otherwise. */
50 static inline bool
51 cmd_result_is_valid (enum cmd_result result)
52 {
53   return (result == CMD_SUCCESS || result == CMD_EOF || result == CMD_FINISH
54           || (result >= CMD_PRIVATE_FIRST && result <= CMD_PRIVATE_LAST)
55           || result == CMD_FAILURE || result == CMD_NOT_IMPLEMENTED
56           || result == CMD_CASCADING_FAILURE);
57 }
58
59 /* Returns true if RESULT indicates success,
60    false otherwise. */
61 bool
62 cmd_result_is_success (enum cmd_result result)
63 {
64   assert (cmd_result_is_valid (result));
65   return result > 0;
66 }
67
68 /* Returns true if RESULT indicates failure,
69    false otherwise. */
70 bool
71 cmd_result_is_failure (enum cmd_result result)
72 {
73   assert (cmd_result_is_valid (result));
74   return result < 0;
75 }
76 \f
77 /* Command processing states. */
78 enum states
79   {
80     S_INITIAL = 0x01,         /* Allowed before active dataset defined. */
81     S_DATA = 0x02,            /* Allowed after active dataset defined. */
82     S_INPUT_PROGRAM = 0x04,   /* Allowed in INPUT PROGRAM. */
83     S_FILE_TYPE = 0x08,       /* Allowed in FILE TYPE. */
84     S_ANY = 0x0f              /* Allowed anywhere. */
85   };
86
87 /* Other command requirements. */
88 enum flags
89   {
90     F_ENHANCED = 0x10,        /* Allowed only in enhanced syntax mode. */
91     F_TESTING = 0x20,         /* Allowed only in testing mode. */
92     F_ABBREV = 0x80           /* Not a candidate for name completion. */
93   };
94
95 /* A single command. */
96 struct command
97   {
98     enum states states;         /* States in which command is allowed. */
99     enum flags flags;           /* Other command requirements. */
100     const char *name;           /* Command name. */
101     int (*function) (struct lexer *, struct dataset *); /* Function to call. */
102   };
103
104 /* Define the command array. */
105 #define DEF_CMD(STATES, FLAGS, NAME, FUNCTION) {STATES, FLAGS, NAME, FUNCTION},
106 #define UNIMPL_CMD(NAME, DESCRIPTION) {S_ANY, 0, NAME, NULL},
107 static const struct command commands[] =
108   {
109 #include "command.def"
110   };
111 #undef DEF_CMD
112 #undef UNIMPL_CMD
113
114 static const size_t command_cnt = sizeof commands / sizeof *commands;
115
116 static bool in_correct_state (const struct command *, enum cmd_state);
117 static bool report_state_mismatch (const struct command *, enum cmd_state);
118 static void set_completion_state (enum cmd_state);
119 \f
120 /* Command parser. */
121
122 static const struct command *parse_command_name (struct lexer *,
123                                                  int *n_tokens);
124 static enum cmd_result do_parse_command (struct lexer *, struct dataset *, enum cmd_state);
125
126 /* Parses an entire command, from command name to terminating
127    dot.  On failure, skips to the terminating dot.
128    Returns the command's success or failure result. */
129 enum cmd_result
130 cmd_parse_in_state (struct lexer *lexer, struct dataset *ds,
131                     enum cmd_state state)
132 {
133   struct session *session = dataset_session (ds);
134   int result;
135
136   result = do_parse_command (lexer, ds, state);
137
138   ds = session_active_dataset (session);
139   assert (!proc_is_open (ds));
140   unset_cmd_algorithm ();
141   dict_clear_aux (dataset_dict (ds));
142   if (!dataset_end_of_command (ds))
143     result = CMD_CASCADING_FAILURE;
144
145   return result;
146 }
147
148 enum cmd_result
149 cmd_parse (struct lexer *lexer, struct dataset *ds)
150 {
151   const struct dictionary *dict = dataset_dict (ds);
152   return cmd_parse_in_state (lexer, ds,
153                              dataset_has_source (ds) &&
154                              dict_get_var_cnt (dict) > 0 ?
155                              CMD_STATE_DATA : CMD_STATE_INITIAL);
156 }
157
158
159 /* Parses an entire command, from command name to terminating
160    dot. */
161 static enum cmd_result
162 do_parse_command (struct lexer *lexer,
163                   struct dataset *ds, enum cmd_state state)
164 {
165   const struct command *command = NULL;
166   enum cmd_result result;
167   bool opened = false;
168   int n_tokens;
169
170   /* Read the command's first token. */
171   set_completion_state (state);
172   if (lex_token (lexer) == T_STOP)
173     {
174       result = CMD_EOF;
175       goto finish;
176     }
177   else if (lex_token (lexer) == T_ENDCMD)
178     {
179       /* Null commands can result from extra empty lines. */
180       result = CMD_SUCCESS;
181       goto finish;
182     }
183
184   /* Parse the command name. */
185   command = parse_command_name (lexer, &n_tokens);
186   if (command == NULL)
187     {
188       result = CMD_FAILURE;
189       goto finish;
190     }
191   text_item_submit (text_item_create (TEXT_ITEM_COMMAND_OPEN, command->name));
192   opened = true;
193
194   if (command->function == NULL)
195     {
196       msg (SE, _("%s is not yet implemented."), command->name);
197       result = CMD_NOT_IMPLEMENTED;
198     }
199   else if ((command->flags & F_TESTING) && !settings_get_testing_mode ())
200     {
201       msg (SE, _("%s may be used only in testing mode."), command->name);
202       result = CMD_FAILURE;
203     }
204   else if ((command->flags & F_ENHANCED) && settings_get_syntax () != ENHANCED)
205     {
206       msg (SE, _("%s may be used only in enhanced syntax mode."),
207            command->name);
208       result = CMD_FAILURE;
209     }
210   else if (!in_correct_state (command, state))
211     {
212       report_state_mismatch (command, state);
213       result = CMD_FAILURE;
214     }
215   else
216     {
217       /* Execute command. */
218       int i;
219
220       for (i = 0; i < n_tokens; i++)
221         lex_get (lexer);
222       result = command->function (lexer, ds);
223     }
224
225   assert (cmd_result_is_valid (result));
226
227 finish:
228   if (cmd_result_is_failure (result))
229     lex_interactive_reset (lexer);
230   else if (result == CMD_SUCCESS)
231     result = lex_end_of_command (lexer);
232
233   lex_discard_rest_of_command (lexer);
234   while (lex_token (lexer) == T_ENDCMD)
235     lex_get (lexer);
236
237   if (opened)
238     text_item_submit (text_item_create (TEXT_ITEM_COMMAND_CLOSE,
239                                         command->name));
240
241   return result;
242 }
243
244 static int
245 find_best_match (struct substring s, const struct command **matchp)
246 {
247   const struct command *cmd;
248   struct command_matcher cm;
249   int missing_words;
250
251   command_matcher_init (&cm, s);
252   for (cmd = commands; cmd < &commands[command_cnt]; cmd++)
253     command_matcher_add (&cm, ss_cstr (cmd->name), CONST_CAST (void *, cmd));
254
255   *matchp = command_matcher_get_match (&cm);
256   missing_words = command_matcher_get_missing_words (&cm);
257
258   command_matcher_destroy (&cm);
259
260   return missing_words;
261 }
262
263 static bool
264 parse_command_word (struct lexer *lexer, struct string *s, int n)
265 {
266   bool need_space = ds_last (s) != EOF && ds_last (s) != '-';
267
268   switch (lex_next_token (lexer, n))
269     {
270     case T_DASH:
271       ds_put_byte (s, '-');
272       return true;
273
274     case T_ID:
275       if (need_space)
276         ds_put_byte (s, ' ');
277       ds_put_cstr (s, lex_next_tokcstr (lexer, n));
278       return true;
279
280     case T_POS_NUM:
281       if (lex_next_is_integer (lexer, n))
282         {
283           int integer = lex_next_integer (lexer, n);
284           if (integer >= 0)
285             {
286               if (need_space)
287                 ds_put_byte (s, ' ');
288               ds_put_format (s, "%ld", lex_next_integer (lexer, n));
289               return true;
290             }
291         }
292       return false;
293
294     default:
295       return false;
296     }
297 }
298
299 /* Parses the command name.  On success returns a pointer to the corresponding
300    struct command and stores the number of tokens in the command name into
301    *N_TOKENS.  On failure, returns a null pointer and stores the number of
302    tokens required to determine that no command name was present into
303    *N_TOKENS. */
304 static const struct command *
305 parse_command_name (struct lexer *lexer, int *n_tokens)
306 {
307   const struct command *command;
308   int missing_words;
309   struct string s;
310   int word;
311
312   command = NULL;
313   missing_words = 0;
314   ds_init_empty (&s);
315   word = 0;
316   while (parse_command_word (lexer, &s, word))
317     {
318       missing_words = find_best_match (ds_ss (&s), &command);
319       if (missing_words <= 0)
320         break;
321       word++;
322     }
323
324   if (command == NULL && missing_words > 0)
325     {
326       ds_put_cstr (&s, " .");
327       missing_words = find_best_match (ds_ss (&s), &command);
328       ds_truncate (&s, ds_length (&s) - 2);
329     }
330
331   if (command == NULL)
332     {
333       if (ds_is_empty (&s))
334         lex_error (lexer, _("expecting command name"));
335       else
336         msg (SE, _("Unknown command `%s'."), ds_cstr (&s));
337     }
338
339   ds_destroy (&s);
340
341   *n_tokens = (word + 1) + missing_words;
342   return command;
343 }
344
345 /* Returns true if COMMAND is allowed in STATE,
346    false otherwise. */
347 static bool
348 in_correct_state (const struct command *command, enum cmd_state state)
349 {
350   return ((state == CMD_STATE_INITIAL && command->states & S_INITIAL)
351           || (state == CMD_STATE_DATA && command->states & S_DATA)
352           || (state == CMD_STATE_INPUT_PROGRAM
353               && command->states & S_INPUT_PROGRAM)
354           || (state == CMD_STATE_FILE_TYPE && command->states & S_FILE_TYPE));
355 }
356
357 /* Emits an appropriate error message for trying to invoke
358    COMMAND in STATE. */
359 static bool
360 report_state_mismatch (const struct command *command, enum cmd_state state)
361 {
362   assert (!in_correct_state (command, state));
363   if (state == CMD_STATE_INITIAL || state == CMD_STATE_DATA)
364     {
365       switch (command->states)
366         {
367           /* One allowed state. */
368         case S_INITIAL:
369           msg (SE, _("%s is allowed only before the active dataset has "
370                      "been defined."), command->name);
371           break;
372         case S_DATA:
373           msg (SE, _("%s is allowed only after the active dataset has "
374                      "been defined."), command->name);
375           break;
376         case S_INPUT_PROGRAM:
377           msg (SE, _("%s is allowed only inside INPUT PROGRAM."),
378                command->name);
379           break;
380         case S_FILE_TYPE:
381           msg (SE, _("%s is allowed only inside FILE TYPE."), command->name);
382           break;
383
384           /* Two allowed states. */
385         case S_INITIAL | S_DATA:
386           NOT_REACHED ();
387         case S_INITIAL | S_INPUT_PROGRAM:
388           msg (SE, _("%s is allowed only before the active dataset has "
389                      "been defined or inside INPUT PROGRAM."), command->name);
390           break;
391         case S_INITIAL | S_FILE_TYPE:
392           msg (SE, _("%s is allowed only before the active dataset has "
393                      "been defined or inside FILE TYPE."), command->name);
394           break;
395         case S_DATA | S_INPUT_PROGRAM:
396           msg (SE, _("%s is allowed only after the active dataset has "
397                      "been defined or inside INPUT PROGRAM."), command->name);
398           break;
399         case S_DATA | S_FILE_TYPE:
400           msg (SE, _("%s is allowed only after the active dataset has "
401                      "been defined or inside FILE TYPE."), command->name);
402           break;
403         case S_INPUT_PROGRAM | S_FILE_TYPE:
404           msg (SE, _("%s is allowed only inside INPUT PROGRAM "
405                      "or inside FILE TYPE."), command->name);
406           break;
407
408           /* Three allowed states. */
409         case S_DATA | S_INPUT_PROGRAM | S_FILE_TYPE:
410           msg (SE, _("%s is allowed only after the active dataset has "
411                      "been defined, inside INPUT PROGRAM, or inside "
412                      "FILE TYPE."), command->name);
413           break;
414         case S_INITIAL | S_INPUT_PROGRAM | S_FILE_TYPE:
415           msg (SE, _("%s is allowed only before the active dataset has "
416                      "been defined, inside INPUT PROGRAM, or inside "
417                      "FILE TYPE."), command->name);
418           break;
419         case S_INITIAL | S_DATA | S_FILE_TYPE:
420           NOT_REACHED ();
421         case S_INITIAL | S_DATA | S_INPUT_PROGRAM:
422           NOT_REACHED ();
423
424           /* Four allowed states. */
425         case S_INITIAL | S_DATA | S_INPUT_PROGRAM | S_FILE_TYPE:
426           NOT_REACHED ();
427
428         default:
429           NOT_REACHED ();
430         }
431     }
432   else if (state == CMD_STATE_INPUT_PROGRAM)
433     msg (SE, _("%s is not allowed inside %s."),
434          command->name, "INPUT PROGRAM" );
435   else if (state == CMD_STATE_FILE_TYPE)
436     msg (SE, _("%s is not allowed inside %s."), command->name, "FILE TYPE");
437
438   return false;
439 }
440 \f
441 /* Command name completion. */
442
443 static enum cmd_state completion_state = CMD_STATE_INITIAL;
444
445 static void
446 set_completion_state (enum cmd_state state)
447 {
448   completion_state = state;
449 }
450
451 /* Returns the next possible completion of a command name that
452    begins with PREFIX, in the current command state, or a null
453    pointer if no completions remain.
454    Before calling the first time, set *CMD to a null pointer. */
455 const char *
456 cmd_complete (const char *prefix, const struct command **cmd)
457 {
458   if (*cmd == NULL)
459     *cmd = commands;
460
461   for (; *cmd < commands + command_cnt; (*cmd)++)
462     if (!memcasecmp ((*cmd)->name, prefix, strlen (prefix))
463         && (!((*cmd)->flags & F_TESTING) || settings_get_testing_mode ())
464         && (!((*cmd)->flags & F_ENHANCED) || settings_get_syntax () == ENHANCED)
465         && !((*cmd)->flags & F_ABBREV)
466         && ((*cmd)->function != NULL)
467         && in_correct_state (*cmd, completion_state))
468       return (*cmd)++->name;
469
470   return NULL;
471 }
472 \f
473 /* Simple commands. */
474
475 /* Parse and execute FINISH command. */
476 int
477 cmd_finish (struct lexer *lexer UNUSED, struct dataset *ds UNUSED)
478 {
479   return CMD_FINISH;
480 }
481
482 /* Parses the N command. */
483 int
484 cmd_n_of_cases (struct lexer *lexer, struct dataset *ds)
485 {
486   /* Value for N. */
487   int x;
488
489   if (!lex_force_int (lexer))
490     return CMD_FAILURE;
491   x = lex_integer (lexer);
492   lex_get (lexer);
493   if (!lex_match_id (lexer, "ESTIMATED"))
494     dict_set_case_limit (dataset_dict (ds), x);
495
496   return CMD_SUCCESS;
497 }
498
499 /* Parses, performs the EXECUTE procedure. */
500 int
501 cmd_execute (struct lexer *lexer UNUSED, struct dataset *ds)
502 {
503   bool ok = casereader_destroy (proc_open (ds));
504   if (!proc_commit (ds) || !ok)
505     return CMD_CASCADING_FAILURE;
506   return CMD_SUCCESS;
507 }
508
509 /* Parses, performs the ERASE command. */
510 int
511 cmd_erase (struct lexer *lexer, struct dataset *ds UNUSED)
512 {
513   char *filename;
514   int retval;
515
516   if (settings_get_safer_mode ())
517     {
518       msg (SE, _("This command not allowed when the SAFER option is set."));
519       return CMD_FAILURE;
520     }
521
522   if (!lex_force_match_id (lexer, "FILE"))
523     return CMD_FAILURE;
524   lex_match (lexer, T_EQUALS);
525   if (!lex_force_string (lexer))
526     return CMD_FAILURE;
527
528   filename = utf8_to_filename (lex_tokcstr (lexer));
529   retval = remove (filename);
530   free (filename);
531
532   if (retval == -1)
533     {
534       msg (SW, _("Error removing `%s': %s."),
535            lex_tokcstr (lexer), strerror (errno));
536       return CMD_FAILURE;
537     }
538   lex_get (lexer);
539
540   return CMD_SUCCESS;
541 }
542
543 /* Parses, performs the NEW FILE command. */
544 int
545 cmd_new_file (struct lexer *lexer UNUSED, struct dataset *ds)
546 {
547   dataset_clear (ds);
548   return CMD_SUCCESS;
549 }