Remove `expout*' globals from parser-defs.h
[platform/upstream/binutils.git] / gdb / ada-lex.l
1 /* FLEX lexer for Ada expressions, for GDB.
2    Copyright (C) 1994-2014 Free Software Foundation, Inc.
3
4    This file is part of GDB.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 /*----------------------------------------------------------------------*/
20
21 /* The converted version of this file is to be included in ada-exp.y, */
22 /* the Ada parser for gdb.  The function yylex obtains characters from */
23 /* the global pointer lexptr.  It returns a syntactic category for */
24 /* each successive token and places a semantic value into yylval */
25 /* (ada-lval), defined by the parser.   */
26
27 DIG     [0-9]
28 NUM10   ({DIG}({DIG}|_)*)
29 HEXDIG  [0-9a-f]
30 NUM16   ({HEXDIG}({HEXDIG}|_)*)
31 OCTDIG  [0-7]
32 LETTER  [a-z_]
33 ID      ({LETTER}({LETTER}|{DIG})*|"<"{LETTER}({LETTER}|{DIG})*">")
34 WHITE   [ \t\n]
35 TICK    ("'"{WHITE}*)
36 GRAPHIC [a-z0-9 #&'()*+,-./:;<>=_|!$%?@\[\]\\^`{}~]
37 OPER    ([-+*/=<>&]|"<="|">="|"**"|"/="|"and"|"or"|"xor"|"not"|"mod"|"rem"|"abs")
38
39 EXP     (e[+-]{NUM10})
40 POSEXP  (e"+"?{NUM10})
41
42 %{
43
44 #define NUMERAL_WIDTH 256
45 #define LONGEST_SIGN ((ULONGEST) 1 << (sizeof(LONGEST) * HOST_CHAR_BIT - 1))
46
47 /* Temporary staging for numeric literals.  */
48 static char numbuf[NUMERAL_WIDTH];
49  static void canonicalizeNumeral (char *s1, const char *);
50 static struct stoken processString (const char*, int);
51 static int processInt (struct parser_state *, const char *, const char *,
52                        const char *);
53 static int processReal (struct parser_state *, const char *);
54 static struct stoken processId (const char *, int);
55 static int processAttribute (const char *);
56 static int find_dot_all (const char *);
57 static void rewind_to_char (int);
58
59 #undef YY_DECL
60 #define YY_DECL static int yylex ( void )
61
62 /* Flex generates a static function "input" which is not used.
63    Defining YY_NO_INPUT comments it out.  */
64 #define YY_NO_INPUT
65
66 #undef YY_INPUT
67 #define YY_INPUT(BUF, RESULT, MAX_SIZE) \
68     if ( *lexptr == '\000' ) \
69       (RESULT) = YY_NULL; \
70     else \
71       { \
72         *(BUF) = *lexptr; \
73         (RESULT) = 1; \
74         lexptr += 1; \
75       }
76
77 static int find_dot_all (const char *);
78
79 %}
80
81 %option case-insensitive interactive nodefault
82
83 %s BEFORE_QUAL_QUOTE
84
85 %%
86
87 {WHITE}          { }
88
89 "--".*           { yyterminate(); }
90
91 {NUM10}{POSEXP}  {
92                    canonicalizeNumeral (numbuf, yytext);
93                    return processInt (pstate, NULL, numbuf,
94                                       strrchr (numbuf, 'e') + 1);
95                  }
96
97 {NUM10}          {
98                    canonicalizeNumeral (numbuf, yytext);
99                    return processInt (pstate, NULL, numbuf, NULL);
100                  }
101
102 {NUM10}"#"{HEXDIG}({HEXDIG}|_)*"#"{POSEXP} {
103                    canonicalizeNumeral (numbuf, yytext);
104                    return processInt (pstate, numbuf,
105                                       strchr (numbuf, '#') + 1,
106                                       strrchr(numbuf, '#') + 1);
107                  }
108
109 {NUM10}"#"{HEXDIG}({HEXDIG}|_)*"#" {
110                    canonicalizeNumeral (numbuf, yytext);
111                    return processInt (pstate, numbuf, strchr (numbuf, '#') + 1,
112                                       NULL);
113                  }
114
115 "0x"{HEXDIG}+   {
116                   canonicalizeNumeral (numbuf, yytext+2);
117                   return processInt (pstate, "16#", numbuf, NULL);
118                 }
119
120
121 {NUM10}"."{NUM10}{EXP} {
122                    canonicalizeNumeral (numbuf, yytext);
123                    return processReal (pstate, numbuf);
124                 }
125
126 {NUM10}"."{NUM10} {
127                    canonicalizeNumeral (numbuf, yytext);
128                    return processReal (pstate, numbuf);
129                 }
130
131 {NUM10}"#"{NUM16}"."{NUM16}"#"{EXP} {
132                    error (_("Based real literals not implemented yet."));
133                 }
134
135 {NUM10}"#"{NUM16}"."{NUM16}"#" {
136                    error (_("Based real literals not implemented yet."));
137                 }
138
139 <INITIAL>"'"({GRAPHIC}|\")"'" {
140                    yylval.typed_val.type = type_char (pstate);
141                    yylval.typed_val.val = yytext[1];
142                    return CHARLIT;
143                 }
144
145 <INITIAL>"'[\""{HEXDIG}{2}"\"]'"   {
146                    int v;
147                    yylval.typed_val.type = type_char (pstate);
148                    sscanf (yytext+3, "%2x", &v);
149                    yylval.typed_val.val = v;
150                    return CHARLIT;
151                 }
152
153 \"({GRAPHIC}|"[\""({HEXDIG}{2}|\")"\"]")*\"   {
154                    yylval.sval = processString (yytext+1, yyleng-2);
155                    return STRING;
156                 }
157
158 \"              {
159                    error (_("ill-formed or non-terminated string literal"));
160                 }
161
162
163 if              {
164                   rewind_to_char ('i');
165                   return 0;
166                 }
167
168 task            {
169                   rewind_to_char ('t');
170                   return 0;
171                 }
172
173 thread{WHITE}+{DIG} {
174                   /* This keyword signals the end of the expression and
175                      will be processed separately.  */
176                   rewind_to_char ('t');
177                   return 0;
178                 }
179
180         /* ADA KEYWORDS */
181
182 abs             { return ABS; }
183 and             { return _AND_; }
184 else            { return ELSE; }
185 in              { return IN; }
186 mod             { return MOD; }
187 new             { return NEW; }
188 not             { return NOT; }
189 null            { return NULL_PTR; }
190 or              { return OR; }
191 others          { return OTHERS; }
192 rem             { return REM; }
193 then            { return THEN; }
194 xor             { return XOR; }
195
196         /* BOOLEAN "KEYWORDS" */
197
198  /* True and False are not keywords in Ada, but rather enumeration constants.
199     However, the boolean type is no longer represented as an enum, so True
200     and False are no longer defined in symbol tables.  We compromise by
201     making them keywords (when bare). */
202
203 true            { return TRUEKEYWORD; }
204 false           { return FALSEKEYWORD; }
205
206         /* ATTRIBUTES */
207
208 {TICK}[a-zA-Z][a-zA-Z]+ { return processAttribute (yytext+1); }
209
210         /* PUNCTUATION */
211
212 "=>"            { return ARROW; }
213 ".."            { return DOTDOT; }
214 "**"            { return STARSTAR; }
215 ":="            { return ASSIGN; }
216 "/="            { return NOTEQUAL; }
217 "<="            { return LEQ; }
218 ">="            { return GEQ; }
219
220 <BEFORE_QUAL_QUOTE>"'" { BEGIN INITIAL; return '\''; }
221
222 [-&*+./:<>=|;\[\]] { return yytext[0]; }
223
224 ","             { if (paren_depth == 0 && comma_terminates)
225                     {
226                       rewind_to_char (',');
227                       return 0;
228                     }
229                   else
230                     return ',';
231                 }
232
233 "("             { paren_depth += 1; return '('; }
234 ")"             { if (paren_depth == 0)
235                     {
236                       rewind_to_char (')');
237                       return 0;
238                     }
239                   else
240                     {
241                       paren_depth -= 1;
242                       return ')';
243                     }
244                 }
245
246 "."{WHITE}*all  { return DOT_ALL; }
247
248 "."{WHITE}*{ID} {
249                   yylval.sval = processId (yytext+1, yyleng-1);
250                   return DOT_ID;
251                 }
252
253 {ID}({WHITE}*"."{WHITE}*({ID}|\"{OPER}\"))*(" "*"'")?  {
254                   int all_posn = find_dot_all (yytext);
255
256                   if (all_posn == -1 && yytext[yyleng-1] == '\'')
257                     {
258                       BEGIN BEFORE_QUAL_QUOTE;
259                       yyless (yyleng-1);
260                     }
261                   else if (all_posn >= 0)
262                     yyless (all_posn);
263                   yylval.sval = processId (yytext, yyleng);
264                   return NAME;
265                }
266
267
268         /* GDB EXPRESSION CONSTRUCTS  */
269
270 "'"[^']+"'"{WHITE}*:: {
271                   yyless (yyleng - 2);
272                   yylval.sval = processId (yytext, yyleng);
273                   return NAME;
274                 }
275
276 "::"            { return COLONCOLON; }
277
278 [{}@]           { return yytext[0]; }
279
280         /* REGISTERS AND GDB CONVENIENCE VARIABLES */
281
282 "$"({LETTER}|{DIG}|"$")*  {
283                   yylval.sval.ptr = yytext;
284                   yylval.sval.length = yyleng;
285                   return SPECIAL_VARIABLE;
286                 }
287
288         /* CATCH-ALL ERROR CASE */
289
290 .               { error (_("Invalid character '%s' in expression."), yytext); }
291 %%
292
293 #include <ctype.h>
294 #include <string.h>
295
296 /* Initialize the lexer for processing new expression. */
297
298 static void
299 lexer_init (FILE *inp)
300 {
301   BEGIN INITIAL;
302   yyrestart (inp);
303 }
304
305
306 /* Copy S2 to S1, removing all underscores, and downcasing all letters.  */
307
308 static void
309 canonicalizeNumeral (char *s1, const char *s2)
310 {
311   for (; *s2 != '\000'; s2 += 1)
312     {
313       if (*s2 != '_')
314         {
315           *s1 = tolower(*s2);
316           s1 += 1;
317         }
318     }
319   s1[0] = '\000';
320 }
321
322 /* Interprets the prefix of NUM that consists of digits of the given BASE
323    as an integer of that BASE, with the string EXP as an exponent.
324    Puts value in yylval, and returns INT, if the string is valid.  Causes
325    an error if the number is improperly formated.   BASE, if NULL, defaults
326    to "10", and EXP to "1".  The EXP does not contain a leading 'e' or 'E'.
327  */
328
329 static int
330 processInt (struct parser_state *par_state, const char *base0,
331             const char *num0, const char *exp0)
332 {
333   ULONGEST result;
334   long exp;
335   int base;
336   const char *trailer;
337
338   if (base0 == NULL)
339     base = 10;
340   else
341     {
342       base = strtol (base0, (char **) NULL, 10);
343       if (base < 2 || base > 16)
344         error (_("Invalid base: %d."), base);
345     }
346
347   if (exp0 == NULL)
348     exp = 0;
349   else
350     exp = strtol(exp0, (char **) NULL, 10);
351
352   errno = 0;
353   result = strtoulst (num0, &trailer, base);
354   if (errno == ERANGE)
355     error (_("Integer literal out of range"));
356   if (isxdigit(*trailer))
357     error (_("Invalid digit `%c' in based literal"), *trailer);
358
359   while (exp > 0)
360     {
361       if (result > (ULONG_MAX / base))
362         error (_("Integer literal out of range"));
363       result *= base;
364       exp -= 1;
365     }
366
367   if ((result >> (gdbarch_int_bit (parse_gdbarch (par_state))-1)) == 0)
368     yylval.typed_val.type = type_int (par_state);
369   else if ((result >> (gdbarch_long_bit (parse_gdbarch (par_state))-1)) == 0)
370     yylval.typed_val.type = type_long (par_state);
371   else if (((result >> (gdbarch_long_bit (parse_gdbarch (par_state))-1)) >> 1) == 0)
372     {
373       /* We have a number representable as an unsigned integer quantity.
374          For consistency with the C treatment, we will treat it as an
375          anonymous modular (unsigned) quantity.  Alas, the types are such
376          that we need to store .val as a signed quantity.  Sorry
377          for the mess, but C doesn't officially guarantee that a simple
378          assignment does the trick (no, it doesn't; read the reference manual).
379        */
380       yylval.typed_val.type
381         = builtin_type (parse_gdbarch (par_state))->builtin_unsigned_long;
382       if (result & LONGEST_SIGN)
383         yylval.typed_val.val =
384           (LONGEST) (result & ~LONGEST_SIGN)
385           - (LONGEST_SIGN>>1) - (LONGEST_SIGN>>1);
386       else
387         yylval.typed_val.val = (LONGEST) result;
388       return INT;
389     }
390   else
391     yylval.typed_val.type = type_long_long (par_state);
392
393   yylval.typed_val.val = (LONGEST) result;
394   return INT;
395 }
396
397 static int
398 processReal (struct parser_state *par_state, const char *num0)
399 {
400   sscanf (num0, "%" DOUBLEST_SCAN_FORMAT, &yylval.typed_val_float.dval);
401
402   yylval.typed_val_float.type = type_float (par_state);
403   if (sizeof(DOUBLEST) >= gdbarch_double_bit (parse_gdbarch (par_state))
404                             / TARGET_CHAR_BIT)
405     yylval.typed_val_float.type = type_double (par_state);
406   if (sizeof(DOUBLEST) >= gdbarch_long_double_bit (parse_gdbarch (par_state))
407                             / TARGET_CHAR_BIT)
408     yylval.typed_val_float.type = type_long_double (par_state);
409
410   return FLOAT;
411 }
412
413
414 /* Store a canonicalized version of NAME0[0..LEN-1] in yylval.ssym.  The
415    resulting string is valid until the next call to ada_parse.  If
416    NAME0 contains the substring "___", it is assumed to be already
417    encoded and the resulting name is equal to it.  Otherwise, it differs
418    from NAME0 in that:
419     + Characters between '...' or <...> are transfered verbatim to 
420       yylval.ssym.
421     + <, >, and trailing "'" characters in quoted sequences are removed
422       (a leading quote is preserved to indicate that the name is not to be
423       GNAT-encoded).
424     + Unquoted whitespace is removed.
425     + Unquoted alphabetic characters are mapped to lower case.
426    Result is returned as a struct stoken, but for convenience, the string
427    is also null-terminated.  Result string valid until the next call of
428    ada_parse.
429  */
430 static struct stoken
431 processId (const char *name0, int len)
432 {
433   char *name = obstack_alloc (&temp_parse_space, len + 11);
434   int i0, i;
435   struct stoken result;
436
437   result.ptr = name;
438   while (len > 0 && isspace (name0[len-1]))
439     len -= 1;
440
441   if (strstr (name0, "___") != NULL)
442     {
443       strncpy (name, name0, len);
444       name[len] = '\000';
445       result.length = len;
446       return result;
447     }
448
449   i = i0 = 0;
450   while (i0 < len)
451     {
452       if (isalnum (name0[i0]))
453         {
454           name[i] = tolower (name0[i0]);
455           i += 1; i0 += 1;
456         }
457       else switch (name0[i0])
458         {
459         default:
460           name[i] = name0[i0];
461           i += 1; i0 += 1;
462           break;
463         case ' ': case '\t':
464           i0 += 1;
465           break;
466         case '\'':
467           do
468             {
469               name[i] = name0[i0];
470               i += 1; i0 += 1;
471             }
472           while (i0 < len && name0[i0] != '\'');
473           i0 += 1;
474           break;
475         case '<':
476           i0 += 1;
477           while (i0 < len && name0[i0] != '>')
478             {
479               name[i] = name0[i0];
480               i += 1; i0 += 1;
481             }
482           i0 += 1;
483           break;
484         }
485     }
486   name[i] = '\000';
487
488   result.length = i;
489   return result;
490 }
491
492 /* Return TEXT[0..LEN-1], a string literal without surrounding quotes,
493    with special hex character notations replaced with characters. 
494    Result valid until the next call to ada_parse.  */
495
496 static struct stoken
497 processString (const char *text, int len)
498 {
499   const char *p;
500   char *q;
501   const char *lim = text + len;
502   struct stoken result;
503
504   q = obstack_alloc (&temp_parse_space, len);
505   result.ptr = q;
506   p = text;
507   while (p < lim)
508     {
509       if (p[0] == '[' && p[1] == '"' && p+2 < lim)
510          {
511            if (p[2] == '"')  /* "...["""]... */
512              {
513                *q = '"';
514                p += 4;
515              }
516            else
517              {
518                int chr;
519                sscanf (p+2, "%2x", &chr);
520                *q = (char) chr;
521                p += 5;
522              }
523          }
524        else
525          *q = *p;
526        q += 1;
527        p += 1;
528      }
529   result.length = q - result.ptr;
530   return result;
531 }
532
533 /* Returns the position within STR of the '.' in a
534    '.{WHITE}*all' component of a dotted name, or -1 if there is none.
535    Note: we actually don't need this routine, since 'all' can never be an
536    Ada identifier.  Thus, looking up foo.all or foo.all.x as a name
537    must fail, and will eventually be interpreted as (foo).all or
538    (foo).all.x.  However, this does avoid an extraneous lookup. */
539
540 static int
541 find_dot_all (const char *str)
542 {
543   int i;
544
545   for (i = 0; str[i] != '\000'; i++)
546     if (str[i] == '.')
547       {
548         int i0 = i;
549
550         do
551           i += 1;
552         while (isspace (str[i]));
553
554         if (strncasecmp (str + i, "all", 3) == 0
555             && !isalnum (str[i + 3]) && str[i + 3] != '_')
556           return i0;
557       }
558   return -1;
559 }
560
561 /* Returns non-zero iff string SUBSEQ matches a subsequence of STR, ignoring
562    case.  */
563
564 static int
565 subseqMatch (const char *subseq, const char *str)
566 {
567   if (subseq[0] == '\0')
568     return 1;
569   else if (str[0] == '\0')
570     return 0;
571   else if (tolower (subseq[0]) == tolower (str[0]))
572     return subseqMatch (subseq+1, str+1) || subseqMatch (subseq, str+1);
573   else
574     return subseqMatch (subseq, str+1);
575 }
576
577
578 static struct { const char *name; int code; }
579 attributes[] = {
580   { "address", TICK_ADDRESS },
581   { "unchecked_access", TICK_ACCESS },
582   { "unrestricted_access", TICK_ACCESS },
583   { "access", TICK_ACCESS },
584   { "first", TICK_FIRST },
585   { "last", TICK_LAST },
586   { "length", TICK_LENGTH },
587   { "max", TICK_MAX },
588   { "min", TICK_MIN },
589   { "modulus", TICK_MODULUS },
590   { "pos", TICK_POS },
591   { "range", TICK_RANGE },
592   { "size", TICK_SIZE },
593   { "tag", TICK_TAG },
594   { "val", TICK_VAL },
595   { NULL, -1 }
596 };
597
598 /* Return the syntactic code corresponding to the attribute name or
599    abbreviation STR.  */
600
601 static int
602 processAttribute (const char *str)
603 {
604   int i, k;
605
606   for (i = 0; attributes[i].code != -1; i += 1)
607     if (strcasecmp (str, attributes[i].name) == 0)
608       return attributes[i].code;
609
610   for (i = 0, k = -1; attributes[i].code != -1; i += 1)
611     if (subseqMatch (str, attributes[i].name))
612       {
613         if (k == -1)
614           k = i;
615         else
616           error (_("ambiguous attribute name: `%s'"), str);
617       }
618   if (k == -1)
619     error (_("unrecognized attribute: `%s'"), str);
620
621   return attributes[k].code;
622 }
623
624 /* Back up lexptr by yyleng and then to the rightmost occurrence of
625    character CH, case-folded (there must be one).  WARNING: since
626    lexptr points to the next input character that Flex has not yet
627    transferred to its internal buffer, the use of this function
628    depends on the assumption that Flex calls YY_INPUT only when it is
629    logically necessary to do so (thus, there is no reading ahead
630    farther than needed to identify the next token.)  */
631
632 static void
633 rewind_to_char (int ch)
634 {
635   lexptr -= yyleng;
636   while (toupper (*lexptr) != toupper (ch))
637     lexptr -= 1;
638   yyrestart (NULL);
639 }
640
641 int
642 yywrap(void)
643 {
644   return 1;
645 }
646
647 /* Dummy definition to suppress warnings about unused static definitions. */
648 typedef void (*dummy_function) ();
649 dummy_function ada_flex_use[] = 
650
651   (dummy_function) yyunput
652 };