1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
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.
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.
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/>. */
19 #include <language/command.h>
27 #include <data/casereader.h>
28 #include <data/dictionary.h>
29 #include <data/procedure.h>
30 #include <data/settings.h>
31 #include <data/variable.h>
32 #include <language/lexer/lexer.h>
33 #include <language/prompt.h>
34 #include <libpspp/alloc.h>
35 #include <libpspp/assertion.h>
36 #include <libpspp/compiler.h>
37 #include <libpspp/message.h>
38 #include <libpspp/message.h>
39 #include <libpspp/str.h>
40 #include <output/manager.h>
41 #include <output/table.h>
42 #include <libpspp/getl.h>
49 #include <readline/readline.h>
53 #define _(msgid) gettext (msgid)
54 #define N_(msgid) msgid
56 /* Returns true if RESULT is a valid "enum cmd_result",
59 cmd_result_is_valid (enum cmd_result result)
61 return (result == CMD_SUCCESS || result == CMD_EOF || result == CMD_FINISH
62 || (result >= CMD_PRIVATE_FIRST && result <= CMD_PRIVATE_LAST)
63 || result == CMD_FAILURE || result == CMD_NOT_IMPLEMENTED
64 || result == CMD_CASCADING_FAILURE);
67 /* Returns true if RESULT indicates success,
70 cmd_result_is_success (enum cmd_result result)
72 assert (cmd_result_is_valid (result));
76 /* Returns true if RESULT indicates failure,
79 cmd_result_is_failure (enum cmd_result result)
81 assert (cmd_result_is_valid (result));
85 /* Command processing states. */
88 S_INITIAL = 0x01, /* Allowed before active file defined. */
89 S_DATA = 0x02, /* Allowed after active file defined. */
90 S_INPUT_PROGRAM = 0x04, /* Allowed in INPUT PROGRAM. */
91 S_FILE_TYPE = 0x08, /* Allowed in FILE TYPE. */
92 S_ANY = 0x0f /* Allowed anywhere. */
95 /* Other command requirements. */
98 F_ENHANCED = 0x10, /* Allowed only in enhanced syntax mode. */
99 F_TESTING = 0x20, /* Allowed only in testing mode. */
100 F_KEEP_FINAL_TOKEN = 0x40,/* Don't skip final token in command name. */
101 F_ABBREV = 0x80 /* Not a candidate for name completion. */
104 /* A single command. */
107 enum states states; /* States in which command is allowed. */
108 enum flags flags; /* Other command requirements. */
109 const char *name; /* Command name. */
110 int (*function) (struct lexer *, struct dataset *); /* Function to call. */
113 /* Define the command array. */
114 #define DEF_CMD(STATES, FLAGS, NAME, FUNCTION) {STATES, FLAGS, NAME, FUNCTION},
115 #define UNIMPL_CMD(NAME, DESCRIPTION) {S_ANY, 0, NAME, NULL},
116 static const struct command commands[] =
118 #include "command.def"
123 static const size_t command_cnt = sizeof commands / sizeof *commands;
125 static bool in_correct_state (const struct command *, enum cmd_state);
126 static bool report_state_mismatch (const struct command *, enum cmd_state);
127 static const struct command *find_command (const char *name);
128 static void set_completion_state (enum cmd_state);
130 /* Command parser. */
132 static const struct command *parse_command_name (struct lexer *lexer);
133 static enum cmd_result do_parse_command (struct lexer *, struct dataset *, enum cmd_state);
135 /* Parses an entire command, from command name to terminating
136 dot. On failure, skips to the terminating dot.
137 Returns the command's success or failure result. */
139 cmd_parse_in_state (struct lexer *lexer, struct dataset *ds,
140 enum cmd_state state)
146 result = do_parse_command (lexer, ds, state);
147 if (cmd_result_is_failure (result))
148 lex_discard_rest_of_command (lexer);
150 assert (!proc_is_open (ds));
151 unset_cmd_algorithm ();
152 dict_clear_aux (dataset_dict (ds));
153 if (!dataset_end_of_command (ds))
154 result = CMD_CASCADING_FAILURE;
160 cmd_parse (struct lexer *lexer, struct dataset *ds)
162 const struct dictionary *dict = dataset_dict (ds);
163 return cmd_parse_in_state (lexer, ds,
164 proc_has_active_file (ds) &&
165 dict_get_var_cnt (dict) > 0 ?
166 CMD_STATE_DATA : CMD_STATE_INITIAL);
170 /* Parses an entire command, from command name to terminating
172 static enum cmd_result
173 do_parse_command (struct lexer *lexer,
174 struct dataset *ds, enum cmd_state state)
176 const struct command *command;
177 enum cmd_result result;
179 /* Read the command's first token. */
180 prompt_set_style (PROMPT_FIRST);
181 set_completion_state (state);
183 if (lex_token (lexer) == T_STOP)
188 else if (lex_token (lexer) == '.')
190 /* Null commands can result from extra empty lines. */
191 result = CMD_SUCCESS;
195 prompt_set_style (PROMPT_LATER);
197 /* Parse the command name. */
198 command = parse_command_name (lexer);
201 result = CMD_FAILURE;
204 else if (command->function == NULL)
206 msg (SE, _("%s is unimplemented."), command->name);
207 result = CMD_NOT_IMPLEMENTED;
210 else if ((command->flags & F_TESTING) && !get_testing_mode ())
212 msg (SE, _("%s may be used only in testing mode."), command->name);
213 result = CMD_FAILURE;
216 else if ((command->flags & F_ENHANCED) && get_syntax () != ENHANCED)
218 msg (SE, _("%s may be used only in enhanced syntax mode."),
220 result = CMD_FAILURE;
223 else if (!in_correct_state (command, state))
225 report_state_mismatch (command, state);
226 result = CMD_FAILURE;
230 /* Execute command. */
231 msg_set_command_name (command->name);
232 tab_set_command_name (command->name);
233 result = command->function (lexer, ds);
234 tab_set_command_name (NULL);
235 msg_set_command_name (NULL);
237 assert (cmd_result_is_valid (result));
240 if ( cmd_result_is_failure (result))
242 const struct source_stream *cs = lex_get_source_stream (lexer);
244 if ( source_stream_current_error_mode (cs) == ERRMODE_STOP )
246 msg (MW, _("Error encountered while ERROR=STOP is effective."));
247 result = CMD_CASCADING_FAILURE;
255 match_strings (const char *a, size_t a_len,
256 const char *b, size_t b_len)
258 size_t match_len = 0;
260 while (a_len > 0 && b_len > 0)
262 /* Mismatch always returns zero. */
263 if (toupper ((unsigned char) *a++) != toupper ((unsigned char) *b++))
275 /* Returns the first character in the first word in STRING,
276 storing the word's length in *WORD_LEN. If no words remain,
277 returns a null pointer and stores 0 in *WORD_LEN. Words are
278 sequences of alphanumeric characters or single
279 non-alphanumeric characters. Words are delimited by
282 find_word (const char *string, size_t *word_len)
284 /* Skip whitespace and asterisks. */
285 while (isspace ((unsigned char) *string))
295 /* Special one-character word? */
296 if (!isalnum ((unsigned char) *string))
302 /* Alphanumeric word. */
304 while (isalnum ((unsigned char) string[*word_len]))
310 /* Returns true if strings A and B can be confused based on
311 their first three letters. */
313 conflicting_3char_prefixes (const char *a, const char *b)
315 size_t aw_len, bw_len;
318 aw = find_word (a, &aw_len);
319 bw = find_word (b, &bw_len);
320 assert (aw != NULL && bw != NULL);
322 /* Words that are the same don't conflict. */
323 if (aw_len == bw_len && !buf_compare_case (aw, bw, aw_len))
326 /* Words that are otherwise the same in the first three letters
328 return ((aw_len > 3 && bw_len > 3)
329 || (aw_len == 3 && bw_len > 3)
330 || (bw_len == 3 && aw_len > 3)) && !buf_compare_case (aw, bw, 3);
333 /* Returns true if CMD can be confused with another command
334 based on the first three letters of its first word. */
336 conflicting_3char_prefix_command (const struct command *cmd)
338 assert (cmd >= commands && cmd < commands + command_cnt);
340 return ((cmd > commands
341 && conflicting_3char_prefixes (cmd[-1].name, cmd[0].name))
342 || (cmd < commands + command_cnt
343 && conflicting_3char_prefixes (cmd[0].name, cmd[1].name)));
346 /* Ways that a set of words can match a command name. */
349 MISMATCH, /* Not a match. */
350 PARTIAL_MATCH, /* The words begin the command name. */
351 COMPLETE_MATCH /* The words are the command name. */
354 /* Figures out how well the WORD_CNT words in WORDS match CMD,
355 and returns the appropriate enum value. If WORDS are a
356 partial match for CMD and the next word in CMD is a dash, then
357 *DASH_POSSIBLE is set to 1 if DASH_POSSIBLE is non-null;
358 otherwise, *DASH_POSSIBLE is unchanged. */
359 static enum command_match
360 cmd_match_words (const struct command *cmd,
361 char *const words[], size_t word_cnt,
368 for (word = find_word (cmd->name, &word_len), word_idx = 0;
369 word != NULL && word_idx < word_cnt;
370 word = find_word (word + word_len, &word_len), word_idx++)
371 if (word_len != strlen (words[word_idx])
372 || buf_compare_case (word, words[word_idx], word_len))
374 size_t match_chars = match_strings (word, word_len,
376 strlen (words[word_idx]));
377 if (match_chars == 0)
382 else if (match_chars == 1 || match_chars == 2)
384 /* One- and two-character abbreviations are not
388 else if (match_chars == 3)
390 /* Three-character abbreviations are acceptable
391 in the first word of a command if there are
392 no name conflicts. They are always
393 acceptable after the first word. */
394 if (word_idx == 0 && conflicting_3char_prefix_command (cmd))
397 else /* match_chars > 3 */
399 /* Four-character and longer abbreviations are
400 always acceptable. */
404 if (word == NULL && word_idx == word_cnt)
406 /* cmd->name = "FOO BAR", words[] = {"FOO", "BAR"}. */
407 return COMPLETE_MATCH;
409 else if (word == NULL)
411 /* cmd->name = "FOO BAR", words[] = {"FOO", "BAR", "BAZ"}. */
416 /* cmd->name = "FOO BAR BAZ", words[] = {"FOO", "BAR"}. */
417 if (word[0] == '-' && dash_possible != NULL)
419 return PARTIAL_MATCH;
423 /* Returns the number of commands for which the WORD_CNT words in
424 WORDS are a partial or complete match. If some partial match
425 has a dash as the next word, then *DASH_POSSIBLE is set to 1,
426 otherwise it is set to 0. */
428 count_matching_commands (char *const words[], size_t word_cnt,
431 const struct command *cmd;
436 for (cmd = commands; cmd < commands + command_cnt; cmd++)
437 if (cmd_match_words (cmd, words, word_cnt, dash_possible) != MISMATCH)
440 return cmd_match_count;
443 /* Returns the command for which the WORD_CNT words in WORDS are
444 a complete match. Returns a null pointer if no such command
446 static const struct command *
447 get_complete_match (char *const words[], size_t word_cnt)
449 const struct command *cmd;
451 for (cmd = commands; cmd < commands + command_cnt; cmd++)
452 if (cmd_match_words (cmd, words, word_cnt, NULL) == COMPLETE_MATCH)
458 /* Returns the command with the given exact NAME.
459 Aborts if no such command exists. */
460 static const struct command *
461 find_command (const char *name)
463 const struct command *cmd;
465 for (cmd = commands; cmd < commands + command_cnt; cmd++)
466 if (!strcmp (cmd->name, name))
471 /* Frees the WORD_CNT words in WORDS. */
473 free_words (char *words[], size_t word_cnt)
477 for (idx = 0; idx < word_cnt; idx++)
481 /* Flags an error that the command whose name is given by the
482 WORD_CNT words in WORDS is unknown. */
484 unknown_command_error (struct lexer *lexer, char *const words[], size_t word_cnt)
487 lex_error (lexer, _("expecting command name"));
494 for (i = 0; i < word_cnt; i++)
497 ds_put_char (&s, ' ');
498 ds_put_cstr (&s, words[i]);
501 msg (SE, _("Unknown command %s."), ds_cstr (&s));
507 /* Parse the command name and return a pointer to the corresponding
508 struct command if successful.
509 If not successful, return a null pointer. */
510 static const struct command *
511 parse_command_name (struct lexer *lexer)
515 int complete_word_cnt;
518 if (lex_token (lexer) == T_EXP ||
519 lex_token (lexer) == '*' || lex_token (lexer) == '[')
520 return find_command ("COMMENT");
523 word_cnt = complete_word_cnt = 0;
524 while (lex_token (lexer) == T_ID || (dash_possible && lex_token (lexer) == '-'))
528 assert (word_cnt < sizeof words / sizeof *words);
529 if (lex_token (lexer) == T_ID)
531 words[word_cnt] = ds_xstrdup (lex_tokstr (lexer));
532 str_uppercase (words[word_cnt]);
534 else if (lex_token (lexer) == '-')
535 words[word_cnt] = xstrdup ("-");
538 cmd_match_cnt = count_matching_commands (words, word_cnt,
540 if (cmd_match_cnt == 0)
542 else if (cmd_match_cnt == 1)
544 const struct command *command = get_complete_match (words, word_cnt);
547 if (!(command->flags & F_KEEP_FINAL_TOKEN))
549 free_words (words, word_cnt);
553 else /* cmd_match_cnt > 1 */
555 /* Do we have a complete command name so far? */
556 if (get_complete_match (words, word_cnt) != NULL)
557 complete_word_cnt = word_cnt;
562 /* If we saw a complete command name earlier, drop back to
564 if (complete_word_cnt)
566 int pushback_word_cnt;
567 const struct command *command;
569 /* Get the command. */
570 command = get_complete_match (words, complete_word_cnt);
571 assert (command != NULL);
573 /* Figure out how many words we want to keep.
574 We normally want to swallow the entire command. */
575 pushback_word_cnt = complete_word_cnt + 1;
576 if (command->flags & F_KEEP_FINAL_TOKEN)
579 /* FIXME: We only support one-token pushback. */
580 assert (pushback_word_cnt + 1 >= word_cnt);
582 while (word_cnt > pushback_word_cnt)
585 if (strcmp (words[word_cnt], "-"))
586 lex_put_back_id (lexer, words[word_cnt]);
588 lex_put_back (lexer, '-');
589 free (words[word_cnt]);
592 free_words (words, word_cnt);
596 /* We didn't get a valid command name. */
597 unknown_command_error (lexer, words, word_cnt);
598 free_words (words, word_cnt);
602 /* Returns true if COMMAND is allowed in STATE,
605 in_correct_state (const struct command *command, enum cmd_state state)
607 return ((state == CMD_STATE_INITIAL && command->states & S_INITIAL)
608 || (state == CMD_STATE_DATA && command->states & S_DATA)
609 || (state == CMD_STATE_INPUT_PROGRAM
610 && command->states & S_INPUT_PROGRAM)
611 || (state == CMD_STATE_FILE_TYPE && command->states & S_FILE_TYPE));
614 /* Emits an appropriate error message for trying to invoke
617 report_state_mismatch (const struct command *command, enum cmd_state state)
619 assert (!in_correct_state (command, state));
620 if (state == CMD_STATE_INITIAL || state == CMD_STATE_DATA)
622 const char *allowed[3];
627 if (command->states & S_INITIAL)
628 allowed[allowed_cnt++] = _("before the active file has been defined");
629 else if (command->states & S_DATA)
630 allowed[allowed_cnt++] = _("after the active file has been defined");
631 if (command->states & S_INPUT_PROGRAM)
632 allowed[allowed_cnt++] = _("inside INPUT PROGRAM");
633 if (command->states & S_FILE_TYPE)
634 allowed[allowed_cnt++] = _("inside FILE TYPE");
636 if (allowed_cnt == 1)
637 s = xstrdup (allowed[0]);
638 else if (allowed_cnt == 2)
639 s = xasprintf (_("%s or %s"), allowed[0], allowed[1]);
640 else if (allowed_cnt == 3)
641 s = xasprintf (_("%s, %s, or %s"), allowed[0], allowed[1], allowed[2]);
645 msg (SE, _("%s is allowed only %s."), command->name, s);
649 else if (state == CMD_STATE_INPUT_PROGRAM)
650 msg (SE, _("%s is not allowed inside INPUT PROGRAM."), command->name);
651 else if (state == CMD_STATE_FILE_TYPE)
652 msg (SE, _("%s is not allowed inside FILE TYPE."), command->name);
657 /* Command name completion. */
659 static enum cmd_state completion_state = CMD_STATE_INITIAL;
662 set_completion_state (enum cmd_state state)
664 completion_state = state;
667 /* Returns the next possible completion of a command name that
668 begins with PREFIX, in the current command state, or a null
669 pointer if no completions remain.
670 Before calling the first time, set *CMD to a null pointer. */
672 cmd_complete (const char *prefix, const struct command **cmd)
677 for (; *cmd < commands + command_cnt; (*cmd)++)
678 if (!memcasecmp ((*cmd)->name, prefix, strlen (prefix))
679 && (!((*cmd)->flags & F_TESTING) || get_testing_mode ())
680 && (!((*cmd)->flags & F_ENHANCED) || get_syntax () == ENHANCED)
681 && !((*cmd)->flags & F_ABBREV)
682 && ((*cmd)->function != NULL)
683 && in_correct_state (*cmd, completion_state))
684 return (*cmd)++->name;
689 /* Simple commands. */
691 /* Parse and execute FINISH command. */
693 cmd_finish (struct lexer *lexer UNUSED, struct dataset *ds UNUSED)
698 /* Parses the N command. */
700 cmd_n_of_cases (struct lexer *lexer, struct dataset *ds)
705 if (!lex_force_int (lexer))
707 x = lex_integer (lexer);
709 if (!lex_match_id (lexer, "ESTIMATED"))
710 dict_set_case_limit (dataset_dict (ds), x);
712 return lex_end_of_command (lexer);
715 /* Parses, performs the EXECUTE procedure. */
717 cmd_execute (struct lexer *lexer, struct dataset *ds)
719 bool ok = casereader_destroy (proc_open (ds));
720 if (!proc_commit (ds) || !ok)
721 return CMD_CASCADING_FAILURE;
722 return lex_end_of_command (lexer);
725 /* Parses, performs the ERASE command. */
727 cmd_erase (struct lexer *lexer, struct dataset *ds UNUSED)
729 if (get_safer_mode ())
731 msg (SE, _("This command not allowed when the SAFER option is set."));
735 if (!lex_force_match_id (lexer, "FILE"))
737 lex_match (lexer, '=');
738 if (!lex_force_string (lexer))
741 if (remove (ds_cstr (lex_tokstr (lexer))) == -1)
743 msg (SW, _("Error removing `%s': %s."),
744 ds_cstr (lex_tokstr (lexer)), strerror (errno));
751 #if HAVE_FORK && HAVE_EXECL
752 /* Spawn an interactive shell process. */
763 const char *shell_fn;
769 for (i = 3; i < 20; i++)
773 shell_fn = getenv ("SHELL");
774 if (shell_fn == NULL)
775 shell_fn = "/bin/sh";
778 const char *cp = strrchr (shell_fn, '/');
779 cp = cp ? &cp[1] : shell_fn;
780 shell_process = local_alloc (strlen (cp) + 8);
781 strcpy (shell_process, "-");
782 strcat (shell_process, cp);
783 if (strcmp (cp, "sh"))
784 shell_process[0] = '+';
787 execl (shell_fn, shell_process, NULL);
793 msg (SE, _("Couldn't fork: %s."), strerror (errno));
798 while (wait (NULL) != pid)
803 #else /* !(HAVE_FORK && HAVE_EXECL) */
804 /* Don't know how to spawn an interactive shell. */
808 msg (SE, _("Interactive shell not supported on this platform."));
813 /* Executes the specified COMMAND in a subshell. Returns true if
814 successful, false otherwise. */
816 run_command (const char *command)
818 if (system (NULL) == 0)
820 msg (SE, _("Command shell not supported on this platform."));
824 /* Execute the command. */
825 if (system (command) == -1)
826 msg (SE, _("Error executing command: %s."), strerror (errno));
831 /* Parses, performs the HOST command. */
833 cmd_host (struct lexer *lexer, struct dataset *ds UNUSED)
837 if (get_safer_mode ())
839 msg (SE, _("This command not allowed when the SAFER option is set."));
843 look_ahead = lex_look_ahead (lexer);
844 if (look_ahead == '.')
847 return shell () ? CMD_SUCCESS : CMD_FAILURE;
849 else if (look_ahead == '\'' || look_ahead == '"')
854 if (!lex_force_string (lexer))
856 ok = run_command (ds_cstr (lex_tokstr (lexer)));
859 return ok ? lex_end_of_command (lexer) : CMD_FAILURE;
863 bool ok = run_command (lex_rest_of_line (lexer));
864 lex_discard_line (lexer);
865 return ok ? CMD_SUCCESS : CMD_FAILURE;
869 /* Parses, performs the NEW FILE command. */
871 cmd_new_file (struct lexer *lexer, struct dataset *ds)
873 proc_discard_active_file (ds);
875 return lex_end_of_command (lexer);
878 /* Parses a comment. */
880 cmd_comment (struct lexer *lexer, struct dataset *ds UNUSED)
882 lex_skip_comment (lexer);