gdb/ada-lex.l - gdb

  1. /* FLEX lexer for Ada expressions, for GDB.
  2.    Copyright (C) 1994-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. /*----------------------------------------------------------------------*/

  15. /* The converted version of this file is to be included in ada-exp.y, */
  16. /* the Ada parser for gdb.  The function yylex obtains characters from */
  17. /* the global pointer lexptr.  It returns a syntactic category for */
  18. /* each successive token and places a semantic value into yylval */
  19. /* (ada-lval), defined by the parser.   */

  20. DIG        [0-9]
  21. NUM10        ({DIG}({DIG}|_)*)
  22. HEXDIG        [0-9a-f]
  23. NUM16        ({HEXDIG}({HEXDIG}|_)*)
  24. OCTDIG        [0-7]
  25. LETTER        [a-z_]
  26. ID        ({LETTER}({LETTER}|{DIG})*|"<"{LETTER}({LETTER}|{DIG})*">")
  27. WHITE        [ \t\n]
  28. TICK        ("'"{WHITE}*)
  29. GRAPHIC [a-z0-9 #&'()*+,-./:;<>=_|!$%?@\[\]\\^`{}~]
  30. OPER    ([-+*/=<>&]|"<="|">="|"**"|"/="|"and"|"or"|"xor"|"not"|"mod"|"rem"|"abs")

  31. EXP        (e[+-]{NUM10})
  32. POSEXP  (e"+"?{NUM10})

  33. %{

  34. #define NUMERAL_WIDTH 256
  35. #define LONGEST_SIGN ((ULONGEST) 1 << (sizeof(LONGEST) * HOST_CHAR_BIT - 1))

  36. /* Temporary staging for numeric literals.  */
  37. static char numbuf[NUMERAL_WIDTH];
  38. static void canonicalizeNumeral (char *s1, const char *);
  39. static struct stoken processString (const char*, int);
  40. static int processInt (struct parser_state *, const char *, const char *,
  41.                        const char *);
  42. static int processReal (struct parser_state *, const char *);
  43. static struct stoken processId (const char *, int);
  44. static int processAttribute (const char *);
  45. static int find_dot_all (const char *);
  46. static void rewind_to_char (int);

  47. #undef YY_DECL
  48. #define YY_DECL static int yylex ( void )

  49. /* Flex generates a static function "input" which is not used.
  50.    Defining YY_NO_INPUT comments it out.  */
  51. #define YY_NO_INPUT

  52. #undef YY_INPUT
  53. #define YY_INPUT(BUF, RESULT, MAX_SIZE) \
  54.     if ( *lexptr == '\000' ) \
  55.       (RESULT) = YY_NULL; \
  56.     else \
  57.       { \
  58.         *(BUF) = *lexptr; \
  59.         (RESULT) = 1; \
  60.         lexptr += 1; \
  61.       }

  62. static int find_dot_all (const char *);

  63. %}

  64. %option case-insensitive interactive nodefault

  65. %s BEFORE_QUAL_QUOTE

  66. %%

  67. {WHITE}                 { }

  68. "--".*                 { yyterminate(); }

  69. {NUM10}{POSEXP}  {
  70.                    canonicalizeNumeral (numbuf, yytext);
  71.                    return processInt (pstate, NULL, numbuf,
  72.                                       strrchr (numbuf, 'e') + 1);
  73.                  }

  74. {NUM10}          {
  75.                    canonicalizeNumeral (numbuf, yytext);
  76.                    return processInt (pstate, NULL, numbuf, NULL);
  77.                  }

  78. {NUM10}"#"{HEXDIG}({HEXDIG}|_)*"#"{POSEXP} {
  79.                    canonicalizeNumeral (numbuf, yytext);
  80.                    return processInt (pstate, numbuf,
  81.                                       strchr (numbuf, '#') + 1,
  82.                                       strrchr(numbuf, '#') + 1);
  83.                  }

  84. {NUM10}"#"{HEXDIG}({HEXDIG}|_)*"#" {
  85.                    canonicalizeNumeral (numbuf, yytext);
  86.                    return processInt (pstate, numbuf, strchr (numbuf, '#') + 1,
  87.                                       NULL);
  88.                  }

  89. "0x"{HEXDIG}+        {
  90.                   canonicalizeNumeral (numbuf, yytext+2);
  91.                   return processInt (pstate, "16#", numbuf, NULL);
  92.                 }


  93. {NUM10}"."{NUM10}{EXP} {
  94.                    canonicalizeNumeral (numbuf, yytext);
  95.                    return processReal (pstate, numbuf);
  96.                 }

  97. {NUM10}"."{NUM10} {
  98.                    canonicalizeNumeral (numbuf, yytext);
  99.                    return processReal (pstate, numbuf);
  100.                 }

  101. {NUM10}"#"{NUM16}"."{NUM16}"#"{EXP} {
  102.                    error (_("Based real literals not implemented yet."));
  103.                 }

  104. {NUM10}"#"{NUM16}"."{NUM16}"#" {
  105.                    error (_("Based real literals not implemented yet."));
  106.                 }

  107. <INITIAL>"'"({GRAPHIC}|\")"'" {
  108.                    yylval.typed_val.type = type_char (pstate);
  109.                    yylval.typed_val.val = yytext[1];
  110.                    return CHARLIT;
  111.                 }

  112. <INITIAL>"'[\""{HEXDIG}{2}"\"]'"   {
  113.                    int v;
  114.                    yylval.typed_val.type = type_char (pstate);
  115.                    sscanf (yytext+3, "%2x", &v);
  116.                    yylval.typed_val.val = v;
  117.                    return CHARLIT;
  118.                 }

  119. \"({GRAPHIC}|"[\""({HEXDIG}{2}|\")"\"]")*\"   {
  120.                    yylval.sval = processString (yytext+1, yyleng-2);
  121.                    return STRING;
  122.                 }

  123. \"              {
  124.                    error (_("ill-formed or non-terminated string literal"));
  125.                 }


  126. if                {
  127.                   rewind_to_char ('i');
  128.                   return 0;
  129.                 }

  130. task            {
  131.                   rewind_to_char ('t');
  132.                   return 0;
  133.                 }

  134. thread{WHITE}+{DIG} {
  135.                   /* This keyword signals the end of the expression and
  136.                      will be processed separately.  */
  137.                   rewind_to_char ('t');
  138.                   return 0;
  139.                 }

  140.         /* ADA KEYWORDS */

  141. abs                { return ABS; }
  142. and                { return _AND_; }
  143. else                { return ELSE; }
  144. in                { return IN; }
  145. mod                { return MOD; }
  146. new                { return NEW; }
  147. not                { return NOT; }
  148. null                { return NULL_PTR; }
  149. or                { return OR; }
  150. others          { return OTHERS; }
  151. rem                { return REM; }
  152. then                { return THEN; }
  153. xor                { return XOR; }

  154.         /* BOOLEAN "KEYWORDS" */

  155. /* True and False are not keywords in Ada, but rather enumeration constants.
  156.     However, the boolean type is no longer represented as an enum, so True
  157.     and False are no longer defined in symbol tables.  We compromise by
  158.     making them keywords (when bare). */

  159. true                { return TRUEKEYWORD; }
  160. false                { return FALSEKEYWORD; }

  161.         /* ATTRIBUTES */

  162. {TICK}[a-zA-Z][a-zA-Z]+ { return processAttribute (yytext+1); }

  163.         /* PUNCTUATION */

  164. "=>"                { return ARROW; }
  165. ".."                { return DOTDOT; }
  166. "**"                { return STARSTAR; }
  167. ":="                { return ASSIGN; }
  168. "/="                { return NOTEQUAL; }
  169. "<="                { return LEQ; }
  170. ">="                { return GEQ; }

  171. <BEFORE_QUAL_QUOTE>"'" { BEGIN INITIAL; return '\''; }

  172. [-&*+./:<>=|;\[\]] { return yytext[0]; }

  173. ","                { if (paren_depth == 0 && comma_terminates)
  174.                     {
  175.                       rewind_to_char (',');
  176.                       return 0;
  177.                     }
  178.                   else
  179.                     return ',';
  180.                 }

  181. "("                { paren_depth += 1; return '('; }
  182. ")"                { if (paren_depth == 0)
  183.                     {
  184.                       rewind_to_char (')');
  185.                       return 0;
  186.                     }
  187.                   else
  188.                      {
  189.                       paren_depth -= 1;
  190.                       return ')';
  191.                     }
  192.                 }

  193. "."{WHITE}*all  { return DOT_ALL; }

  194. "."{WHITE}*{ID} {
  195.                    yylval.sval = processId (yytext+1, yyleng-1);
  196.                   return DOT_ID;
  197.                 }

  198. {ID}({WHITE}*"."{WHITE}*({ID}|\"{OPER}\"))*(" "*"'")?  {
  199.                   int all_posn = find_dot_all (yytext);

  200.                   if (all_posn == -1 && yytext[yyleng-1] == '\'')
  201.                     {
  202.                       BEGIN BEFORE_QUAL_QUOTE;
  203.                       yyless (yyleng-1);
  204.                     }
  205.                   else if (all_posn >= 0)
  206.                     yyless (all_posn);
  207.                   yylval.sval = processId (yytext, yyleng);
  208.                   return NAME;
  209.                }


  210.         /* GDB EXPRESSION CONSTRUCTS  */

  211. "'"[^']+"'"{WHITE}*:: {
  212.                   yyless (yyleng - 2);
  213.                   yylval.sval = processId (yytext, yyleng);
  214.                   return NAME;
  215.                 }

  216. "::"            { return COLONCOLON; }

  217. [{}@]                { return yytext[0]; }

  218.         /* REGISTERS AND GDB CONVENIENCE VARIABLES */

  219. "$"({LETTER}|{DIG}|"$")*  {
  220.                   yylval.sval.ptr = yytext;
  221.                   yylval.sval.length = yyleng;
  222.                   return SPECIAL_VARIABLE;
  223.                 }

  224.         /* CATCH-ALL ERROR CASE */

  225. .                { error (_("Invalid character '%s' in expression."), yytext); }
  226. %%

  227. #include <ctype.h>
  228. /* Initialize the lexer for processing new expression. */

  229. static void
  230. lexer_init (FILE *inp)
  231. {
  232.   BEGIN INITIAL;
  233.   yyrestart (inp);
  234. }


  235. /* Copy S2 to S1, removing all underscores, and downcasing all letters.  */

  236. static void
  237. canonicalizeNumeral (char *s1, const char *s2)
  238. {
  239.   for (; *s2 != '\000'; s2 += 1)
  240.     {
  241.       if (*s2 != '_')
  242.         {
  243.           *s1 = tolower(*s2);
  244.           s1 += 1;
  245.         }
  246.     }
  247.   s1[0] = '\000';
  248. }

  249. /* Interprets the prefix of NUM that consists of digits of the given BASE
  250.    as an integer of that BASE, with the string EXP as an exponent.
  251.    Puts value in yylval, and returns INT, if the string is valid.  Causes
  252.    an error if the number is improperly formated.   BASE, if NULL, defaults
  253.    to "10", and EXP to "1".  The EXP does not contain a leading 'e' or 'E'.
  254. */

  255. static int
  256. processInt (struct parser_state *par_state, const char *base0,
  257.             const char *num0, const char *exp0)
  258. {
  259.   ULONGEST result;
  260.   long exp;
  261.   int base;
  262.   const char *trailer;

  263.   if (base0 == NULL)
  264.     base = 10;
  265.   else
  266.     {
  267.       base = strtol (base0, (char **) NULL, 10);
  268.       if (base < 2 || base > 16)
  269.         error (_("Invalid base: %d."), base);
  270.     }

  271.   if (exp0 == NULL)
  272.     exp = 0;
  273.   else
  274.     exp = strtol(exp0, (char **) NULL, 10);

  275.   errno = 0;
  276.   result = strtoulst (num0, &trailer, base);
  277.   if (errno == ERANGE)
  278.     error (_("Integer literal out of range"));
  279.   if (isxdigit(*trailer))
  280.     error (_("Invalid digit `%c' in based literal"), *trailer);

  281.   while (exp > 0)
  282.     {
  283.       if (result > (ULONG_MAX / base))
  284.         error (_("Integer literal out of range"));
  285.       result *= base;
  286.       exp -= 1;
  287.     }

  288.   if ((result >> (gdbarch_int_bit (parse_gdbarch (par_state))-1)) == 0)
  289.     yylval.typed_val.type = type_int (par_state);
  290.   else if ((result >> (gdbarch_long_bit (parse_gdbarch (par_state))-1)) == 0)
  291.     yylval.typed_val.type = type_long (par_state);
  292.   else if (((result >> (gdbarch_long_bit (parse_gdbarch (par_state))-1)) >> 1) == 0)
  293.     {
  294.       /* We have a number representable as an unsigned integer quantity.
  295.          For consistency with the C treatment, we will treat it as an
  296.          anonymous modular (unsigned) quantity.  Alas, the types are such
  297.          that we need to store .val as a signed quantity.  Sorry
  298.          for the mess, but C doesn't officially guarantee that a simple
  299.          assignment does the trick (no, it doesn't; read the reference manual).
  300.        */
  301.       yylval.typed_val.type
  302.         = builtin_type (parse_gdbarch (par_state))->builtin_unsigned_long;
  303.       if (result & LONGEST_SIGN)
  304.         yylval.typed_val.val =
  305.           (LONGEST) (result & ~LONGEST_SIGN)
  306.           - (LONGEST_SIGN>>1) - (LONGEST_SIGN>>1);
  307.       else
  308.         yylval.typed_val.val = (LONGEST) result;
  309.       return INT;
  310.     }
  311.   else
  312.     yylval.typed_val.type = type_long_long (par_state);

  313.   yylval.typed_val.val = (LONGEST) result;
  314.   return INT;
  315. }

  316. static int
  317. processReal (struct parser_state *par_state, const char *num0)
  318. {
  319.   sscanf (num0, "%" DOUBLEST_SCAN_FORMAT, &yylval.typed_val_float.dval);

  320.   yylval.typed_val_float.type = type_float (par_state);
  321.   if (sizeof(DOUBLEST) >= gdbarch_double_bit (parse_gdbarch (par_state))
  322.                             / TARGET_CHAR_BIT)
  323.     yylval.typed_val_float.type = type_double (par_state);
  324.   if (sizeof(DOUBLEST) >= gdbarch_long_double_bit (parse_gdbarch (par_state))
  325.                             / TARGET_CHAR_BIT)
  326.     yylval.typed_val_float.type = type_long_double (par_state);

  327.   return FLOAT;
  328. }


  329. /* Store a canonicalized version of NAME0[0..LEN-1] in yylval.ssym.  The
  330.    resulting string is valid until the next call to ada_parse.  If
  331.    NAME0 contains the substring "___", it is assumed to be already
  332.    encoded and the resulting name is equal to it.  Otherwise, it differs
  333.    from NAME0 in that:
  334.     + Characters between '...' or <...> are transfered verbatim to
  335.       yylval.ssym.
  336.     + <, >, and trailing "'" characters in quoted sequences are removed
  337.       (a leading quote is preserved to indicate that the name is not to be
  338.       GNAT-encoded).
  339.     + Unquoted whitespace is removed.
  340.     + Unquoted alphabetic characters are mapped to lower case.
  341.    Result is returned as a struct stoken, but for convenience, the string
  342.    is also null-terminated.  Result string valid until the next call of
  343.    ada_parse.
  344. */
  345. static struct stoken
  346. processId (const char *name0, int len)
  347. {
  348.   char *name = obstack_alloc (&temp_parse_space, len + 11);
  349.   int i0, i;
  350.   struct stoken result;

  351.   result.ptr = name;
  352.   while (len > 0 && isspace (name0[len-1]))
  353.     len -= 1;

  354.   if (strstr (name0, "___") != NULL)
  355.     {
  356.       strncpy (name, name0, len);
  357.       name[len] = '\000';
  358.       result.length = len;
  359.       return result;
  360.     }

  361.   i = i0 = 0;
  362.   while (i0 < len)
  363.     {
  364.       if (isalnum (name0[i0]))
  365.         {
  366.           name[i] = tolower (name0[i0]);
  367.           i += 1; i0 += 1;
  368.         }
  369.       else switch (name0[i0])
  370.         {
  371.         default:
  372.           name[i] = name0[i0];
  373.           i += 1; i0 += 1;
  374.           break;
  375.         case ' ': case '\t':
  376.           i0 += 1;
  377.           break;
  378.         case '\'':
  379.           do
  380.             {
  381.               name[i] = name0[i0];
  382.               i += 1; i0 += 1;
  383.             }
  384.           while (i0 < len && name0[i0] != '\'');
  385.           i0 += 1;
  386.           break;
  387.         case '<':
  388.           i0 += 1;
  389.           while (i0 < len && name0[i0] != '>')
  390.             {
  391.               name[i] = name0[i0];
  392.               i += 1; i0 += 1;
  393.             }
  394.           i0 += 1;
  395.           break;
  396.         }
  397.     }
  398.   name[i] = '\000';

  399.   result.length = i;
  400.   return result;
  401. }

  402. /* Return TEXT[0..LEN-1], a string literal without surrounding quotes,
  403.    with special hex character notations replaced with characters.
  404.    Result valid until the next call to ada_parse.  */

  405. static struct stoken
  406. processString (const char *text, int len)
  407. {
  408.   const char *p;
  409.   char *q;
  410.   const char *lim = text + len;
  411.   struct stoken result;

  412.   q = obstack_alloc (&temp_parse_space, len);
  413.   result.ptr = q;
  414.   p = text;
  415.   while (p < lim)
  416.     {
  417.       if (p[0] == '[' && p[1] == '"' && p+2 < lim)
  418.          {
  419.            if (p[2] == '"'/* "...["""]... */
  420.              {
  421.                *q = '"';
  422.                p += 4;
  423.              }
  424.            else
  425.              {
  426.                int chr;
  427.                sscanf (p+2, "%2x", &chr);
  428.                *q = (char) chr;
  429.                p += 5;
  430.              }
  431.          }
  432.        else
  433.          *q = *p;
  434.        q += 1;
  435.        p += 1;
  436.      }
  437.   result.length = q - result.ptr;
  438.   return result;
  439. }

  440. /* Returns the position within STR of the '.' in a
  441.    '.{WHITE}*all' component of a dotted name, or -1 if there is none.
  442.    Note: we actually don't need this routine, since 'all' can never be an
  443.    Ada identifier.  Thus, looking up foo.all or foo.all.x as a name
  444.    must fail, and will eventually be interpreted as (foo).all or
  445.    (foo).all.x.  However, this does avoid an extraneous lookup. */

  446. static int
  447. find_dot_all (const char *str)
  448. {
  449.   int i;

  450.   for (i = 0; str[i] != '\000'; i++)
  451.     if (str[i] == '.')
  452.       {
  453.         int i0 = i;

  454.         do
  455.           i += 1;
  456.         while (isspace (str[i]));

  457.         if (strncasecmp (str + i, "all", 3) == 0
  458.             && !isalnum (str[i + 3]) && str[i + 3] != '_')
  459.           return i0;
  460.       }
  461.   return -1;
  462. }

  463. /* Returns non-zero iff string SUBSEQ matches a subsequence of STR, ignoring
  464.    case.  */

  465. static int
  466. subseqMatch (const char *subseq, const char *str)
  467. {
  468.   if (subseq[0] == '\0')
  469.     return 1;
  470.   else if (str[0] == '\0')
  471.     return 0;
  472.   else if (tolower (subseq[0]) == tolower (str[0]))
  473.     return subseqMatch (subseq+1, str+1) || subseqMatch (subseq, str+1);
  474.   else
  475.     return subseqMatch (subseq, str+1);
  476. }


  477. static struct { const char *name; int code; }
  478. attributes[] = {
  479.   { "address", TICK_ADDRESS },
  480.   { "unchecked_access", TICK_ACCESS },
  481.   { "unrestricted_access", TICK_ACCESS },
  482.   { "access", TICK_ACCESS },
  483.   { "first", TICK_FIRST },
  484.   { "last", TICK_LAST },
  485.   { "length", TICK_LENGTH },
  486.   { "max", TICK_MAX },
  487.   { "min", TICK_MIN },
  488.   { "modulus", TICK_MODULUS },
  489.   { "pos", TICK_POS },
  490.   { "range", TICK_RANGE },
  491.   { "size", TICK_SIZE },
  492.   { "tag", TICK_TAG },
  493.   { "val", TICK_VAL },
  494.   { NULL, -1 }
  495. };

  496. /* Return the syntactic code corresponding to the attribute name or
  497.    abbreviation STR.  */

  498. static int
  499. processAttribute (const char *str)
  500. {
  501.   int i, k;

  502.   for (i = 0; attributes[i].code != -1; i += 1)
  503.     if (strcasecmp (str, attributes[i].name) == 0)
  504.       return attributes[i].code;

  505.   for (i = 0, k = -1; attributes[i].code != -1; i += 1)
  506.     if (subseqMatch (str, attributes[i].name))
  507.       {
  508.         if (k == -1)
  509.           k = i;
  510.         else
  511.           error (_("ambiguous attribute name: `%s'"), str);
  512.       }
  513.   if (k == -1)
  514.     error (_("unrecognized attribute: `%s'"), str);

  515.   return attributes[k].code;
  516. }

  517. /* Back up lexptr by yyleng and then to the rightmost occurrence of
  518.    character CH, case-folded (there must be one).  WARNING: since
  519.    lexptr points to the next input character that Flex has not yet
  520.    transferred to its internal buffer, the use of this function
  521.    depends on the assumption that Flex calls YY_INPUT only when it is
  522.    logically necessary to do so (thus, there is no reading ahead
  523.    farther than needed to identify the next token.)  */

  524. static void
  525. rewind_to_char (int ch)
  526. {
  527.   lexptr -= yyleng;
  528.   while (toupper (*lexptr) != toupper (ch))
  529.     lexptr -= 1;
  530.   yyrestart (NULL);
  531. }

  532. int
  533. yywrap(void)
  534. {
  535.   return 1;
  536. }

  537. /* Dummy definition to suppress warnings about unused static definitions. */
  538. typedef void (*dummy_function) ();
  539. dummy_function ada_flex_use[] =
  540. {
  541.   (dummy_function) yyunput
  542. };