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/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. */
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) (void); /* 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 (void);
132 static enum cmd_result do_parse_command (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 (enum cmd_state state)
144 result = do_parse_command (state);
145 if (cmd_result_is_failure (result))
146 lex_discard_rest_of_command ();
148 unset_cmd_algorithm ();
149 dict_clear_aux (default_dict);
154 /* Parses an entire command, from command name to terminating
156 static enum cmd_result
157 do_parse_command (enum cmd_state state)
159 const struct command *command;
160 enum cmd_result result;
162 /* Read the command's first token. */
163 getl_set_prompt_style (GETL_PROMPT_FIRST);
164 set_completion_state (state);
168 else if (token == '.')
170 /* Null commands can result from extra empty lines. */
173 getl_set_prompt_style (GETL_PROMPT_LATER);
175 /* Parse the command name. */
176 command = parse_command_name ();
179 else if (command->function == NULL)
180 return CMD_NOT_IMPLEMENTED;
181 else if ((command->flags & F_TESTING) && !get_testing_mode ())
183 msg (SE, _("%s may be used only in testing mode."), command->name);
186 else if ((command->flags & F_ENHANCED) && get_syntax () != ENHANCED)
188 msg (SE, _("%s may be used only in enhanced syntax mode."),
192 else if (!in_correct_state (command, state))
194 report_state_mismatch (command, state);
198 /* Execute command. */
199 msg_set_command_name (command->name);
200 tab_set_command_name (command->name);
201 result = command->function ();
202 tab_set_command_name (NULL);
203 msg_set_command_name (NULL);
205 assert (cmd_result_is_valid (result));
210 match_strings (const char *a, size_t a_len,
211 const char *b, size_t b_len)
213 size_t match_len = 0;
215 while (a_len > 0 && b_len > 0)
217 /* Mismatch always returns zero. */
218 if (toupper ((unsigned char) *a++) != toupper ((unsigned char) *b++))
230 /* Returns the first character in the first word in STRING,
231 storing the word's length in *WORD_LEN. If no words remain,
232 returns a null pointer and stores 0 in *WORD_LEN. Words are
233 sequences of alphanumeric characters or single
234 non-alphanumeric characters. Words are delimited by
237 find_word (const char *string, size_t *word_len)
239 /* Skip whitespace and asterisks. */
240 while (isspace ((unsigned char) *string))
250 /* Special one-character word? */
251 if (!isalnum ((unsigned char) *string))
257 /* Alphanumeric word. */
259 while (isalnum ((unsigned char) string[*word_len]))
265 /* Returns nonzero if strings A and B can be confused based on
266 their first three letters. */
268 conflicting_3char_prefixes (const char *a, const char *b)
270 size_t aw_len, bw_len;
273 aw = find_word (a, &aw_len);
274 bw = find_word (b, &bw_len);
275 assert (aw != NULL && bw != NULL);
277 /* Words that are the same don't conflict. */
278 if (aw_len == bw_len && !buf_compare_case (aw, bw, aw_len))
281 /* Words that are otherwise the same in the first three letters
283 return ((aw_len > 3 && bw_len > 3)
284 || (aw_len == 3 && bw_len > 3)
285 || (bw_len == 3 && aw_len > 3)) && !buf_compare_case (aw, bw, 3);
288 /* Returns nonzero if CMD can be confused with another command
289 based on the first three letters of its first word. */
291 conflicting_3char_prefix_command (const struct command *cmd)
293 assert (cmd >= commands && cmd < commands + command_cnt);
295 return ((cmd > commands
296 && conflicting_3char_prefixes (cmd[-1].name, cmd[0].name))
297 || (cmd < commands + command_cnt
298 && conflicting_3char_prefixes (cmd[0].name, cmd[1].name)));
301 /* Ways that a set of words can match a command name. */
304 MISMATCH, /* Not a match. */
305 PARTIAL_MATCH, /* The words begin the command name. */
306 COMPLETE_MATCH /* The words are the command name. */
309 /* Figures out how well the WORD_CNT words in WORDS match CMD,
310 and returns the appropriate enum value. If WORDS are a
311 partial match for CMD and the next word in CMD is a dash, then
312 *DASH_POSSIBLE is set to 1 if DASH_POSSIBLE is non-null;
313 otherwise, *DASH_POSSIBLE is unchanged. */
314 static enum command_match
315 cmd_match_words (const struct command *cmd,
316 char *const words[], size_t word_cnt,
323 for (word = find_word (cmd->name, &word_len), word_idx = 0;
324 word != NULL && word_idx < word_cnt;
325 word = find_word (word + word_len, &word_len), word_idx++)
326 if (word_len != strlen (words[word_idx])
327 || buf_compare_case (word, words[word_idx], word_len))
329 size_t match_chars = match_strings (word, word_len,
331 strlen (words[word_idx]));
332 if (match_chars == 0)
337 else if (match_chars == 1 || match_chars == 2)
339 /* One- and two-character abbreviations are not
343 else if (match_chars == 3)
345 /* Three-character abbreviations are acceptable
346 in the first word of a command if there are
347 no name conflicts. They are always
348 acceptable after the first word. */
349 if (word_idx == 0 && conflicting_3char_prefix_command (cmd))
352 else /* match_chars > 3 */
354 /* Four-character and longer abbreviations are
355 always acceptable. */
359 if (word == NULL && word_idx == word_cnt)
361 /* cmd->name = "FOO BAR", words[] = {"FOO", "BAR"}. */
362 return COMPLETE_MATCH;
364 else if (word == NULL)
366 /* cmd->name = "FOO BAR", words[] = {"FOO", "BAR", "BAZ"}. */
371 /* cmd->name = "FOO BAR BAZ", words[] = {"FOO", "BAR"}. */
372 if (word[0] == '-' && dash_possible != NULL)
374 return PARTIAL_MATCH;
378 /* Returns the number of commands for which the WORD_CNT words in
379 WORDS are a partial or complete match. If some partial match
380 has a dash as the next word, then *DASH_POSSIBLE is set to 1,
381 otherwise it is set to 0. */
383 count_matching_commands (char *const words[], size_t word_cnt,
386 const struct command *cmd;
391 for (cmd = commands; cmd < commands + command_cnt; cmd++)
392 if (cmd_match_words (cmd, words, word_cnt, dash_possible) != MISMATCH)
395 return cmd_match_count;
398 /* Returns the command for which the WORD_CNT words in WORDS are
399 a complete match. Returns a null pointer if no such command
401 static const struct command *
402 get_complete_match (char *const words[], size_t word_cnt)
404 const struct command *cmd;
406 for (cmd = commands; cmd < commands + command_cnt; cmd++)
407 if (cmd_match_words (cmd, words, word_cnt, NULL) == COMPLETE_MATCH)
413 /* Returns the command with the given exact NAME.
414 Aborts if no such command exists. */
415 static const struct command *
416 find_command (const char *name)
418 const struct command *cmd;
420 for (cmd = commands; cmd < commands + command_cnt; cmd++)
421 if (!strcmp (cmd->name, name))
426 /* Frees the WORD_CNT words in WORDS. */
428 free_words (char *words[], size_t word_cnt)
432 for (idx = 0; idx < word_cnt; idx++)
436 /* Flags an error that the command whose name is given by the
437 WORD_CNT words in WORDS is unknown. */
439 unknown_command_error (char *const words[], size_t word_cnt)
442 lex_error (_("expecting command name"));
449 for (i = 0; i < word_cnt; i++)
452 ds_put_char (&s, ' ');
453 ds_put_cstr (&s, words[i]);
456 msg (SE, _("Unknown command %s."), ds_cstr (&s));
462 /* Parse the command name and return a pointer to the corresponding
463 struct command if successful.
464 If not successful, return a null pointer. */
465 static const struct command *
466 parse_command_name (void)
470 int complete_word_cnt;
473 if (token == T_EXP || token == '*' || token == '[')
474 return find_command ("COMMENT");
477 word_cnt = complete_word_cnt = 0;
478 while (token == T_ID || (dash_possible && token == '-'))
482 assert (word_cnt < sizeof words / sizeof *words);
485 words[word_cnt] = ds_xstrdup (&tokstr);
486 str_uppercase (words[word_cnt]);
488 else if (token == '-')
489 words[word_cnt] = xstrdup ("-");
492 cmd_match_cnt = count_matching_commands (words, word_cnt,
494 if (cmd_match_cnt == 0)
496 else if (cmd_match_cnt == 1)
498 const struct command *command = get_complete_match (words, word_cnt);
501 if (!(command->flags & F_KEEP_FINAL_TOKEN))
503 free_words (words, word_cnt);
507 else /* cmd_match_cnt > 1 */
509 /* Do we have a complete command name so far? */
510 if (get_complete_match (words, word_cnt) != NULL)
511 complete_word_cnt = word_cnt;
516 /* If we saw a complete command name earlier, drop back to
518 if (complete_word_cnt)
520 int pushback_word_cnt;
521 const struct command *command;
523 /* Get the command. */
524 command = get_complete_match (words, complete_word_cnt);
525 assert (command != NULL);
527 /* Figure out how many words we want to keep.
528 We normally want to swallow the entire command. */
529 pushback_word_cnt = complete_word_cnt + 1;
530 if (command->flags & F_KEEP_FINAL_TOKEN)
533 /* FIXME: We only support one-token pushback. */
534 assert (pushback_word_cnt + 1 >= word_cnt);
536 while (word_cnt > pushback_word_cnt)
539 if (strcmp (words[word_cnt], "-"))
540 lex_put_back_id (words[word_cnt]);
543 free (words[word_cnt]);
546 free_words (words, word_cnt);
550 /* We didn't get a valid command name. */
551 unknown_command_error (words, word_cnt);
552 free_words (words, word_cnt);
556 /* Returns true if COMMAND is allowed in STATE,
559 in_correct_state (const struct command *command, enum cmd_state state)
561 return ((state == CMD_STATE_INITIAL && command->states & S_INITIAL)
562 || (state == CMD_STATE_DATA && command->states & S_DATA)
563 || (state == CMD_STATE_INPUT_PROGRAM
564 && command->states & S_INPUT_PROGRAM)
565 || (state == CMD_STATE_FILE_TYPE && command->states & S_FILE_TYPE));
568 /* Emits an appropriate error message for trying to invoke
571 report_state_mismatch (const struct command *command, enum cmd_state state)
573 assert (!in_correct_state (command, state));
574 if (state == CMD_STATE_INITIAL || state == CMD_STATE_DATA)
576 const char *allowed[3];
581 if (command->states & S_INITIAL)
582 allowed[allowed_cnt++] = _("before the active file has been defined");
583 else if (command->states & S_DATA)
584 allowed[allowed_cnt++] = _("after the active file has been defined");
585 if (command->states & S_INPUT_PROGRAM)
586 allowed[allowed_cnt++] = _("inside INPUT PROGRAM");
587 if (command->states & S_FILE_TYPE)
588 allowed[allowed_cnt++] = _("inside FILE TYPE");
590 if (allowed_cnt == 1)
591 s = xstrdup (allowed[0]);
592 else if (allowed_cnt == 2)
593 s = xasprintf (_("%s or %s"), allowed[0], allowed[1]);
594 else if (allowed_cnt == 3)
595 s = xasprintf (_("%s, %s, or %s"), allowed[0], allowed[1], allowed[2]);
599 msg (SE, _("%s is allowed only %s."), command->name, s);
603 else if (state == CMD_STATE_INPUT_PROGRAM)
604 msg (SE, _("%s is not allowed inside INPUT PROGRAM."), command->name);
605 else if (state == CMD_STATE_FILE_TYPE)
606 msg (SE, _("%s is not allowed inside FILE TYPE."), command->name);
611 /* Command name completion. */
613 static enum cmd_state completion_state = CMD_STATE_INITIAL;
616 set_completion_state (enum cmd_state state)
618 completion_state = state;
621 /* Returns the next possible completion of a command name that
622 begins with PREFIX, in the current command state, or a null
623 pointer if no completions remain.
624 Before calling the first time, set *CMD to a null pointer. */
626 cmd_complete (const char *prefix, const struct command **cmd)
631 for (; *cmd < commands + command_cnt; (*cmd)++)
632 if (!memcasecmp ((*cmd)->name, prefix, strlen (prefix))
633 && (!((*cmd)->flags & F_TESTING) || get_testing_mode ())
634 && (!((*cmd)->flags & F_ENHANCED) || get_syntax () == ENHANCED)
635 && ((*cmd)->function != NULL)
636 && in_correct_state (*cmd, completion_state))
637 return (*cmd)++->name;
642 /* Simple commands. */
644 /* Parse and execute FINISH command. */
651 /* Parses the N command. */
653 cmd_n_of_cases (void)
658 if (!lex_force_int ())
662 if (!lex_match_id ("ESTIMATED"))
663 dict_set_case_limit (default_dict, x);
665 return lex_end_of_command ();
668 /* Parses, performs the EXECUTE procedure. */
672 if (!procedure (NULL, NULL))
673 return CMD_CASCADING_FAILURE;
674 return lex_end_of_command ();
677 /* Parses, performs the ERASE command. */
681 if (get_safer_mode ())
683 msg (SE, _("This command not allowed when the SAFER option is set."));
687 if (!lex_force_match_id ("FILE"))
690 if (!lex_force_string ())
693 if (remove (ds_cstr (&tokstr)) == -1)
695 msg (SW, _("Error removing `%s': %s."),
696 ds_cstr (&tokstr), strerror (errno));
704 /* Spawn a shell process. */
715 const char *shell_fn;
721 for (i = 3; i < 20; i++)
725 shell_fn = getenv ("SHELL");
726 if (shell_fn == NULL)
727 shell_fn = "/bin/sh";
730 const char *cp = strrchr (shell_fn, '/');
731 cp = cp ? &cp[1] : shell_fn;
732 shell_process = local_alloc (strlen (cp) + 8);
733 strcpy (shell_process, "-");
734 strcat (shell_process, cp);
735 if (strcmp (cp, "sh"))
736 shell_process[0] = '+';
739 execl (shell_fn, shell_process, NULL);
745 msg (SE, _("Couldn't fork: %s."), strerror (errno));
750 while (wait (NULL) != pid)
757 /* Parses the HOST command argument and executes the specified
758 command. Returns a suitable command return code. */
765 /* Handle either a string argument or a full-line argument. */
767 int c = lex_look_ahead ();
769 if (c == '\'' || c == '"')
772 if (!lex_force_string ())
774 cmd = ds_cstr (&tokstr);
779 cmd = lex_rest_of_line (NULL);
785 /* Execute the command. */
786 if (system (cmd) == -1)
787 msg (SE, _("Error executing command: %s."), strerror (errno));
789 /* Finish parsing. */
796 lex_error (_("expecting end of command"));
806 /* Parses, performs the HOST command. */
812 if (get_safer_mode ())
814 msg (SE, _("This command not allowed when the SAFER option is set."));
819 /* Figure out whether to invoke an interactive shell or to execute a
820 single shell command. */
821 if (lex_look_ahead () == '.')
824 code = shell () ? CMD_FAILURE : CMD_SUCCESS;
827 code = run_command ();
829 /* Make sure that the system has a command interpreter, then run a
831 if (system (NULL) != 0)
832 code = run_command ();
835 msg (SE, _("No operating system support for this command."));
843 /* Parses, performs the NEW FILE command. */
847 discard_variables ();
849 return lex_end_of_command ();
852 /* Parses a comment. */