1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful, but
10 WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 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, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21 #include <language/command.h>
29 #include <data/dictionary.h>
30 #include <data/procedure.h>
31 #include <data/settings.h>
32 #include <data/variable.h>
33 #include <language/lexer/lexer.h>
34 #include <language/prompt.h>
35 #include <libpspp/alloc.h>
36 #include <libpspp/assertion.h>
37 #include <libpspp/compiler.h>
38 #include <libpspp/message.h>
39 #include <libpspp/message.h>
40 #include <libpspp/str.h>
41 #include <output/manager.h>
42 #include <output/table.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 (struct lexer *lexer, struct dataset *ds, 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 unset_cmd_algorithm ();
150 dict_clear_aux (dataset_dict (ds));
155 /* Parses an entire command, from command name to terminating
157 static enum cmd_result
158 do_parse_command (struct lexer *lexer, struct dataset *ds, enum cmd_state state)
160 const struct command *command;
161 enum cmd_result result;
163 /* Read the command's first token. */
164 prompt_set_style (PROMPT_FIRST);
165 set_completion_state (state);
167 if (lex_token (lexer) == T_STOP)
169 else if (lex_token (lexer) == '.')
171 /* Null commands can result from extra empty lines. */
174 prompt_set_style (PROMPT_LATER);
176 /* Parse the command name. */
177 command = parse_command_name (lexer);
180 else if (command->function == NULL)
182 msg (SE, _("%s is unimplemented."), command->name);
183 return CMD_NOT_IMPLEMENTED;
185 else if ((command->flags & F_TESTING) && !get_testing_mode ())
187 msg (SE, _("%s may be used only in testing mode."), command->name);
190 else if ((command->flags & F_ENHANCED) && get_syntax () != ENHANCED)
192 msg (SE, _("%s may be used only in enhanced syntax mode."),
196 else if (!in_correct_state (command, state))
198 report_state_mismatch (command, state);
202 /* Execute command. */
203 msg_set_command_name (command->name);
204 tab_set_command_name (command->name);
205 result = command->function (lexer, ds);
206 tab_set_command_name (NULL);
207 msg_set_command_name (NULL);
209 assert (cmd_result_is_valid (result));
214 match_strings (const char *a, size_t a_len,
215 const char *b, size_t b_len)
217 size_t match_len = 0;
219 while (a_len > 0 && b_len > 0)
221 /* Mismatch always returns zero. */
222 if (toupper ((unsigned char) *a++) != toupper ((unsigned char) *b++))
234 /* Returns the first character in the first word in STRING,
235 storing the word's length in *WORD_LEN. If no words remain,
236 returns a null pointer and stores 0 in *WORD_LEN. Words are
237 sequences of alphanumeric characters or single
238 non-alphanumeric characters. Words are delimited by
241 find_word (const char *string, size_t *word_len)
243 /* Skip whitespace and asterisks. */
244 while (isspace ((unsigned char) *string))
254 /* Special one-character word? */
255 if (!isalnum ((unsigned char) *string))
261 /* Alphanumeric word. */
263 while (isalnum ((unsigned char) string[*word_len]))
269 /* Returns true if strings A and B can be confused based on
270 their first three letters. */
272 conflicting_3char_prefixes (const char *a, const char *b)
274 size_t aw_len, bw_len;
277 aw = find_word (a, &aw_len);
278 bw = find_word (b, &bw_len);
279 assert (aw != NULL && bw != NULL);
281 /* Words that are the same don't conflict. */
282 if (aw_len == bw_len && !buf_compare_case (aw, bw, aw_len))
285 /* Words that are otherwise the same in the first three letters
287 return ((aw_len > 3 && bw_len > 3)
288 || (aw_len == 3 && bw_len > 3)
289 || (bw_len == 3 && aw_len > 3)) && !buf_compare_case (aw, bw, 3);
292 /* Returns true if CMD can be confused with another command
293 based on the first three letters of its first word. */
295 conflicting_3char_prefix_command (const struct command *cmd)
297 assert (cmd >= commands && cmd < commands + command_cnt);
299 return ((cmd > commands
300 && conflicting_3char_prefixes (cmd[-1].name, cmd[0].name))
301 || (cmd < commands + command_cnt
302 && conflicting_3char_prefixes (cmd[0].name, cmd[1].name)));
305 /* Ways that a set of words can match a command name. */
308 MISMATCH, /* Not a match. */
309 PARTIAL_MATCH, /* The words begin the command name. */
310 COMPLETE_MATCH /* The words are the command name. */
313 /* Figures out how well the WORD_CNT words in WORDS match CMD,
314 and returns the appropriate enum value. If WORDS are a
315 partial match for CMD and the next word in CMD is a dash, then
316 *DASH_POSSIBLE is set to 1 if DASH_POSSIBLE is non-null;
317 otherwise, *DASH_POSSIBLE is unchanged. */
318 static enum command_match
319 cmd_match_words (const struct command *cmd,
320 char *const words[], size_t word_cnt,
327 for (word = find_word (cmd->name, &word_len), word_idx = 0;
328 word != NULL && word_idx < word_cnt;
329 word = find_word (word + word_len, &word_len), word_idx++)
330 if (word_len != strlen (words[word_idx])
331 || buf_compare_case (word, words[word_idx], word_len))
333 size_t match_chars = match_strings (word, word_len,
335 strlen (words[word_idx]));
336 if (match_chars == 0)
341 else if (match_chars == 1 || match_chars == 2)
343 /* One- and two-character abbreviations are not
347 else if (match_chars == 3)
349 /* Three-character abbreviations are acceptable
350 in the first word of a command if there are
351 no name conflicts. They are always
352 acceptable after the first word. */
353 if (word_idx == 0 && conflicting_3char_prefix_command (cmd))
356 else /* match_chars > 3 */
358 /* Four-character and longer abbreviations are
359 always acceptable. */
363 if (word == NULL && word_idx == word_cnt)
365 /* cmd->name = "FOO BAR", words[] = {"FOO", "BAR"}. */
366 return COMPLETE_MATCH;
368 else if (word == NULL)
370 /* cmd->name = "FOO BAR", words[] = {"FOO", "BAR", "BAZ"}. */
375 /* cmd->name = "FOO BAR BAZ", words[] = {"FOO", "BAR"}. */
376 if (word[0] == '-' && dash_possible != NULL)
378 return PARTIAL_MATCH;
382 /* Returns the number of commands for which the WORD_CNT words in
383 WORDS are a partial or complete match. If some partial match
384 has a dash as the next word, then *DASH_POSSIBLE is set to 1,
385 otherwise it is set to 0. */
387 count_matching_commands (char *const words[], size_t word_cnt,
390 const struct command *cmd;
395 for (cmd = commands; cmd < commands + command_cnt; cmd++)
396 if (cmd_match_words (cmd, words, word_cnt, dash_possible) != MISMATCH)
399 return cmd_match_count;
402 /* Returns the command for which the WORD_CNT words in WORDS are
403 a complete match. Returns a null pointer if no such command
405 static const struct command *
406 get_complete_match (char *const words[], size_t word_cnt)
408 const struct command *cmd;
410 for (cmd = commands; cmd < commands + command_cnt; cmd++)
411 if (cmd_match_words (cmd, words, word_cnt, NULL) == COMPLETE_MATCH)
417 /* Returns the command with the given exact NAME.
418 Aborts if no such command exists. */
419 static const struct command *
420 find_command (const char *name)
422 const struct command *cmd;
424 for (cmd = commands; cmd < commands + command_cnt; cmd++)
425 if (!strcmp (cmd->name, name))
430 /* Frees the WORD_CNT words in WORDS. */
432 free_words (char *words[], size_t word_cnt)
436 for (idx = 0; idx < word_cnt; idx++)
440 /* Flags an error that the command whose name is given by the
441 WORD_CNT words in WORDS is unknown. */
443 unknown_command_error (struct lexer *lexer, char *const words[], size_t word_cnt)
446 lex_error (lexer, _("expecting command name"));
453 for (i = 0; i < word_cnt; i++)
456 ds_put_char (&s, ' ');
457 ds_put_cstr (&s, words[i]);
460 msg (SE, _("Unknown command %s."), ds_cstr (&s));
466 /* Parse the command name and return a pointer to the corresponding
467 struct command if successful.
468 If not successful, return a null pointer. */
469 static const struct command *
470 parse_command_name (struct lexer *lexer)
474 int complete_word_cnt;
477 if (lex_token (lexer) == T_EXP ||
478 lex_token (lexer) == '*' || lex_token (lexer) == '[')
479 return find_command ("COMMENT");
482 word_cnt = complete_word_cnt = 0;
483 while (lex_token (lexer) == T_ID || (dash_possible && lex_token (lexer) == '-'))
487 assert (word_cnt < sizeof words / sizeof *words);
488 if (lex_token (lexer) == T_ID)
490 words[word_cnt] = ds_xstrdup (lex_tokstr (lexer));
491 str_uppercase (words[word_cnt]);
493 else if (lex_token (lexer) == '-')
494 words[word_cnt] = xstrdup ("-");
497 cmd_match_cnt = count_matching_commands (words, word_cnt,
499 if (cmd_match_cnt == 0)
501 else if (cmd_match_cnt == 1)
503 const struct command *command = get_complete_match (words, word_cnt);
506 if (!(command->flags & F_KEEP_FINAL_TOKEN))
508 free_words (words, word_cnt);
512 else /* cmd_match_cnt > 1 */
514 /* Do we have a complete command name so far? */
515 if (get_complete_match (words, word_cnt) != NULL)
516 complete_word_cnt = word_cnt;
521 /* If we saw a complete command name earlier, drop back to
523 if (complete_word_cnt)
525 int pushback_word_cnt;
526 const struct command *command;
528 /* Get the command. */
529 command = get_complete_match (words, complete_word_cnt);
530 assert (command != NULL);
532 /* Figure out how many words we want to keep.
533 We normally want to swallow the entire command. */
534 pushback_word_cnt = complete_word_cnt + 1;
535 if (command->flags & F_KEEP_FINAL_TOKEN)
538 /* FIXME: We only support one-token pushback. */
539 assert (pushback_word_cnt + 1 >= word_cnt);
541 while (word_cnt > pushback_word_cnt)
544 if (strcmp (words[word_cnt], "-"))
545 lex_put_back_id (lexer, words[word_cnt]);
547 lex_put_back (lexer, '-');
548 free (words[word_cnt]);
551 free_words (words, word_cnt);
555 /* We didn't get a valid command name. */
556 unknown_command_error (lexer, words, word_cnt);
557 free_words (words, word_cnt);
561 /* Returns true if COMMAND is allowed in STATE,
564 in_correct_state (const struct command *command, enum cmd_state state)
566 return ((state == CMD_STATE_INITIAL && command->states & S_INITIAL)
567 || (state == CMD_STATE_DATA && command->states & S_DATA)
568 || (state == CMD_STATE_INPUT_PROGRAM
569 && command->states & S_INPUT_PROGRAM)
570 || (state == CMD_STATE_FILE_TYPE && command->states & S_FILE_TYPE));
573 /* Emits an appropriate error message for trying to invoke
576 report_state_mismatch (const struct command *command, enum cmd_state state)
578 assert (!in_correct_state (command, state));
579 if (state == CMD_STATE_INITIAL || state == CMD_STATE_DATA)
581 const char *allowed[3];
586 if (command->states & S_INITIAL)
587 allowed[allowed_cnt++] = _("before the active file has been defined");
588 else if (command->states & S_DATA)
589 allowed[allowed_cnt++] = _("after the active file has been defined");
590 if (command->states & S_INPUT_PROGRAM)
591 allowed[allowed_cnt++] = _("inside INPUT PROGRAM");
592 if (command->states & S_FILE_TYPE)
593 allowed[allowed_cnt++] = _("inside FILE TYPE");
595 if (allowed_cnt == 1)
596 s = xstrdup (allowed[0]);
597 else if (allowed_cnt == 2)
598 s = xasprintf (_("%s or %s"), allowed[0], allowed[1]);
599 else if (allowed_cnt == 3)
600 s = xasprintf (_("%s, %s, or %s"), allowed[0], allowed[1], allowed[2]);
604 msg (SE, _("%s is allowed only %s."), command->name, s);
608 else if (state == CMD_STATE_INPUT_PROGRAM)
609 msg (SE, _("%s is not allowed inside INPUT PROGRAM."), command->name);
610 else if (state == CMD_STATE_FILE_TYPE)
611 msg (SE, _("%s is not allowed inside FILE TYPE."), command->name);
616 /* Command name completion. */
618 static enum cmd_state completion_state = CMD_STATE_INITIAL;
621 set_completion_state (enum cmd_state state)
623 completion_state = state;
626 /* Returns the next possible completion of a command name that
627 begins with PREFIX, in the current command state, or a null
628 pointer if no completions remain.
629 Before calling the first time, set *CMD to a null pointer. */
631 cmd_complete (const char *prefix, const struct command **cmd)
636 for (; *cmd < commands + command_cnt; (*cmd)++)
637 if (!memcasecmp ((*cmd)->name, prefix, strlen (prefix))
638 && (!((*cmd)->flags & F_TESTING) || get_testing_mode ())
639 && (!((*cmd)->flags & F_ENHANCED) || get_syntax () == ENHANCED)
640 && !((*cmd)->flags & F_ABBREV)
641 && ((*cmd)->function != NULL)
642 && in_correct_state (*cmd, completion_state))
643 return (*cmd)++->name;
648 /* Simple commands. */
650 /* Parse and execute FINISH command. */
652 cmd_finish (struct lexer *lexer UNUSED, struct dataset *ds UNUSED)
657 /* Parses the N command. */
659 cmd_n_of_cases (struct lexer *lexer, struct dataset *ds)
664 if (!lex_force_int (lexer))
666 x = lex_integer (lexer);
668 if (!lex_match_id (lexer, "ESTIMATED"))
669 dict_set_case_limit (dataset_dict (ds), x);
671 return lex_end_of_command (lexer);
674 /* Parses, performs the EXECUTE procedure. */
676 cmd_execute (struct lexer *lexer, struct dataset *ds)
678 if (!procedure (ds, NULL, NULL))
679 return CMD_CASCADING_FAILURE;
680 return lex_end_of_command (lexer);
683 /* Parses, performs the ERASE command. */
685 cmd_erase (struct lexer *lexer, struct dataset *ds UNUSED)
687 if (get_safer_mode ())
689 msg (SE, _("This command not allowed when the SAFER option is set."));
693 if (!lex_force_match_id (lexer, "FILE"))
695 lex_match (lexer, '=');
696 if (!lex_force_string (lexer))
699 if (remove (ds_cstr (lex_tokstr (lexer))) == -1)
701 msg (SW, _("Error removing `%s': %s."),
702 ds_cstr (lex_tokstr (lexer)), strerror (errno));
710 /* Spawn a shell process. */
721 const char *shell_fn;
727 for (i = 3; i < 20; i++)
731 shell_fn = getenv ("SHELL");
732 if (shell_fn == NULL)
733 shell_fn = "/bin/sh";
736 const char *cp = strrchr (shell_fn, '/');
737 cp = cp ? &cp[1] : shell_fn;
738 shell_process = local_alloc (strlen (cp) + 8);
739 strcpy (shell_process, "-");
740 strcat (shell_process, cp);
741 if (strcmp (cp, "sh"))
742 shell_process[0] = '+';
745 execl (shell_fn, shell_process, NULL);
751 msg (SE, _("Couldn't fork: %s."), strerror (errno));
756 while (wait (NULL) != pid)
763 /* Parses the HOST command argument and executes the specified
764 command. Returns a suitable command return code. */
766 run_command (struct lexer *lexer)
771 /* Handle either a string argument or a full-line argument. */
773 int c = lex_look_ahead (lexer);
775 if (c == '\'' || c == '"')
778 if (!lex_force_string (lexer))
780 cmd = ds_cstr (lex_tokstr (lexer));
785 cmd = lex_rest_of_line (lexer, NULL);
786 lex_discard_line (lexer);
791 /* Execute the command. */
792 if (system (cmd) == -1)
793 msg (SE, _("Error executing command: %s."), strerror (errno));
795 /* Finish parsing. */
800 if (lex_token (lexer) != '.')
802 lex_error (lexer, _("expecting end of command"));
810 /* Parses, performs the HOST command. */
812 cmd_host (struct lexer *lexer, struct dataset *ds UNUSED)
816 if (get_safer_mode ())
818 msg (SE, _("This command not allowed when the SAFER option is set."));
823 /* Figure out whether to invoke an interactive shell or to execute a
824 single shell command. */
825 if (lex_look_ahead (lexer) == '.')
828 code = shell () ? CMD_FAILURE : CMD_SUCCESS;
831 code = run_command (lexer);
833 /* Make sure that the system has a command interpreter, then run a
835 if (system (NULL) != 0)
836 code = run_command (lexer);
839 msg (SE, _("No operating system support for this command."));
847 /* Parses, performs the NEW FILE command. */
849 cmd_new_file (struct lexer *lexer, struct dataset *ds)
851 discard_variables (ds);
853 return lex_end_of_command (lexer);
856 /* Parses a comment. */
858 cmd_comment (struct lexer *lexer, struct dataset *ds UNUSED)
860 lex_skip_comment (lexer);