Subject: bug#62412: 29.0.60; strange c++ indentation behavior with tree sitter

From: Daniel Martín <[email-masked]>
Date: Sun, 26 Mar 2023 15:25:15 +0200

Theodor Thornhill <[email-masked]> writes:

> I'll look more deeply into the cause of this, but the rule is covering some preproc directives iirc.
>
> Unfortunately tree-sitter behaves better when auto pairs is used. I
> would advise people to use electric-pairs-mode (if that's the correct
> name, on mobile now) to avoid these sorts of issues.
>

Yes, I think that having an error node in the indentation rules is not a
good idea.  It can cause unexpected issues like the one described in
this thread.  I'd explore the idea of removing error nodes from the
rules before resorting to tweak the electric or pairing features of
Emacs.

Let's look into the problem that the introduction of the error node
tried to solve, the indentation of preprocessor directives.  Starting
with this code:

int
main()
{
  |
}

if I type '#', automatic indentation does not happen because, at that
stage, the AST doesn't recognize the full preprocessor directive (the
node in the AST is an error node).  If I continue writing the
preprocessor directive (say, "#ifdef DEBUG"), the preprocessor node is
created correctly, but it would require a manual TAB to go to column 0
because we haven't inserted any electric character while we completed
the directive.  The same manual TAB is required by c++-mode, so I
wouldn't see this as a regression.

However, there might be still minor divergences between c++-mode and
c++-ts-mode.  For example:

int
main()
{
#if
}

This in-progress code would indent correctly in c++-mode, but on
c-ts-mode the node is an error node, so we won't reliably know that it
should indent to column 0.  If we want to fix these minor divergences, I
see two possible approaches:

- Investigate if the C/C++ grammars can be improved to cover these cases
  better.

- Without changing the grammars, could we insert our own preprocessor
  nodes in the AST tree by checking if the first non-whitespace
  character of the line is the beginning of #assert, #define, #include,
  #if, #ifndef, #elif, etc.?