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