1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3 Written by Ben Pfaff <blp@gnu.org>.
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
10 This program is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 #include <language/command.h>
30 #include <data/dictionary.h>
31 #include <data/procedure.h>
32 #include <data/settings.h>
33 #include <data/variable.h>
34 #include <language/lexer/lexer.h>
35 #include <language/line-buffer.h>
36 #include <libpspp/alloc.h>
37 #include <libpspp/assertion.h>
38 #include <libpspp/compiler.h>
39 #include <libpspp/message.h>
40 #include <libpspp/message.h>
41 #include <libpspp/str.h>
42 #include <output/manager.h>
43 #include <output/table.h>
50 #include <readline/readline.h>
54 #define _(msgid) gettext (msgid)
55 #define N_(msgid) msgid
57 /* Returns true if RESULT is a valid "enum cmd_result",
60 cmd_result_is_valid (enum cmd_result result)
62 return (result == CMD_SUCCESS || result == CMD_EOF || result == CMD_FINISH
63 || (result >= CMD_PRIVATE_FIRST && result <= CMD_PRIVATE_LAST)
64 || result == CMD_FAILURE || result == CMD_NOT_IMPLEMENTED
65 || result == CMD_CASCADING_FAILURE);
68 /* Returns true if RESULT indicates success,
71 cmd_result_is_success (enum cmd_result result)
73 assert (cmd_result_is_valid (result));
77 /* Returns true if RESULT indicates failure,
80 cmd_result_is_failure (enum cmd_result result)
82 assert (cmd_result_is_valid (result));
86 /* Command processing states. */
89 S_INITIAL = 0x01, /* Allowed before active file defined. */
90 S_DATA = 0x02, /* Allowed after active file defined. */
91 S_INPUT_PROGRAM = 0x04, /* Allowed in INPUT PROGRAM. */
92 S_FILE_TYPE = 0x08, /* Allowed in FILE TYPE. */
93 S_ANY = 0x0f /* Allowed anywhere. */
96 /* Other command requirements. */
99 F_ENHANCED = 0x10, /* Allowed only in enhanced syntax mode. */
100 F_TESTING = 0x20, /* Allowed only in testing mode. */
101 F_KEEP_FINAL_TOKEN = 0x40,/* Don't skip final token in command name. */
102 F_ABBREV = 0x80 /* Not a candidate for name completion. */
105 /* A single command. */
108 enum states states; /* States in which command is allowed. */
109 enum flags flags; /* Other command requirements. */
110 const char *name; /* Command name. */
111 int (*function) (void); /* Function to call. */
114 /* Define the command array. */
115 #define DEF_CMD(STATES, FLAGS, NAME, FUNCTION) {STATES, FLAGS, NAME, FUNCTION},
116 #define UNIMPL_CMD(NAME, DESCRIPTION) {S_ANY, 0, NAME, NULL},
117 static const struct command commands[] =
119 #include "command.def"
124 static const size_t command_cnt = sizeof commands / sizeof *commands;
126 static bool in_correct_state (const struct command *, enum cmd_state);
127 static bool report_state_mismatch (const struct command *, enum cmd_state);
128 static const struct command *find_command (const char *name);
129 static void set_completion_state (enum cmd_state);
131 /* Command parser. */
133 static const struct command *parse_command_name (void);
134 static enum cmd_result do_parse_command (enum cmd_state);
136 /* Parses an entire command, from command name to terminating
137 dot. On failure, skips to the terminating dot.
138 Returns the command's success or failure result. */
140 cmd_parse (enum cmd_state state)
146 result = do_parse_command (state);
147 if (cmd_result_is_failure (result))
148 lex_discard_rest_of_command ();
150 unset_cmd_algorithm ();
151 dict_clear_aux (default_dict);
156 /* Parses an entire command, from command name to terminating
158 static enum cmd_result
159 do_parse_command (enum cmd_state state)
161 const struct command *command;
162 enum cmd_result result;
164 /* Read the command's first token. */
165 getl_set_prompt_style (GETL_PROMPT_FIRST);
166 set_completion_state (state);
170 else if (token == '.')
172 /* Null commands can result from extra empty lines. */
175 getl_set_prompt_style (GETL_PROMPT_LATER);
177 /* Parse the command name. */
178 command = parse_command_name ();
181 else if (command->function == NULL)
182 return CMD_NOT_IMPLEMENTED;
183 else if ((command->flags & F_TESTING) && !get_testing_mode ())
185 msg (SE, _("%s may be used only in testing mode."), command->name);
188 else if ((command->flags & F_ENHANCED) && get_syntax () != ENHANCED)
190 msg (SE, _("%s may be used only in enhanced syntax mode."),
194 else if (!in_correct_state (command, state))
196 report_state_mismatch (command, state);
200 /* Execute command. */
201 msg_set_command_name (command->name);
202 tab_set_command_name (command->name);
203 result = command->function ();
204 tab_set_command_name (NULL);
205 msg_set_command_name (NULL);
207 assert (cmd_result_is_valid (result));
212 match_strings (const char *a, size_t a_len,
213 const char *b, size_t b_len)
215 size_t match_len = 0;
217 while (a_len > 0 && b_len > 0)
219 /* Mismatch always returns zero. */
220 if (toupper ((unsigned char) *a++) != toupper ((unsigned char) *b++))
232 /* Returns the first character in the first word in STRING,
233 storing the word's length in *WORD_LEN. If no words remain,
234 returns a null pointer and stores 0 in *WORD_LEN. Words are
235 sequences of alphanumeric characters or single
236 non-alphanumeric characters. Words are delimited by
239 find_word (const char *string, size_t *word_len)
241 /* Skip whitespace and asterisks. */
242 while (isspace ((unsigned char) *string))
252 /* Special one-character word? */
253 if (!isalnum ((unsigned char) *string))
259 /* Alphanumeric word. */
261 while (isalnum ((unsigned char) string[*word_len]))
267 /* Returns nonzero if strings A and B can be confused based on
268 their first three letters. */
270 conflicting_3char_prefixes (const char *a, const char *b)
272 size_t aw_len, bw_len;
275 aw = find_word (a, &aw_len);
276 bw = find_word (b, &bw_len);
277 assert (aw != NULL && bw != NULL);
279 /* Words that are the same don't conflict. */
280 if (aw_len == bw_len && !buf_compare_case (aw, bw, aw_len))
283 /* Words that are otherwise the same in the first three letters
285 return ((aw_len > 3 && bw_len > 3)
286 || (aw_len == 3 && bw_len > 3)
287 || (bw_len == 3 && aw_len > 3)) && !buf_compare_case (aw, bw, 3);
290 /* Returns nonzero if CMD can be confused with another command
291 based on the first three letters of its first word. */
293 conflicting_3char_prefix_command (const struct command *cmd)
295 assert (cmd >= commands && cmd < commands + command_cnt);
297 return ((cmd > commands
298 && conflicting_3char_prefixes (cmd[-1].name, cmd[0].name))
299 || (cmd < commands + command_cnt
300 && conflicting_3char_prefixes (cmd[0].name, cmd[1].name)));
303 /* Ways that a set of words can match a command name. */
306 MISMATCH, /* Not a match. */
307 PARTIAL_MATCH, /* The words begin the command name. */
308 COMPLETE_MATCH /* The words are the command name. */
311 /* Figures out how well the WORD_CNT words in WORDS match CMD,
312 and returns the appropriate enum value. If WORDS are a
313 partial match for CMD and the next word in CMD is a dash, then
314 *DASH_POSSIBLE is set to 1 if DASH_POSSIBLE is non-null;
315 otherwise, *DASH_POSSIBLE is unchanged. */
316 static enum command_match
317 cmd_match_words (const struct command *cmd,
318 char *const words[], size_t word_cnt,
325 for (word = find_word (cmd->name, &word_len), word_idx = 0;
326 word != NULL && word_idx < word_cnt;
327 word = find_word (word + word_len, &word_len), word_idx++)
328 if (word_len != strlen (words[word_idx])
329 || buf_compare_case (word, words[word_idx], word_len))
331 size_t match_chars = match_strings (word, word_len,
333 strlen (words[word_idx]));
334 if (match_chars == 0)
339 else if (match_chars == 1 || match_chars == 2)
341 /* One- and two-character abbreviations are not
345 else if (match_chars == 3)
347 /* Three-character abbreviations are acceptable
348 in the first word of a command if there are
349 no name conflicts. They are always
350 acceptable after the first word. */
351 if (word_idx == 0 && conflicting_3char_prefix_command (cmd))
354 else /* match_chars > 3 */
356 /* Four-character and longer abbreviations are
357 always acceptable. */
361 if (word == NULL && word_idx == word_cnt)
363 /* cmd->name = "FOO BAR", words[] = {"FOO", "BAR"}. */
364 return COMPLETE_MATCH;
366 else if (word == NULL)
368 /* cmd->name = "FOO BAR", words[] = {"FOO", "BAR", "BAZ"}. */
373 /* cmd->name = "FOO BAR BAZ", words[] = {"FOO", "BAR"}. */
374 if (word[0] == '-' && dash_possible != NULL)
376 return PARTIAL_MATCH;
380 /* Returns the number of commands for which the WORD_CNT words in
381 WORDS are a partial or complete match. If some partial match
382 has a dash as the next word, then *DASH_POSSIBLE is set to 1,
383 otherwise it is set to 0. */
385 count_matching_commands (char *const words[], size_t word_cnt,
388 const struct command *cmd;
393 for (cmd = commands; cmd < commands + command_cnt; cmd++)
394 if (cmd_match_words (cmd, words, word_cnt, dash_possible) != MISMATCH)
397 return cmd_match_count;
400 /* Returns the command for which the WORD_CNT words in WORDS are
401 a complete match. Returns a null pointer if no such command
403 static const struct command *
404 get_complete_match (char *const words[], size_t word_cnt)
406 const struct command *cmd;
408 for (cmd = commands; cmd < commands + command_cnt; cmd++)
409 if (cmd_match_words (cmd, words, word_cnt, NULL) == COMPLETE_MATCH)
415 /* Returns the command with the given exact NAME.
416 Aborts if no such command exists. */
417 static const struct command *
418 find_command (const char *name)
420 const struct command *cmd;
422 for (cmd = commands; cmd < commands + command_cnt; cmd++)
423 if (!strcmp (cmd->name, name))
428 /* Frees the WORD_CNT words in WORDS. */
430 free_words (char *words[], size_t word_cnt)
434 for (idx = 0; idx < word_cnt; idx++)
438 /* Flags an error that the command whose name is given by the
439 WORD_CNT words in WORDS is unknown. */
441 unknown_command_error (char *const words[], size_t word_cnt)
444 lex_error (_("expecting command name"));
451 for (i = 0; i < word_cnt; i++)
454 ds_put_char (&s, ' ');
455 ds_put_cstr (&s, words[i]);
458 msg (SE, _("Unknown command %s."), ds_cstr (&s));
464 /* Parse the command name and return a pointer to the corresponding
465 struct command if successful.
466 If not successful, return a null pointer. */
467 static const struct command *
468 parse_command_name (void)
472 int complete_word_cnt;
475 if (token == T_EXP || token == '*' || token == '[')
476 return find_command ("COMMENT");
479 word_cnt = complete_word_cnt = 0;
480 while (token == T_ID || (dash_possible && token == '-'))
484 assert (word_cnt < sizeof words / sizeof *words);
487 words[word_cnt] = ds_xstrdup (&tokstr);
488 str_uppercase (words[word_cnt]);
490 else if (token == '-')
491 words[word_cnt] = xstrdup ("-");
494 cmd_match_cnt = count_matching_commands (words, word_cnt,
496 if (cmd_match_cnt == 0)
498 else if (cmd_match_cnt == 1)
500 const struct command *command = get_complete_match (words, word_cnt);
503 if (!(command->flags & F_KEEP_FINAL_TOKEN))
505 free_words (words, word_cnt);
509 else /* cmd_match_cnt > 1 */
511 /* Do we have a complete command name so far? */
512 if (get_complete_match (words, word_cnt) != NULL)
513 complete_word_cnt = word_cnt;
518 /* If we saw a complete command name earlier, drop back to
520 if (complete_word_cnt)
522 int pushback_word_cnt;
523 const struct command *command;
525 /* Get the command. */
526 command = get_complete_match (words, complete_word_cnt);
527 assert (command != NULL);
529 /* Figure out how many words we want to keep.
530 We normally want to swallow the entire command. */
531 pushback_word_cnt = complete_word_cnt + 1;
532 if (command->flags & F_KEEP_FINAL_TOKEN)
535 /* FIXME: We only support one-token pushback. */
536 assert (pushback_word_cnt + 1 >= word_cnt);
538 while (word_cnt > pushback_word_cnt)
541 if (strcmp (words[word_cnt], "-"))
542 lex_put_back_id (words[word_cnt]);
545 free (words[word_cnt]);
548 free_words (words, word_cnt);
552 /* We didn't get a valid command name. */
553 unknown_command_error (words, word_cnt);
554 free_words (words, word_cnt);
558 /* Returns true if COMMAND is allowed in STATE,
561 in_correct_state (const struct command *command, enum cmd_state state)
563 return ((state == CMD_STATE_INITIAL && command->states & S_INITIAL)
564 || (state == CMD_STATE_DATA && command->states & S_DATA)
565 || (state == CMD_STATE_INPUT_PROGRAM
566 && command->states & S_INPUT_PROGRAM)
567 || (state == CMD_STATE_FILE_TYPE && command->states & S_FILE_TYPE));
570 /* Emits an appropriate error message for trying to invoke
573 report_state_mismatch (const struct command *command, enum cmd_state state)
575 assert (!in_correct_state (command, state));
576 if (state == CMD_STATE_INITIAL || state == CMD_STATE_DATA)
578 const char *allowed[3];
583 if (command->states & S_INITIAL)
584 allowed[allowed_cnt++] = _("before the active file has been defined");
585 else if (command->states & S_DATA)
586 allowed[allowed_cnt++] = _("after the active file has been defined");
587 if (command->states & S_INPUT_PROGRAM)
588 allowed[allowed_cnt++] = _("inside INPUT PROGRAM");
589 if (command->states & S_FILE_TYPE)
590 allowed[allowed_cnt++] = _("inside FILE TYPE");
592 if (allowed_cnt == 1)
593 s = xstrdup (allowed[0]);
594 else if (allowed_cnt == 2)
595 s = xasprintf (_("%s or %s"), allowed[0], allowed[1]);
596 else if (allowed_cnt == 3)
597 s = xasprintf (_("%s, %s, or %s"), allowed[0], allowed[1], allowed[2]);
601 msg (SE, _("%s is allowed only %s."), command->name, s);
605 else if (state == CMD_STATE_INPUT_PROGRAM)
606 msg (SE, _("%s is not allowed inside INPUT PROGRAM."), command->name);
607 else if (state == CMD_STATE_FILE_TYPE)
608 msg (SE, _("%s is not allowed inside FILE TYPE."), command->name);
613 /* Command name completion. */
615 static enum cmd_state completion_state = CMD_STATE_INITIAL;
618 set_completion_state (enum cmd_state state)
620 completion_state = state;
623 /* Returns the next possible completion of a command name that
624 begins with PREFIX, in the current command state, or a null
625 pointer if no completions remain.
626 Before calling the first time, set *CMD to a null pointer. */
628 cmd_complete (const char *prefix, const struct command **cmd)
633 for (; *cmd < commands + command_cnt; (*cmd)++)
634 if (!memcasecmp ((*cmd)->name, prefix, strlen (prefix))
635 && (!((*cmd)->flags & F_TESTING) || get_testing_mode ())
636 && (!((*cmd)->flags & F_ENHANCED) || get_syntax () == ENHANCED)
637 && !((*cmd)->flags & F_ABBREV)
638 && ((*cmd)->function != NULL)
639 && in_correct_state (*cmd, completion_state))
640 return (*cmd)++->name;
645 /* Simple commands. */
647 /* Parse and execute FINISH command. */
654 /* Parses the N command. */
656 cmd_n_of_cases (void)
661 if (!lex_force_int ())
665 if (!lex_match_id ("ESTIMATED"))
666 dict_set_case_limit (default_dict, x);
668 return lex_end_of_command ();
671 /* Parses, performs the EXECUTE procedure. */
675 if (!procedure (NULL, NULL))
676 return CMD_CASCADING_FAILURE;
677 return lex_end_of_command ();
680 /* Parses, performs the ERASE command. */
684 if (get_safer_mode ())
686 msg (SE, _("This command not allowed when the SAFER option is set."));
690 if (!lex_force_match_id ("FILE"))
693 if (!lex_force_string ())
696 if (remove (ds_cstr (&tokstr)) == -1)
698 msg (SW, _("Error removing `%s': %s."),
699 ds_cstr (&tokstr), strerror (errno));
707 /* Spawn a shell process. */
718 const char *shell_fn;
724 for (i = 3; i < 20; i++)
728 shell_fn = getenv ("SHELL");
729 if (shell_fn == NULL)
730 shell_fn = "/bin/sh";
733 const char *cp = strrchr (shell_fn, '/');
734 cp = cp ? &cp[1] : shell_fn;
735 shell_process = local_alloc (strlen (cp) + 8);
736 strcpy (shell_process, "-");
737 strcat (shell_process, cp);
738 if (strcmp (cp, "sh"))
739 shell_process[0] = '+';
742 execl (shell_fn, shell_process, NULL);
748 msg (SE, _("Couldn't fork: %s."), strerror (errno));
753 while (wait (NULL) != pid)
760 /* Parses the HOST command argument and executes the specified
761 command. Returns a suitable command return code. */
768 /* Handle either a string argument or a full-line argument. */
770 int c = lex_look_ahead ();
772 if (c == '\'' || c == '"')
775 if (!lex_force_string ())
777 cmd = ds_cstr (&tokstr);
782 cmd = lex_rest_of_line (NULL);
788 /* Execute the command. */
789 if (system (cmd) == -1)
790 msg (SE, _("Error executing command: %s."), strerror (errno));
792 /* Finish parsing. */
799 lex_error (_("expecting end of command"));
809 /* Parses, performs the HOST command. */
815 if (get_safer_mode ())
817 msg (SE, _("This command not allowed when the SAFER option is set."));
822 /* Figure out whether to invoke an interactive shell or to execute a
823 single shell command. */
824 if (lex_look_ahead () == '.')
827 code = shell () ? CMD_FAILURE : CMD_SUCCESS;
830 code = run_command ();
832 /* Make sure that the system has a command interpreter, then run a
834 if (system (NULL) != 0)
835 code = run_command ();
838 msg (SE, _("No operating system support for this command."));
846 /* Parses, performs the NEW FILE command. */
850 discard_variables ();
852 return lex_end_of_command ();
855 /* Parses a comment. */