Subject: bug#73877: 30; rust-ts-mode: highlight the possible type suffix of number literals

From: Christophe TROESTLER <[email-masked]>
Date: Sat, 19 Oct 2024 10:56:02 +0000

Hi,

In order to make Rust number literals such as 1usize, 1.0_f64,... more legible, the type suffix should be highlighted.  The attached patch to rust-ts-mode does that.

Best,
Christophe

From e1cf2f8c59f2abd75688721d08653327c5427da9 Mon Sep 17 00:00:00 2001
From: Christophe Troestler <[email-masked]>
Date: Fri, 18 Oct 2024 23:50:06 +0200
Subject: [PATCH] rust-ts-mode: highlight the possible type suffix of number
 literals
Content-Type: text/plain; charset="utf-8"

---
 lisp/progmodes/rust-ts-mode.el | 25 ++++++++++++++++++++++++-
 1 file changed, 24 insertions(+), 1 deletion(-)

diff --git a/lisp/progmodes/rust-ts-mode.el b/lisp/progmodes/rust-ts-mode.el
index 571ffa9b220..0454c46261f 100644
--- a/lisp/progmodes/rust-ts-mode.el
+++ b/lisp/progmodes/rust-ts-mode.el
@@ -116,6 +116,12 @@ rust-ts-mode--indent-rules
      ((parent-is "use_list") parent-bol rust-ts-mode-indent-offset)))
   "Tree-sitter indent rules for `rust-ts-mode'.")
 
+(defconst rust-ts-mode--number-types
+  (regexp-opt '("u8" "i8" "u16" "i16" "u32" "i32" "u64"
+                "i64" "u128" "i128" "usize" "isize" "f32" "f64"))
+  "Regexp that matches any suffix on number litterals as documented
+at https://doc.rust-lang.org/reference/tokens.html#suffixes")
+
 (defvar rust-ts-mode--builtin-macros
   '("concat_bytes" "concat_idents" "const_format_args"
     "format_args_nl" "log_syntax" "trace_macros" "assert" "assert_eq"
@@ -221,7 +227,8 @@ rust-ts-mode--font-lock-settings
 
    :language 'rust
    :feature 'number
-   '([(float_literal) (integer_literal)] @font-lock-number-face)
+   '([(float_literal) (integer_literal)]
+     @rust-ts-mode--fontify-number-literal)
 
    :language 'rust
    :feature 'operator
@@ -365,6 +372,22 @@ 'rust-ts-mode--fontify-pattern
              (treesit-node-start id) (treesit-node-end id)
              'font-lock-variable-name-face override start end)))))))
 
+(defun rust-ts-mode--fontify-number-literal (node override start stop &rest _)
+  "Fontify number literals, highlighting the optional type if present"
+  (let* ((beg (treesit-node-start node))
+         (end (treesit-node-end node)))
+    (save-excursion
+      (goto-char end)
+      (if (looking-back rust-ts-mode--number-types beg)
+          (let* ((ty (match-beginning 0))
+                 (nb (if (eq (char-before ty) ?_) (1- ty) ty)))
+            (treesit-fontify-with-override
+             ty end 'font-lock-type-face override start stop)
+            (treesit-fontify-with-override
+             beg nb 'font-lock-number-face override start stop))
+          (treesit-fontify-with-override
+           beg end 'font-lock-number-face override start stop)))))
+
 (defun rust-ts-mode--defun-name (node)
   "Return the defun name of NODE.
 Return nil if there is no name or if NODE is not a defun node."
-- 
2.45.2