On Jul 24, 2021, at 1:20 PM, Eli Zaretskii <eliz@gnu.org> wrote:

From: Yuan Fu <casouri@gmail.com>
Date: Sat, 24 Jul 2021 13:14:50 -0400
Cc: Stefan Monnier <monnier@iro.umontreal.ca>,
cpitclaudel@gmail.com,
emacs-devel@gnu.org

IIUC if we want tree-sitter to use our malloc, we need to build it with Emacs, where should I put the
source of tree-sitter?

tree-sitter itself should be a library we link against.  If you meant
the tree-sitter support code, then it should go on a separate file in
src/.  Or did I misunderstand your question?

If we link against libtree-sitter, how do we change its malloc behavior? Tree-sitter has these kind of things:

#ifndef ts_malloc
#define ts_malloc  ts_malloc_default
#endif

So I assume we need to define ts_malloc to, say, xmalloc when compiling libtree-sitter. And if we only link to
it, we can’t redefine ts_malloc.

How does TS propose the client projects to do that?  Are you saying
that the only way to replace its malloc is to recompile tree-sitter??

Here is the relevant lines in alloc.h in tree-sitter:

// Allow clients to override allocation functions

#ifndef ts_malloc
#define ts_malloc  ts_malloc_default
#endif
#ifndef ts_calloc
#define ts_calloc  ts_calloc_default
#endif
#ifndef ts_realloc
#define ts_realloc ts_realloc_default
#endif
#ifndef ts_free
#define ts_free    ts_free_default
#endif

I’m not a C expert, does this allow us to replace its malloc in runtime?

Relative discussion found on the issue tracker: https://github.com/tree-sitter/tree-sitter/issues/739

Yuan