Subject: bug#79363: 31.0.50; Font locking issue in go-ts-mode when tree-sitter grammar is automatically installed

From: Roi Martin <[email-masked]>
Date: Tue, 02 Sep 2025 12:17:58 +0200

Juri Linkov <[email-masked]> writes:

> One idea is to turn defvar into defun that memoizes its return value.

Do you mean something like this?

  (defvar go-ts-mode--font-lock-settings nil
    "Tree-sitter font-lock settings for `go-ts-mode'.")
  
  (defun go-ts-mode--font-lock-settings ()
    "Return tree-sitter font-lock settings for `go-ts-mode'.
  
  Tree-sitter font-lock rules are evaluated the first time this function
  is called.  Subsequent calls return the first evaluated value."
    (or go-ts-mode--font-lock-settings
        (setq go-ts-mode--font-lock-settings
              (treesit-font-lock-rules
               ...))))
  
  (define-derived-mode go-ts-mode prog-mode "Go"
    ...
    (when (treesit-ensure-installed 'go)
      ...
      (setq-local treesit-font-lock-settings (go-ts-mode--font-lock-settings))
      ...))

I tried and I can confirm it works fine.  I can work on a patch for all
the affected ts modes if you want.

BTW is this a common pattern?  If it is, does the Elisp core library
provide something similar?  At the end of the day it is a sort of "lazy
defvar", isn't it?

        Roi