Merge branch 'vendor/BYACC'
[dragonfly.git] / usr.bin / xlint / lint1 / scan.l
1 %{
2 /*      $NetBSD: scan.l,v 1.8 1995/10/23 13:38:51 jpo Exp $     */
3
4 /*
5  * Copyright (c) 1994, 1995 Jochen Pohl
6  * All Rights Reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by Jochen Pohl for
19  *      The NetBSD Project.
20  * 4. The name of the author may not be used to endorse or promote products
21  *    derived from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  *
34  * $NetBSD: scan.l,v 1.8 1995/10/23 13:38:51 jpo Exp $
35  * $DragonFly: src/usr.bin/xlint/lint1/scan.l,v 1.9 2008/06/21 20:05:04 swildner Exp $
36  */
37
38 #include <stdlib.h>
39 #include <string.h>
40 #include <limits.h>
41 #include <float.h>
42 #include <ctype.h>
43 #include <errno.h>
44 #include <err.h>
45 #include <math.h>
46
47 #include "lint1.h"
48 #include "y.tab.h"
49
50 #define CHAR_MASK       (~(~0 << CHAR_BIT))
51
52 /* Current position (its also updated when an included file is parsed) */
53 pos_t   curr_pos = { 1, "" };
54
55 /*
56  * Current position in C source (not updated when an included file is
57  * parsed).
58  */
59 pos_t   csrc_pos = { 1, "" };
60
61 static  void    incline(void);
62 static  void    badchar(int);
63 static  sbuf_t  *allocsb(void);
64 static  void    freesb(sbuf_t *);
65 static  int     inpc(void);
66 static  int     hash(const char *);
67 static  sym_t   *search(sbuf_t *);
68 static  int     name(void);
69 static  int     keyw(sym_t *);
70 static  int     icon(int);
71 static  int     fcon(void);
72 static  int     operator(int, op_t);
73 static  int     ccon(void);
74 static  int     wccon(void);
75 static  int     getescc(int);
76 static  void    directive(void);
77 static  void    comment(void);
78 static  int     string(void);
79 static  int     wcstrg(void);
80
81 %}
82
83 L       [_A-Za-z]
84 D       [0-9]
85 NZD     [1-9]
86 OD      [0-7]
87 HD      [0-9A-Fa-f]
88 EX      ([eE][+-]?[0-9]+)
89
90 %%
91
92 {L}({L}|{D})*                   return (name());
93 0{OD}*[lLuU]*                   return (icon(8));
94 {NZD}{D}*[lLuU]*                return (icon(10));
95 0[xX]{HD}+[lLuU]*               return (icon(16));
96 {D}+\.{D}*{EX}?[fFlL]?          |
97 {D}+{EX}[fFlL]?                 |
98 \.{D}+{EX}?[fFlL]?              return (fcon());
99 "="                             return (operator(T_ASSIGN, ASSIGN));
100 "*="                            return (operator(T_OPASS, MULASS));
101 "/="                            return (operator(T_OPASS, DIVASS));
102 "%="                            return (operator(T_OPASS, MODASS));
103 "+="                            return (operator(T_OPASS, ADDASS));
104 "-="                            return (operator(T_OPASS, SUBASS));
105 "<<="                           return (operator(T_OPASS, SHLASS));
106 ">>="                           return (operator(T_OPASS, SHRASS));
107 "&="                            return (operator(T_OPASS, ANDASS));
108 "^="                            return (operator(T_OPASS, XORASS));
109 "|="                            return (operator(T_OPASS, ORASS));
110 "||"                            return (operator(T_LOGOR, LOGOR));
111 "&&"                            return (operator(T_LOGAND, LOGAND));
112 "|"                             return (operator(T_OR, OR));
113 "&"                             return (operator(T_AND, AND));
114 "^"                             return (operator(T_XOR, XOR));
115 "=="                            return (operator(T_EQOP, EQ));
116 "!="                            return (operator(T_EQOP, NE));
117 "<"                             return (operator(T_RELOP, LT));
118 ">"                             return (operator(T_RELOP, GT));
119 "<="                            return (operator(T_RELOP, LE));
120 ">="                            return (operator(T_RELOP, GE));
121 "<<"                            return (operator(T_SHFTOP, SHL));
122 ">>"                            return (operator(T_SHFTOP, SHR));
123 "++"                            return (operator(T_INCDEC, INC));
124 "--"                            return (operator(T_INCDEC, DEC));
125 "->"                            return (operator(T_STROP, ARROW));
126 "."                             return (operator(T_STROP, POINT));
127 "+"                             return (operator(T_ADDOP, PLUS));
128 "-"                             return (operator(T_ADDOP, MINUS));
129 "*"                             return (operator(T_MULT, MULT));
130 "/"                             return (operator(T_DIVOP, DIV));
131 "%"                             return (operator(T_DIVOP, MOD));
132 "!"                             return (operator(T_UNOP, NOT));
133 "~"                             return (operator(T_UNOP, COMPL));
134 "\""                            return (string());
135 "L\""                           return (wcstrg());
136 ";"                             return (T_SEMI);
137 "{"                             return (T_LBRACE);
138 "}"                             return (T_RBRACE);
139 ","                             return (T_COMMA);
140 ":"                             return (T_COLON);
141 "?"                             return (T_QUEST);
142 "["                             return (T_LBRACK);
143 "]"                             return (T_RBRACK);
144 "("                             return (T_LPARN);
145 ")"                             return (T_RPARN);
146 "..."                           return (T_ELLIPSE);
147 "'"                             return (ccon());
148 "L'"                            return (wccon());
149 ^#.*$                           directive();
150 \n                              incline();
151 \t|" "|\f|\v                    ;
152 "/*"                            comment();
153 .                               badchar(yytext[0]);
154
155 %%
156
157 static void
158 incline(void)
159 {
160         curr_pos.p_line++;
161         if (curr_pos.p_file == csrc_pos.p_file)
162                 csrc_pos.p_line++;
163 }
164
165 static void
166 badchar(int c)
167 {
168         /* unknown character \%o */
169         error(250, c);
170 }
171
172 /*
173  * Keywords.
174  * During initialisation they are written to the symbol table.
175  */
176 static  struct  kwtab {
177         const   char *kw_name;  /* keyword */
178         int     kw_token;       /* token returned by yylex() */
179         scl_t   kw_scl;         /* storage class if kw_token T_SCLASS */
180         tspec_t kw_tspec;       /* type spec. if kw_token T_TYPE or T_SOU */
181         tqual_t kw_tqual;       /* type qual. fi kw_token T_QUAL */
182         u_int   kw_stdc : 1;    /* STDC keyword */
183         u_int   kw_gcc : 1;     /* GCC keyword */
184 } kwtab[] = {
185         { "asm",        T_ASM,          0,      0,      0,        0, 1 },
186         { "__asm",      T_ASM,          0,      0,      0,        0, 0 },
187         { "__asm__",    T_ASM,          0,      0,      0,        0, 0 },
188         { "auto",       T_SCLASS,       AUTO,   0,      0,        0, 0 },
189         { "break",      T_BREAK,        0,      0,      0,        0, 0 },
190         { "case",       T_CASE,         0,      0,      0,        0, 0 },
191         { "char",       T_TYPE,         0,      CHAR,   0,        0, 0 },
192         { "const",      T_QUAL,         0,      0,      CONST,    1, 0 },
193         { "__const__",  T_QUAL,         0,      0,      CONST,    0, 0 },
194         { "__const",    T_QUAL,         0,      0,      CONST,    0, 0 },
195         { "continue",   T_CONTINUE,     0,      0,      0,        0, 0 },
196         { "default",    T_DEFAULT,      0,      0,      0,        0, 0 },
197         { "do",         T_DO,           0,      0,      0,        0, 0 },
198         { "double",     T_TYPE,         0,      DOUBLE, 0,        0, 0 },
199         { "else",       T_ELSE,         0,      0,      0,        0, 0 },
200         { "enum",       T_ENUM,         0,      0,      0,        0, 0 },
201         { "extern",     T_SCLASS,       EXTERN, 0,      0,        0, 0 },
202         { "float",      T_TYPE,         0,      FLOAT,  0,        0, 0 },
203         { "for",        T_FOR,          0,      0,      0,        0, 0 },
204         { "goto",       T_GOTO,         0,      0,      0,        0, 0 },
205         { "if",         T_IF,           0,      0,      0,        0, 0 },
206         { "inline",     T_SCLASS,       INLINE, 0,      0,        0, 1 },
207         { "__inline__", T_SCLASS,       INLINE, 0,      0,        0, 0 },
208         { "__inline",   T_SCLASS,       INLINE, 0,      0,        0, 0 },
209         { "int",        T_TYPE,         0,      INT,    0,        0, 0 },
210         { "long",       T_TYPE,         0,      LONG,   0,        0, 0 },
211         { "register",   T_SCLASS,       REG,    0,      0,        0, 0 },
212         { "return",     T_RETURN,       0,      0,      0,        0, 0 },
213         { "short",      T_TYPE,         0,      SHORT,  0,        0, 0 },
214         { "signed",     T_TYPE,         0,      SIGNED, 0,        1, 0 },
215         { "__signed__", T_TYPE,         0,      SIGNED, 0,        0, 0 },
216         { "__signed",   T_TYPE,         0,      SIGNED, 0,        0, 0 },
217         { "sizeof",     T_SIZEOF,       0,      0,      0,        0, 0 },
218         { "static",     T_SCLASS,       STATIC, 0,      0,        0, 0 },
219         { "struct",     T_SOU,          0,      STRUCT, 0,        0, 0 },
220         { "switch",     T_SWITCH,       0,      0,      0,        0, 0 },
221         { "typedef",    T_SCLASS,       TYPEDEF, 0,     0,        0, 0 },
222         { "union",      T_SOU,          0,      UNION,  0,        0, 0 },
223         { "unsigned",   T_TYPE,         0,      UNSIGN, 0,        0, 0 },
224         { "void",       T_TYPE,         0,      VOID,   0,        0, 0 },
225         { "volatile",   T_QUAL,         0,      0,      VOLATILE, 1, 0 },
226         { "__volatile__", T_QUAL,       0,      0,      VOLATILE, 0, 0 },
227         { "__volatile", T_QUAL,         0,      0,      VOLATILE, 0, 0 },
228         { "while",      T_WHILE,        0,      0,      0,        0, 0 },
229         { NULL,         0,              0,      0,      0,        0, 0 }
230 };
231
232 /* Symbol table */
233 static  sym_t   *symtab[HSHSIZ1];
234
235 /* bit i of the entry with index i is set */
236 u_quad_t qbmasks[sizeof(u_quad_t) * CHAR_BIT];
237
238 /* least significant i bits are set in the entry with index i */
239 u_quad_t qlmasks[sizeof(u_quad_t) * CHAR_BIT + 1];
240
241 /* least significant i bits are not set in the entry with index i */
242 u_quad_t qumasks[sizeof(u_quad_t) * CHAR_BIT + 1];
243
244 /* free list for sbuf structures */
245 static  sbuf_t   *sbfrlst;
246
247 /* Typ of next expected symbol */
248 symt_t  symtyp;
249
250
251 /*
252  * All keywords are written to the symbol table. This saves us looking
253  * in a extra table for each name we found.
254  */
255 void
256 initscan(void)
257 {
258         struct  kwtab *kw;
259         sym_t   *sym;
260         int     h, i;
261         u_quad_t uq;
262
263         for (kw = kwtab; kw->kw_name != NULL; kw++) {
264                 if (kw->kw_stdc && tflag)
265                         continue;
266                 if (kw->kw_gcc && !gflag)
267                         continue;
268                 sym = getblk(sizeof (sym_t));
269                 sym->s_name = kw->kw_name;
270                 sym->s_keyw = 1;
271                 sym->s_value.v_quad = kw->kw_token;
272                 if (kw->kw_token == T_TYPE || kw->kw_token == T_SOU) {
273                         sym->s_tspec = kw->kw_tspec;
274                 } else if (kw->kw_token == T_SCLASS) {
275                         sym->s_scl = kw->kw_scl;
276                 } else if (kw->kw_token == T_QUAL) {
277                         sym->s_tqual = kw->kw_tqual;
278                 }
279                 h = hash(sym->s_name);
280                 if ((sym->s_link = symtab[h]) != NULL)
281                         symtab[h]->s_rlink = &sym->s_link;
282                 (symtab[h] = sym)->s_rlink = &symtab[h];
283         }
284
285         /* initialize bit-masks for quads */
286         for (i = 0; i < sizeof (u_quad_t) * CHAR_BIT; i++) {
287                 qbmasks[i] = (u_quad_t)1 << i;
288                 uq = ~(u_quad_t)0 << i;
289                 qumasks[i] = uq;
290                 qlmasks[i] = ~uq;
291         }
292         qumasks[i] = 0;
293         qlmasks[i] = ~(u_quad_t)0;
294 }
295
296 /*
297  * Get a free sbuf structure, if possible from the free list
298  */
299 static sbuf_t *
300 allocsb(void)
301 {
302         sbuf_t  *sb;
303
304         if ((sb = sbfrlst) != NULL) {
305                 sbfrlst = sb->sb_nxt;
306         } else {
307                 sb = xmalloc(sizeof (sbuf_t));
308         }
309         (void)memset(sb, 0, sizeof (*sb));
310         return (sb);
311 }
312
313 /*
314  * Put a sbuf structure to the free list
315  */
316 static void
317 freesb(sbuf_t *sb)
318 {
319         sb->sb_nxt = sbfrlst;
320         sbfrlst = sb;
321 }
322
323 /*
324  * Read a character and ensure that it is positive (except EOF).
325  * Increment line count(s) if necessary.
326  */
327 static int
328 inpc(void)
329 {
330         int     c;
331
332         if ((c = input()) != EOF && (c &= CHAR_MASK) == '\n')
333                 incline();
334         return (c);
335 }
336
337 static int
338 hash(const char *s)
339 {
340         u_int   v;
341         const   u_char *us;
342
343         v = 0;
344         for (us = (const u_char *)s; *us != '\0'; us++) {
345                 v = (v << sizeof (v)) + *us;
346                 v ^= v >> (sizeof (v) * CHAR_BIT - sizeof (v));
347         }
348         return (v % HSHSIZ1);
349 }
350
351 /*
352  * Lex has found a letter followed by zero or more letters or digits.
353  * It looks for a symbol in the symbol table with the same name. This
354  * symbol must either be a keyword or a symbol of the type required by
355  * symtyp (label, member, tag, ...).
356  *
357  * If it is a keyword, the token is returned. In some cases it is described
358  * more deeply by data written to yylval.
359  *
360  * If it is a symbol, T_NAME is returned and the pointer to a sbuf struct
361  * is stored in yylval. This struct contains the name of the symbol, it's
362  * length and hash value. If there is already a symbol of the same name
363  * and type in the symbol table, the sbuf struct also contains a pointer
364  * to the symbol table entry.
365  */
366 static int
367 name(void)
368 {
369         char    *s;
370         sbuf_t  *sb;
371         sym_t   *sym;
372         int     tok;
373
374         sb = allocsb();
375         sb->sb_name = yytext;
376         sb->sb_len = yyleng;
377         sb->sb_hash = hash(yytext);
378
379         if ((sym = search(sb)) != NULL && sym->s_keyw) {
380                 freesb(sb);
381                 return (keyw(sym));
382         }
383
384         sb->sb_sym = sym;
385
386         if (sym != NULL) {
387                 if (blklev < sym->s_blklev)
388                         lerror("name() 1");
389                 sb->sb_name = sym->s_name;
390                 sb->sb_len = strlen(sym->s_name);
391                 tok = sym->s_scl == TYPEDEF ? T_TYPENAME : T_NAME;
392         } else {
393                 s = getblk(yyleng + 1);
394                 (void)memcpy(s, yytext, yyleng + 1);
395                 sb->sb_name = s;
396                 sb->sb_len = yyleng;
397                 tok = T_NAME;
398         }
399
400         yylval.y_sb = sb;
401         return (tok);
402 }
403
404 static sym_t *
405 search(sbuf_t *sb)
406 {
407         sym_t   *sym;
408
409         for (sym = symtab[sb->sb_hash]; sym != NULL; sym = sym->s_link) {
410                 if (strcmp(sym->s_name, sb->sb_name) == 0) {
411                         if (sym->s_keyw || sym->s_kind == symtyp)
412                                 return (sym);
413                 }
414         }
415
416         return (NULL);
417 }
418
419 static int
420 keyw(sym_t *sym)
421 {
422         int     t;
423
424         if ((t = (int)sym->s_value.v_quad) == T_SCLASS) {
425                 yylval.y_scl = sym->s_scl;
426         } else if (t == T_TYPE || t == T_SOU) {
427                 yylval.y_tspec = sym->s_tspec;
428         } else if (t == T_QUAL) {
429                 yylval.y_tqual = sym->s_tqual;
430         }
431         return (t);
432 }
433
434 /*
435  * Convert a string representing an integer into internal representation.
436  * The value is returned in yylval. icon() (and yylex()) returns T_CON.
437  */
438 static int
439 icon(int base)
440 {
441         int     l_suffix, u_suffix;
442         int     len;
443         const   char *cp;
444         char    c, *eptr;
445         tspec_t typ;
446         u_long  ul;
447         u_quad_t uq;
448         int     ansiu;
449         static  tspec_t contypes[2][3] = {
450                 { INT,  LONG,  QUAD },
451                 { UINT, ULONG, UQUAD }
452         };
453
454         cp = yytext;
455         len = yyleng;
456
457         /* skip 0x */
458         if (base == 16) {
459                 cp += 2;
460                 len -= 2;
461         }
462
463         /* read suffixes */
464         l_suffix = u_suffix = 0;
465         for ( ; ; ) {
466                 if ((c = cp[len - 1]) == 'l' || c == 'L') {
467                         l_suffix++;
468                 } else if (c == 'u' || c == 'U') {
469                         u_suffix++;
470                 } else {
471                         break;
472                 }
473                 len--;
474         }
475         if (l_suffix > 2 || u_suffix > 1) {
476                 /* malformed integer constant */
477                 warning(251);
478                 if (l_suffix > 2)
479                         l_suffix = 2;
480                 if (u_suffix > 1)
481                         u_suffix = 1;
482         }
483         if (tflag && u_suffix != 0) {
484                 /* suffix U is illegal in traditional C */
485                 warning(97);
486         }
487         typ = contypes[u_suffix][l_suffix];
488
489         errno = 0;
490         if (l_suffix < 2) {
491                 ul = strtoul(cp, &eptr, base);
492         } else {
493                 uq = strtouq(cp, &eptr, base);
494         }
495         if (eptr != cp + len)
496                 lerror("icon() 1");
497         if (errno != 0)
498                 /* integer constant out of range */
499                 warning(252);
500
501         /*
502          * If the value is to big for the current type, we must choose
503          * another type.
504          */
505         ansiu = 0;
506         switch (typ) {
507         case INT:
508                 if (ul <= INT_MAX) {
509                         /* ok */
510                 } else if (ul <= (unsigned)UINT_MAX && base != 10) {
511                         typ = UINT;
512                 } else if (ul <= LONG_MAX) {
513                         typ = LONG;
514                 } else {
515                         typ = ULONG;
516                 }
517                 if (typ == UINT || typ == ULONG) {
518                         if (tflag) {
519                                 typ = LONG;
520                         } else if (!sflag) {
521                                 /*
522                                  * Remember that the constant is unsigned
523                                  * only in ANSI C
524                                  */
525                                 ansiu = 1;
526                         }
527                 }
528                 break;
529         case UINT:
530                 if (ul > (u_int)UINT_MAX)
531                         typ = ULONG;
532                 break;
533         case LONG:
534                 if (ul > LONG_MAX && !tflag) {
535                         typ = ULONG;
536                         if (!sflag)
537                                 ansiu = 1;
538                 }
539                 break;
540         case QUAD:
541                 if (uq > QUAD_MAX && !tflag) {
542                         typ = UQUAD;
543                         if (!sflag)
544                                 ansiu = 1;
545                 }
546                 break;
547                 /* LINTED (enumeration values not handled in switch) */
548         default:
549                 break;
550         }
551
552         if (typ != QUAD && typ != UQUAD) {
553                 if (isutyp(typ)) {
554                         uq = ul;
555                 } else {
556                         uq = (quad_t)(long)ul;
557                 }
558         }
559
560         uq = (u_quad_t)xsign((quad_t)uq, typ, -1);
561
562         (yylval.y_val = xcalloc(1, sizeof (val_t)))->v_tspec = typ;
563         yylval.y_val->v_ansiu = ansiu;
564         yylval.y_val->v_quad = (quad_t)uq;
565
566         return (T_CON);
567 }
568
569 /*
570  * Returns 1 if t is a signed type and the value is negative.
571  *
572  * len is the number of significant bits. If len is -1, len is set
573  * to the width of type t.
574  */
575 int
576 sign(quad_t q, tspec_t t, int len)
577 {
578         if (t == PTR || isutyp(t))
579                 return (0);
580         return (msb(q, t, len));
581 }
582
583 int
584 msb(quad_t q, tspec_t t, int len)
585 {
586         if (len <= 0)
587                 len = size(t);
588         return ((q & qbmasks[len - 1]) != 0);
589 }
590
591 /*
592  * Extends the sign of q.
593  */
594 quad_t
595 xsign(quad_t q, tspec_t t, int len)
596 {
597         if (len <= 0)
598                 len = size(t);
599
600         if (t == PTR || isutyp(t) || !sign(q, t, len)) {
601                 q &= qlmasks[len];
602         } else {
603                 q |= qumasks[len];
604         }
605         return (q);
606 }
607
608 /*
609  * Convert a string representing a floating point value into its interal
610  * representation. Type and value are returned in yylval. fcon()
611  * (and yylex()) returns T_CON.
612  * XXX Currently it is not possible to convert constants of type
613  * long double which are greater then DBL_MAX.
614  */
615 static int
616 fcon(void)
617 {
618         const   char *cp;
619         int     len;
620         tspec_t typ;
621         char    c, *eptr;
622         double  d;
623         float   f;
624
625         cp = yytext;
626         len = yyleng;
627
628         if ((c = cp[len - 1]) == 'f' || c == 'F') {
629                 typ = FLOAT;
630                 len--;
631         } else if (c == 'l' || c == 'L') {
632                 typ = LDOUBLE;
633                 len--;
634         } else {
635                 typ = DOUBLE;
636         }
637
638         if (tflag && typ != DOUBLE) {
639                 /* suffixes F and L are illegal in traditional C */
640                 warning(98);
641         }
642
643         errno = 0;
644         d = strtod(cp, &eptr);
645         if (eptr != cp + len)
646                 lerror("fcon() 1");
647         if (errno != 0)
648                 /* floating-point constant out of range */
649                 warning(248);
650
651         if (typ == FLOAT) {
652                 f = (float)d;
653                 if (isinf(f)) {
654                         /* floating-point constant out of range */
655                         warning(248);
656                         f = f > 0 ? FLT_MAX : -FLT_MAX;
657                 }
658         }
659
660         (yylval.y_val = xcalloc(1, sizeof (val_t)))->v_tspec = typ;
661         if (typ == FLOAT) {
662                 yylval.y_val->v_ldbl = f;
663         } else {
664                 yylval.y_val->v_ldbl = d;
665         }
666
667         return (T_CON);
668 }
669
670 static int
671 operator(int t, op_t o)
672 {
673         yylval.y_op = o;
674         return (t);
675 }
676
677 /*
678  * Called if lex found a leading \'.
679  */
680 static int
681 ccon(void)
682 {
683         int     n, val, c;
684         char    cv;
685
686         n = 0;
687         val = 0;
688         while ((c = getescc('\'')) >= 0) {
689                 val = (val << CHAR_BIT) + c;
690                 n++;
691         }
692         if (c == -2) {
693                 /* unterminated character constant */
694                 error(253);
695         } else {
696                 if (n > sizeof (int) || (n > 1 && (pflag || hflag))) {
697                         /* too many characters in character constant */
698                         error(71);
699                 } else if (n > 1) {
700                         /* multi-character character constant */
701                         warning(294);
702                 } else if (n == 0) {
703                         /* empty character constant */
704                         error(73);
705                 }
706         }
707         if (n == 1) {
708                 cv = (char)val;
709                 val = cv;
710         }
711
712         yylval.y_val = xcalloc(1, sizeof (val_t));
713         yylval.y_val->v_tspec = INT;
714         yylval.y_val->v_quad = val;
715
716         return (T_CON);
717 }
718
719 /*
720  * Called if lex found a leading L\'
721  */
722 static int
723 wccon(void)
724 {
725         static  char buf[MB_LEN_MAX + 1];
726         int     i, c;
727         wchar_t wc;
728
729         i = 0;
730         while ((c = getescc('\'')) >= 0) {
731                 if (i < MB_CUR_MAX)
732                         buf[i] = (char)c;
733                 i++;
734         }
735
736         wc = 0;
737
738         if (c == -2) {
739                 /* unterminated character constant */
740                 error(253);
741         } else if (c == 0) {
742                 /* empty character constant */
743                 error(73);
744         } else {
745                 if (i > MB_CUR_MAX) {
746                         i = MB_CUR_MAX;
747                         /* too many characters in character constant */
748                         error(71);
749                 } else {
750                         buf[i] = '\0';
751                         (void)mbtowc(NULL, NULL, 0);
752                         if (mbtowc(&wc, buf, MB_CUR_MAX) < 0)
753                                 /* invalid multibyte character */
754                                 error(291);
755                 }
756         }
757
758         yylval.y_val = xcalloc(1, sizeof (val_t));
759         yylval.y_val->v_tspec = WCHAR;
760         yylval.y_val->v_quad = wc;
761
762         return (T_CON);
763 }
764
765 /*
766  * Read a character which is part of a character constant or of a string
767  * and handle escapes.
768  *
769  * The Argument is the character which delimits the character constant or
770  * string.
771  *
772  * Returns -1 if the end of the character constant or string is reached,
773  * -2 if the EOF is reached, and the charachter otherwise.
774  */
775 static int
776 getescc(int d)
777 {
778         static  int pbc = -1;
779         int     n, c, v;
780
781         if (pbc == -1) {
782                 c = inpc();
783         } else {
784                 c = pbc;
785                 pbc = -1;
786         }
787         if (c == d)
788                 return (-1);
789         switch (c) {
790         case '\n':
791                 /* newline in string or char constant */
792                 error(254);
793                 return (-2);
794         case EOF:
795                 return (-2);
796         case '\\':
797                 switch (c = inpc()) {
798                 case '"':
799                         if (tflag && d == '\'')
800                                 /* \" inside character constant undef. ... */
801                                 warning(262);
802                         return ('"');
803                 case '\'':
804                         return ('\'');
805                 case '?':
806                         if (tflag)
807                                 /* \? undefined in traditional C */
808                                 warning(263);
809                         return ('?');
810                 case '\\':
811                         return ('\\');
812                 case 'a':
813                         if (tflag)
814                                 /* \a undefined in traditional C */
815                                 warning(81);
816                         return ('\a');
817                 case 'b':
818                         return ('\b');
819                 case 'f':
820                         return ('\f');
821                 case 'n':
822                         return ('\n');
823                 case 'r':
824                         return ('\r');
825                 case 't':
826                         return ('\t');
827                 case 'v':
828                         if (tflag)
829                                 /* \v undefined in traditional C */
830                                 warning(264);
831                         return ('\v');
832                 case '8': case '9':
833                         /* bad octal digit %c */
834                         warning(77, c);
835                         /* FALLTHROUGH */
836                 case '0': case '1': case '2': case '3':
837                 case '4': case '5': case '6': case '7':
838                         n = 3;
839                         v = 0;
840                         do {
841                                 v = (v << 3) + (c - '0');
842                                 c = inpc();
843                         } while (--n && isdigit(c) && (tflag || c <= '7'));
844                         if (tflag && n > 0 && isdigit(c))
845                                 /* bad octal digit %c */
846                                 warning(77, c);
847                         pbc = c;
848                         if (v > UCHAR_MAX) {
849                                 /* character escape does not fit in char. */
850                                 warning(76);
851                                 v &= CHAR_MASK;
852                         }
853                         return (v);
854                 case 'x':
855                         if (tflag)
856                                 /* \x undefined in traditional C */
857                                 warning(82);
858                         v = 0;
859                         n = 0;
860                         while ((c = inpc()) >= 0 && isxdigit(c)) {
861                                 c = isdigit(c) ?
862                                         c - '0' : toupper(c) - 'A' + 10;
863                                 v = (v << 4) + c;
864                                 if (n >= 0) {
865                                         if ((v & ~CHAR_MASK) != 0) {
866                                                 /* overflow in hex escape */
867                                                 warning(75);
868                                                 n = -1;
869                                         } else {
870                                                 n++;
871                                         }
872                                 }
873                         }
874                         pbc = c;
875                         if (n == 0) {
876                                 /* no hex digits follow \x */
877                                 error(74);
878                         } if (n == -1) {
879                                 v &= CHAR_MASK;
880                         }
881                         return (v);
882                 case '\n':
883                         return (getescc(d));
884                 case EOF:
885                         return (-2);
886                 default:
887                         if (isprint(c)) {
888                                 /* dubious escape \%c */
889                                 warning(79, c);
890                         } else {
891                                 /* dubious escape \%o */
892                                 warning(80, c);
893                         }
894                 }
895         }
896         return (c);
897 }
898
899 /*
900  * Called for preprocessor directives. Currently implemented are:
901  *      # lineno
902  *      # lineno "filename"
903  */
904 static void
905 directive(void)
906 {
907         const   char *cp, *fn;
908         char    c, *eptr;
909         size_t  fnl;
910         long    ln;
911         static  int first = 1;
912
913         /* Go to first non-whitespace after # */
914         for (cp = yytext + 1; (c = *cp) == ' ' || c == '\t'; cp++) ;
915
916         if (!isdigit(c)) {
917         error:
918                 /* undefined or invalid # directive */
919                 warning(255);
920                 return;
921         }
922         ln = strtol(--cp, &eptr, 10);
923         if (cp == eptr)
924                 goto error;
925         if ((c = *(cp = eptr)) != ' ' && c != '\t' && c != '\0')
926                 goto error;
927         while ((c = *cp++) == ' ' || c == '\t') ;
928         if (c != '\0') {
929                 if (c != '"')
930                         goto error;
931                 fn = cp;
932                 while ((c = *cp) != '"' && c != '\0')
933                         cp++;
934                 if (c != '"')
935                         goto error;
936                 if ((fnl = cp++ - fn) > PATH_MAX)
937                         goto error;
938                 while ((c = *cp++) == ' ' || c == '\t') ;
939 #if 0
940                 if (c != '\0')
941                         warning("extra character(s) after directive");
942 #endif
943                 curr_pos.p_file = fnnalloc(fn, fnl);
944                 /*
945                  * If this is the first directive, the name is the name
946                  * of the C source file as specified at the command line.
947                  * It is written to the output file.
948                  */
949                 if (first) {
950                         csrc_pos.p_file = curr_pos.p_file;
951                         outsrc(curr_pos.p_file);
952                         first = 0;
953                 }
954         }
955         curr_pos.p_line = (int)ln - 1;
956         if (curr_pos.p_file == csrc_pos.p_file)
957                 csrc_pos.p_line = (int)ln - 1;
958 }
959
960 /*
961  * Handle lint comments. Following comments are currently understood:
962  *      ARGSUSEDn
963  *      CONSTCOND CONSTANTCOND CONSTANTCONDITION
964  *      FALLTHRU FALLTHROUGH
965  *      LINTLIBRARY
966  *      LINTED NOSTRICT
967  *      LONGLONG
968  *      NOTREACHED
969  *      PRINTFLIKEn
970  *      PROTOLIB
971  *      SCANFLIKEn
972  *      VARARGSn
973  * If one of this comments is recognized, the arguments, if any, are
974  * parsed and a function which handles this comment is called.
975  */
976 static void
977 comment(void)
978 {
979         int     c, lc;
980         static struct {
981                 const   char *keywd;
982                 int     arg;
983                 void    (*func)(int);
984         } keywtab[] = {
985                 { "ARGSUSED",           1,      argsused        },
986                 { "CONSTCOND",          0,      constcond       },
987                 { "CONSTANTCOND",       0,      constcond       },
988                 { "CONSTANTCONDITION",  0,      constcond       },
989                 { "FALLTHRU",           0,      fallthru        },
990                 { "FALLTHROUGH",        0,      fallthru        },
991                 { "LINTLIBRARY",        0,      lintlib         },
992                 { "LINTED",             0,      linted          },
993                 { "LONGLONG",           0,      longlong        },
994                 { "NOSTRICT",           0,      linted          },
995                 { "NOTREACHED",         0,      notreach        },
996                 { "PRINTFLIKE",         1,      printflike      },
997                 { "PROTOLIB",           1,      protolib        },
998                 { "SCANFLIKE",          1,      scanflike       },
999                 { "VARARGS",            1,      varargs         },
1000         };
1001         char    keywd[32];
1002         char    arg[32];
1003         int     l, i, a;
1004         int     eoc;
1005
1006         eoc = 0;
1007
1008         /* Skip white spaces after the start of the comment */
1009         while ((c = inpc()) != EOF && isspace(c)) ;
1010
1011         /* Read the potential keyword to keywd */
1012         l = 0;
1013         while (c != EOF && isupper(c) && l < sizeof (keywd) - 1) {
1014                 keywd[l++] = (char)c;
1015                 c = inpc();
1016         }
1017         keywd[l] = '\0';
1018
1019         /* look for the keyword */
1020         for (i = 0; i < sizeof (keywtab) / sizeof (keywtab[0]); i++) {
1021                 if (strcmp(keywtab[i].keywd, keywd) == 0)
1022                         break;
1023         }
1024         if (i == sizeof (keywtab) / sizeof (keywtab[0]))
1025                 goto skip_rest;
1026
1027         /* skip white spaces after the keyword */
1028         while (c != EOF && isspace(c))
1029                 c = inpc();
1030
1031         /* read the argument, if the keyword accepts one and there is one */
1032         l = 0;
1033         if (keywtab[i].arg) {
1034                 while (c != EOF && isdigit(c) && l < sizeof (arg) - 1) {
1035                         arg[l++] = (char)c;
1036                         c = inpc();
1037                 }
1038         }
1039         arg[l] = '\0';
1040         a = l != 0 ? atoi(arg) : -1;
1041
1042         /* skip white spaces after the argument */
1043         while (c != EOF && isspace(c))
1044                 c = inpc();
1045
1046         if (c != '*' || (c = inpc()) != '/') {
1047                 if (keywtab[i].func != linted)
1048                         /* extra characters in lint comment */
1049                         warning(257);
1050         } else {
1051                 /*
1052                  * remember that we have already found the end of the
1053                  * comment
1054                  */
1055                 eoc = 1;
1056         }
1057
1058         if (keywtab[i].func != NULL)
1059                 (*keywtab[i].func)(a);
1060
1061  skip_rest:
1062         while (!eoc) {
1063                 lc = c;
1064                 if ((c = inpc()) == EOF) {
1065                         /* unterminated comment */
1066                         error(256);
1067                         break;
1068                 }
1069                 if (lc == '*' && c == '/')
1070                         eoc = 1;
1071         }
1072 }
1073
1074 /*
1075  * Clear flags for lint comments LINTED, LONGLONG and CONSTCOND.
1076  * clrwflgs() is called after function definitions and global and
1077  * local declarations and definitions. It is also called between
1078  * the controlling expression and the body of control statements
1079  * (if, switch, for, while).
1080  */
1081 void
1082 clrwflgs(void)
1083 {
1084         nowarn = 0;
1085         quadflg = 0;
1086         ccflg = 0;
1087 }
1088
1089 /*
1090  * Strings are stored in a dynamically alloceted buffer and passed
1091  * in yylval.y_xstrg to the parser. The parser or the routines called
1092  * by the parser are responsible for freeing this buffer.
1093  */
1094 static int
1095 string(void)
1096 {
1097         u_char  *s;
1098         int     c;
1099         size_t  len, max;
1100         strg_t  *strg;
1101
1102         s = xmalloc(max = 64);
1103
1104         len = 0;
1105         while ((c = getescc('"')) >= 0) {
1106                 /* +1 to reserve space for a trailing NUL character */
1107                 if (len + 1 == max)
1108                         s = xrealloc(s, max *= 2);
1109                 s[len++] = (char)c;
1110         }
1111         s[len] = '\0';
1112         if (c == -2)
1113                 /* unterminated string constant */
1114                 error(258);
1115
1116         strg = xcalloc(1, sizeof (strg_t));
1117         strg->st_tspec = CHAR;
1118         strg->st_len = len;
1119         strg->st_cp = s;
1120
1121         yylval.y_strg = strg;
1122         return (T_STRING);
1123 }
1124
1125 static int
1126 wcstrg(void)
1127 {
1128         char    *s;
1129         int     c, i, n, wi;
1130         size_t  len, max, wlen;
1131         wchar_t *ws;
1132         strg_t  *strg;
1133
1134         s = xmalloc(max = 64);
1135         len = 0;
1136         while ((c = getescc('"')) >= 0) {
1137                 /* +1 to save space for a trailing NUL character */
1138                 if (len + 1 >= max)
1139                         s = xrealloc(s, max *= 2);
1140                 s[len++] = (char)c;
1141         }
1142         s[len] = '\0';
1143         if (c == -2)
1144                 /* unterminated string constant */
1145                 error(258);
1146
1147         /* get length of wide character string */
1148         (void)mblen(NULL, 0);
1149         for (i = 0, wlen = 0; i < len; i += n, wlen++) {
1150                 if ((n = mblen(&s[i], MB_CUR_MAX)) == -1) {
1151                         /* invalid multibyte character */
1152                         error(291);
1153                         break;
1154                 }
1155                 if (n == 0)
1156                         n = 1;
1157         }
1158
1159         ws = xmalloc((wlen + 1) * sizeof (wchar_t));
1160
1161         /* convert from multibyte to wide char */
1162         (void)mbtowc(NULL, NULL, 0);
1163         for (i = 0, wi = 0; i < len; i += n, wi++) {
1164                 if ((n = mbtowc(&ws[wi], &s[i], MB_CUR_MAX)) == -1)
1165                         break;
1166                 if (n == 0)
1167                         n = 1;
1168         }
1169         ws[wi] = 0;
1170         free(s);
1171
1172         strg = xcalloc(1, sizeof (strg_t));
1173         strg->st_tspec = WCHAR;
1174         strg->st_len = wlen;
1175         strg->st_wcp = ws;
1176
1177         yylval.y_strg = strg;
1178         return (T_STRING);
1179 }
1180
1181 /*
1182  * As noted above the scanner does not create new symbol table entries
1183  * for symbols it cannot find in the symbol table. This is to avoid
1184  * putting undeclared symbols into the symbol table if a syntax error
1185  * occurs.
1186  *
1187  * getsym() is called as soon as it is probably ok to put the symbol to
1188  * the symbol table. This does not mean that it is not possible that
1189  * symbols are put to the symbol table which are than not completely
1190  * declared due to syntax errors. To avoid too many problems in this
1191  * case symbols get type int in getsym().
1192  *
1193  * XXX calls to getsym() should be delayed until decl1*() is called
1194  */
1195 sym_t *
1196 getsym(sbuf_t *sb)
1197 {
1198         dinfo_t *di;
1199         char    *s;
1200         sym_t   *sym;
1201
1202         sym = sb->sb_sym;
1203
1204         /*
1205          * During member declaration it is possible that name() looked
1206          * for symbols of type FVFT, although it should have looked for
1207          * symbols of type FTAG. Same can happen for labels. Both cases
1208          * are compensated here.
1209          */
1210         if (symtyp == FMOS || symtyp == FLAB) {
1211                 if (sym == NULL || sym->s_kind == FVFT)
1212                         sym = search(sb);
1213         }
1214
1215         if (sym != NULL) {
1216                 if (sym->s_kind != symtyp)
1217                         lerror("storesym() 1");
1218                 symtyp = FVFT;
1219                 freesb(sb);
1220                 return (sym);
1221         }
1222
1223         /* create a new symbol table entry */
1224
1225         /* labels must always be allocated at level 1 (outhermost block) */
1226         if (symtyp == FLAB) {
1227                 sym = getlblk(1, sizeof (sym_t));
1228                 s = getlblk(1, sb->sb_len + 1);
1229                 (void)memcpy(s, sb->sb_name, sb->sb_len + 1);
1230                 sym->s_name = s;
1231                 sym->s_blklev = 1;
1232                 di = dcs;
1233                 while (di->d_nxt != NULL && di->d_nxt->d_nxt != NULL)
1234                         di = di->d_nxt;
1235                 if (di->d_ctx != AUTO)
1236                         lerror("storesym() 2");
1237         } else {
1238                 sym = getblk(sizeof (sym_t));
1239                 sym->s_name = sb->sb_name;
1240                 sym->s_blklev = blklev;
1241                 di = dcs;
1242         }
1243
1244         STRUCT_ASSIGN(sym->s_dpos, curr_pos);
1245         if ((sym->s_kind = symtyp) != FLAB)
1246                 sym->s_type = gettyp(INT);
1247
1248         symtyp = FVFT;
1249
1250         if ((sym->s_link = symtab[sb->sb_hash]) != NULL)
1251                 symtab[sb->sb_hash]->s_rlink = &sym->s_link;
1252         (symtab[sb->sb_hash] = sym)->s_rlink = &symtab[sb->sb_hash];
1253
1254         *di->d_ldlsym = sym;
1255         di->d_ldlsym = &sym->s_dlnxt;
1256
1257         freesb(sb);
1258         return (sym);
1259 }
1260
1261 /*
1262  * Remove a symbol forever from the symbol table. s_blklev
1263  * is set to -1 to avoid that the symbol will later be put
1264  * back to the symbol table.
1265  */
1266 void
1267 rmsym(sym_t *sym)
1268 {
1269         if ((*sym->s_rlink = sym->s_link) != NULL)
1270                 sym->s_link->s_rlink = sym->s_rlink;
1271         sym->s_blklev = -1;
1272         sym->s_link = NULL;
1273 }
1274
1275 /*
1276  * Remove a list of symbols declared at one level from the symbol
1277  * table.
1278  */
1279 void
1280 rmsyms(sym_t *syms)
1281 {
1282         sym_t   *sym;
1283
1284         for (sym = syms; sym != NULL; sym = sym->s_dlnxt) {
1285                 if (sym->s_blklev != -1) {
1286                         if ((*sym->s_rlink = sym->s_link) != NULL)
1287                                 sym->s_link->s_rlink = sym->s_rlink;
1288                         sym->s_link = NULL;
1289                         sym->s_rlink = NULL;
1290                 }
1291         }
1292 }
1293
1294 /*
1295  * Put a symbol into the symbol table
1296  */
1297 void
1298 inssym(int bl, sym_t *sym)
1299 {
1300         int     h;
1301
1302         h = hash(sym->s_name);
1303         if ((sym->s_link = symtab[h]) != NULL)
1304                 symtab[h]->s_rlink = &sym->s_link;
1305         (symtab[h] = sym)->s_rlink = &symtab[h];
1306         sym->s_blklev = bl;
1307         if (sym->s_link != NULL && sym->s_blklev < sym->s_link->s_blklev)
1308                 lerror("inssym()");
1309 }
1310
1311 /*
1312  * Called at level 0 after syntax errors
1313  * Removes all symbols which are not declared at level 0 from the
1314  * symbol table. Also frees all memory which is not associated with
1315  * level 0.
1316  */
1317 void
1318 cleanup(void)
1319 {
1320         sym_t   *sym, *nsym;
1321         int     i;
1322
1323         for (i = 0; i < HSHSIZ1; i++) {
1324                 for (sym = symtab[i]; sym != NULL; sym = nsym) {
1325                         nsym = sym->s_link;
1326                         if (sym->s_blklev >= 1) {
1327                                 if ((*sym->s_rlink = nsym) != NULL)
1328                                         nsym->s_rlink = sym->s_rlink;
1329                         }
1330                 }
1331         }
1332
1333         for (i = mblklev; i > 0; i--)
1334                 freelblk(i);
1335 }
1336
1337 /*
1338  * Create a new symbol with the name of an existing symbol.
1339  */
1340 sym_t *
1341 pushdown(sym_t *sym)
1342 {
1343         int     h;
1344         sym_t   *nsym;
1345
1346         h = hash(sym->s_name);
1347         nsym = getblk(sizeof (sym_t));
1348         if (sym->s_blklev > blklev)
1349                 lerror("pushdown()");
1350         nsym->s_name = sym->s_name;
1351         STRUCT_ASSIGN(nsym->s_dpos, curr_pos);
1352         nsym->s_kind = sym->s_kind;
1353         nsym->s_blklev = blklev;
1354
1355         if ((nsym->s_link = symtab[h]) != NULL)
1356                 symtab[h]->s_rlink = &nsym->s_link;
1357         (symtab[h] = nsym)->s_rlink = &symtab[h];
1358
1359         *dcs->d_ldlsym = nsym;
1360         dcs->d_ldlsym = &nsym->s_dlnxt;
1361
1362         return (nsym);
1363 }
1364
1365 /*
1366  * Free any dynamically allocated memory referenced by
1367  * the value stack or yylval.
1368  * The type of information in yylval is described by tok.
1369  */
1370 void
1371 freeyyv(void *sp, int tok)
1372 {
1373         if (tok == T_NAME || tok == T_TYPENAME) {
1374                 sbuf_t *sb = *(sbuf_t **)sp;
1375                 freesb(sb);
1376         } else if (tok == T_CON) {
1377                 val_t *val = *(val_t **)sp;
1378                 free(val);
1379         } else if (tok == T_STRING) {
1380                 strg_t *strg = *(strg_t **)sp;
1381                 if (strg->st_tspec == CHAR) {
1382                         free(strg->st_cp);
1383                 } else if (strg->st_tspec == WCHAR) {
1384                         free(strg->st_wcp);
1385                 } else {
1386                         lerror("fryylv() 1");
1387                 }
1388                 free(strg);
1389         }
1390 }