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