Subject: bug#75406: 31.0.50; [PATCH] csharp-ts-mode does not highlight type in typeof() expressions

From: Yuan Fu <[email-masked]>
Date: Tue, 7 Jan 2025 22:14:28 -0800

> On Jan 6, 2025, at 6:12 AM, Jostein Kjønigsen <[email-masked]> wrote:
> 
> Hey everyone.
> 
> When using csharp-ts-mode to edit C# files, you may encounter the use of the typeof() operator in typeof()-expressions. The typeof() operater has 1 required parameter, which is always a type-name.
> 
>     public class Gnu
>     {
>         public void Demo()
>         {
>             var type = typeof(IQueryable);
>         }
>     }
> 
> This type parameter should be fontified using font-lock-type-face. Currently it is not.
> 
> There are explicit rules in csharp-ts-mode defined to attempt to fontify this, but they do not seem to be working:
> 
>      ,@(when (csharp-ts-mode--test-type-of-expression)
>          '((type_of_expression (identifier) @font-lock-type-face))
>          '((typeof_expression (identifier) @font-lock-type-face)))
> 
> Based on my inspection in treesit-explore mode, I see the grammar reports back these nodes as typeof_expression-nodes, but these rules are not activated because the preceeding (when ...) condition fails.
> 
> (defun csharp-ts-mode--test-type-of-expression ()
>   "Return non-nil if (type_of_expression) is in the grammar."
>   (ignore-errors
>     (treesit-query-compile 'c-sharp "(type_of_expression)" t)
>     t))
> 
> Changing this implementation to the following (matching the node-names I see in treesit-explore mode) makes highlighting work for me:
> 
> (defun csharp-ts-mode--test-type-of-expression ()
>   "Return non-nil if (type_of_expression) is in the grammar."
>   (ignore-errors
>     (treesit-query-compile 'c-sharp "(typeof_expression)" t)
>     t))
> 
> Attached is a patch which provides this change.
> 
> Note: This bug/fix was reproduced using tree-sitter-c-sharp grammar built on December 18th, 2024. I haven't tested with other versions.
> 
> Kind regards
> Jostein
> 
> <0001-lisp-progmodes-csharp-mode.el-Fix-fontification-of-t.patch>

Thanks! I suspect that an earlier grammar version used type_of_expression. Can you see if it’s true? If it is, we should keep the rules for both type_of_expression and typeof_expression, WDYT?

On the same note, we could use some utility function that makes it less verbose to test queries and use different query based on the test result.

Yuan