Require "unistd" gnulib module. Removed tests for HAVE_UNISTD_H from
[pspp-builds.git] / src / language / command.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
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.
9
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.
14
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
18    02110-1301, USA. */
19
20 #include <config.h>
21 #include <libpspp/message.h>
22 #include <language/command.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <ctype.h>
26 #include <errno.h>
27 #include <unistd.h>
28 #include <libpspp/alloc.h>
29 #include <libpspp/compiler.h>
30 #include <data/dictionary.h>
31 #include <libpspp/message.h>
32 #include <language/lexer/lexer.h>
33 #include <data/settings.h>
34 #include <output/manager.h>
35 #include <libpspp/str.h>
36 #include <output/table.h>
37 #include <data/variable.h>
38 #include <procedure.h>
39
40 #if HAVE_SYS_WAIT_H
41 #include <sys/wait.h>
42 #endif
43
44 #include "gettext.h"
45 #define _(msgid) gettext (msgid)
46 #define N_(msgid) msgid
47 \f
48 /* Global variables. */
49
50 /* A STATE_* constant giving the current program state. */
51 int pgm_state;
52 \f
53 /* Static variables. */
54
55 /* A single command. */
56 struct command
57   {
58     const char *name;           /* Command name. */
59     int transition[4];          /* Transitions to make from each state. */
60     int (*func) (void);         /* Function to call. */
61     int skip_entire_name;       /* If zero, we don't skip the
62                                    final token in the command name. */
63     short debug;                /* Set if this cmd available only in test mode*/
64   };
65
66 /* Define the command array. */
67 #define DEFCMD(NAME, T1, T2, T3, T4, FUNC)              \
68         {NAME, {T1, T2, T3, T4}, FUNC, 1, 0},
69 #define DBGCMD(NAME, T1, T2, T3, T4, FUNC)              \
70         {NAME, {T1, T2, T3, T4}, FUNC, 1, 1},
71 #define SPCCMD(NAME, T1, T2, T3, T4, FUNC)              \
72         {NAME, {T1, T2, T3, T4}, FUNC, 0, 0},
73 #define UNIMPL(NAME, T1, T2, T3, T4, DESC)              \
74         {NAME, {T1, T2, T3, T4}, NULL, 1, 0},
75 static const struct command commands[] = 
76   {
77 #include "command.def"
78   };
79 #undef DEFCMD
80 #undef DBGCMD
81 #undef UNIMPL
82
83
84 /* Complete the line using the name of a command, 
85  * based upon the current prg_state
86  */
87 char * 
88 pspp_completion_function (const char *text,   int state)
89 {
90   static int skip=0;
91   const struct command *cmd = 0;
92   
93   for(;;)
94     {
95       if ( state + skip >= sizeof(commands)/ sizeof(struct command))
96         {
97           skip = 0;
98           return 0;
99         }
100
101       cmd = &commands[state + skip];
102   
103       if ( cmd->transition[pgm_state] == STATE_ERROR || ( cmd->debug  &&  ! get_testing_mode () ) ) 
104         {
105           skip++; 
106           continue;
107         }
108       
109       if ( text == 0 || 0 == strncasecmp (cmd->name, text, strlen(text)))
110         {
111           break;
112         }
113
114       skip++;
115     }
116   
117
118   return xstrdup(cmd->name);
119 }
120
121
122
123 #define COMMAND_CNT (sizeof commands / sizeof *commands)
124 \f
125 /* Command parser. */
126
127 static const struct command *parse_command_name (void);
128
129 /* Determines whether command C is appropriate to call in this
130    part of a FILE TYPE structure. */
131 static int
132 FILE_TYPE_okay (const struct command *c UNUSED)
133 #if 0
134 {
135   int okay = 0;
136   
137   if (c->func != cmd_record_type
138       && c->func != cmd_data_list
139       && c->func != cmd_repeating_data
140       && c->func != cmd_end_file_type)
141     msg (SE, _("%s not allowed inside FILE TYPE/END FILE TYPE."), c->name);
142   /* FIXME */
143   else if (c->func == cmd_repeating_data && fty.type == FTY_GROUPED)
144     msg (SE, _("%s not allowed inside FILE TYPE GROUPED/END FILE TYPE."),
145          c->name);
146   else if (!fty.had_rec_type && c->func != cmd_record_type)
147     msg (SE, _("RECORD TYPE must be the first command inside a "
148                       "FILE TYPE structure."));
149   else
150     okay = 1;
151
152   if (c->func == cmd_record_type)
153     fty.had_rec_type = 1;
154
155   return okay;
156 }
157 #else
158 {
159   return 1;
160 }
161 #endif
162
163 /* Parses an entire PSPP command.  This includes everything from the
164    command name to the terminating dot.  Does most of its work by
165    passing it off to the respective command dispatchers.  Only called
166    by parse() in main.c. */
167 int
168 cmd_parse (void)
169 {
170   const struct command *cp;     /* Iterator used to find the proper command. */
171
172 #if C_ALLOCA
173   /* The generic alloca package performs garbage collection when it is
174      called with an argument of zero. */
175   alloca (0);
176 #endif /* C_ALLOCA */
177
178   /* Null commands can result from extra empty lines. */
179   if (token == '.')
180     return CMD_SUCCESS;
181
182   /* Parse comments. */
183   if ((token == T_ID && !strcasecmp (tokid, "COMMENT"))
184       || token == T_EXP || token == '*' || token == '[')
185     {
186       lex_skip_comment ();
187       return CMD_SUCCESS;
188     }
189
190   /* Otherwise the line must begin with a command name, which is
191      always an ID token. */
192   if (token != T_ID)
193     {
194       lex_error (_("expecting command name"));
195       return CMD_FAILURE;
196     }
197
198   /* Parse the command name. */
199   cp = parse_command_name ();
200   if (cp == NULL)
201     return CMD_FAILURE;
202   if (cp->func == NULL)
203     {
204       msg (SE, _("%s is not yet implemented."), cp->name);
205       while (token && token != '.')
206         lex_get ();
207       return CMD_SUCCESS;
208     }
209
210   /* If we're in a FILE TYPE structure, only certain commands can be
211      allowed. */
212   if (pgm_state == STATE_INPUT
213       && case_source_is_class (vfm_source, &file_type_source_class)
214       && !FILE_TYPE_okay (cp))
215     return CMD_FAILURE;
216
217   /* Certain state transitions are not allowed.  Check for these. */
218   assert (pgm_state >= 0 && pgm_state < STATE_ERROR);
219   if (cp->transition[pgm_state] == STATE_ERROR)
220     {
221       static const char *state_name[4] =
222       {
223         N_("%s is not allowed (1) before a command to specify the "
224            "input program, such as DATA LIST, (2) between FILE TYPE "
225            "and END FILE TYPE, (3) between INPUT PROGRAM and END "
226            "INPUT PROGRAM."),
227         N_("%s is not allowed within an input program."),
228         N_("%s is only allowed within an input program."),
229         N_("%s is only allowed within an input program."),
230       };
231
232       msg (SE, gettext (state_name[pgm_state]), cp->name);
233       return CMD_FAILURE;
234     }
235
236   /* The structured output manager numbers all its tables.  Increment
237      the major table number for each separate procedure. */
238   som_new_series ();
239   
240   {
241     int result;
242     
243     /* Call the command dispatcher. */
244     err_set_command_name (cp->name);
245     tab_set_command_name (cp->name);
246     result = cp->func ();
247     err_set_command_name (NULL);
248     tab_set_command_name (NULL);
249     
250     /* Perform the state transition if the command completed
251        successfully (at least in part). */
252     if (result != CMD_FAILURE && result != CMD_CASCADING_FAILURE)
253       {
254         pgm_state = cp->transition[pgm_state];
255
256         if (pgm_state == STATE_ERROR)
257           {
258             discard_variables ();
259             pgm_state = STATE_INIT;
260           }
261       }
262
263     /* Pass the command's success value up to the caller. */
264     return result;
265   }
266 }
267
268 static size_t
269 match_strings (const char *a, size_t a_len,
270                const char *b, size_t b_len) 
271 {
272   size_t match_len = 0;
273   
274   while (a_len > 0 && b_len > 0) 
275     {
276       /* Mismatch always returns zero. */
277       if (toupper ((unsigned char) *a++) != toupper ((unsigned char) *b++))
278         return 0;
279
280       /* Advance. */
281       a_len--;
282       b_len--;
283       match_len++;
284     }
285
286   return match_len;
287 }
288
289 /* Returns the first character in the first word in STRING,
290    storing the word's length in *WORD_LEN.  If no words remain,
291    returns a null pointer and stores 0 in *WORD_LEN.  Words are
292    sequences of alphanumeric characters or single
293    non-alphanumeric characters.  Words are delimited by
294    spaces. */
295 static const char *
296 find_word (const char *string, size_t *word_len) 
297 {
298   /* Skip whitespace and asterisks. */
299   while (isspace ((unsigned char) *string))
300     string++;
301
302   /* End of string? */
303   if (*string == '\0') 
304     {
305       *word_len = 0;
306       return NULL;
307     }
308
309   /* Special one-character word? */
310   if (!isalnum ((unsigned char) *string)) 
311     {
312       *word_len = 1;
313       return string;
314     }
315
316   /* Alphanumeric word. */
317   *word_len = 1;
318   while (isalnum ((unsigned char) string[*word_len]))
319     (*word_len)++;
320
321   return string;
322 }
323
324 /* Returns nonzero if strings A and B can be confused based on
325    their first three letters. */
326 static int
327 conflicting_3char_prefixes (const char *a, const char *b) 
328 {
329   size_t aw_len, bw_len;
330   const char *aw, *bw;
331
332   aw = find_word (a, &aw_len);
333   bw = find_word (b, &bw_len);
334   assert (aw != NULL && bw != NULL);
335
336   /* Words that are the same don't conflict. */
337   if (aw_len == bw_len && !buf_compare_case (aw, bw, aw_len))
338     return 0;
339   
340   /* Words that are otherwise the same in the first three letters
341      do conflict. */
342   return ((aw_len > 3 && bw_len > 3)
343           || (aw_len == 3 && bw_len > 3)
344           || (bw_len == 3 && aw_len > 3)) && !buf_compare_case (aw, bw, 3);
345 }
346
347 /* Returns nonzero if CMD can be confused with another command
348    based on the first three letters of its first word. */
349 static int
350 conflicting_3char_prefix_command (const struct command *cmd) 
351 {
352   assert (cmd >= commands && cmd < commands + COMMAND_CNT);
353
354   return ((cmd > commands
355            && conflicting_3char_prefixes (cmd[-1].name, cmd[0].name))
356           || (cmd < commands + COMMAND_CNT
357               && conflicting_3char_prefixes (cmd[0].name, cmd[1].name)));
358 }
359
360 /* Ways that a set of words can match a command name. */
361 enum command_match
362   {
363     MISMATCH,           /* Not a match. */
364     PARTIAL_MATCH,      /* The words begin the command name. */
365     COMPLETE_MATCH      /* The words are the command name. */
366   };
367
368 /* Figures out how well the WORD_CNT words in WORDS match CMD,
369    and returns the appropriate enum value.  If WORDS are a
370    partial match for CMD and the next word in CMD is a dash, then
371    *DASH_POSSIBLE is set to 1 if DASH_POSSIBLE is non-null;
372    otherwise, *DASH_POSSIBLE is unchanged. */
373 static enum command_match
374 cmd_match_words (const struct command *cmd,
375                  char *const words[], size_t word_cnt,
376                  int *dash_possible)
377 {
378   const char *word;
379   size_t word_len;
380   size_t word_idx;
381
382   for (word = find_word (cmd->name, &word_len), word_idx = 0;
383        word != NULL && word_idx < word_cnt;
384        word = find_word (word + word_len, &word_len), word_idx++)
385     if (word_len != strlen (words[word_idx])
386         || buf_compare_case (word, words[word_idx], word_len))
387       {
388         size_t match_chars = match_strings (word, word_len,
389                                             words[word_idx],
390                                             strlen (words[word_idx]));
391         if (match_chars == 0) 
392           {
393             /* Mismatch. */
394             return MISMATCH;
395           }
396         else if (match_chars == 1 || match_chars == 2) 
397           {
398             /* One- and two-character abbreviations are not
399                acceptable. */
400             return MISMATCH; 
401           }
402         else if (match_chars == 3) 
403           {
404             /* Three-character abbreviations are acceptable
405                in the first word of a command if there are
406                no name conflicts.  They are always
407                acceptable after the first word. */
408             if (word_idx == 0 && conflicting_3char_prefix_command (cmd))
409               return MISMATCH;
410           }
411         else /* match_chars > 3 */ 
412           {
413             /* Four-character and longer abbreviations are
414                always acceptable.  */
415           }
416       }
417
418   if (word == NULL && word_idx == word_cnt) 
419     {
420       /* cmd->name = "FOO BAR", words[] = {"FOO", "BAR"}. */
421       return COMPLETE_MATCH;
422     }
423   else if (word == NULL) 
424     {
425       /* cmd->name = "FOO BAR", words[] = {"FOO", "BAR", "BAZ"}. */
426       return MISMATCH; 
427     }
428   else 
429     {
430       /* cmd->name = "FOO BAR BAZ", words[] = {"FOO", "BAR"}. */
431       if (word[0] == '-' && dash_possible != NULL)
432         *dash_possible = 1;
433       return PARTIAL_MATCH; 
434     }
435 }
436
437 /* Returns the number of commands for which the WORD_CNT words in
438    WORDS are a partial or complete match.  If some partial match
439    has a dash as the next word, then *DASH_POSSIBLE is set to 1,
440    otherwise it is set to 0. */
441 static int
442 count_matching_commands (char *const words[], size_t word_cnt,
443                          int *dash_possible) 
444 {
445   const struct command *cmd;
446   int cmd_match_count;
447
448   cmd_match_count = 0;
449   *dash_possible = 0;
450   for (cmd = commands; cmd < commands + COMMAND_CNT; cmd++) 
451     if (cmd_match_words (cmd, words, word_cnt, dash_possible) != MISMATCH) 
452       cmd_match_count++; 
453
454   return cmd_match_count;
455 }
456
457 /* Returns the command for which the WORD_CNT words in WORDS are
458    a complete match.  Returns a null pointer if no such command
459    exists. */
460 static const struct command *
461 get_complete_match (char *const words[], size_t word_cnt) 
462 {
463   const struct command *cmd;
464   
465   for (cmd = commands; cmd < commands + COMMAND_CNT; cmd++) 
466     if (cmd_match_words (cmd, words, word_cnt, NULL) == COMPLETE_MATCH) 
467       return cmd; 
468   
469   return NULL;
470 }
471
472 /* Frees the WORD_CNT words in WORDS. */
473 static void
474 free_words (char *words[], size_t word_cnt) 
475 {
476   size_t idx;
477   
478   for (idx = 0; idx < word_cnt; idx++)
479     free (words[idx]);
480 }
481
482 /* Flags an error that the command whose name is given by the
483    WORD_CNT words in WORDS is unknown. */
484 static void
485 unknown_command_error (char *const words[], size_t word_cnt) 
486 {
487   size_t idx;
488   size_t words_len;
489   char *name, *cp;
490
491   words_len = 0;
492   for (idx = 0; idx < word_cnt; idx++)
493     words_len += strlen (words[idx]);
494
495   cp = name = xmalloc (words_len + word_cnt + 16);
496   for (idx = 0; idx < word_cnt; idx++) 
497     {
498       if (idx != 0)
499         *cp++ = ' ';
500       cp = stpcpy (cp, words[idx]);
501     }
502   *cp = '\0';
503
504   msg (SE, _("Unknown command %s."), name);
505
506   free (name);
507 }
508
509
510 /* Parse the command name and return a pointer to the corresponding
511    struct command if successful.
512    If not successful, return a null pointer. */
513 static const struct command *
514 parse_command_name (void)
515 {
516   char *words[16];
517   int word_cnt;
518   int complete_word_cnt;
519   int dash_possible;
520
521   dash_possible = 0;
522   word_cnt = complete_word_cnt = 0;
523   while (token == T_ID || (dash_possible && token == '-')) 
524     {
525       int cmd_match_cnt;
526       
527       assert (word_cnt < sizeof words / sizeof *words);
528       if (token == T_ID)
529         words[word_cnt] = xstrdup (ds_c_str (&tokstr));
530       else
531         words[word_cnt] = xstrdup ("-");
532       str_uppercase (words[word_cnt]);
533       word_cnt++;
534
535       cmd_match_cnt = count_matching_commands (words, word_cnt,
536                                                &dash_possible);
537       if (cmd_match_cnt == 0) 
538         break;
539       else if (cmd_match_cnt == 1) 
540         {
541           const struct command *command = get_complete_match (words, word_cnt);
542           if (command != NULL) 
543             {
544               if (command->skip_entire_name)
545                 lex_get ();
546               if ( command->debug & !get_testing_mode () ) 
547                 goto error;
548               free_words (words, word_cnt);
549               return command;
550             }
551         }
552       else /* cmd_match_cnt > 1 */
553         {
554           /* Do we have a complete command name so far? */
555           if (get_complete_match (words, word_cnt) != NULL)
556             complete_word_cnt = word_cnt;
557         }
558       lex_get ();
559     }
560
561   /* If we saw a complete command name earlier, drop back to
562      it. */
563   if (complete_word_cnt) 
564     {
565       int pushback_word_cnt;
566       const struct command *command;
567
568       /* Get the command. */
569       command = get_complete_match (words, complete_word_cnt);
570       assert (command != NULL);
571
572       /* Figure out how many words we want to keep.
573          We normally want to swallow the entire command. */
574       pushback_word_cnt = complete_word_cnt + 1;
575       if (!command->skip_entire_name)
576         pushback_word_cnt--;
577       
578       /* FIXME: We only support one-token pushback. */
579       assert (pushback_word_cnt + 1 >= word_cnt);
580
581       while (word_cnt > pushback_word_cnt) 
582         {
583           word_cnt--;
584           if (strcmp (words[word_cnt], "-")) 
585             lex_put_back_id (words[word_cnt]);
586           else
587             lex_put_back ('-');
588           free (words[word_cnt]);
589         }
590
591       if ( command->debug && !get_testing_mode () ) 
592         goto error;
593
594       free_words (words, word_cnt);
595       return command;
596     }
597
598 error:
599   unknown_command_error (words, word_cnt);
600   free_words (words, word_cnt);
601   return NULL;
602 }
603 \f
604 /* Simple commands. */
605
606 /* Parse and execute FINISH command. */
607 int
608 cmd_finish (void)
609 {
610   return CMD_EOF;
611 }
612
613 /* Parses the N command. */
614 int
615 cmd_n_of_cases (void)
616 {
617   /* Value for N. */
618   int x;
619
620   if (!lex_force_int ())
621     return CMD_FAILURE;
622   x = lex_integer ();
623   lex_get ();
624   if (!lex_match_id ("ESTIMATED"))
625     dict_set_case_limit (default_dict, x);
626
627   return lex_end_of_command ();
628 }
629
630 /* Parses, performs the EXECUTE procedure. */
631 int
632 cmd_execute (void)
633 {
634   if (!procedure (NULL, NULL))
635     return CMD_CASCADING_FAILURE;
636   return lex_end_of_command ();
637 }
638
639 /* Parses, performs the ERASE command. */
640 int
641 cmd_erase (void)
642 {
643   if (get_safer_mode ()) 
644     { 
645       msg (SE, _("This command not allowed when the SAFER option is set.")); 
646       return CMD_FAILURE; 
647     } 
648   
649   if (!lex_force_match_id ("FILE"))
650     return CMD_FAILURE;
651   lex_match ('=');
652   if (!lex_force_string ())
653     return CMD_FAILURE;
654
655   if (remove (ds_c_str (&tokstr)) == -1)
656     {
657       msg (SW, _("Error removing `%s': %s."),
658            ds_c_str (&tokstr), strerror (errno));
659       return CMD_FAILURE;
660     }
661
662   return CMD_SUCCESS;
663 }
664
665 #ifdef unix
666 /* Spawn a shell process. */
667 static int
668 shell (void)
669 {
670   int pid;
671   
672   pid = fork ();
673   switch (pid)
674     {
675     case 0:
676       {
677         const char *shell_fn;
678         char *shell_process;
679         
680         {
681           int i;
682           
683           for (i = 3; i < 20; i++)
684             close (i);
685         }
686
687         shell_fn = getenv ("SHELL");
688         if (shell_fn == NULL)
689           shell_fn = "/bin/sh";
690         
691         {
692           const char *cp = strrchr (shell_fn, '/');
693           cp = cp ? &cp[1] : shell_fn;
694           shell_process = local_alloc (strlen (cp) + 8);
695           strcpy (shell_process, "-");
696           strcat (shell_process, cp);
697           if (strcmp (cp, "sh"))
698             shell_process[0] = '+';
699         }
700         
701         execl (shell_fn, shell_process, NULL);
702
703         _exit (1);
704       }
705
706     case -1:
707       msg (SE, _("Couldn't fork: %s."), strerror (errno));
708       return 0;
709
710     default:
711       assert (pid > 0);
712       while (wait (NULL) != pid)
713         ;
714       return 1;
715     }
716 }
717 #endif /* unix */
718
719 /* Parses the HOST command argument and executes the specified
720    command.  Returns a suitable command return code. */
721 static int
722 run_command (void)
723 {
724   const char *cmd;
725   int string;
726
727   /* Handle either a string argument or a full-line argument. */
728   {
729     int c = lex_look_ahead ();
730
731     if (c == '\'' || c == '"')
732       {
733         lex_get ();
734         if (!lex_force_string ())
735           return CMD_FAILURE;
736         cmd = ds_c_str (&tokstr);
737         string = 1;
738       }
739     else
740       {
741         cmd = lex_rest_of_line (NULL);
742         lex_discard_line ();
743         string = 0;
744       }
745   }
746
747   /* Execute the command. */
748   if (system (cmd) == -1)
749     msg (SE, _("Error executing command: %s."), strerror (errno));
750
751   /* Finish parsing. */
752   if (string)
753     {
754       lex_get ();
755
756       if (token != '.')
757         {
758           lex_error (_("expecting end of command"));
759           return CMD_TRAILING_GARBAGE;
760         }
761     }
762   else
763     token = '.';
764
765   return CMD_SUCCESS;
766 }
767
768 /* Parses, performs the HOST command. */
769 int
770 cmd_host (void)
771 {
772   int code;
773
774   if (get_safer_mode ()) 
775     { 
776       msg (SE, _("This command not allowed when the SAFER option is set.")); 
777       return CMD_FAILURE; 
778     } 
779
780 #ifdef unix
781   /* Figure out whether to invoke an interactive shell or to execute a
782      single shell command. */
783   if (lex_look_ahead () == '.')
784     {
785       lex_get ();
786       code = shell () ? CMD_PART_SUCCESS_MAYBE : CMD_SUCCESS;
787     }
788   else
789     code = run_command ();
790 #else /* !unix */
791   /* Make sure that the system has a command interpreter, then run a
792      command. */
793   if (system (NULL) != 0)
794     code = run_command ();
795   else
796     {
797       msg (SE, _("No operating system support for this command."));
798       code = CMD_FAILURE;
799     }
800 #endif /* !unix */
801
802   return code;
803 }
804
805 /* Parses, performs the NEW FILE command. */
806 int
807 cmd_new_file (void)
808 {
809   discard_variables ();
810
811   return lex_end_of_command ();
812 }
813
814 /* Parses, performs the CLEAR TRANSFORMATIONS command. */
815 int
816 cmd_clear_transformations (void)
817 {
818   cancel_transformations ();
819   /* FIXME: what about variables created by transformations?
820      They need to be properly initialized. */
821
822   return CMD_SUCCESS;
823 }