unofficial mirror of emacs-devel@gnu.org 
 help / color / mirror / code / Atom feed
blob e9f8ddc7e32303f1a5365258e8f7e1ea6ea1c497 23440 bytes (raw)
name: src/tree_sitter.c 	 # note: path name is non-authoritative(*)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
 
/* Tree-sitter integration for GNU Emacs.

Copyright (C) 2021 Free Software Foundation, Inc.

This file is part of GNU Emacs.

GNU Emacs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */

#include <config.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "lisp.h"
#include "buffer.h"
#include "coding.h"
#include "tree_sitter.h"

/* parser.h defines a macro ADVANCE that conflicts with alloc.c.  */
#include <tree_sitter/parser.h>

/*** Functions related to parser and node object.  */

DEFUN ("tree-sitter-parser-p",
       Ftree_sitter_parser_p, Stree_sitter_parser_p, 1, 1, 0,
       doc: /* Return t if OBJECT is a tree-sitter parser.  */)
  (Lisp_Object object)
{
  if (TS_PARSERP (object))
    return Qt;
  else
    return Qnil;
}

DEFUN ("tree-sitter-node-p",
       Ftree_sitter_node_p, Stree_sitter_node_p, 1, 1, 0,
       doc: /* Return t if OBJECT is a tree-sitter node.  */)
  (Lisp_Object object)
{
  if (TS_NODEP (object))
    return Qt;
  else
    return Qnil;
}

/*** Parsing functions */

/* Update each parser's tree after the user made an edit.  This
function does not parse the buffer and only updates the tree. (So it
should be very fast.)  */
void
ts_record_change (ptrdiff_t start_byte, ptrdiff_t old_end_byte,
		  ptrdiff_t new_end_byte)
{
  Lisp_Object parser_list = Fsymbol_value (Qtree_sitter_parser_list);
  TSPoint dummy_point = {0, 0};
  TSInputEdit edit = {start_byte, old_end_byte, new_end_byte,
		      dummy_point, dummy_point, dummy_point};
  while (!NILP (parser_list))
    {
      Lisp_Object lisp_parser = Fcar (parser_list);
      TSTree *tree = XTS_PARSER (lisp_parser)->tree;
      if (tree != NULL)
	ts_tree_edit (tree, &edit);
      XTS_PARSER (lisp_parser)->need_reparse = true;
      parser_list = Fcdr (parser_list);
    }
}

/* Parse the buffer.  We don't parse until we have to. When we have
to, we call this function to parse and update the tree.  */
void
ts_ensure_parsed (Lisp_Object parser)
{
  if (!XTS_PARSER (parser)->need_reparse)
    return;
  TSParser *ts_parser = XTS_PARSER (parser)->parser;
  TSTree *tree = XTS_PARSER(parser)->tree;
  TSInput input = XTS_PARSER (parser)->input;
  TSTree *new_tree = ts_parser_parse(ts_parser, tree, input);
  /* This should be very rare: it only happens when 1) language is not
     set (impossible in Emacs because the user has to supply a
     language to create a parser), 2) parse canceled due to timeout
     (impossible because we don't set a timeout), 3) parse canceled
     due to cancellation flag (impossible because we don't set the
     flag).  (See comments for ts_parser_parse in
     tree_sitter/api.h.)  */
  if (new_tree == NULL)
    signal_error ("Parse failed", parser);
  ts_tree_delete (tree);
  XTS_PARSER (parser)->tree = new_tree;
  XTS_PARSER (parser)->need_reparse = false;
  TSNode node = ts_tree_root_node (new_tree);
}

/* This is the read function provided to tree-sitter to read from a
   buffer.  It reads one character at a time and automatically skip
   the gap.  */
const char*
ts_read_buffer (void *buffer, uint32_t byte_index,
		TSPoint position, uint32_t *bytes_read)
{
  ptrdiff_t byte_pos = byte_index + 1;

  /* Read one character.  Tree-sitter wants us to set bytes_read to 0
     if it reads to the end of buffer.  It doesn't say what it wants
     for the return value in that case, so we just give it an empty
     string.  */
  char *beg;
  int len;
  /* This function could run from a user command, so it is better to
     do nothing instead of raising an error. (It was a pain in the a**
     to read mega-if-conditions in Emacs source, so I write the two
     branches separately, hoping the compiler can merge them.)  */
  if (!BUFFER_LIVE_P ((struct buffer *) buffer))
    {
      beg = "";
      len = 0;
    }
  // TODO BUF_ZV_BYTE?
  else if (byte_pos >= BUF_Z_BYTE ((struct buffer *) buffer))
    {
      beg = "";
      len = 0;
    }
  else
    {
      beg = (char *) BUF_BYTE_ADDRESS (buffer, byte_pos);
      len = BYTES_BY_CHAR_HEAD ((int) beg);
    }
  *bytes_read = (uint32_t) len;

  return beg;
}

/*** Creators and accessors for parser and node */

/* Wrap the parser in a Lisp_Object to be used in the Lisp machine.  */
Lisp_Object
make_ts_parser (struct buffer *buffer, TSParser *parser,
		TSTree *tree, Lisp_Object name)
{
  struct Lisp_TS_Parser *lisp_parser
    = ALLOCATE_PSEUDOVECTOR (struct Lisp_TS_Parser, name, PVEC_TS_PARSER);
  lisp_parser->name = name;
  lisp_parser->buffer = buffer;
  lisp_parser->parser = parser;
  lisp_parser->tree = tree;
  TSInput input = {buffer, ts_read_buffer, TSInputEncodingUTF8};
  lisp_parser->input = input;
  lisp_parser->need_reparse = true;
  return make_lisp_ptr (lisp_parser, Lisp_Vectorlike);
}

/* Wrap the node in a Lisp_Object to be used in the Lisp machine.  */
Lisp_Object
make_ts_node (Lisp_Object parser, TSNode node)
{
  struct Lisp_TS_Node *lisp_node
    = ALLOCATE_PSEUDOVECTOR (struct Lisp_TS_Node, parser, PVEC_TS_NODE);
  lisp_node->parser = parser;
  lisp_node->node = node;
  return make_lisp_ptr (lisp_node, Lisp_Vectorlike);
}

DEFUN ("tree-sitter-node-parser",
       Ftree_sitter_node_parser, Stree_sitter_node_parser,
       1, 1, 0,
       doc: /* Return the parser to which NODE belongs.  */)
  (Lisp_Object node)
{
  CHECK_TS_NODE (node);
  return XTS_NODE (node)->parser;
}

DEFUN ("tree-sitter-create-parser",
       Ftree_sitter_create_parser, Stree_sitter_create_parser,
       2, 3, 0,
       doc: /* Create and return a parser in BUFFER for LANGUAGE.

The parser is automatically added to BUFFER's
`tree-sitter-parser-list'.  LANGUAGE should be the language provided
by a tree-sitter language dynamic module.

NAME (a string) is the name assigned to the parser, like the name for
a process.  Unlike process names, not care is taken to make each
parser's name unique.  By default, no name is assigned to the parser;
the only consequence of that is you can't use
`tree-sitter-get-parser' to find the parser by its name.  */)
  (Lisp_Object buffer, Lisp_Object language, Lisp_Object name)
{
  CHECK_BUFFER(buffer);
  if (!NILP (name))
    CHECK_STRING (name);

  /* LANGUAGE is a USER_PTR that contains the pointer to a TSLanguage
     struct.  */
  TSParser *parser = ts_parser_new ();
  TSLanguage *lang = (XUSER_PTR (language)->p);
  ts_parser_set_language (parser, lang);

  Lisp_Object lisp_parser
    = make_ts_parser (XBUFFER(buffer), parser, NULL, name);

  struct buffer *old_buffer = current_buffer;
  set_buffer_internal (XBUFFER (buffer));

  Fset (Qtree_sitter_parser_list,
	Fcons (lisp_parser, Fsymbol_value (Qtree_sitter_parser_list)));

  set_buffer_internal (old_buffer);
  return lisp_parser;
}

DEFUN ("tree-sitter-parser-buffer",
       Ftree_sitter_parser_buffer, Stree_sitter_parser_buffer,
       1, 1, 0,
       doc: /* Return the buffer of PARSER.  */)
  (Lisp_Object parser)
{
  CHECK_TS_PARSER (parser);
  Lisp_Object buf;
  XSETBUFFER (buf, XTS_PARSER (parser)->buffer);
  return buf;
}

DEFUN ("tree-sitter-parser-name",
       Ftree_sitter_parser_name, Stree_sitter_parser_name,
       1, 1, 0,
       doc: /* Return parser's name.  */)
  (Lisp_Object parser)
{
  CHECK_TS_PARSER (parser);
  return XTS_PARSER (parser)->name;
}

/*** Parser API */

DEFUN ("tree-sitter-parser-root-node",
       Ftree_sitter_parser_root_node, Stree_sitter_parser_root_node,
       1, 1, 0,
       doc: /* Return the root node of PARSER.  */)
  (Lisp_Object parser)
{
  CHECK_TS_PARSER (parser);
  ts_ensure_parsed(parser);
  TSNode root_node = ts_tree_root_node (XTS_PARSER (parser)->tree);
  return make_ts_node (parser, root_node);
}

DEFUN ("tree-sitter-parse-string",
       Ftree_sitter_parse_string, Stree_sitter_parse_string,
       2, 2, 0,
       doc: /* Parse STRING and return the root node.
LANGUAGE should be the language provided by a tree-sitter language
dynamic module.  */)
  (Lisp_Object string, Lisp_Object language)
{
  CHECK_STRING (string);

  /* LANGUAGE is a USER_PTR that contains the pointer to a TSLanguage
     struct.  */
  TSParser *parser = ts_parser_new ();
  TSLanguage *lang = (XUSER_PTR (language)->p);
  ts_parser_set_language (parser, lang);

  TSTree *tree = ts_parser_parse_string (parser, NULL,
					 SSDATA (string),
					 strlen (SSDATA (string)));

  /* See comment in ts_ensure_parsed for possible reasons for a
     failure.  */
  if (tree == NULL)
    signal_error ("Failed to parse STRING", string);

  TSNode root_node = ts_tree_root_node (tree);

  Lisp_Object lisp_parser = make_ts_parser (NULL, parser, tree, Qnil);
  Lisp_Object lisp_node = make_ts_node (lisp_parser, root_node);

  return lisp_node;
}

/*** Node API  */

DEFUN ("tree-sitter-node-type",
       Ftree_sitter_node_type, Stree_sitter_node_type, 1, 1, 0,
       doc: /* Return the NODE's type as a symbol.  */)
  (Lisp_Object node)
{
  CHECK_TS_NODE (node);
  TSNode ts_node = XTS_NODE (node)->node;
  const char *type = ts_node_type(ts_node);
  // TODO: Maybe return a string instead.
  return intern_c_string (type);
}

DEFUN ("tree-sitter-node-start-byte",
       Ftree_sitter_node_start_byte, Stree_sitter_node_start_byte, 1, 1, 0,
       doc: /* Return the NODE's start byte position.  */)
  (Lisp_Object node)
{
  CHECK_TS_NODE (node);
  TSNode ts_node = XTS_NODE (node)->node;
  uint32_t start_byte = ts_node_start_byte(ts_node);
  return make_fixnum(start_byte + 1);
}

DEFUN ("tree-sitter-node-end-byte",
       Ftree_sitter_node_end_byte, Stree_sitter_node_end_byte, 1, 1, 0,
       doc: /* Return the NODE's end byte position.  */)
  (Lisp_Object node)
{
  CHECK_TS_NODE (node);
  TSNode ts_node = XTS_NODE (node)->node;
  uint32_t end_byte = ts_node_end_byte(ts_node);
  return make_fixnum(end_byte + 1);
}

DEFUN ("tree-sitter-node-string",
       Ftree_sitter_node_string, Stree_sitter_node_string, 1, 1, 0,
       doc: /* Return the string representation of NODE.  */)
  (Lisp_Object node)
{
  CHECK_TS_NODE (node);
  TSNode ts_node = XTS_NODE (node)->node;
  char *string = ts_node_string(ts_node);
  return make_string(string, strlen (string));
}

DEFUN ("tree-sitter-node-parent",
       Ftree_sitter_node_parent, Stree_sitter_node_parent, 1, 1, 0,
       doc: /* Return the immediate parent of NODE.
Return nil if there isn't any.  */)
  (Lisp_Object node)
{
  CHECK_TS_NODE (node);
  TSNode ts_node = XTS_NODE (node)->node;
  TSNode parent = ts_node_parent (ts_node);

  if (ts_node_is_null(parent))
    return Qnil;

  return make_ts_node (XTS_NODE (node)->parser, parent);
}

DEFUN ("tree-sitter-node-child",
       Ftree_sitter_node_child, Stree_sitter_node_child, 2, 3, 0,
       doc: /* Return the Nth child of NODE.
Return nil if there isn't any.  If NAMED is non-nil, look for named
child only.  NAMED defaults to nil.  */)
  (Lisp_Object node, Lisp_Object n, Lisp_Object named)
{
  CHECK_TS_NODE (node);
  CHECK_INTEGER (n);
  EMACS_INT idx = XFIXNUM (n);
  TSNode ts_node = XTS_NODE (node)->node;
  TSNode child;
  if (NILP (named))
    child = ts_node_child (ts_node, (uint32_t) idx);
  else
    child = ts_node_named_child (ts_node, (uint32_t) idx);

  if (ts_node_is_null(child))
    return Qnil;

  return make_ts_node(XTS_NODE (node)->parser, child);
}

DEFUN ("tree-sitter-node-check",
       Ftree_sitter_node_check, Stree_sitter_node_check, 2, 2, 0,
       doc: /* Return non-nil if NODE is in condition COND, nil otherwise.

COND could be 'named, 'missing, 'extra, 'has-changes, 'has-error.
Named nodes correspond to named rules in the grammar, whereas
"anonymous" nodes correspond to string literals in the grammar.

Missing nodes are inserted by the parser in order to recover from
certain kinds of syntax errors, i.e., should be there but not there.

Extra nodes represent things like comments, which are not required the
grammar, but can appear anywhere.

A node "has changes" if the buffer changed since the node is
created. (Don't forget the "s" at the end of 'has-changes.)

A node "has error" if itself is a syntax error or contains any syntax
errors.  */)
  (Lisp_Object node, Lisp_Object cond)
{
  CHECK_TS_NODE (node);
  CHECK_SYMBOL (cond);
  TSNode ts_node = XTS_NODE (node)->node;
  bool result;
  if (EQ (cond, Qnamed))
    result = ts_node_is_named (ts_node);
  else if (EQ (cond, Qmissing))
    result = ts_node_is_missing (ts_node);
  else if (EQ (cond, Qextra))
    result = ts_node_is_extra (ts_node);
  else if (EQ (cond, Qhas_error))
    result = ts_node_has_error (ts_node);
  else if (EQ (cond, Qhas_changes))
    result = ts_node_has_changes (ts_node);
  else
    // TODO: Is this a good error message?
    signal_error ("Expecting one of four symbols, see docstring", cond);
  return result ? Qt : Qnil;
}

DEFUN ("tree-sitter-node-field-name-for-child",
       Ftree_sitter_node_field_name_for_child,
       Stree_sitter_node_field_name_for_child, 2, 2, 0,
       doc: /* Return the field name of the Nth child of NODE.
Return nil if there isn't any child or no field is found.  */)
  (Lisp_Object node, Lisp_Object n)
{
  CHECK_INTEGER (n);
  EMACS_INT idx = XFIXNUM (n);
  TSNode ts_node = XTS_NODE (node)->node;
  const char *name
    = ts_node_field_name_for_child (ts_node, (uint32_t) idx);

  if (name == NULL)
    return Qnil;

  return make_string (name, strlen (name));
}

DEFUN ("tree-sitter-node-child-count",
       Ftree_sitter_node_child_count,
       Stree_sitter_node_child_count, 1, 2, 0,
       doc: /* Return the number of children of NODE.
If NAMED is non-nil, count named child only.  NAMED defaults to
nil.  */)
  (Lisp_Object node, Lisp_Object named)
{
  TSNode ts_node = XTS_NODE (node)->node;
  uint32_t count;
  if (NILP (named))
    count = ts_node_child_count (ts_node);
  else
    count = ts_node_named_child_count (ts_node);
  return make_fixnum (count);
}

DEFUN ("tree-sitter-node-child-by-field-name",
       Ftree_sitter_node_child_by_field_name,
       Stree_sitter_node_child_by_field_name, 2, 2, 0,
       doc: /* Return the child of NODE with field name NAME.
Return nil if there isn't any.  */)
  (Lisp_Object node, Lisp_Object name)
{
  CHECK_STRING (name);
  char *name_str = SSDATA (name);
  TSNode ts_node = XTS_NODE (node)->node;
  TSNode child
    = ts_node_child_by_field_name (ts_node, name_str, strlen (name_str));

  if (ts_node_is_null(child))
    return Qnil;

  return make_ts_node(XTS_NODE (node)->parser, child);
}

DEFUN ("tree-sitter-node-next-sibling",
       Ftree_sitter_node_next_sibling,
       Stree_sitter_node_next_sibling, 1, 2, 0,
       doc: /* Return the next sibling of NODE.
Return nil if there isn't any.  If NAMED is non-nil, look for named
child only.  NAMED defaults to nil.  */)
  (Lisp_Object node, Lisp_Object named)
{
  TSNode ts_node = XTS_NODE (node)->node;
  TSNode sibling;
  if (NILP (named))
    sibling = ts_node_next_sibling (ts_node);
  else
    sibling = ts_node_next_named_sibling (ts_node);

  if (ts_node_is_null(sibling))
    return Qnil;

  return make_ts_node(XTS_NODE (node)->parser, sibling);
}

DEFUN ("tree-sitter-node-prev-sibling",
       Ftree_sitter_node_prev_sibling,
       Stree_sitter_node_prev_sibling, 1, 2, 0,
       doc: /* Return the previous sibling of NODE.
Return nil if there isn't any.  If NAMED is non-nil, look for named
child only.  NAMED defaults to nil.  */)
  (Lisp_Object node, Lisp_Object named)
{
  TSNode ts_node = XTS_NODE (node)->node;
  TSNode sibling;

  if (NILP (named))
    sibling = ts_node_prev_sibling (ts_node);
  else
    sibling = ts_node_prev_named_sibling (ts_node);

  if (ts_node_is_null(sibling))
    return Qnil;

  return make_ts_node(XTS_NODE (node)->parser, sibling);
}

DEFUN ("tree-sitter-node-first-child-for-byte",
       Ftree_sitter_node_first_child_for_byte,
       Stree_sitter_node_first_child_for_byte, 2, 3, 0,
       doc: /* Return the first child of NODE on POS.
Specifically, return the first child that extends beyond POS.  POS is
a byte position in the buffer counting from 1.  Return nil if there
isn't any.  If NAMED is non-nil, look for named child only.  NAMED
defaults to nil.  Note that this function returns an immediate child,
not the smallest (grand)child.  */)
  (Lisp_Object node, Lisp_Object pos, Lisp_Object named)
{
  CHECK_INTEGER (pos);

  struct buffer *buf = (XTS_PARSER (XTS_NODE (node)->parser)->buffer);
  ptrdiff_t byte_pos = XFIXNUM (pos);

  if (byte_pos < BUF_BEGV_BYTE (buf) || byte_pos > BUF_ZV_BYTE (buf))
    xsignal1 (Qargs_out_of_range, pos);

  TSNode ts_node = XTS_NODE (node)->node;
  TSNode child;
  if (NILP (named))
    child = ts_node_first_child_for_byte (ts_node, byte_pos - 1);
  else
    child = ts_node_first_named_child_for_byte (ts_node, byte_pos - 1);

  if (ts_node_is_null(child))
    return Qnil;

  return make_ts_node(XTS_NODE (node)->parser, child);
}

DEFUN ("tree-sitter-node-descendant-for-byte-range",
       Ftree_sitter_node_descendant_for_byte_range,
       Stree_sitter_node_descendant_for_byte_range, 3, 4, 0,
       doc: /* Return the smallest node that covers BEG to END.
The returned node is a descendant of NODE.  POS is a byte position
counting from 1.  Return nil if there isn't any.  If NAMED is non-nil,
look for named child only.  NAMED defaults to nil.  */)
  (Lisp_Object node, Lisp_Object beg, Lisp_Object end, Lisp_Object named)
{
  CHECK_INTEGER (beg);
  CHECK_INTEGER (end);

  struct buffer *buf = (XTS_PARSER (XTS_NODE (node)->parser)->buffer);
  ptrdiff_t byte_beg = XFIXNUM (beg);
  ptrdiff_t byte_end = XFIXNUM (end);

  /* Checks for BUFFER_BEG <= BEG <= END <= BUFFER_END.  */
  if (!(BUF_BEGV_BYTE (buf) <= byte_beg
	&& byte_beg <= byte_end
	&& byte_end <= BUF_ZV_BYTE (buf)))
    xsignal2 (Qargs_out_of_range, beg, end);

  TSNode ts_node = XTS_NODE (node)->node;
  TSNode child;
  if (NILP (named))
    child = ts_node_descendant_for_byte_range
      (ts_node, byte_beg - 1 , byte_end - 1);
  else
    child = ts_node_named_descendant_for_byte_range
      (ts_node, byte_beg - 1, byte_end - 1);

  if (ts_node_is_null(child))
    return Qnil;

  return make_ts_node(XTS_NODE (node)->parser, child);
}

/* Query functions */

Lisp_Object ts_query_error_to_string (TSQueryError error)
{
  char *error_name;
  switch (error)
    {
    case TSQueryErrorNone:
      error_name = "none";
      break;
    case TSQueryErrorSyntax:
      error_name = "syntax";
      break;
    case TSQueryErrorNodeType:
      error_name = "node type";
      break;
    case TSQueryErrorField:
      error_name = "field";
      break;
    case TSQueryErrorCapture:
      error_name = "capture";
      break;
    case TSQueryErrorStructure:
      error_name = "structure";
      break;
    }
  return  make_pure_c_string (error_name, strlen(error_name));
}

DEFUN ("tree-sitter-query-capture",
       Ftree_sitter_query_capture,
       Stree_sitter_query_capture, 2, 4, 0,
       doc: /* Query NODE with PATTERN.

Returns a list of (CAPTURE_NAME . NODE).  CAPTURE_NAME is the name
assigned to the node in PATTERN.  NODE is the captured node.

PATTERN is a string containing one or more matching patterns.  See
manual for further explanation for how to write a match pattern.

BEG and END, if _both_ non-nil, specifies the range in which the query
is executed.

Return nil if the query failed.  */)
  (Lisp_Object node, Lisp_Object pattern,
   Lisp_Object beg, Lisp_Object end)
{
  CHECK_TS_NODE (node);
  CHECK_STRING (pattern);

  TSNode ts_node = XTS_NODE (node)->node;
  Lisp_Object lisp_parser = XTS_NODE (node)->parser;
  const TSLanguage *lang = ts_parser_language
    (XTS_PARSER (lisp_parser)->parser);
  char *source = SSDATA (pattern);

  uint32_t error_offset;
  uint32_t error_type;
  TSQuery *query = ts_query_new (lang, source, strlen (source),
				 &error_offset, &error_type);
  TSQueryCursor *cursor = ts_query_cursor_new ();

  if (query == NULL)
    {
      // FIXME: Signal an error?
      return Qnil;
    }
  if (!NILP (beg) && !NILP (end))
    {
      EMACS_INT beg_byte = XFIXNUM (beg);
      EMACS_INT end_byte = XFIXNUM (end);
      ts_query_cursor_set_byte_range
	(cursor, (uint32_t) beg_byte - 1, (uint32_t) end_byte - 1);
    }

  ts_query_cursor_exec (cursor, query, ts_node);
  TSQueryMatch match;
  TSQueryCapture capture;
  Lisp_Object result = Qnil;
  Lisp_Object entry;
  Lisp_Object captured_node;
  const char *capture_name;
  uint32_t capture_name_len;
  while (ts_query_cursor_next_match (cursor, &match))
    {
      const TSQueryCapture *captures = match.captures;
      for (int idx=0; idx < match.capture_count; idx++)
	{
	  capture = captures[idx];
	  captured_node = make_ts_node(lisp_parser, capture.node);
	  capture_name = ts_query_capture_name_for_id
	    (query, capture.index, &capture_name_len);
	  entry = Fcons (intern_c_string (capture_name),
			 captured_node);
	  result = Fcons (entry, result);
	}
    }
  ts_query_delete (query);
  ts_query_cursor_delete (cursor);
  return Freverse (result);
}

/* Initialize the tree-sitter routines.  */
void
syms_of_tree_sitter (void)
{
  DEFSYM (Qtree_sitter_parser_p, "tree-sitter-parser-p");
  DEFSYM (Qtree_sitter_node_p, "tree-sitter-node-p");
  DEFSYM (Qnamed, "named");
  DEFSYM (Qmissing, "missing");
  DEFSYM (Qextra, "extra");
  DEFSYM (Qhas_changes, "has-changes");
  DEFSYM (Qhas_error, "has-error");

  DEFSYM (Qtree_sitter_query_error, "tree-sitter-query-error");
  Fput (Qtree_sitter_query_error, Qerror_conditions,
	pure_list (Qtree_sitter_query_error, Qerror));
  Fput (Qtree_sitter_query_error, Qerror_message,
	build_pure_c_string ("Error with query pattern"))

  DEFSYM (Qtree_sitter_parser_list, "tree-sitter-parser-list");
  DEFVAR_LISP ("tree-sitter-parser-list", Vtree_sitter_parser_list,
	       doc: /* A list of tree-sitter parsers.
// TODO: more doc.
If you removed a parser from this list, do not put it back in.  */);
  Vtree_sitter_parser_list = Qnil;
  Fmake_variable_buffer_local (Qtree_sitter_parser_list);

  defsubr (&Stree_sitter_parser_p);
  defsubr (&Stree_sitter_node_p);

  defsubr (&Stree_sitter_node_parser);

  defsubr (&Stree_sitter_create_parser);
  defsubr (&Stree_sitter_parser_buffer);
  defsubr (&Stree_sitter_parser_name);

  defsubr (&Stree_sitter_parser_root_node);
  defsubr (&Stree_sitter_parse_string);

  defsubr (&Stree_sitter_node_type);
  defsubr (&Stree_sitter_node_start_byte);
  defsubr (&Stree_sitter_node_end_byte);
  defsubr (&Stree_sitter_node_string);
  defsubr (&Stree_sitter_node_parent);
  defsubr (&Stree_sitter_node_child);
  defsubr (&Stree_sitter_node_check);
  defsubr (&Stree_sitter_node_field_name_for_child);
  defsubr (&Stree_sitter_node_child_count);
  defsubr (&Stree_sitter_node_child_by_field_name);
  defsubr (&Stree_sitter_node_next_sibling);
  defsubr (&Stree_sitter_node_prev_sibling);
  defsubr (&Stree_sitter_node_first_child_for_byte);
  defsubr (&Stree_sitter_node_descendant_for_byte_range);

  defsubr (&Stree_sitter_query_capture);
}

debug log:

solving e9f8ddc7e3 ...
found e9f8ddc7e3 in https://yhetil.org/emacs-devel/CF42CD83-02FF-4945-B3A5-0D71E8299EE2@gmail.com/
found a6a8912c84 in https://yhetil.org/emacs-devel/F95D0E9B-0B21-450A-B91D-87E9E05873CE@gmail.com/
found 7d1225161c in https://yhetil.org/emacs-devel/258CB68D-1CC1-42C8-BDCD-2A8A8099B783@gmail.com/
found f2134c571a in https://yhetil.org/emacs-devel/9F1D903D-0BD2-44F5-B83C-4E9F3D12AC85@gmail.com/

applying [1/4] https://yhetil.org/emacs-devel/9F1D903D-0BD2-44F5-B83C-4E9F3D12AC85@gmail.com/
diff --git a/src/tree_sitter.c b/src/tree_sitter.c
new file mode 100644
index 0000000000..f2134c571a


applying [2/4] https://yhetil.org/emacs-devel/258CB68D-1CC1-42C8-BDCD-2A8A8099B783@gmail.com/
diff --git a/src/tree_sitter.c b/src/tree_sitter.c
index f2134c571a..7d1225161c 100644


applying [3/4] https://yhetil.org/emacs-devel/F95D0E9B-0B21-450A-B91D-87E9E05873CE@gmail.com/
diff --git a/src/tree_sitter.c b/src/tree_sitter.c
index 7d1225161c..a6a8912c84 100644


applying [4/4] https://yhetil.org/emacs-devel/CF42CD83-02FF-4945-B3A5-0D71E8299EE2@gmail.com/
diff --git a/src/tree_sitter.c b/src/tree_sitter.c
index a6a8912c84..e9f8ddc7e3 100644

Checking patch src/tree_sitter.c...
Applied patch src/tree_sitter.c cleanly.
Checking patch src/tree_sitter.c...
Applied patch src/tree_sitter.c cleanly.
Checking patch src/tree_sitter.c...
Applied patch src/tree_sitter.c cleanly.
Checking patch src/tree_sitter.c...
Applied patch src/tree_sitter.c cleanly.

index at:
100644 e9f8ddc7e32303f1a5365258e8f7e1ea6ea1c497	src/tree_sitter.c

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this public inbox

	https://git.savannah.gnu.org/cgit/emacs.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).