Implemented long variable names a la spss V12.
[pspp-builds.git] / src / lexer.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., 59 Temple Place - Suite 330, Boston, MA
18    02111-1307, USA. */
19
20 #include <config.h>
21 #include "lexer.h"
22 #include "error.h"
23 #include <ctype.h>
24 #include <errno.h>
25 #include <limits.h>
26 #include <math.h>
27 #include <stdarg.h>
28 #include <stdlib.h>
29 #include "alloc.h"
30 #include "command.h"
31 #include "error.h"
32 #include "getline.h"
33 #include "magic.h"
34 #include "settings.h"
35 #include "str.h"
36
37 /*
38 #define DUMP_TOKENS 1
39 */
40
41 \f
42 /* Global variables. */
43
44 /* Current token. */
45 int token;
46
47 /* T_POS_NUM, T_NEG_NUM: the token's value. */
48 double tokval;
49
50 /* T_ID: the identifier. */
51 char tokid[LONG_NAME_LEN + 1];
52
53 /* T_ID, T_STRING: token string value.
54    For T_ID, this is not truncated to SHORT_NAME_LEN characters as is tokid. */
55 struct string tokstr;
56 \f
57 /* Static variables. */
58
59 /* Table of keywords. */
60 static const char *keywords[T_N_KEYWORDS + 1] = 
61   {
62     "AND", "OR", "NOT",
63     "EQ", "GE", "GT", "LE", "LT", "NE",
64     "ALL", "BY", "TO", "WITH",
65     NULL,
66   };
67
68 /* Pointer to next token in getl_buf. */
69 static char *prog;
70
71 /* Nonzero only if this line ends with a terminal dot. */
72 static int dot;
73
74 /* Nonzero only if the last token returned was T_STOP. */
75 static int eof;
76
77 /* If nonzero, next token returned by lex_get().
78    Used only in exceptional circumstances. */
79 static int put_token;
80 static struct string put_tokstr;
81 static double put_tokval;
82
83 static void unexpected_eof (void);
84 static void convert_numeric_string_to_char_string (int type);
85 static int parse_string (int type);
86
87 #if DUMP_TOKENS
88 static void dump_token (void);
89 #endif
90 \f
91 /* Initialization. */
92
93 /* Initializes the lexer. */
94 void
95 lex_init (void)
96 {
97   ds_init (&put_tokstr, 64);
98   if (!lex_get_line ())
99     unexpected_eof ();
100 }
101
102 void
103 lex_done (void)
104 {
105   ds_destroy(&put_tokstr);
106 }
107
108 \f
109 /* Common functions. */
110
111 /* Copies put_token, put_tokstr, put_tokval into token, tokstr,
112    tokval, respectively, and sets tokid appropriately. */
113 static void
114 restore_token (void) 
115 {
116   assert (put_token != 0);
117   token = put_token;
118   ds_replace (&tokstr, ds_c_str (&put_tokstr));
119   strncpy (tokid, ds_c_str (&put_tokstr), SHORT_NAME_LEN);
120   tokid[SHORT_NAME_LEN] = 0;
121   tokval = put_tokval;
122   put_token = 0;
123 }
124
125 /* Copies token, tokstr, tokval into put_token, put_tokstr,
126    put_tokval respectively. */
127 static void
128 save_token (void) 
129 {
130   put_token = token;
131   ds_replace (&put_tokstr, ds_c_str (&tokstr));
132   put_tokval = tokval;
133 }
134
135 /* Parses a single token, setting appropriate global variables to
136    indicate the token's attributes. */
137 void
138 lex_get (void)
139 {
140   int i;
141
142   /* If a token was pushed ahead, return it. */
143   if (put_token)
144     {
145       restore_token ();
146 #if DUMP_TOKENS
147       dump_token ();
148 #endif
149       return;
150     }
151
152   /* Find a token. */
153   for (;;)
154     {
155       char *cp;
156
157       /* Skip whitespace. */
158       if (eof)
159         unexpected_eof ();
160
161       for (;;)
162         {
163           while (isspace ((unsigned char) *prog))
164             prog++;
165           if (*prog)
166             break;
167
168           if (dot)
169             {
170               dot = 0;
171               token = '.';
172 #if DUMP_TOKENS
173               dump_token ();
174 #endif
175               return;
176             }
177           else if (!lex_get_line ())
178             {
179               eof = 1;
180               token = T_STOP;
181 #if DUMP_TOKENS
182               dump_token ();
183 #endif
184               return;
185             }
186
187           if (put_token)
188             {
189               restore_token ();
190 #if DUMP_TOKENS
191               dump_token ();
192 #endif
193               return;
194             }
195         }
196
197
198       /* Actually parse the token. */
199       cp = prog;
200       ds_clear (&tokstr);
201       
202       switch (*prog)
203         {
204         case '-': case '.':
205         case '0': case '1': case '2': case '3': case '4':
206         case '5': case '6': case '7': case '8': case '9':
207           {
208             char *tail;
209
210             /* `-' can introduce a negative number, or it can be a
211                token by itself.  If it is not followed by a digit or a
212                decimal point, it is definitely not a number.
213                Otherwise, it might be either, but most of the time we
214                want it as a number.  When the syntax calls for a `-'
215                token, lex_negative_to_dash() must be used to break
216                negative numbers into two tokens. */
217             if (*cp == '-')
218               {
219                 ds_putc (&tokstr, *prog++);
220                 while (isspace ((unsigned char) *prog))
221                   prog++;
222
223                 if (!isdigit ((unsigned char) *prog) && *prog != '.')
224                   {
225                     token = '-';
226                     break;
227                   }
228                 token = T_NEG_NUM;
229               }
230             else 
231               token = T_POS_NUM;
232                 
233             /* Parse the number, copying it into tokstr. */
234             while (isdigit ((unsigned char) *prog))
235               ds_putc (&tokstr, *prog++);
236             if (*prog == '.')
237               {
238                 ds_putc (&tokstr, *prog++);
239                 while (isdigit ((unsigned char) *prog))
240                   ds_putc (&tokstr, *prog++);
241               }
242             if (*prog == 'e' || *prog == 'E')
243               {
244                 ds_putc (&tokstr, *prog++);
245                 if (*prog == '+' || *prog == '-')
246                   ds_putc (&tokstr, *prog++);
247                 while (isdigit ((unsigned char) *prog))
248                   ds_putc (&tokstr, *prog++);
249               }
250
251             /* Parse as floating point. */
252             tokval = strtod (ds_c_str (&tokstr), &tail);
253             if (*tail)
254               {
255                 msg (SE, _("%s does not form a valid number."),
256                      ds_c_str (&tokstr));
257                 tokval = 0.0;
258
259                 ds_clear (&tokstr);
260                 ds_putc (&tokstr, '0');
261               }
262
263             break;
264           }
265
266         case '\'': case '"':
267           token = parse_string (0);
268           break;
269
270         case '(': case ')': case ',': case '=': case '+': case '/':
271           token = *prog++;
272           break;
273
274         case '*':
275           if (*++prog == '*')
276             {
277               prog++;
278               token = T_EXP;
279             }
280           else
281             token = '*';
282           break;
283
284         case '<':
285           if (*++prog == '=')
286             {
287               prog++;
288               token = T_LE;
289             }
290           else if (*prog == '>')
291             {
292               prog++;
293               token = T_NE;
294             }
295           else
296             token = T_LT;
297           break;
298
299         case '>':
300           if (*++prog == '=')
301             {
302               prog++;
303               token = T_GE;
304             }
305           else
306             token = T_GT;
307           break;
308
309         case '~':
310           if (*++prog == '=')
311             {
312               prog++;
313               token = T_NE;
314             }
315           else
316             token = T_NOT;
317           break;
318
319         case '&':
320           prog++;
321           token = T_AND;
322           break;
323
324         case '|':
325           prog++;
326           token = T_OR;
327           break;
328
329         case 'a': case 'b': case 'c': case 'd': case 'e':
330         case 'f': case 'g': case 'h': case 'i': case 'j':
331         case 'k': case 'l': case 'm': case 'n': case 'o':
332         case 'p': case 'q': case 'r': case 's': case 't':
333         case 'u': case 'v': case 'w': case 'x': case 'y':
334         case 'z':
335         case 'A': case 'B': case 'C': case 'D': case 'E':
336         case 'F': case 'G': case 'H': case 'I': case 'J':
337         case 'K': case 'L': case 'M': case 'N': case 'O':
338         case 'P': case 'Q': case 'R': case 'S': case 'T':
339         case 'U': case 'V': case 'W': case 'X': case 'Y':
340         case 'Z':
341         case '#': case '$': case '@': 
342           /* Strings can be specified in binary, octal, or hex using
343                this special syntax. */
344           if (prog[1] == '\'' || prog[1] == '"')
345             {
346               static const char special[3] = "box";
347               const char *p;
348
349               p = strchr (special, tolower ((unsigned char) *prog));
350               if (p)
351                 {
352                   prog++;
353                   token = parse_string (p - special + 1);
354                   break;
355                 }
356             }
357
358           /* Copy id to tokstr. */
359           ds_putc (&tokstr, *prog++);
360           while (CHAR_IS_IDN (*prog))
361             ds_putc (&tokstr, *prog++);
362
363           /* Copy tokstr to tokid, truncating it to LONG_NAME_LEN characters.*/
364           strncpy (tokid, ds_c_str (&tokstr), LONG_NAME_LEN);
365           tokid[LONG_NAME_LEN] = 0;
366
367           /* Convert to upper case */
368           for ( i = 0 ; i < ds_length(&tokstr) ; ++i ) 
369                   tokstr.string[i] = toupper(tokstr.string[i]);
370
371           token = lex_id_to_token (ds_c_str (&tokstr), ds_length (&tokstr));
372           break;
373
374         default:
375           if (isgraph ((unsigned char) *prog))
376             msg (SE, _("Bad character in input: `%c'."), *prog++);
377           else
378             msg (SE, _("Bad character in input: `\\%o'."), *prog++);
379           continue;
380         }
381
382       break;
383     }
384
385 #if DUMP_TOKENS
386   dump_token ();
387 #endif
388 }
389
390 /* Prints a syntax error message containing the current token and
391    given message MESSAGE (if non-null). */
392 void
393 lex_error (const char *message, ...)
394 {
395   char *token_rep;
396
397   token_rep = lex_token_representation ();
398   if (token_rep[0] == 0)
399     msg (SE, _("Syntax error at end of file."));
400   else if (message)
401     {
402       char buf[1024];
403       va_list args;
404       
405       va_start (args, message);
406       vsnprintf (buf, 1024, message, args);
407       va_end (args);
408
409       msg (SE, _("Syntax error %s at `%s'."), buf, token_rep);
410     }
411   else
412     msg (SE, _("Syntax error at `%s'."), token_rep);
413   
414   free (token_rep);
415 }
416
417 /* Checks that we're at end of command.
418    If so, returns a successful command completion code.
419    If not, flags a syntax error and returns an error command
420    completion code. */
421 int
422 lex_end_of_command (void)
423 {
424   if (token != '.')
425     {
426       lex_error (_("expecting end of command"));
427       return CMD_TRAILING_GARBAGE;
428     }
429   else
430     return CMD_SUCCESS;
431 }
432 \f
433 /* Token testing functions. */
434
435 /* Returns true if the current token is a number. */
436 bool
437 lex_is_number (void) 
438 {
439   return token == T_POS_NUM || token == T_NEG_NUM;
440 }
441
442 /* Returns the value of the current token, which must be a
443    floating point number. */
444 double
445 lex_number (void)
446 {
447   assert (lex_is_number ());
448   return tokval;
449 }
450
451 /* Returns true iff the current token is an integer. */
452 bool
453 lex_is_integer (void)
454 {
455   return (lex_is_number ()
456           && tokval != NOT_LONG
457           && tokval >= LONG_MIN
458           && tokval <= LONG_MAX
459           && floor (tokval) == tokval);
460 }
461
462 /* Returns the value of the current token, which must be an
463    integer. */
464 long
465 lex_integer (void)
466 {
467   assert (lex_is_integer ());
468   return tokval;
469 }
470 \f  
471 /* Token matching functions. */
472
473 /* If TOK is the current token, skips it and returns nonzero.
474    Otherwise, returns zero. */
475 int
476 lex_match (int t)
477 {
478   if (token == t)
479     {
480       lex_get ();
481       return 1;
482     }
483   else
484     return 0;
485 }
486
487 /* If the current token is the identifier S, skips it and returns
488    nonzero.
489    Otherwise, returns zero. */
490 int
491 lex_match_id (const char *s)
492 {
493   if (token == T_ID && lex_id_match (s, tokid))
494     {
495       lex_get ();
496       return 1;
497     }
498   else
499     return 0;
500 }
501
502 /* If the current token is integer N, skips it and returns nonzero.
503    Otherwise, returns zero. */
504 int
505 lex_match_int (int x)
506 {
507   if (lex_is_integer () && lex_integer () == x)
508     {
509       lex_get ();
510       return 1;
511     }
512   else
513     return 0;
514 }
515 \f
516 /* Forced matches. */
517
518 /* If this token is identifier S, fetches the next token and returns
519    nonzero.
520    Otherwise, reports an error and returns zero. */
521 int
522 lex_force_match_id (const char *s)
523 {
524   if (token == T_ID && lex_id_match (s, tokid))
525     {
526       lex_get ();
527       return 1;
528     }
529   else
530     {
531       lex_error (_("expecting `%s'"), s);
532       return 0;
533     }
534 }
535
536 /* If the current token is T, skips the token.  Otherwise, reports an
537    error and returns from the current function with return value 0. */
538 int
539 lex_force_match (int t)
540 {
541   if (token == t)
542     {
543       lex_get ();
544       return 1;
545     }
546   else
547     {
548       lex_error (_("expecting %s"), lex_token_name (t));
549       return 0;
550     }
551 }
552
553 /* If this token is a string, does nothing and returns nonzero.
554    Otherwise, reports an error and returns zero. */
555 int
556 lex_force_string (void)
557 {
558   if (token == T_STRING)
559     return 1;
560   else
561     {
562       lex_error (_("expecting string"));
563       return 0;
564     }
565 }
566
567 /* If this token is an integer, does nothing and returns nonzero.
568    Otherwise, reports an error and returns zero. */
569 int
570 lex_force_int (void)
571 {
572   if (lex_is_integer ())
573     return 1;
574   else
575     {
576       lex_error (_("expecting integer"));
577       return 0;
578     }
579 }
580         
581 /* If this token is a number, does nothing and returns nonzero.
582    Otherwise, reports an error and returns zero. */
583 int
584 lex_force_num (void)
585 {
586   if (lex_is_number ())
587     return 1;
588   else
589     {
590       lex_error (_("expecting number"));
591       return 0;
592     }
593 }
594         
595 /* If this token is an identifier, does nothing and returns nonzero.
596    Otherwise, reports an error and returns zero. */
597 int
598 lex_force_id (void)
599 {
600   if (token == T_ID)
601     return 1;
602   else
603     {
604       lex_error (_("expecting identifier"));
605       return 0;
606     }
607 }
608 \f
609 /* Comparing identifiers. */
610
611 /* Keywords match if one of the following is true: KW and TOK are
612    identical (barring differences in case), or TOK is at least 3
613    characters long and those characters are identical to KW.  KW_LEN
614    is the length of KW, TOK_LEN is the length of TOK. */
615 int
616 lex_id_match_len (const char *kw, size_t kw_len,
617                   const char *tok, size_t tok_len)
618 {
619   size_t i = 0;
620
621   assert (kw && tok);
622   for (;;)
623     {
624       if (i == kw_len && i == tok_len)
625         return 1;
626       else if (i == tok_len)
627         return i >= 3;
628       else if (i == kw_len)
629         return 0;
630       else if (toupper ((unsigned char) kw[i])
631                != toupper ((unsigned char) tok[i]))
632         return 0;
633
634       i++;
635     }
636 }
637
638 /* Same as lex_id_match_len() minus the need to pass in the lengths. */
639 int
640 lex_id_match (const char *kw, const char *tok)
641 {
642   return lex_id_match_len (kw, strlen (kw), tok, strlen (tok));
643 }
644
645 /* Returns the proper token type, either T_ID or a reserved keyword
646    enum, for ID[], which must contain LEN characters. */
647 int
648 lex_id_to_token (const char *id, size_t len)
649 {
650   const char **kwp;
651
652   if (len < 2 || len > 4)
653     return T_ID;
654   
655   for (kwp = keywords; *kwp; kwp++)
656     if (!strcasecmp (*kwp, id))
657       return T_FIRST_KEYWORD + (kwp - keywords);
658
659   return T_ID;
660 }
661 \f
662 /* Weird token functions. */
663
664 /* Returns the first character of the next token, except that if the
665    next token is not an identifier, the character returned will not be
666    a character that can begin an identifier.  Specifically, the
667    hexstring lead-in X' causes lookahead() to return '.  Note that an
668    alphanumeric return value doesn't guarantee an ID token, it could
669    also be a reserved-word token. */
670 int
671 lex_look_ahead (void)
672 {
673   if (put_token)
674     return put_token;
675
676   for (;;)
677     {
678       if (eof)
679         unexpected_eof ();
680
681       for (;;)
682         {
683           while (isspace ((unsigned char) *prog))
684             prog++;
685           if (*prog)
686             break;
687
688           if (dot)
689             return '.';
690           else if (!lex_get_line ())
691             unexpected_eof ();
692
693           if (put_token) 
694             return put_token;
695         }
696
697       if ((toupper ((unsigned char) *prog) == 'X'
698            || toupper ((unsigned char) *prog) == 'B')
699           && (prog[1] == '\'' || prog[1] == '"'))
700         return '\'';
701
702       return *prog;
703     }
704 }
705
706 /* Makes the current token become the next token to be read; the
707    current token is set to T. */
708 void
709 lex_put_back (int t)
710 {
711   save_token ();
712   token = t;
713 }
714
715 /* Makes the current token become the next token to be read; the
716    current token is set to the identifier ID. */
717 void
718 lex_put_back_id (const char *id)
719 {
720   save_token ();
721   token = T_ID;
722   ds_replace (&tokstr, id);
723   strncpy (tokid, ds_c_str (&tokstr), SHORT_NAME_LEN);
724   tokid[SHORT_NAME_LEN] = 0;
725 }
726 \f
727 /* Weird line processing functions. */
728
729 /* Returns the entire contents of the current line. */
730 const char *
731 lex_entire_line (void)
732 {
733   return ds_c_str (&getl_buf);
734 }
735
736 /* As lex_entire_line(), but only returns the part of the current line
737    that hasn't already been tokenized.
738    If END_DOT is non-null, stores nonzero into *END_DOT if the line
739    ends with a terminal dot, or zero if it doesn't. */
740 const char *
741 lex_rest_of_line (int *end_dot)
742 {
743   if (end_dot)
744     *end_dot = dot;
745   return prog;
746 }
747
748 /* Causes the rest of the current input line to be ignored for
749    tokenization purposes. */
750 void
751 lex_discard_line (void)
752 {
753   prog = ds_end (&getl_buf);
754   dot = put_token = 0;
755 }
756
757 /* Sets the current position in the current line to P, which must be
758    in getl_buf. */
759 void
760 lex_set_prog (char *p)
761 {
762   prog = p;
763 }
764 \f
765 /* Weird line reading functions. */
766
767 /* Read a line for use by the tokenizer. */
768 int
769 lex_get_line (void)
770 {
771   if (!getl_read_line ())
772     return 0;
773
774   lex_preprocess_line ();
775   return 1;
776 }
777
778 /* Preprocesses getl_buf by removing comments, stripping trailing
779    whitespace and the terminal dot, and removing leading indentors. */
780 void
781 lex_preprocess_line (void)
782 {
783   /* Strips comments. */
784   {
785     /* getl_buf iterator. */
786     char *cp;
787
788     /* Nonzero inside a comment. */
789     int comment;
790
791     /* Nonzero inside a quoted string. */
792     int quote;
793
794     /* Remove C-style comments begun by slash-star and terminated by
795      star-slash or newline. */
796     quote = comment = 0;
797     for (cp = ds_c_str (&getl_buf); *cp; )
798       {
799         /* If we're not commented out, toggle quoting. */
800         if (!comment)
801           {
802             if (*cp == quote)
803               quote = 0;
804             else if (*cp == '\'' || *cp == '"')
805               quote = *cp;
806           }
807       
808         /* If we're not quoting, toggle commenting. */
809         if (!quote)
810           {
811             if (cp[0] == '/' && cp[1] == '*')
812               {
813                 comment = 1;
814                 *cp++ = ' ';
815                 *cp++ = ' ';
816                 continue;
817               }
818             else if (cp[0] == '*' && cp[1] == '/' && comment)
819               {
820                 comment = 0;
821                 *cp++ = ' ';
822                 *cp++ = ' ';
823                 continue;
824               }
825           }
826       
827         /* Check commenting. */
828         if (!comment)
829           cp++;
830         else
831           *cp++ = ' ';
832       }
833   }
834   
835   /* Strip trailing whitespace and terminal dot. */
836   {
837     size_t len = ds_length (&getl_buf);
838     char *s = ds_c_str (&getl_buf);
839     
840     /* Strip trailing whitespace. */
841     while (len > 0 && isspace ((unsigned char) s[len - 1]))
842       len--;
843
844     /* Check for and remove terminal dot. */
845     if (len > 0 && s[len - 1] == get_endcmd() )
846       {
847         dot = 1;
848         len--;
849       }
850     else if (len == 0 && get_nullline() )
851       dot = 1;
852     else
853       dot = 0;
854
855     /* Set length. */
856     ds_truncate (&getl_buf, len);
857   }
858   
859   /* In batch mode, strip leading indentors and insert a terminal dot
860      as necessary. */
861   if (getl_interactive != 2 && getl_mode == GETL_MODE_BATCH)
862     {
863       char *s = ds_c_str (&getl_buf);
864       
865       if (s[0] == '+' || s[0] == '-' || s[0] == '.')
866         s[0] = ' ';
867       else if (s[0] && !isspace ((unsigned char) s[0]))
868         put_token = '.';
869     }
870
871   prog = ds_c_str (&getl_buf);
872 }
873 \f
874 /* Token names. */
875
876 /* Returns the name of a token in a static buffer. */
877 const char *
878 lex_token_name (int token)
879 {
880   if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
881     return keywords[token - T_FIRST_KEYWORD];
882
883   if (token < 256)
884     {
885       static char t[2];
886       t[0] = token;
887       return t;
888     }
889
890   return _("<ERROR>");
891 }
892
893 /* Returns an ASCII representation of the current token as a
894    malloc()'d string. */
895 char *
896 lex_token_representation (void)
897 {
898   char *token_rep;
899   
900   switch (token)
901     {
902     case T_ID:
903     case T_POS_NUM:
904     case T_NEG_NUM:
905       return xstrdup (ds_c_str (&tokstr));
906       break;
907
908     case T_STRING:
909       {
910         int hexstring = 0;
911         char *sp, *dp;
912
913         for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
914           if (!isprint ((unsigned char) *sp))
915             {
916               hexstring = 1;
917               break;
918             }
919               
920         token_rep = xmalloc (2 + ds_length (&tokstr) * 2 + 1 + 1);
921
922         dp = token_rep;
923         if (hexstring)
924           *dp++ = 'X';
925         *dp++ = '\'';
926
927         if (!hexstring)
928           for (sp = ds_c_str (&tokstr); *sp; )
929             {
930               if (*sp == '\'')
931                 *dp++ = '\'';
932               *dp++ = (unsigned char) *sp++;
933             }
934         else
935           for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
936             {
937               *dp++ = (((unsigned char) *sp) >> 4)["0123456789ABCDEF"];
938               *dp++ = (((unsigned char) *sp) & 15)["0123456789ABCDEF"];
939             }
940         *dp++ = '\'';
941         *dp = '\0';
942         
943         return token_rep;
944       }
945     break;
946
947     case T_STOP:
948       token_rep = xmalloc (1);
949       *token_rep = '\0';
950       return token_rep;
951
952     case T_EXP:
953       return xstrdup ("**");
954
955     default:
956       if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
957         return xstrdup (keywords [token - T_FIRST_KEYWORD]);
958       else
959         {
960           token_rep = xmalloc (2);
961           token_rep[0] = token;
962           token_rep[1] = '\0';
963           return token_rep;
964         }
965     }
966         
967   assert (0);
968 }
969 \f
970 /* Really weird functions. */
971
972 /* Most of the time, a `-' is a lead-in to a negative number.  But
973    sometimes it's actually part of the syntax.  If a dash can be part
974    of syntax then this function is called to rip it off of a
975    number. */
976 void
977 lex_negative_to_dash (void)
978 {
979   if (token == T_NEG_NUM)
980     {
981       token = T_POS_NUM;
982       tokval = -tokval;
983       ds_replace (&tokstr, ds_c_str (&tokstr) + 1);
984       save_token ();
985       token = '-';
986     }
987 }
988    
989 /* We're not at eof any more. */
990 void
991 lex_reset_eof (void)
992 {
993   eof = 0;
994 }
995
996 /* Skip a COMMENT command. */
997 void
998 lex_skip_comment (void)
999 {
1000   for (;;)
1001     {
1002       if (!lex_get_line ()) 
1003         {
1004           put_token = T_STOP;
1005           eof = 1;
1006           return;
1007         }
1008       
1009       if (put_token == '.')
1010         break;
1011
1012       prog = ds_end (&getl_buf);
1013       if (dot)
1014         break;
1015     }
1016 }
1017 \f
1018 /* Private functions. */
1019
1020 /* Unexpected end of file. */
1021 static void
1022 unexpected_eof (void)
1023 {
1024   msg (FE, _("Unexpected end of file."));
1025 }
1026
1027 /* When invoked, tokstr contains a string of binary, octal, or hex
1028    digits, for values of TYPE of 0, 1, or 2, respectively.  The string
1029    is converted to characters having the specified values. */
1030 static void
1031 convert_numeric_string_to_char_string (int type)
1032 {
1033   static const char *base_names[] = {N_("binary"), N_("octal"), N_("hex")};
1034   static const int bases[] = {2, 8, 16};
1035   static const int chars_per_byte[] = {8, 3, 2};
1036
1037   const char *const base_name = base_names[type];
1038   const int base = bases[type];
1039   const int cpb = chars_per_byte[type];
1040   const int nb = ds_length (&tokstr) / cpb;
1041   int i;
1042   char *p;
1043
1044   assert (type >= 0 && type <= 2);
1045
1046   if (ds_length (&tokstr) % cpb)
1047     msg (SE, _("String of %s digits has %d characters, which is not a "
1048                "multiple of %d."),
1049          gettext (base_name), ds_length (&tokstr), cpb);
1050
1051   p = ds_c_str (&tokstr);
1052   for (i = 0; i < nb; i++)
1053     {
1054       int value;
1055       int j;
1056           
1057       value = 0;
1058       for (j = 0; j < cpb; j++, p++)
1059         {
1060           int v;
1061
1062           if (*p >= '0' && *p <= '9')
1063             v = *p - '0';
1064           else
1065             {
1066               static const char alpha[] = "abcdef";
1067               const char *q = strchr (alpha, tolower ((unsigned char) *p));
1068
1069               if (q)
1070                 v = q - alpha + 10;
1071               else
1072                 v = base;
1073             }
1074
1075           if (v >= base)
1076             msg (SE, _("`%c' is not a valid %s digit."), *p, base_name);
1077
1078           value = value * base + v;
1079         }
1080
1081       ds_c_str (&tokstr)[i] = (unsigned char) value;
1082     }
1083
1084   ds_truncate (&tokstr, nb);
1085 }
1086
1087 /* Parses a string from the input buffer into tokstr.  The input
1088    buffer pointer prog must point to the initial single or double
1089    quote.  TYPE is 0 if it is an ordinary string, or 1, 2, or 3 for a
1090    binary, octal, or hexstring, respectively.  Returns token type. */
1091 static int 
1092 parse_string (int type)
1093 {
1094   /* Accumulate the entire string, joining sections indicated by +
1095      signs. */
1096   for (;;)
1097     {
1098       /* Single or double quote. */
1099       int c = *prog++;
1100       
1101       /* Accumulate section. */
1102       for (;;)
1103         {
1104           /* Check end of line. */
1105           if (*prog == 0)
1106             {
1107               msg (SE, _("Unterminated string constant."));
1108               goto finish;
1109             }
1110           
1111           /* Double quote characters to embed them in strings. */
1112           if (*prog == c)
1113             {
1114               if (prog[1] == c)
1115                 prog++;
1116               else
1117                 break;
1118             }
1119
1120           ds_putc (&tokstr, *prog++);
1121         }
1122       prog++;
1123
1124       /* Skip whitespace after final quote mark. */
1125       if (eof)
1126         break;
1127       for (;;)
1128         {
1129           while (isspace ((unsigned char) *prog))
1130             prog++;
1131           if (*prog)
1132             break;
1133
1134           if (dot)
1135             goto finish;
1136
1137           if (!lex_get_line ())
1138             unexpected_eof ();
1139         }
1140
1141       /* Skip plus sign. */
1142       if (*prog != '+')
1143         break;
1144       prog++;
1145
1146       /* Skip whitespace after plus sign. */
1147       if (eof)
1148         break;
1149       for (;;)
1150         {
1151           while (isspace ((unsigned char) *prog))
1152             prog++;
1153           if (*prog)
1154             break;
1155
1156           if (dot)
1157             goto finish;
1158
1159           if (!lex_get_line ())
1160             unexpected_eof ();
1161         }
1162
1163       /* Ensure that a valid string follows. */
1164       if (*prog != '\'' && *prog != '"')
1165         {
1166           msg (SE, "String expected following `+'.");
1167           goto finish;
1168         }
1169     }
1170
1171   /* We come here when we've finished concatenating all the string sections
1172      into one large string. */
1173 finish:
1174   if (type != 0)
1175     convert_numeric_string_to_char_string (type - 1);
1176
1177   if (ds_length (&tokstr) > 255)
1178     {
1179       msg (SE, _("String exceeds 255 characters in length (%d characters)."),
1180            ds_length (&tokstr));
1181       ds_truncate (&tokstr, 255);
1182     }
1183       
1184   {
1185     /* FIXME. */
1186     size_t i;
1187     int warned = 0;
1188
1189     for (i = 0; i < ds_length (&tokstr); i++)
1190       if (ds_c_str (&tokstr)[i] == 0)
1191         {
1192           if (!warned)
1193             {
1194               msg (SE, _("Sorry, literal strings may not contain null "
1195                          "characters.  Replacing with spaces."));
1196               warned = 1;
1197             }
1198           ds_c_str (&tokstr)[i] = ' ';
1199         }
1200   }
1201
1202   return T_STRING;
1203 }
1204 \f       
1205 #if DUMP_TOKENS
1206 /* Reads one token from the lexer and writes a textual representation
1207    on stdout for debugging purposes. */
1208 static void
1209 dump_token (void)
1210 {
1211   {
1212     const char *curfn;
1213     int curln;
1214
1215     getl_location (&curfn, &curln);
1216     if (curfn)
1217       fprintf (stderr, "%s:%d\t", curfn, curln);
1218   }
1219   
1220   switch (token)
1221     {
1222     case T_ID:
1223       fprintf (stderr, "ID\t%s\n", tokid);
1224       break;
1225
1226     case T_POS_NUM:
1227     case T_NEG_NUM:
1228       fprintf (stderr, "NUM\t%f\n", tokval);
1229       break;
1230
1231     case T_STRING:
1232       fprintf (stderr, "STRING\t\"%s\"\n", ds_c_str (&tokstr));
1233       break;
1234
1235     case T_STOP:
1236       fprintf (stderr, "STOP\n");
1237       break;
1238
1239     case T_EXP:
1240       fprintf (stderr, "MISC\tEXP\"");
1241       break;
1242
1243     case 0:
1244       fprintf (stderr, "MISC\tEOF\n");
1245       break;
1246
1247     default:
1248       if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
1249         fprintf (stderr, "KEYWORD\t%s\n", lex_token_name (token));
1250       else
1251         fprintf (stderr, "PUNCT\t%c\n", token);
1252       break;
1253     }
1254 }
1255 #endif /* DUMP_TOKENS */