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