Rewrite the Ada lexer

Message ID 20261103142330.1512630-1-tromey@adacore.com
State New
Headers
Series Rewrite the Ada lexer |

Checks

Context Check Description
linaro-tcwg-bot/tcwg_gdb_build--master-aarch64 success Build passed
linaro-tcwg-bot/tcwg_gdb_build--master-arm success Build passed
linaro-tcwg-bot/tcwg_gdb_check--master-arm success Test passed
linaro-tcwg-bot/tcwg_gdb_check--master-aarch64 success Test passed

Commit Message

Tom Tromey Nov. 3, 2026, 2:23 p.m. UTC
  Recently a series landed that changed how the Ada lexer was built.  In
particular, commit d3d68d79 ("gdb: let the parser and lexer generators
prefix their symbols") changed gdb to require a newer version of flex.

Unfortunately, this version of flex is reported as being difficult to
build with mingw; and this change broke all the Windows-hosted builds
at AdaCore.

Rather than try to puzzle out the flex build, I decided to rewrite the
lexer to avoid the flex dependency.  This patch is the result.  I
tried for a fairly minimal transition, so some oddities are preserved.
Further cleanups are possible (I have a few I will send later).

I've also added some unit tests.  In some cases these test things that
previously were not tested in the tree.

Regression tested on x86-64 Fedora 43.
---
 gdb/Makefile.in      |  30 +-
 gdb/ada-exp-parser.c | 847 ++++++++++++++++++++++++++++++++++++++++---
 gdb/ada-exp-parser.h | 116 +++---
 gdb/ada-exp-parser.y |  11 +-
 gdb/ada-lex.l        | 346 ------------------
 5 files changed, 866 insertions(+), 484 deletions(-)
 delete mode 100644 gdb/ada-lex.l


base-commit: 9db3b515b964c1bbdc4d20c1202fbf27719be269
  

Comments

Simon Marchi Nov. 3, 2026, 8:28 p.m. UTC | #1
On 11/3/26 9:23 AM, Tom Tromey wrote:
> Recently a series landed that changed how the Ada lexer was built.  In
> particular, commit d3d68d79 ("gdb: let the parser and lexer generators
> prefix their symbols") changed gdb to require a newer version of flex.
> 
> Unfortunately, this version of flex is reported as being difficult to
> build with mingw; and this change broke all the Windows-hosted builds
> at AdaCore.

I am terribly sorry about that... I could have helped find a workaround,
or worst case reverted the patch.

> 
> Rather than try to puzzle out the flex build, I decided to rewrite the
> lexer to avoid the flex dependency.  This patch is the result.  I
> tried for a fairly minimal transition, so some oddities are preserved.
> Further cleanups are possible (I have a few I will send later).

At least this has the advantage of making the Ada parser more like the
others, and it's one less hassle to deal with.

> I've also added some unit tests.  In some cases these test things that
> previously were not tested in the tree.

The flex-based lexer calls processId like this:

  processId (yytext, yyleng);

IIUC correctly, yytext points to a null-terminated string that contains
only the just-lexed token.

The new lexer calls it like this:

  processId (pstate->lexptr, id_end - pstate->lexptr);

which means processId now receives a pointer into the original text.
processId does an unbounded search:

  if (name0[0] == '<' || strstr (name0, "___") != NULL)

That strstr will search past LEN, and could match something else later
in the string, outside the current token.  It would need to be adjusted
to stop at "name0 + LEN".

You can try with the input:

  FOO + x___y

> +/* Helper to check a lexing sequence, also checking string values of
> +   tokens.  */
> +static void
> +ada_lex_test_sequence (const char *input, gdb::array_view<int> expected,
> +		       std::optional<gdb::array_view<const char *>> strings,
> +		       bool completion = false)
> +{
> +  gdb_assert (!strings.has_value () || expected.size () == strings->size ());

It might be easier to follow to have just one combined array_view.  This
way, it would be easier to see what is produced at each step, since the
expected string will be next to the corresponding expected token.  For
instance, this:

  std::array cc_test { NAME, COLONCOLON, NAME, 0 };
  std::array<const char *, 4> cc_text { "blockname", nullptr,
					"duck", nullptr };
  ada_lex_test_sequence ("blockname::duck", cc_test, cc_text);

could become:

  lex_res cc_test[]
    = { { NAME, "blockname" },
	{ COLONCOLON },
	{ NAME, "duck" },
	{} };
  ada_lex_test_sequence ("blockname::duck", cc_test);

Where lex_res is a dummy struct:

struct lex_res
{
  int token;
  const char *str;
};

> @@ -64,18 +61,69 @@ struct ada_parse_state
>  
>    auto_obstack temp_space;
>  
> -  /* Depth of parentheses, used by the lexer.  */
> -  int paren_depth = 0;
> -
> -  /* When completing, we'll return a special character at the end of the
> -     input, to signal the completion position to the lexer.  This is
> -     done because flex does not have a generally useful way to detect
> -     EOF in a pattern.  This variable records whether the special
> -     character has been emitted.  */
> -  bool returned_complete = false;
> +  /* Lex a single token.  ada_yylval is updated if needed.  The token
> +     value is returned.  The lexer state in this object or in the
> +     parser_state object will be updated as appropriate.  */
> +  int lex ();
>  
>  private:
>  
> +  /* A lexer helper function to lex a number.  */
> +  int lex_number ();
> +
> +  /* A lexer helper function to lex a dollar variable like $x or
> +     $$.  */
> +  int lex_dollar ();
> +
> +  /* A lexer helper that is called when a '.' is seen.  */
> +  int lex_dot ();
> +
> +  /* A lexer helper that is called when a single quote is seen.  */
> +  int lex_single_quote ();
> +
> +  /* A lexer helper for lexing a string.  */
> +  int lex_double_quote ();
> +
> +  /* A helper function that examines TEXT.  If TEXT looks like a
> +     simple identifier, a pointer to the character past the end of the
> +     identifier is returned.  Otherwise, nullptr is returned.  */
> +  const char *lex_simple_identifier (const char *text);
> +
> +  /* A helper that does some extra checking for the "thread"
> +     pseudo-keyword.  It returns true if this instance of "thread"
> +     should be reported as an EOF rather than an identifier.  TEXT
> +     points to just past the end of the "thread" keyword.  */
> +  bool check_thread_keyword (const char *text);
> +
> +  /* Check whether the current token, held at pstate->lexptr with
> +     length LEN, is a keyword.  Returns the token value if so; returns
> +     nullopt if not.  */
> +  std::optional<int> check_keyword (size_t len);

I think it would be a bit clearer if you passed the string to this
function instead of having it read pstate->lexptr.

> diff --git a/gdb/ada-exp-parser.y b/gdb/ada-exp-parser.y
> index d37ab12c3bc..f5ceb7d390a 100644
> --- a/gdb/ada-exp-parser.y
> +++ b/gdb/ada-exp-parser.y
> @@ -50,7 +50,11 @@
>  using namespace expr;
>  using namespace ada_exp_parser;
>  
> -static int yylex (void);
> +static inline int
> +yylex ()
> +{
> +  return ada_parser->lex ();
> +}

"inline" not really needed I guess.

> +int
> +ada_parse_state::lex_single_quote ()
> +{
> +  gdb_assert (*pstate->lexptr == '\'');
> +
> +  bool before_qual_quote = m_before_qual_quote;
> +  m_before_qual_quote = false;
> +
> +  if (!before_qual_quote)
> +    {
> +      /* Look for the GDB block extension "'STUFF'::".  */
> +      const char *block_iter = pstate->lexptr + 1;
> +      while (*block_iter != '\0' && *block_iter != '\'')
> +	++block_iter;
> +      /* Require a non-empty block.  */
> +      if (block_iter[0] == '\'' && block_iter - pstate->lexptr - 1 > 0)
> +	{
> +	  const char *block_end = skip_spaces (block_iter + 1);
> +	  if (block_end[0] == ':' && block_end[1] == ':')
> +	    {
> +	      ada_yylval.sval = processId (pstate->lexptr,
> +					   block_end - pstate->lexptr);
> +	      /* Leave the "::" to be lexed later.  */
> +	      pstate->lexptr = block_end;
> +	      return NAME;
> +	    }
> +	}
> +
> +      if (c_isprint (pstate->lexptr[1]) && pstate->lexptr[2] == '\'')
> +	{
> +	  /* Ordinary character literal.  */
> +	  int the_char = pstate->lexptr[1];
> +	  ada_yylval.typed_char.val = the_char;
> +	  ada_yylval.typed_char.type = type_for_char (pstate, the_char);
> +	  pstate->lexptr += 3;
> +	  return CHARLIT;
> +	}
> +
> +      const char *end_bracket = recognize_encoded_char (pstate->lexptr + 1);
> +      if (end_bracket != nullptr)
> +	{
> +	  /* The character starts at an offset from the initial single
> +	     quote.  */
> +	  ULONGEST v = strtoulst (pstate->lexptr + 3, nullptr, 16);
> +	  ada_yylval.typed_char.val = v;
> +	  ada_yylval.typed_char.type = type_for_char (pstate, v);
> +	  pstate->lexptr = end_bracket + 1;
> +	  return CHARLIT;
> +	}
> +    }

The new code misses checking that *end_bracket is a single quote, so I
guess it can accept some invalid inputs:

  '["61"]

  '["61"]x


> diff --git a/gdb/ada-exp-parser.h b/gdb/ada-exp-parser.h
> index 09a716e6636..48bc9e7fb72 100644
> --- a/gdb/ada-exp-parser.h
> +++ b/gdb/ada-exp-parser.h
> @@ -23,9 +23,6 @@
>  #include "ada-exp.h"
>  #include "parser-defs.h"
>  
> -/* The character we use to represent the completion point.  */
> -constexpr char COMPLETE_CHAR = '\001';
> -
>  namespace ada_exp_parser
>  {
>  
> @@ -64,18 +61,69 @@ struct ada_parse_state
>  
>    auto_obstack temp_space;
>  
> -  /* Depth of parentheses, used by the lexer.  */
> -  int paren_depth = 0;
> -
> -  /* When completing, we'll return a special character at the end of the
> -     input, to signal the completion position to the lexer.  This is
> -     done because flex does not have a generally useful way to detect
> -     EOF in a pattern.  This variable records whether the special
> -     character has been emitted.  */
> -  bool returned_complete = false;
> +  /* Lex a single token.  ada_yylval is updated if needed.  The token
> +     value is returned.  The lexer state in this object or in the
> +     parser_state object will be updated as appropriate.  */
> +  int lex ();
>  
>  private:
>  
> +  /* A lexer helper function to lex a number.  */
> +  int lex_number ();
> +
> +  /* A lexer helper function to lex a dollar variable like $x or
> +     $$.  */
> +  int lex_dollar ();
> +
> +  /* A lexer helper that is called when a '.' is seen.  */
> +  int lex_dot ();
> +
> +  /* A lexer helper that is called when a single quote is seen.  */
> +  int lex_single_quote ();
> +
> +  /* A lexer helper for lexing a string.  */
> +  int lex_double_quote ();
> +
> +  /* A helper function that examines TEXT.  If TEXT looks like a
> +     simple identifier, a pointer to the character past the end of the
> +     identifier is returned.  Otherwise, nullptr is returned.  */
> +  const char *lex_simple_identifier (const char *text);
> +
> +  /* A helper that does some extra checking for the "thread"
> +     pseudo-keyword.  It returns true if this instance of "thread"
> +     should be reported as an EOF rather than an identifier.  TEXT
> +     points to just past the end of the "thread" keyword.  */
> +  bool check_thread_keyword (const char *text);
> +
> +  /* Check whether the current token, held at pstate->lexptr with
> +     length LEN, is a keyword.  Returns the token value if so; returns
> +     nullopt if not.  */
> +  std::optional<int> check_keyword (size_t len);

I think it would be a bit clearer if you passed the string to this
function instead of having it read pstate->lexptr.

> diff --git a/gdb/ada-exp-parser.y b/gdb/ada-exp-parser.y
> index d37ab12c3bc..f5ceb7d390a 100644
> --- a/gdb/ada-exp-parser.y
> +++ b/gdb/ada-exp-parser.y
> @@ -50,7 +50,11 @@
>  using namespace expr;
>  using namespace ada_exp_parser;
>  
> -static int yylex (void);
> +static inline int
> +yylex ()
> +{
> +  return ada_parser->lex ();
> +}

"inline" not really needed I guess.

Simon
  

Patch

diff --git a/gdb/Makefile.in b/gdb/Makefile.in
index 8cd12460000..6d28aa7d87d 100644
--- a/gdb/Makefile.in
+++ b/gdb/Makefile.in
@@ -128,11 +128,6 @@  COMPILE = $(ECHO_CXX) $(COMPILE.pre) $(INTERNAL_CFLAGS) $(CXXFLAGS) \
 
 YACC = @YACC@
 
-# This is used to rebuild ada-lex-gen.c from ada-lex.l.  If the program
-# is not defined, but ada-lex-gen.c is present, compilation will continue,
-# possibly with a warning.
-FLEX = flex
-
 YLWRAP = $(srcdir)/../ylwrap
 
 # where to find makeinfo, preferably one designed for texinfo-2
@@ -2075,7 +2070,6 @@  REQUIRED_SUBDIRS = doc | testsuite | data-directory
 # Parser intermediate files.
 YYFILES = \
 	ada-exp-parser-gen.c \
-	ada-lex-gen.c \
 	c-exp-parser-gen.c \
 	cp-name-parser-gen.c \
 	d-exp-parser-gen.c \
@@ -2084,11 +2078,9 @@  YYFILES = \
 	m2-exp-parser-gen.c \
 	p-exp-parser-gen.c
 
-# ada-lex-gen.c is included by another file, so it shouldn't wind up as
-# a .o itself.
-YYOBJ = $(filter-out ada-lex-gen.o,$(patsubst %.c,%.o,$(YYFILES)))
+YYOBJ = $(patsubst %.c,%.o,$(YYFILES))
 
-# The headers bison/byacc and flex generate alongside the files above.
+# The headers bison/byacc generate alongside the files above.
 YYHFILES = $(patsubst %-gen.c,%-gen.h,$(YYFILES))
 
 # Files that used to be generated in the build directory (for builds from git
@@ -2107,7 +2099,6 @@  DISTSTUFF = $(YYFILES) $(YYHFILES)
 
 # All generated files which can be included by another file.
 generated_files = \
-	ada-lex-gen.c \
 	config.h \
 	jit-reader.h \
 	$(YYHFILES) \
@@ -2730,7 +2721,7 @@  po/$(PACKAGE).pot: force
 
 
 #
-# YACC/LEX dependencies
+# YACC dependencies
 #
 # LANG-exp-parser-gen.c is generated in objdir from LANG-exp-parser.y if
 # it doesn't exist in srcdir, then compiled in objdir to
@@ -2741,23 +2732,21 @@  po/$(PACKAGE).pot: force
 # Strictly speaking c-exp-parser-gen.c should therefore depend on
 # Makefile.in, but that was a pretty big annoyance.
 
-# Cancel make's built-in rules for producing a .c file from a .y or .l
+# Cancel make's built-in rules for producing a .c file from a .y
 # file, to avoid them producing a <build>/foo-exp.c file from
 # <source>/foo-exp.y, when we also have a hand-written <source>/foo-exp.c
 # file.
 %.c: %.y
-%.c: %.l
 
 # Post-process a file produced by a parser generator, see the script
 # for details.
 POST_PROCESS_PARSER_OUTPUT_SH = $(srcdir)/post-process-parser-output.sh
 POST_PROCESS_PARSER_OUTPUT = $(SHELL) $(POST_PROCESS_PARSER_OUTPUT_SH)
 
-# The prefix to give to the symbols each parser or lexer generator
+# The prefix to give to the symbols each parser generator
 # produces, so that they can coexist in the same program.  There is no
 # rule tying it to the file name, so spell it out for each one.
 YY_PREFIX_ada-exp-parser = ada_yy
-YY_PREFIX_ada-lex = ada_yy
 YY_PREFIX_c-exp-parser = c_yy
 YY_PREFIX_cp-name-parser = cpname_yy
 YY_PREFIX_d-exp-parser = d_yy
@@ -2777,15 +2766,6 @@  YY_PREFIX_p-exp-parser = pascal_yy
 	@$(POST_PROCESS_PARSER_OUTPUT) bison $* < $*-gen.h.tmp > $*-gen.h.new \
 		&& rm -f $*-gen.h.tmp && mv $*-gen.h.new $*-gen.h
 
-%-gen.c %-gen.h: %.l $(POST_PROCESS_PARSER_OUTPUT_SH)
-	$(ECHO_LEX) $(FLEX) -t -P $(YY_PREFIX_$*) \
-		--header-file=$*-gen.h.tmp $< > $*-gen.c.tmp \
-			|| (rm -f $*-gen.c.tmp $*-gen.h.tmp; false)
-	@$(POST_PROCESS_PARSER_OUTPUT) flex $* < $*-gen.c.tmp > $*-gen.c.new \
-		&& rm -f $*-gen.c.tmp && mv $*-gen.c.new $*-gen.c
-	@$(POST_PROCESS_PARSER_OUTPUT) flex $* < $*-gen.h.tmp > $*-gen.h.new \
-		&& rm -f $*-gen.h.tmp && mv $*-gen.h.new $*-gen.h
-
 # XML rules
 
 xml-builtin.c: stamp-xml; @true
diff --git a/gdb/ada-exp-parser.c b/gdb/ada-exp-parser.c
index 4cae9e4d1fe..8b8e63dc964 100644
--- a/gdb/ada-exp-parser.c
+++ b/gdb/ada-exp-parser.c
@@ -20,11 +20,12 @@ 
 #include "ada-exp-parser.h"
 #include "ada-exp-parser-gen.h"
 #include "ada-lang.h"
-#include "ada-lex-gen.h"
 #include "block.h"
 #include "cli/cli-style.h"
 #include "gdbsupport/scoped_restore.h"
+#include "gdbsupport/selftest.h"
 #include "parser-defs.h"
+#include "inferior.h"
 
 using namespace expr;
 
@@ -38,9 +39,75 @@  int ada_yyparse ();
 
 extern int ada_yydebug;
 
+/* A regular expression matching Ada numbers.  */
+
+static const char number_regex_text[] =
+  /* We have to match the first character.  */
+  "^"
+
+  /* Hex number.  */
+  "(0x[0-9a-f][0-9a-f]*)"
+#define HEX_NUMBER 1
+  "|"
+
+  /* Floating point number with positive exponent.  */
+  "([0-9][0-9_]*e[+]?[0-9][0-9_]*)"
+#define FLOAT_POSEXP 2
+  "|"
+
+  /* Floating point number with optional exponent.  */
+  "([0-9][0-9_]*\\.[0-9][0-9_]*(e[+-][0-9][0-9_]*)?)"
+#define FLOAT_OPTEXP 3
+  "|"
+
+  /* Floating point numbers but in another base.  The "llf" is a gdb
+     extension, see lex_number.  The regexp is a little funny so that
+     it can match only 0, 1, or 2 "l"s.  */
+  "([0-9][0-9_]*(l?l?f)?#[0-9a-f][0-9a-f_]*#(e[+]?[0-9][0-9_]*)?)"
+#define FLOAT_EXTENSION 5
+#define EXPONENT 7
+  "|"
+
+  /* Based real literals.  */
+  "([0-9][0-9_]*#[0-9a-f][0-9a-f_]*\\.[0-9a-f][0-9a-f_]*#(e[+-][0-9][0-9_]*)?)"
+#define BASED_REAL 8
+  "|"
+
+  /* Lowly integers.  */
+  "[0-9][0-9_]*";
+
+/* The number of subexpressions to allocate space for, including the
+   "0th" whole match subexpression.  */
+#define NUM_SUBEXPRESSIONS 10
+
+/* The compiled number-matching regex.  */
+
+static regex_t number_regex;
+
+/* A regular expression matching an Ada operator, surrounded by
+   quotes.  */
+
+static const char operator_regex_text[] =
+  "^\"(<=|>=|\\*\\*|/=|and|or|xor|not|mod|rem|abs|[-+*/=<>&])\"";
+
+/* The number of subexpressions to allocate space for, including the
+   "0th" whole match subexpression.  */
+#define NUM_OPER_SUBEXPRESSIONS 2
+
+/* The compiled operator-matching regex.  */
+
+static regex_t operator_regex;
+
 namespace ada_exp_parser
 {
 
+/* Map a string to a code.  */
+struct code_entry
+{
+  const char *name;
+  int code;
+};
+
 /* See ada-exp-parser.h.  */
 
 struct parser_state *pstate;
@@ -49,12 +116,13 @@  struct parser_state *pstate;
 
 struct ada_parse_state *ada_parser;
 
-/* See ada-exp-parser.h.  */
+/* Copy S2 to S1, removing all underscores, and downcasing all
+   letters.  Stops at END.  */
 
-void
-canonicalizeNumeral (char *s1, const char *s2)
+static void
+canonicalize_numeral (char *s1, const char *s2, const char *end)
 {
-  for (; *s2 != '\000'; s2 += 1)
+  for (; s2 != end; s2 += 1)
     {
       if (*s2 != '_')
 	{
@@ -229,12 +297,7 @@  processId (const char *name0, int len)
   i = i0 = 0;
   while (i0 < len)
     {
-      if (name0[i0] == COMPLETE_CHAR)
-	{
-	  /* Just ignore.  */
-	  ++i0;
-	}
-      else if (in_quotes)
+      if (in_quotes)
 	name[i++] = name0[i0++];
       else if (c_isalnum (name0[i0]))
 	{
@@ -300,29 +363,6 @@  processString (const char *text, int len)
   return result;
 }
 
-/* See ada-exp-parser.h.  */
-
-int
-find_dot_all (const char *str)
-{
-  int i;
-
-  for (i = 0; str[i] != '\000'; i++)
-    if (str[i] == '.')
-      {
-	int i0 = i;
-
-	do
-	  i += 1;
-	while (c_isspace (str[i]));
-
-	if (strncasecmp (str + i, "all", 3) == 0
-	    && !c_isalnum (str[i + 3]) && str[i + 3] != '_')
-	  return i0;
-      }
-  return -1;
-}
-
 /* Returns non-zero iff string SUBSEQ matches a subsequence of STR, ignoring
    case.  */
 
@@ -340,8 +380,8 @@  subseqMatch (const char *subseq, const char *str)
 }
 
 
-static const struct { const char *name; int code; }
-attributes[] = {
+static const struct code_entry attributes[] =
+{
   { "address", TICK_ADDRESS },
   { "unchecked_access", TICK_ACCESS },
   { "unrestricted_access", TICK_ACCESS },
@@ -365,39 +405,32 @@  attributes[] = {
 /* See ada-exp-parser.h.  */
 
 int
-processAttribute (const char *str)
+ada_parse_state::process_attribute (const std::string &str, bool completing)
 {
-  gdb_assert (*str == '\'');
-  ++str;
-  while (c_isspace (*str))
-    ++str;
-
-  int len = strlen (str);
-  if (len > 0 && str[len - 1] == COMPLETE_CHAR)
+  size_t len = str.length ();
+  if (completing)
     {
-      /* This is enforced by YY_INPUT.  */
-      gdb_assert (pstate->parse_completion);
       ada_yylval.sval.ptr = obstack_strndup (&ada_parser->temp_space,
-					 str, len - 1);
-      ada_yylval.sval.length = len - 1;
+					     str.c_str (), len);
+      ada_yylval.sval.length = len;
       return TICK_COMPLETE;
     }
 
   for (const auto &item : attributes)
-    if (strcasecmp (str, item.name) == 0)
+    if (strcasecmp (str.c_str (), item.name) == 0)
       return item.code;
 
   std::optional<int> found;
   for (const auto &item : attributes)
-    if (subseqMatch (str, item.name))
+    if (subseqMatch (str.c_str (), item.name))
       {
 	if (!found.has_value ())
 	  found = item.code;
 	else
-	  error (_("ambiguous attribute name: `%s'"), str);
+	  error (_("ambiguous attribute name: `%s'"), str.c_str ());
       }
   if (!found.has_value ())
-    error (_("unrecognized attribute: `%s'"), str);
+    error (_("unrecognized attribute: `%s'"), str.c_str ());
 
   return *found;
 }
@@ -416,17 +449,697 @@  ada_tick_completer::complete (struct expression *exp,
   return true;
 }
 
-/* See ada-exp-parser.h.  */
+int
+ada_parse_state::lex_number ()
+{
+  const char *num_start = pstate->lexptr;
+  gdb_assert (c_isdigit (*num_start));
+
+  regmatch_t subexps[NUM_SUBEXPRESSIONS];
+  int match = regexec (&number_regex, num_start, ARRAY_SIZE (subexps),
+		       subexps, 0);
+  /* Failure means the regexp is broken.  */
+  gdb_assert (match == 0);
+
+  pstate->lexptr += subexps[0].rm_eo;
+
+#define NUMERAL_WIDTH 256
+  char numbuf[NUMERAL_WIDTH];
+  if (subexps[HEX_NUMBER].rm_so != -1)
+    {
+      canonicalize_numeral (numbuf, num_start + 2, pstate->lexptr);
+      return processInt (pstate, "16#", numbuf, nullptr);
+    }
+  else if (subexps[FLOAT_POSEXP].rm_so != -1)
+    {
+      canonicalize_numeral (numbuf, num_start, pstate->lexptr);
+      char *e_ptr = strrchr (numbuf, 'e');
+      *e_ptr = '\0';
+      return processInt (pstate, nullptr, numbuf, e_ptr + 1);
+    }
+  else if (subexps[FLOAT_OPTEXP].rm_so != -1)
+    {
+      canonicalize_numeral (numbuf, num_start, pstate->lexptr);
+      return processReal (pstate, numbuf);
+    }
+  else if (subexps[FLOAT_EXTENSION].rm_so != -1)
+    {
+      canonicalize_numeral (numbuf, num_start, pstate->lexptr);
+      char *e_ptr = nullptr;
+      if (subexps[EXPONENT].rm_so != -1)
+	{
+	  /* We can't use the 'rm_so' here because
+	     canonicalize_numeral might have removed some underscores.
+	     But we know the 'e' appears after the '#' so we can
+	     search for it and not get one of the (possibly hex)
+	     numerals.  */
+	  e_ptr = strrchr (numbuf, 'e');
+	  gdb_assert (e_ptr != nullptr);
+	  *e_ptr = '\0';
+	  ++e_ptr;
+	}
+      return processInt (pstate, numbuf, strchr (numbuf, '#') + 1, e_ptr);
+    }
+  else if (subexps[BASED_REAL].rm_so != -1)
+    error (_("Based real literals not implemented yet."));
+
+  /* Must be a simple integer.  */
+  canonicalize_numeral (numbuf, num_start, pstate->lexptr);
+  return processInt (pstate, nullptr, numbuf, nullptr);
+}
+
+static const code_entry keywords[] =
+{
+  { "abs", ABS },
+  { "and", _AND_ },
+  { "delta", DELTA },
+  { "else", ELSE },
+  { "for", FOR },
+  { "in", IN },
+  { "mod", MOD },
+  { "new", NEW },
+  { "not", NOT },
+  { "null", NULL_PTR },
+  { "or", OR },
+  { "others", OTHERS },
+  { "rem", REM },
+  { "then", THEN },
+  { "with", WITH },
+  { "xor", XOR },
+  /* True and False are not keywords in Ada, but rather enumeration
+     constants.  However, the boolean type is no longer represented as
+     an enum, so True and False are no longer defined in symbol
+     tables.  We compromise by making them keywords (when bare). */
+  { "true", TRUEKEYWORD },
+  { "false", FALSEKEYWORD },
+  { "if", 0 },
+  { "task", 0 },
+  { "thread", -1 },
+};
+
+bool
+ada_parse_state::check_thread_keyword (const char *text)
+{
+  /* "thread" has to be followed by whitespace and then a digit in
+     order to be treated as a keyword.  */
+  if (!c_isspace (*text))
+    return false;
+  const char *after = skip_spaces (text);
+  return c_isdigit (*after);
+}
+
+std::optional<int>
+ada_parse_state::check_keyword (size_t len)
+{
+  const char *start = pstate->lexptr;
+  for (const code_entry &entry : keywords)
+    {
+      if (strlen (entry.name) == len
+	  && strncasecmp (entry.name, start, len) == 0)
+	{
+	  int result = entry.code;
+	  if (result == -1)
+	    {
+	      /* Special handling for the "thread" keyword.  */
+	      if (!check_thread_keyword (pstate->lexptr + len))
+		continue;
+	      result = 0;
+	    }
+	  return result;
+	}
+    }
+
+  return std::nullopt;
+}
+
+const char *
+ada_parse_state::lex_operator (const char *start)
+{
+  gdb_assert (*start == '"');
+  regmatch_t subexps[NUM_SUBEXPRESSIONS];
+  int match = regexec (&operator_regex, start, ARRAY_SIZE (subexps),
+		       subexps, 0);
+  if (match != 0)
+    return nullptr;
+  return start + subexps[0].rm_eo;
+}
+
+int
+ada_parse_state::lex_identifier (const char *id_end)
+{
+  bool is_quoted = *pstate->lexptr == '<';
+  bool completing = *id_end == '\0' && pstate->parse_completion;
+
+  /* Only check keywords when the identifier is unquoted, and when not
+     completing.  */
+  if (!is_quoted && !completing)
+    {
+      std::optional<int> result = check_keyword (id_end - pstate->lexptr);
+      if (result.has_value ())
+	{
+	  /* If the keyword results in an EOF, leave the parser's
+	     lexptr pointing at the start of the keyword.  Otherwise,
+	     update to the end.  */
+	  if (*result != 0)
+	    pstate->lexptr = id_end;
+	  return *result;
+	}
+    }
+
+  while (true)
+    {
+      const char *iter = skip_spaces (id_end);
+      if (*iter != '.')
+	break;
+      iter = skip_spaces (iter + 1);
+
+      const char *new_id_end = nullptr;
+      if (*iter == '"')
+	new_id_end = lex_operator (iter);
+      else if (c_isalpha (*iter) || *iter == '_' || *iter == '<')
+	new_id_end = lex_simple_identifier (iter);
+      if (new_id_end == nullptr)
+	break;
+
+      /* Skip ".all" and leave it for a later DOT_ID lex.  */
+      if (new_id_end - iter == 3 && strncasecmp (iter, "all", 3) == 0)
+	break;
+
+      id_end = new_id_end;
+      completing = *id_end == '\0' && pstate->parse_completion;
+    }
+
+  ada_yylval.sval = processId (pstate->lexptr, id_end - pstate->lexptr);
+
+  id_end = skip_spaces (id_end);
+  if (*id_end == '\'')
+    m_before_qual_quote = true;
+
+  pstate->lexptr = id_end;
+  return completing ? NAME_COMPLETE : NAME;
+}
 
 void
-rewind_to_char (int ch)
+ada_parse_state::invalid_char ()
 {
-  pstate->lexptr -= ada_yyleng;
-  while (c_toupper (*pstate->lexptr) != c_toupper (ch))
-    pstate->lexptr -= 1;
-  ada_yyrestart (NULL);
+  error (_("Invalid character '%s' in expression."), pstate->lexptr);
+}
+
+const char *
+ada_parse_state::lex_simple_identifier (const char *text)
+{
+  gdb_assert (c_isalpha (*text) || *text == '_' || *text == '<');
+
+  const char *iter = text;
+  bool quoted = (*iter == '<');
+  if (quoted)
+    {
+      ++iter;
+      if (!c_isalpha (*iter) && *iter != '_')
+	return nullptr;
+      ++iter;
+    }
+
+  auto as_unsigned = [] (const char *ptr)
+    {
+      return *(const unsigned char *) ptr;
+    };
+
+  while (c_isalnum (*iter) || *iter == '_'
+	 || (!quoted && as_unsigned (iter) >= 0x80
+	     && as_unsigned (iter) <= 0xff))
+    ++iter;
+
+  if (quoted)
+    {
+      /* A quirk of the flex lexer was that completion didn't work for
+	 Ada-quoted symbols like <some_encoded_name>.  Perhaps TAB
+	 somewhere before the '>' ought to work.  */
+      if (*iter != '>')
+	return nullptr;
+      ++iter;
+    }
+
+  return iter;
+}
+
+int
+ada_parse_state::lex_dot ()
+{
+  gdb_assert (*pstate->lexptr == '.');
+  const char *save = pstate->lexptr;
+  pstate->lexptr = skip_spaces (pstate->lexptr + 1);
+
+  int name_token = 0;
+  if (*pstate->lexptr == '<' || *pstate->lexptr == '_'
+      || c_isalpha (*pstate->lexptr))
+    {
+      const char *id_end = lex_simple_identifier (pstate->lexptr);
+      if (id_end != nullptr)
+	{
+	  pstate->lexptr = id_end;
+	  name_token = NAME;
+	}
+    }
+
+  if (*pstate->lexptr == '\0' && pstate->parse_completion)
+    name_token = NAME_COMPLETE;
+
+  if (name_token != NAME && name_token != NAME_COMPLETE)
+    {
+      pstate->lexptr = save;
+      invalid_char ();
+    }
+
+  ada_yylval.sval = processId (save + 1, pstate->lexptr - save - 1);
+  return name_token == NAME_COMPLETE ? DOT_COMPLETE : DOT_ID;
 }
 
+const char *
+ada_parse_state::recognize_encoded_char (const char *bracket)
+{
+  if (bracket[0] == '[' && bracket[1] == '"')
+    {
+      const char *start = bracket + 2;
+      const char *iter = start;
+
+      /* Handle the weird case of ["""], which just means a double
+	 quote.  */
+      if (*iter == '"')
+	++iter;
+      else
+	{
+	  while (c_isxdigit (*iter))
+	    ++iter;
+	  if (iter - start < 2)
+	    return nullptr;
+	}
+
+      if (iter[0] == '"' && iter[1] == ']')
+	{
+	  /* Ada-style quoted character.  */
+	  return iter + 2;
+	}
+    }
+  return nullptr;
+}
+
+int
+ada_parse_state::lex_single_quote ()
+{
+  gdb_assert (*pstate->lexptr == '\'');
+
+  bool before_qual_quote = m_before_qual_quote;
+  m_before_qual_quote = false;
+
+  if (!before_qual_quote)
+    {
+      /* Look for the GDB block extension "'STUFF'::".  */
+      const char *block_iter = pstate->lexptr + 1;
+      while (*block_iter != '\0' && *block_iter != '\'')
+	++block_iter;
+      /* Require a non-empty block.  */
+      if (block_iter[0] == '\'' && block_iter - pstate->lexptr - 1 > 0)
+	{
+	  const char *block_end = skip_spaces (block_iter + 1);
+	  if (block_end[0] == ':' && block_end[1] == ':')
+	    {
+	      ada_yylval.sval = processId (pstate->lexptr,
+					   block_end - pstate->lexptr);
+	      /* Leave the "::" to be lexed later.  */
+	      pstate->lexptr = block_end;
+	      return NAME;
+	    }
+	}
+
+      if (c_isprint (pstate->lexptr[1]) && pstate->lexptr[2] == '\'')
+	{
+	  /* Ordinary character literal.  */
+	  int the_char = pstate->lexptr[1];
+	  ada_yylval.typed_char.val = the_char;
+	  ada_yylval.typed_char.type = type_for_char (pstate, the_char);
+	  pstate->lexptr += 3;
+	  return CHARLIT;
+	}
+
+      const char *end_bracket = recognize_encoded_char (pstate->lexptr + 1);
+      if (end_bracket != nullptr)
+	{
+	  /* The character starts at an offset from the initial single
+	     quote.  */
+	  ULONGEST v = strtoulst (pstate->lexptr + 3, nullptr, 16);
+	  ada_yylval.typed_char.val = v;
+	  ada_yylval.typed_char.type = type_for_char (pstate, v);
+	  pstate->lexptr = end_bracket + 1;
+	  return CHARLIT;
+	}
+    }
+
+  /* Handle 'ATTRIBUTE; with a special case when completing just after
+     a single quote.  */
+  const char *attr_start = skip_spaces (pstate->lexptr + 1);
+  if (c_isalpha (*attr_start)
+      || (pstate->parse_completion && *attr_start == '\0'))
+    {
+      const char *iter = attr_start;
+      while (*iter == '_' || c_isalpha (*iter))
+	++iter;
+      bool completing = pstate->parse_completion && *iter == '\0';
+      pstate->lexptr = iter;
+      return process_attribute (std::string (attr_start, iter - attr_start),
+				completing);
+    }
+
+  ++pstate->lexptr;
+  return '\'';
+}
+
+int
+ada_parse_state::lex_double_quote ()
+{
+  gdb_assert (*pstate->lexptr == '"');
+  const char *start = pstate->lexptr + 1;
+
+  const char *iter = start;
+  while (*iter != '"' && *iter != '\0')
+    {
+      /* Note that we don't handle bracket sequences of more than 2
+	 digits here.  Currently there's no support for wide or
+	 wide-wide strings.  */
+      const char *end_bracket = recognize_encoded_char (iter);
+      if (end_bracket != nullptr)
+	iter = end_bracket;
+      else if (c_isprint (*iter))
+	++iter;
+      else
+	break;
+    }
+
+  if (*iter != '"')
+    error (_("ill-formed or non-terminated string literal"));
+
+  ada_yylval.sval = processString (start, iter - start);
+  pstate->lexptr = iter + 1;
+  return STRING;
+}
+
+int
+ada_parse_state::lex_dollar ()
+{
+  gdb_assert (*pstate->lexptr == '$');
+  const char *start = pstate->lexptr++;
+  while (c_isalnum (*pstate->lexptr) || *pstate->lexptr == '_'
+	 || *pstate->lexptr == '$')
+    ++pstate->lexptr;
+  ada_yylval.sval.ptr = start;
+  ada_yylval.sval.length = pstate->lexptr - start;
+  return DOLLAR_VARIABLE;
+}
+
+static const code_entry punct[] =
+{
+  { "=>", ARROW },
+  { "..", DOTDOT },
+  { "**", STARSTAR },
+  { ":=", ASSIGN },
+  { "/=", NOTEQUAL },
+  { "<=", LEQ },
+  { ">=", GEQ },
+  { "::", COLONCOLON },
+  /* "--" is documented in the manual as being a comment.  */
+  { "--", 0 },
+};
+
+int
+ada_parse_state::lex ()
+{
+  /* If m_before_qual_quote is set, we must be examining a single
+     quote.  */
+  gdb_assert (!m_before_qual_quote || *pstate->lexptr == '\'');
+
+  pstate->lexptr = skip_spaces (pstate->lexptr);
+
+  if (pstate->lexptr[0] != '\0' && pstate->lexptr[1] != '\0')
+    for (const code_entry &entry : punct)
+      {
+	size_t len = strlen (entry.name);
+	gdb_assert (len == 2);
+	if (strncmp (entry.name, pstate->lexptr, len) == 0)
+	  {
+	    /* Handle the "--" comment case specially.  */
+	    if (entry.code == 0)
+	      {
+		size_t rest = strlen (pstate->lexptr);
+		pstate->lexptr += rest;
+	      }
+	    else
+	      pstate->lexptr += len;
+	    return entry.code;
+	  }
+      }
+
+  switch (*pstate->lexptr)
+    {
+    case '\0':
+      return 0;
+
+    case '-':
+    case '=':
+    case '*':
+    case ':':
+    case '&':
+    case '+':
+    case '{':
+    case '}':
+    case '@':
+    case '/':
+    case '>':
+    case '|':
+    case ';':
+    case '[':
+    case ']':
+      return *pstate->lexptr++;
+
+    case ',':
+      if (m_paren_depth == 0 && pstate->comma_terminates)
+	return 0;
+      else
+	return *pstate->lexptr++;
+
+    case '(':
+      ++m_paren_depth;
+      return *pstate->lexptr++;
+
+    case ')':
+      if (m_paren_depth == 0)
+	return 0;
+      --m_paren_depth;
+      return *pstate->lexptr++;
+
+    case '\'':
+      return lex_single_quote ();
+
+    case '"':
+      return lex_double_quote ();
+
+    case '$':
+      return lex_dollar ();
+
+    case '.':
+      return lex_dot ();
+    }
+
+  if (c_isalpha (*pstate->lexptr) || *pstate->lexptr == '_'
+      || *pstate->lexptr == '<')
+    {
+      const char *id_end = lex_simple_identifier (pstate->lexptr);
+      if (id_end == nullptr)
+	{
+	  /* It shouldn't be possible to reach here when starting with
+	     a letter or underscore.  */
+	  gdb_assert (*pstate->lexptr == '<');
+	  return *pstate->lexptr++;
+	}
+      return lex_identifier (id_end);
+    }
+
+  if (c_isdigit (*pstate->lexptr))
+    return lex_number ();
+
+  invalid_char ();
+}
+
+#if GDB_SELF_TEST
+
+namespace selftests
+{
+
+/* Helper that checks that a given lex causes an exception.  */
+static void
+ada_lex_test_error (const char *input)
+{
+  /* We need a dummy parser.  */
+  parser_state ps (language_def (language_ada), current_inferior ()->arch (),
+		   nullptr, 0, 0, input, false, nullptr);
+  scoped_restore save_parser = make_scoped_restore (&pstate, &ps);
+
+  ada_parse_state ada_ps (input);
+  /* This is probably not needed, but also it doesn't hurt.  */
+  scoped_restore save_aps = make_scoped_restore (&ada_parser, &ada_ps);
+
+  bool saw_failure = false;
+  try
+    {
+      ada_ps.lex ();
+    }
+  catch (const gdb_exception_error &err)
+    {
+      saw_failure = true;
+    }
+  SELF_CHECK (saw_failure);
+}
+
+/* Helper to check a lexing sequence, also checking string values of
+   tokens.  */
+static void
+ada_lex_test_sequence (const char *input, gdb::array_view<int> expected,
+		       std::optional<gdb::array_view<const char *>> strings,
+		       bool completion = false)
+{
+  gdb_assert (!strings.has_value () || expected.size () == strings->size ());
+
+  /* We need a dummy parser.  */
+  parser_state ps (language_def (language_ada), current_inferior ()->arch (),
+		   nullptr, 0, 0, input, completion, nullptr);
+  scoped_restore save_parser = make_scoped_restore (&pstate, &ps);
+
+  ada_parse_state ada_ps (input);
+  /* This is probably not needed, but also it doesn't hurt.  */
+  scoped_restore save_aps = make_scoped_restore (&ada_parser, &ada_ps);
+  for (int i = 0; i < expected.size (); ++i)
+    {
+      int token = ada_ps.lex ();
+      SELF_CHECK (token == expected[i]);
+
+      if (strings.has_value ())
+	{
+	  bool has_string_value = (token == NAME || token == NAME_COMPLETE
+				   || token == DOT_ID || token == DOT_COMPLETE
+				   || token == STRING
+				   || token == DOLLAR_VARIABLE
+				   || token == TICK_COMPLETE);
+	  if (has_string_value)
+	    {
+	      std::string_view contents (ada_yylval.sval.ptr,
+					 ada_yylval.sval.length);
+	      SELF_CHECK (contents == (*strings)[i]);
+	    }
+	  else
+	    SELF_CHECK ((*strings)[i] == nullptr);
+	}
+    }
+
+  /* Test that all the input was used.  */
+  SELF_CHECK (*ps.lexptr == '\0');
+}
+
+/* Helper that checks an integer value.  */
+static void
+ada_lex_test_integer (const char *input, int value)
+{
+  /* We need a dummy parser.  */
+  parser_state ps (language_def (language_ada), current_inferior ()->arch (),
+		   nullptr, 0, 0, input, false, nullptr);
+  scoped_restore save_parser = make_scoped_restore (&pstate, &ps);
+
+  ada_parse_state ada_ps (input);
+  /* This is probably not needed, but also it doesn't hurt.  */
+  scoped_restore save_aps = make_scoped_restore (&ada_parser, &ada_ps);
+
+  int token = ada_ps.lex ();
+  SELF_CHECK (token == INT);
+  SELF_CHECK (*ada_yylval.typed_val.val == value);
+}
+
+static void
+ada_lex_tests ()
+{
+  std::array cc_test { NAME, COLONCOLON, NAME, 0 };
+  std::array<const char *, 4> cc_text { "blockname", nullptr,
+					"duck", nullptr };
+  ada_lex_test_sequence ("blockname::duck", cc_test, cc_text);
+
+  std::array<const char *, 4> ccq_text { "'blockname'", nullptr,
+					 "duck", nullptr };
+  ada_lex_test_sequence ("'blockname'::duck", cc_test, ccq_text);
+  ada_lex_test_sequence ("'blockname'  ::  duck", cc_test, ccq_text);
+
+  /* This should not lex as a character literal.  */
+  std::array<const char *, 4> ccq2_text { "'a'", nullptr,
+					  "duck", nullptr };
+  ada_lex_test_sequence ("'a'::duck", cc_test, ccq2_text);
+
+  std::array comment_test { NAME, 0 };
+  std::array<const char *, 2> comment_text { "variable", nullptr };
+  ada_lex_test_sequence ("variable -- comment text here",
+			 comment_test, comment_text);
+
+  std::array oper_test { NAME, 0 };
+  std::array<const char *, 2> oper_text { "name.\"mod\"", nullptr };
+  ada_lex_test_sequence ("   name . \"MoD\"   ", oper_test, oper_text);
+
+  std::array quote_test { NAME, DOT_ID, DOT_ID, 0 };
+  std::array<const char *, 4> quote_text { "<some__Weird_Name>.whatever",
+					   "all", "rest", nullptr };
+  ada_lex_test_sequence ("<some__Weird_Name>.whatever.all.rest",
+			 quote_test, quote_text);
+
+  std::array uquote_test { NAME, 0 };
+  std::array<const char *, 2> uquote_text { "<__leading_uscore>", nullptr };
+  ada_lex_test_sequence ("<__leading_uscore>", uquote_test, uquote_text);
+
+  std::array<int, 6> qual_test { NAME, '\'', '(', CHARLIT, ')', 0 };
+  ada_lex_test_sequence ("  Char_Enum ' ( 'B' )  ", qual_test, {});
+
+  /* This failed historically since the TAB character is not
+     "printable".  */
+  ada_lex_test_error ("\"\t\"");
+
+  std::array char_test { CHARLIT, 0 };
+  ada_lex_test_sequence ("'[\"61\"]'", char_test, {});
+  ada_lex_test_sequence ("'\"'", char_test, {});
+  ada_lex_test_sequence ("' '", char_test, {});
+
+  std::array str_test { STRING, 0 };
+  std::array<const char *, 2> str_text { "a string \"", nullptr };
+  ada_lex_test_sequence ("\"[\"61\"] string [\"\"\"]\"", str_test, str_text);
+
+  std::array compl_test { NAME, TICK_COMPLETE, 0 };
+  std::array<const char *, 3> compl_text { "duck.duck", "goose", nullptr };
+  ada_lex_test_sequence ("duck.duck'goose", compl_test, compl_text, true);
+
+  std::array tick_test { NAME, TICK_MIN, 0 };
+  std::array<const char *, 3> tick_text { "duck.duck", nullptr, nullptr };
+  ada_lex_test_sequence ("duck.duck  '  min", tick_test, tick_text);
+
+  ada_lex_test_integer ("0xff", 255);
+  ada_lex_test_integer ("0xffff", 65535);
+  ada_lex_test_integer ("019", 19);
+  ada_lex_test_integer ("0", 0);
+  ada_lex_test_integer ("16#ff#", 255);
+  ada_lex_test_integer ("16#ee#", 238);
+  ada_lex_test_integer ("16#EE#", 238);
+  ada_lex_test_integer ("8#77#", 63);
+
+  /* Based reals aren't handled.  */
+  ada_lex_test_error ("16#abcd.ef01#");
+  ada_lex_test_error ("16#abcd.ef01#e+23");
+}
+
+} /* namespace selftests */
+
+#endif /* GDB_SELF_TEST */
+
 /* See ada-exp-parser.h.  */
 
 operation_up
@@ -1337,8 +2050,6 @@  ada_parse (struct parser_state *par_state)
   scoped_restore restore_yydebug = make_scoped_restore (&ada_yydebug,
 							par_state->debug);
 
-  lexer_init (ada_yyin);		/* (Re-)initialize lexer.  */
-
   int result = ada_yyparse ();
   if (!result)
     {
@@ -1349,3 +2060,19 @@  ada_parse (struct parser_state *par_state)
     }
   return result;
 }
+
+INIT_GDB_FILE (ada_exp_parser)
+{
+  int code = regcomp (&number_regex, number_regex_text,
+		      REG_EXTENDED | REG_ICASE);
+  /* If the regular expression was incorrect, it was a programming
+     error.  */
+  gdb_assert (code == 0);
+  code = regcomp (&operator_regex, operator_regex_text,
+		  REG_EXTENDED | REG_ICASE);
+  gdb_assert (code == 0);
+
+#if GDB_SELF_TEST
+  selftests::register_test ("ada-lex", ada_exp_parser::selftests::ada_lex_tests);
+#endif
+}
diff --git a/gdb/ada-exp-parser.h b/gdb/ada-exp-parser.h
index 09a716e6636..48bc9e7fb72 100644
--- a/gdb/ada-exp-parser.h
+++ b/gdb/ada-exp-parser.h
@@ -23,9 +23,6 @@ 
 #include "ada-exp.h"
 #include "parser-defs.h"
 
-/* The character we use to represent the completion point.  */
-constexpr char COMPLETE_CHAR = '\001';
-
 namespace ada_exp_parser
 {
 
@@ -64,18 +61,69 @@  struct ada_parse_state
 
   auto_obstack temp_space;
 
-  /* Depth of parentheses, used by the lexer.  */
-  int paren_depth = 0;
-
-  /* When completing, we'll return a special character at the end of the
-     input, to signal the completion position to the lexer.  This is
-     done because flex does not have a generally useful way to detect
-     EOF in a pattern.  This variable records whether the special
-     character has been emitted.  */
-  bool returned_complete = false;
+  /* Lex a single token.  ada_yylval is updated if needed.  The token
+     value is returned.  The lexer state in this object or in the
+     parser_state object will be updated as appropriate.  */
+  int lex ();
 
 private:
 
+  /* A lexer helper function to lex a number.  */
+  int lex_number ();
+
+  /* A lexer helper function to lex a dollar variable like $x or
+     $$.  */
+  int lex_dollar ();
+
+  /* A lexer helper that is called when a '.' is seen.  */
+  int lex_dot ();
+
+  /* A lexer helper that is called when a single quote is seen.  */
+  int lex_single_quote ();
+
+  /* A lexer helper for lexing a string.  */
+  int lex_double_quote ();
+
+  /* A helper function that examines TEXT.  If TEXT looks like a
+     simple identifier, a pointer to the character past the end of the
+     identifier is returned.  Otherwise, nullptr is returned.  */
+  const char *lex_simple_identifier (const char *text);
+
+  /* A helper that does some extra checking for the "thread"
+     pseudo-keyword.  It returns true if this instance of "thread"
+     should be reported as an EOF rather than an identifier.  TEXT
+     points to just past the end of the "thread" keyword.  */
+  bool check_thread_keyword (const char *text);
+
+  /* Check whether the current token, held at pstate->lexptr with
+     length LEN, is a keyword.  Returns the token value if so; returns
+     nullopt if not.  */
+  std::optional<int> check_keyword (size_t len);
+
+  /* Check whether BRACKET holds text matching a hex character as
+     would be seen in an Ada string or character literal.  If so,
+     returns a pointer to the character just past the end of the form;
+     otherwise returns nullptr.  */
+  const char *recognize_encoded_char (const char *bracket);
+
+  /* A lexer helper for lexing an identifier.  */
+  int lex_identifier (const char *id_end);
+
+  /* A helper that examines START.  If this is a quoted operator name
+     (like "mod" or "+"), returns a pointer to just after the final
+     quote.  Otherwise, returns nullptr.  */
+  const char *lex_operator (const char *start);
+
+  /* Return the syntactic code corresponding to the attribute name or
+     abbreviation STR.  COMPLETING should be true if the name was
+     lexed at the end of the input and completion is enabled for this
+     parse.  */
+  int process_attribute (const std::string &str, bool completing);
+
+  /* Throw an exception when lexing, indicating that an invalid
+     character was seen.  */
+  [[noreturn]] void invalid_char ();
+
   /* We don't have a good way to manage non-POD data in Yacc, so store
      values here.  The storage here is only valid for the duration of
      the parse.  */
@@ -83,6 +131,15 @@  struct ada_parse_state
 
   /* The original expression string.  */
   const char *m_original_expr;
+
+  /* Depth of parentheses, used by the lexer.  */
+  int m_paren_depth = 0;
+
+  /* This holds some state needed when lexing a single quote.
+     Normally, a single quote will introduce a character literal.
+     However, after an identifier, it will not, to support cases like
+     Char_Enum_Type'('B'); see char_enum.exp for examples.  */
+  bool m_before_qual_quote = false;
 };
 
 /* Expression completer for attributes.  */
@@ -110,17 +167,6 @@  extern struct parser_state *pstate;
 
 extern struct ada_parse_state *ada_parser;
 
-/* Initialize the lexer for processing new expression.
-
-   This function is implemented in ada-lex.l, because it needs to see some
-   macros in ada-lex-gen.c.  */
-
-void lexer_init (FILE *inp);
-
-/* Copy S2 to S1, removing all underscores, and downcasing all letters.  */
-
-void canonicalizeNumeral (char *s1, const char *s2);
-
 /* Return TEXT[0..LEN-1], a string literal without surrounding quotes,
    with special hex character notations replaced with characters.
    Result valid until the next call to ada_parse.  */
@@ -160,30 +206,6 @@  int processReal (struct parser_state *par_state, const char *num0);
 
 stoken processId (const char *name0, int len);
 
-/* Return the syntactic code corresponding to the attribute name or
-   abbreviation STR.  */
-
-int processAttribute (const char *str);
-
-/* Returns the position within STR of the '.' in a
-   '.{WHITE}*all' component of a dotted name, or -1 if there is none.
-   Note: we actually don't need this routine, since 'all' can never be an
-   Ada identifier.  Thus, looking up foo.all or foo.all.x as a name
-   must fail, and will eventually be interpreted as (foo).all or
-   (foo).all.x.  However, this does avoid an extraneous lookup. */
-
-int find_dot_all (const char *str);
-
-/* Back up lexptr by yyleng and then to the rightmost occurrence of
-   character CH, case-folded (there must be one).  WARNING: since
-   lexptr points to the next input character that Flex has not yet
-   transferred to its internal buffer, the use of this function
-   depends on the assumption that Flex calls YY_INPUT only when it is
-   logically necessary to do so (thus, there is no reading ahead
-   farther than needed to identify the next token.)  */
-
-void rewind_to_char (int ch);
-
 /* Like parser_state::pop, but handles Ada type resolution.
    DEPROCEDURE_P and CONTEXT_TYPE are passed to the resolve method, if
    called.  */
diff --git a/gdb/ada-exp-parser.y b/gdb/ada-exp-parser.y
index d37ab12c3bc..f5ceb7d390a 100644
--- a/gdb/ada-exp-parser.y
+++ b/gdb/ada-exp-parser.y
@@ -50,7 +50,11 @@ 
 using namespace expr;
 using namespace ada_exp_parser;
 
-static int yylex (void);
+static inline int
+yylex ()
+{
+  return ada_parser->lex ();
+}
 
 %}
 
@@ -834,8 +838,3 @@  primary	:	'*' primary		%prec '.'
 	;
 
 %%
-
-/* yylex defined in ada-lex-gen.c: Reads one token, getting characters */
-/* through lexptr.  */
-
-#include "ada-lex-gen.c"
diff --git a/gdb/ada-lex.l b/gdb/ada-lex.l
deleted file mode 100644
index 857176c4d83..00000000000
--- a/gdb/ada-lex.l
+++ /dev/null
@@ -1,346 +0,0 @@ 
-/* FLEX lexer for Ada expressions, for GDB. -*- c++ -*-
-   Copyright (C) 1994-2026 Free Software Foundation, Inc.
-
-   This file is part of GDB.
-
-   This program is free software; you can redistribute it and/or modify
-   it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 3 of the License, or
-   (at your option) any later version.
-
-   This program is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-   GNU General Public License for more details.
-
-   You should have received a copy of the GNU General Public License
-   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
-
-/*----------------------------------------------------------------------*/
-
-/* The converted version of this file is to be included in ada-exp-parser.y, */
-/* the Ada parser for gdb.  The function yylex obtains characters from */
-/* the global pointer lexptr.  It returns a syntactic category for */
-/* each successive token and places a semantic value into yylval */
-/* (ada-lval), defined by the parser.   */
-
-DIG	[0-9]
-NUM10	({DIG}({DIG}|_)*)
-HEXDIG	[0-9a-f]
-NUM16	({HEXDIG}({HEXDIG}|_)*)
-OCTDIG	[0-7]
-LETTER	[a-z_]
-ID	({LETTER}({LETTER}|{DIG}|[\x80-\xff])*|"<"{LETTER}({LETTER}|{DIG})*">")
-WHITE	[ \t\n]
-TICK	("'"{WHITE}*)
-GRAPHIC [a-z0-9 #&'()*+,-./:;<>=_|!$%?@\[\]\\^`{}~]
-OPER    ([-+*/=<>&]|"<="|">="|"**"|"/="|"and"|"or"|"xor"|"not"|"mod"|"rem"|"abs")
-
-EXP	(e[+-]{NUM10})
-POSEXP  (e"+"?{NUM10})
-
-/* This must agree with COMPLETE_CHAR in ada-exp-parser.h.  See the
-   comment on ada_parse_state::returned_complete for the explanation.  */
-COMPLETE "\001"
-NOT_COMPLETE [^\001]
-
-%{
-
-#include "diagnostics.h"
-
-/* Some old versions of flex (2.5.x) generate code that uses the "register"
-   keyword, which compilers warn about, because it is not allowed in ISO
-   C++17.  */
-DIAGNOSTIC_PUSH
-DIAGNOSTIC_IGNORE_REGISTER
-
-#define NUMERAL_WIDTH 256
-#define LONGEST_SIGN ((ULONGEST) 1 << (sizeof(LONGEST) * HOST_CHAR_BIT - 1))
-
-#undef YY_DECL
-#define YY_DECL static int yylex ( void )
-
-/* Flex generates a static function "input" which is not used.
-   Defining YY_NO_INPUT comments it out.  */
-#define YY_NO_INPUT
-
-#undef YY_INPUT
-#define YY_INPUT(BUF, RESULT, MAX_SIZE)					\
-  if ( *pstate->lexptr == '\000' )					\
-    {									\
-      if (pstate->parse_completion && !ada_parser->returned_complete)	\
-	{								\
-	  ada_parser->returned_complete = true;				\
-	  *(BUF) = COMPLETE_CHAR;					\
-	  (RESULT) = 1;							\
-	}								\
-      else								\
-	(RESULT) = YY_NULL;						\
-    }									\
-  else									\
-    {									\
-      *(BUF) = *pstate->lexptr == COMPLETE_CHAR ? ' ' : *pstate->lexptr; \
-      (RESULT) = 1;							\
-      pstate->lexptr += 1;						\
-    }
-
-%}
-
-%option case-insensitive interactive nodefault noyywrap
-
-%s BEFORE_QUAL_QUOTE
-
-%%
-
-{WHITE}		 { }
-
-"--".*		 { yyterminate(); }
-
-{NUM10}{POSEXP}  {
-		   char numbuf[NUMERAL_WIDTH];
-		   canonicalizeNumeral (numbuf, yytext);
-		   char *e_ptr = strrchr (numbuf, 'e');
-		   *e_ptr = '\0';
-		   return processInt (pstate, nullptr, numbuf, e_ptr + 1);
-		 }
-
-{NUM10}          {
-		   char numbuf[NUMERAL_WIDTH];
-		   canonicalizeNumeral (numbuf, yytext);
-		   return processInt (pstate, NULL, numbuf, NULL);
-		 }
-
-{NUM10}"#"{HEXDIG}({HEXDIG}|_)*"#"{POSEXP} {
-		   char numbuf[NUMERAL_WIDTH];
-		   canonicalizeNumeral (numbuf, yytext);
-		   char *e_ptr = strrchr (numbuf, 'e');
-		   *e_ptr = '\0';
-		   return processInt (pstate, numbuf,
-				      strchr (numbuf, '#') + 1,
-				      e_ptr + 1);
-		 }
-
-	/* The "llf" is a gdb extension to allow a floating-point
-	   constant to be written in some other base.  The
-	   floating-point number is formed by reinterpreting the
-	   bytes, allowing direct control over the bits.  */
-{NUM10}(l{0,2}f)?"#"{HEXDIG}({HEXDIG}|_)*"#" {
-		   char numbuf[NUMERAL_WIDTH];
-		   canonicalizeNumeral (numbuf, yytext);
-		   return processInt (pstate, numbuf, strchr (numbuf, '#') + 1,
-				      NULL);
-		 }
-
-"0x"{HEXDIG}+	{
-		  char numbuf[NUMERAL_WIDTH];
-		  canonicalizeNumeral (numbuf, yytext+2);
-		  return processInt (pstate, "16#", numbuf, NULL);
-		}
-
-
-{NUM10}"."{NUM10}{EXP} {
-		   char numbuf[NUMERAL_WIDTH];
-		   canonicalizeNumeral (numbuf, yytext);
-		   return processReal (pstate, numbuf);
-		}
-
-{NUM10}"."{NUM10} {
-		   char numbuf[NUMERAL_WIDTH];
-		   canonicalizeNumeral (numbuf, yytext);
-		   return processReal (pstate, numbuf);
-		}
-
-{NUM10}"#"{NUM16}"."{NUM16}"#"{EXP} {
-		   error (_("Based real literals not implemented yet."));
-		}
-
-{NUM10}"#"{NUM16}"."{NUM16}"#" {
-		   error (_("Based real literals not implemented yet."));
-		}
-
-<INITIAL>"'"({GRAPHIC}|\")"'" {
-		   yylval.typed_char.val = yytext[1];
-		   yylval.typed_char.type = type_for_char (pstate, yytext[1]);
-		   return CHARLIT;
-		}
-
-<INITIAL>"'[\""{HEXDIG}{2,}"\"]'"   {
-		   ULONGEST v = strtoulst (yytext+3, nullptr, 16);
-		   yylval.typed_char.val = v;
-		   yylval.typed_char.type = type_for_char (pstate, v);
-		   return CHARLIT;
-		}
-
-	/* Note that we don't handle bracket sequences of more than 2
-	   digits here.  Currently there's no support for wide or
-	   wide-wide strings.  */
-\"({GRAPHIC}|"[\""({HEXDIG}{2,}|\")"\"]")*\"   {
-		   yylval.sval = processString (yytext+1, yyleng-2);
-		   return STRING;
-		}
-
-\"              {
-		   error (_("ill-formed or non-terminated string literal"));
-		}
-
-
-if		{
-		  rewind_to_char ('i');
-		  return 0;
-		}
-
-task            {
-		  rewind_to_char ('t');
-		  return 0;
-		}
-
-thread{WHITE}+{DIG} {
-		  /* This keyword signals the end of the expression and
-		     will be processed separately.  */
-		  rewind_to_char ('t');
-		  return 0;
-		}
-
-	/* ADA KEYWORDS */
-
-abs		{ return ABS; }
-and		{ return _AND_; }
-delta		{ return DELTA; }
-else		{ return ELSE; }
-for		{ return FOR; }
-in		{ return IN; }
-mod		{ return MOD; }
-new		{ return NEW; }
-not		{ return NOT; }
-null		{ return NULL_PTR; }
-or		{ return OR; }
-others          { return OTHERS; }
-rem		{ return REM; }
-then		{ return THEN; }
-with		{ return WITH; }
-xor		{ return XOR; }
-
-	/* BOOLEAN "KEYWORDS" */
-
- /* True and False are not keywords in Ada, but rather enumeration constants.
-    However, the boolean type is no longer represented as an enum, so True
-    and False are no longer defined in symbol tables.  We compromise by
-    making them keywords (when bare). */
-
-true		{ return TRUEKEYWORD; }
-false		{ return FALSEKEYWORD; }
-
-	/* ATTRIBUTES */
-
-{TICK}([a-z][a-z_]*)?{COMPLETE}? { BEGIN INITIAL; return processAttribute (yytext); }
-
-	/* PUNCTUATION */
-
-"=>"		{ return ARROW; }
-".."		{ return DOTDOT; }
-"**"		{ return STARSTAR; }
-":="		{ return ASSIGN; }
-"/="		{ return NOTEQUAL; }
-"<="		{ return LEQ; }
-">="		{ return GEQ; }
-
-<BEFORE_QUAL_QUOTE>"'"/{NOT_COMPLETE} { BEGIN INITIAL; return '\''; }
-
-[-&*+{}@/:<>=|;\[\]] { return yytext[0]; }
-
-","		{ if (ada_parser->paren_depth == 0 && pstate->comma_terminates)
-		    {
-		      rewind_to_char (',');
-		      return 0;
-		    }
-		  else
-		    return ',';
-		}
-
-"("		{ ada_parser->paren_depth += 1; return '('; }
-")"		{ if (ada_parser->paren_depth == 0)
-		    {
-		      rewind_to_char (')');
-		      return 0;
-		    }
-		  else
-		    {
-		      ada_parser->paren_depth -= 1;
-		      return ')';
-		    }
-		}
-
-"."{WHITE}*{ID}{COMPLETE}? {
-		  yylval.sval = processId (yytext+1, yyleng-1);
-		  if (yytext[yyleng - 1] == COMPLETE_CHAR)
-		    return DOT_COMPLETE;
-		  return DOT_ID;
-		}
-
-"."{WHITE}*{COMPLETE} {
-		  yylval.sval.ptr = "";
-		  yylval.sval.length = 0;
-		  return DOT_COMPLETE;
-		}
-
-{ID}({WHITE}*"."{WHITE}*({ID}|\"{OPER}\"))*(" "*"'"|{COMPLETE})?  {
-		  int all_posn = find_dot_all (yytext);
-
-		  if (all_posn == -1 && yytext[yyleng-1] == '\'')
-		    {
-		      BEGIN BEFORE_QUAL_QUOTE;
-		      yyless (yyleng-1);
-		    }
-		  else if (all_posn >= 0)
-		    yyless (all_posn);
-		  bool is_completion = yytext[yyleng - 1] == COMPLETE_CHAR;
-		  yylval.sval = processId (yytext, yyleng);
-		  return is_completion ? NAME_COMPLETE : NAME;
-	       }
-
-
-	/* GDB EXPRESSION CONSTRUCTS  */
-
-"'"[^']+"'"{WHITE}*:: {
-		  yyless (yyleng - 2);
-		  yylval.sval = processId (yytext, yyleng);
-		  return NAME;
-		}
-
-"::"            { return COLONCOLON; }
-
-	/* REGISTERS AND GDB CONVENIENCE VARIABLES */
-
-"$"({LETTER}|{DIG}|"$")*  {
-		  yylval.sval.ptr = yytext;
-		  yylval.sval.length = yyleng;
-		  return DOLLAR_VARIABLE;
-		}
-
-	/* CATCH-ALL ERROR CASE */
-
-.		{ error (_("Invalid character '%s' in expression."), yytext); }
-%%
-
-namespace ada_exp_parser
-{
-
-/* See ada-exp-parser.h.  */
-
-void
-lexer_init (FILE *inp)
-{
-  BEGIN INITIAL;
-  yyrestart (inp);
-}
-
-} /* namespace ada_exp_parser */
-
-/* Dummy definition to suppress warnings about unused static definitions. */
-typedef void (*dummy_function) ();
-dummy_function ada_flex_use[] =
-{
-  (dummy_function) yyunput
-};
-
-DIAGNOSTIC_POP