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>
48 #include <readline/readline.h>
52 #define _(msgid) gettext (msgid)
53 #define N_(msgid) msgid
55 /* Returns true if RESULT is a valid "enum cmd_result",
58 cmd_result_is_valid (enum cmd_result result)
60 return (result == CMD_SUCCESS || result == CMD_EOF || result == CMD_FINISH
61 || (result >= CMD_PRIVATE_FIRST && result <= CMD_PRIVATE_LAST)
62 || result == CMD_FAILURE || result == CMD_NOT_IMPLEMENTED
63 || result == CMD_CASCADING_FAILURE);
66 /* Returns true if RESULT indicates success,
69 cmd_result_is_success (enum cmd_result result)
71 assert (cmd_result_is_valid (result));
75 /* Returns true if RESULT indicates failure,
78 cmd_result_is_failure (enum cmd_result result)
80 assert (cmd_result_is_valid (result));
84 /* Command processing states. */
87 S_INITIAL = 0x01, /* Allowed before active file defined. */
88 S_DATA = 0x02, /* Allowed after active file defined. */
89 S_INPUT_PROGRAM = 0x04, /* Allowed in INPUT PROGRAM. */
90 S_FILE_TYPE = 0x08, /* Allowed in FILE TYPE. */
91 S_ANY = 0x0f /* Allowed anywhere. */
94 /* Other command requirements. */
97 F_ENHANCED = 0x10, /* Allowed only in enhanced syntax mode. */
98 F_TESTING = 0x20, /* Allowed only in testing mode. */
99 F_KEEP_FINAL_TOKEN = 0x40,/* Don't skip final token in command name. */
100 F_ABBREV = 0x80 /* Not a candidate for name completion. */
103 /* A single command. */
106 enum states states; /* States in which command is allowed. */
107 enum flags flags; /* Other command requirements. */
108 const char *name; /* Command name. */
109 int (*function) (struct lexer *, struct dataset *); /* Function to call. */
112 /* Define the command array. */
113 #define DEF_CMD(STATES, FLAGS, NAME, FUNCTION) {STATES, FLAGS, NAME, FUNCTION},
114 #define UNIMPL_CMD(NAME, DESCRIPTION) {S_ANY, 0, NAME, NULL},
115 static const struct command commands[] =
117 #include "command.def"
122 static const size_t command_cnt = sizeof commands / sizeof *commands;
124 static bool in_correct_state (const struct command *, enum cmd_state);
125 static bool report_state_mismatch (const struct command *, enum cmd_state);
126 static const struct command *find_command (const char *name);
127 static void set_completion_state (enum cmd_state);
129 /* Command parser. */
131 static const struct command *parse_command_name (struct lexer *lexer);
132 static enum cmd_result do_parse_command (struct lexer *, struct dataset *, enum cmd_state);
134 /* Parses an entire command, from command name to terminating
135 dot. On failure, skips to the terminating dot.
136 Returns the command's success or failure result. */
138 cmd_parse_in_state (struct lexer *lexer, struct dataset *ds,
139 enum cmd_state state)
145 result = do_parse_command (lexer, ds, state);
146 if (cmd_result_is_failure (result))
147 lex_discard_rest_of_command (lexer);
149 assert (!proc_is_open (ds));
150 unset_cmd_algorithm ();
151 dict_clear_aux (dataset_dict (ds));
152 if (!dataset_end_of_command (ds))
153 result = CMD_CASCADING_FAILURE;
159 cmd_parse (struct lexer *lexer, struct dataset *ds)
161 const struct dictionary *dict = dataset_dict (ds);
162 return cmd_parse_in_state (lexer, ds,
163 proc_has_active_file (ds) &&
164 dict_get_var_cnt (dict) > 0 ?
165 CMD_STATE_DATA : CMD_STATE_INITIAL);
169 /* Parses an entire command, from command name to terminating
171 static enum cmd_result
172 do_parse_command (struct lexer *lexer, struct dataset *ds, enum cmd_state state)
174 const struct command *command;
175 enum cmd_result result;
177 /* Read the command's first token. */
178 prompt_set_style (PROMPT_FIRST);
179 set_completion_state (state);
181 if (lex_token (lexer) == T_STOP)
183 else if (lex_token (lexer) == '.')
185 /* Null commands can result from extra empty lines. */
188 prompt_set_style (PROMPT_LATER);
190 /* Parse the command name. */
191 command = parse_command_name (lexer);
194 else if (command->function == NULL)
196 msg (SE, _("%s is unimplemented."), command->name);
197 return CMD_NOT_IMPLEMENTED;
199 else if ((command->flags & F_TESTING) && !get_testing_mode ())
201 msg (SE, _("%s may be used only in testing mode."), command->name);
204 else if ((command->flags & F_ENHANCED) && get_syntax () != ENHANCED)
206 msg (SE, _("%s may be used only in enhanced syntax mode."),
210 else if (!in_correct_state (command, state))
212 report_state_mismatch (command, state);
216 /* Execute command. */
217 msg_set_command_name (command->name);
218 tab_set_command_name (command->name);
219 result = command->function (lexer, ds);
220 tab_set_command_name (NULL);
221 msg_set_command_name (NULL);
223 assert (cmd_result_is_valid (result));
228 match_strings (const char *a, size_t a_len,
229 const char *b, size_t b_len)
231 size_t match_len = 0;
233 while (a_len > 0 && b_len > 0)
235 /* Mismatch always returns zero. */
236 if (toupper ((unsigned char) *a++) != toupper ((unsigned char) *b++))
248 /* Returns the first character in the first word in STRING,
249 storing the word's length in *WORD_LEN. If no words remain,
250 returns a null pointer and stores 0 in *WORD_LEN. Words are
251 sequences of alphanumeric characters or single
252 non-alphanumeric characters. Words are delimited by
255 find_word (const char *string, size_t *word_len)
257 /* Skip whitespace and asterisks. */
258 while (isspace ((unsigned char) *string))
268 /* Special one-character word? */
269 if (!isalnum ((unsigned char) *string))
275 /* Alphanumeric word. */
277 while (isalnum ((unsigned char) string[*word_len]))
283 /* Returns true if strings A and B can be confused based on
284 their first three letters. */
286 conflicting_3char_prefixes (const char *a, const char *b)
288 size_t aw_len, bw_len;
291 aw = find_word (a, &aw_len);
292 bw = find_word (b, &bw_len);
293 assert (aw != NULL && bw != NULL);
295 /* Words that are the same don't conflict. */
296 if (aw_len == bw_len && !buf_compare_case (aw, bw, aw_len))
299 /* Words that are otherwise the same in the first three letters
301 return ((aw_len > 3 && bw_len > 3)
302 || (aw_len == 3 && bw_len > 3)
303 || (bw_len == 3 && aw_len > 3)) && !buf_compare_case (aw, bw, 3);
306 /* Returns true if CMD can be confused with another command
307 based on the first three letters of its first word. */
309 conflicting_3char_prefix_command (const struct command *cmd)
311 assert (cmd >= commands && cmd < commands + command_cnt);
313 return ((cmd > commands
314 && conflicting_3char_prefixes (cmd[-1].name, cmd[0].name))
315 || (cmd < commands + command_cnt
316 && conflicting_3char_prefixes (cmd[0].name, cmd[1].name)));
319 /* Ways that a set of words can match a command name. */
322 MISMATCH, /* Not a match. */
323 PARTIAL_MATCH, /* The words begin the command name. */
324 COMPLETE_MATCH /* The words are the command name. */
327 /* Figures out how well the WORD_CNT words in WORDS match CMD,
328 and returns the appropriate enum value. If WORDS are a
329 partial match for CMD and the next word in CMD is a dash, then
330 *DASH_POSSIBLE is set to 1 if DASH_POSSIBLE is non-null;
331 otherwise, *DASH_POSSIBLE is unchanged. */
332 static enum command_match
333 cmd_match_words (const struct command *cmd,
334 char *const words[], size_t word_cnt,
341 for (word = find_word (cmd->name, &word_len), word_idx = 0;
342 word != NULL && word_idx < word_cnt;
343 word = find_word (word + word_len, &word_len), word_idx++)
344 if (word_len != strlen (words[word_idx])
345 || buf_compare_case (word, words[word_idx], word_len))
347 size_t match_chars = match_strings (word, word_len,
349 strlen (words[word_idx]));
350 if (match_chars == 0)
355 else if (match_chars == 1 || match_chars == 2)
357 /* One- and two-character abbreviations are not
361 else if (match_chars == 3)
363 /* Three-character abbreviations are acceptable
364 in the first word of a command if there are
365 no name conflicts. They are always
366 acceptable after the first word. */
367 if (word_idx == 0 && conflicting_3char_prefix_command (cmd))
370 else /* match_chars > 3 */
372 /* Four-character and longer abbreviations are
373 always acceptable. */
377 if (word == NULL && word_idx == word_cnt)
379 /* cmd->name = "FOO BAR", words[] = {"FOO", "BAR"}. */
380 return COMPLETE_MATCH;
382 else if (word == NULL)
384 /* cmd->name = "FOO BAR", words[] = {"FOO", "BAR", "BAZ"}. */
389 /* cmd->name = "FOO BAR BAZ", words[] = {"FOO", "BAR"}. */
390 if (word[0] == '-' && dash_possible != NULL)
392 return PARTIAL_MATCH;
396 /* Returns the number of commands for which the WORD_CNT words in
397 WORDS are a partial or complete match. If some partial match
398 has a dash as the next word, then *DASH_POSSIBLE is set to 1,
399 otherwise it is set to 0. */
401 count_matching_commands (char *const words[], size_t word_cnt,
404 const struct command *cmd;
409 for (cmd = commands; cmd < commands + command_cnt; cmd++)
410 if (cmd_match_words (cmd, words, word_cnt, dash_possible) != MISMATCH)
413 return cmd_match_count;
416 /* Returns the command for which the WORD_CNT words in WORDS are
417 a complete match. Returns a null pointer if no such command
419 static const struct command *
420 get_complete_match (char *const words[], size_t word_cnt)
422 const struct command *cmd;
424 for (cmd = commands; cmd < commands + command_cnt; cmd++)
425 if (cmd_match_words (cmd, words, word_cnt, NULL) == COMPLETE_MATCH)
431 /* Returns the command with the given exact NAME.
432 Aborts if no such command exists. */
433 static const struct command *
434 find_command (const char *name)
436 const struct command *cmd;
438 for (cmd = commands; cmd < commands + command_cnt; cmd++)
439 if (!strcmp (cmd->name, name))
444 /* Frees the WORD_CNT words in WORDS. */
446 free_words (char *words[], size_t word_cnt)
450 for (idx = 0; idx < word_cnt; idx++)
454 /* Flags an error that the command whose name is given by the
455 WORD_CNT words in WORDS is unknown. */
457 unknown_command_error (struct lexer *lexer, char *const words[], size_t word_cnt)
460 lex_error (lexer, _("expecting command name"));
467 for (i = 0; i < word_cnt; i++)
470 ds_put_char (&s, ' ');
471 ds_put_cstr (&s, words[i]);
474 msg (SE, _("Unknown command %s."), ds_cstr (&s));
480 /* Parse the command name and return a pointer to the corresponding
481 struct command if successful.
482 If not successful, return a null pointer. */
483 static const struct command *
484 parse_command_name (struct lexer *lexer)
488 int complete_word_cnt;
491 if (lex_token (lexer) == T_EXP ||
492 lex_token (lexer) == '*' || lex_token (lexer) == '[')
493 return find_command ("COMMENT");
496 word_cnt = complete_word_cnt = 0;
497 while (lex_token (lexer) == T_ID || (dash_possible && lex_token (lexer) == '-'))
501 assert (word_cnt < sizeof words / sizeof *words);
502 if (lex_token (lexer) == T_ID)
504 words[word_cnt] = ds_xstrdup (lex_tokstr (lexer));
505 str_uppercase (words[word_cnt]);
507 else if (lex_token (lexer) == '-')
508 words[word_cnt] = xstrdup ("-");
511 cmd_match_cnt = count_matching_commands (words, word_cnt,
513 if (cmd_match_cnt == 0)
515 else if (cmd_match_cnt == 1)
517 const struct command *command = get_complete_match (words, word_cnt);
520 if (!(command->flags & F_KEEP_FINAL_TOKEN))
522 free_words (words, word_cnt);
526 else /* cmd_match_cnt > 1 */
528 /* Do we have a complete command name so far? */
529 if (get_complete_match (words, word_cnt) != NULL)
530 complete_word_cnt = word_cnt;
535 /* If we saw a complete command name earlier, drop back to
537 if (complete_word_cnt)
539 int pushback_word_cnt;
540 const struct command *command;
542 /* Get the command. */
543 command = get_complete_match (words, complete_word_cnt);
544 assert (command != NULL);
546 /* Figure out how many words we want to keep.
547 We normally want to swallow the entire command. */
548 pushback_word_cnt = complete_word_cnt + 1;
549 if (command->flags & F_KEEP_FINAL_TOKEN)
552 /* FIXME: We only support one-token pushback. */
553 assert (pushback_word_cnt + 1 >= word_cnt);
555 while (word_cnt > pushback_word_cnt)
558 if (strcmp (words[word_cnt], "-"))
559 lex_put_back_id (lexer, words[word_cnt]);
561 lex_put_back (lexer, '-');
562 free (words[word_cnt]);
565 free_words (words, word_cnt);
569 /* We didn't get a valid command name. */
570 unknown_command_error (lexer, words, word_cnt);
571 free_words (words, word_cnt);
575 /* Returns true if COMMAND is allowed in STATE,
578 in_correct_state (const struct command *command, enum cmd_state state)
580 return ((state == CMD_STATE_INITIAL && command->states & S_INITIAL)
581 || (state == CMD_STATE_DATA && command->states & S_DATA)
582 || (state == CMD_STATE_INPUT_PROGRAM
583 && command->states & S_INPUT_PROGRAM)
584 || (state == CMD_STATE_FILE_TYPE && command->states & S_FILE_TYPE));
587 /* Emits an appropriate error message for trying to invoke
590 report_state_mismatch (const struct command *command, enum cmd_state state)
592 assert (!in_correct_state (command, state));
593 if (state == CMD_STATE_INITIAL || state == CMD_STATE_DATA)
595 const char *allowed[3];
600 if (command->states & S_INITIAL)
601 allowed[allowed_cnt++] = _("before the active file has been defined");
602 else if (command->states & S_DATA)
603 allowed[allowed_cnt++] = _("after the active file has been defined");
604 if (command->states & S_INPUT_PROGRAM)
605 allowed[allowed_cnt++] = _("inside INPUT PROGRAM");
606 if (command->states & S_FILE_TYPE)
607 allowed[allowed_cnt++] = _("inside FILE TYPE");
609 if (allowed_cnt == 1)
610 s = xstrdup (allowed[0]);
611 else if (allowed_cnt == 2)
612 s = xasprintf (_("%s or %s"), allowed[0], allowed[1]);
613 else if (allowed_cnt == 3)
614 s = xasprintf (_("%s, %s, or %s"), allowed[0], allowed[1], allowed[2]);
618 msg (SE, _("%s is allowed only %s."), command->name, s);
622 else if (state == CMD_STATE_INPUT_PROGRAM)
623 msg (SE, _("%s is not allowed inside INPUT PROGRAM."), command->name);
624 else if (state == CMD_STATE_FILE_TYPE)
625 msg (SE, _("%s is not allowed inside FILE TYPE."), command->name);
630 /* Command name completion. */
632 static enum cmd_state completion_state = CMD_STATE_INITIAL;
635 set_completion_state (enum cmd_state state)
637 completion_state = state;
640 /* Returns the next possible completion of a command name that
641 begins with PREFIX, in the current command state, or a null
642 pointer if no completions remain.
643 Before calling the first time, set *CMD to a null pointer. */
645 cmd_complete (const char *prefix, const struct command **cmd)
650 for (; *cmd < commands + command_cnt; (*cmd)++)
651 if (!memcasecmp ((*cmd)->name, prefix, strlen (prefix))
652 && (!((*cmd)->flags & F_TESTING) || get_testing_mode ())
653 && (!((*cmd)->flags & F_ENHANCED) || get_syntax () == ENHANCED)
654 && !((*cmd)->flags & F_ABBREV)
655 && ((*cmd)->function != NULL)
656 && in_correct_state (*cmd, completion_state))
657 return (*cmd)++->name;
662 /* Simple commands. */
664 /* Parse and execute FINISH command. */
666 cmd_finish (struct lexer *lexer UNUSED, struct dataset *ds UNUSED)
671 /* Parses the N command. */
673 cmd_n_of_cases (struct lexer *lexer, struct dataset *ds)
678 if (!lex_force_int (lexer))
680 x = lex_integer (lexer);
682 if (!lex_match_id (lexer, "ESTIMATED"))
683 dict_set_case_limit (dataset_dict (ds), x);
685 return lex_end_of_command (lexer);
688 /* Parses, performs the EXECUTE procedure. */
690 cmd_execute (struct lexer *lexer, struct dataset *ds)
692 bool ok = casereader_destroy (proc_open (ds));
693 if (!proc_commit (ds) || !ok)
694 return CMD_CASCADING_FAILURE;
695 return lex_end_of_command (lexer);
698 /* Parses, performs the ERASE command. */
700 cmd_erase (struct lexer *lexer, struct dataset *ds UNUSED)
702 if (get_safer_mode ())
704 msg (SE, _("This command not allowed when the SAFER option is set."));
708 if (!lex_force_match_id (lexer, "FILE"))
710 lex_match (lexer, '=');
711 if (!lex_force_string (lexer))
714 if (remove (ds_cstr (lex_tokstr (lexer))) == -1)
716 msg (SW, _("Error removing `%s': %s."),
717 ds_cstr (lex_tokstr (lexer)), strerror (errno));
724 #if HAVE_FORK && HAVE_EXECL
725 /* Spawn an interactive shell process. */
736 const char *shell_fn;
742 for (i = 3; i < 20; i++)
746 shell_fn = getenv ("SHELL");
747 if (shell_fn == NULL)
748 shell_fn = "/bin/sh";
751 const char *cp = strrchr (shell_fn, '/');
752 cp = cp ? &cp[1] : shell_fn;
753 shell_process = local_alloc (strlen (cp) + 8);
754 strcpy (shell_process, "-");
755 strcat (shell_process, cp);
756 if (strcmp (cp, "sh"))
757 shell_process[0] = '+';
760 execl (shell_fn, shell_process, NULL);
766 msg (SE, _("Couldn't fork: %s."), strerror (errno));
771 while (wait (NULL) != pid)
776 #else /* !(HAVE_FORK && HAVE_EXECL) */
777 /* Don't know how to spawn an interactive shell. */
781 msg (SE, _("Interactive shell not supported on this platform."));
786 /* Executes the specified COMMAND in a subshell. Returns true if
787 successful, false otherwise. */
789 run_command (const char *command)
791 if (system (NULL) == 0)
793 msg (SE, _("Command shell not supported on this platform."));
797 /* Execute the command. */
798 if (system (command) == -1)
799 msg (SE, _("Error executing command: %s."), strerror (errno));
804 /* Parses, performs the HOST command. */
806 cmd_host (struct lexer *lexer, struct dataset *ds UNUSED)
810 if (get_safer_mode ())
812 msg (SE, _("This command not allowed when the SAFER option is set."));
816 look_ahead = lex_look_ahead (lexer);
817 if (look_ahead == '.')
820 return shell () ? CMD_SUCCESS : CMD_FAILURE;
822 else if (look_ahead == '\'' || look_ahead == '"')
827 if (!lex_force_string (lexer))
829 ok = run_command (ds_cstr (lex_tokstr (lexer)));
832 return ok ? lex_end_of_command (lexer) : CMD_FAILURE;
836 bool ok = run_command (lex_rest_of_line (lexer));
837 lex_discard_line (lexer);
838 return ok ? CMD_SUCCESS : CMD_FAILURE;
842 /* Parses, performs the NEW FILE command. */
844 cmd_new_file (struct lexer *lexer, struct dataset *ds)
846 proc_discard_active_file (ds);
848 return lex_end_of_command (lexer);
851 /* Parses a comment. */
853 cmd_comment (struct lexer *lexer, struct dataset *ds UNUSED)
855 lex_skip_comment (lexer);