@willbooster/tree-sitter-c 48.0.0 → 48.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -146,7 +146,21 @@ Keep the shared first-word dispatch so a failed lookahead never falls back from
146
146
  When both post-type guards are valid, prefer the continuation suffix so annotation chains remain on their existing path.
147
147
  First prototype guards check the prototype tail; post-type continuation guards inspect only their own argument group.
148
148
  Regenerate Unicode and keyword tables from the derived grammar's metadata.
149
- The generation source is `script/generateIdentifierRanges.js` in this repository.
149
+ Import `buildIdentifierTables` from `@willbooster/tree-sitter-c/script/buildIdentifierTables.mjs` and pass the text of the generated `src/parser.c` to obtain the C declarations for the identifier ranges and ASCII masks. Define `TREE_SITTER_C_IDENTIFIER_HEADER` and `TREE_SITTER_C_KEYWORDS_HEADER` as quoted header names before including the scanner headers to select the grammar’s own tables. The default headers are `identifier.h` and `keywords.h`. Add the selected header paths to the grammar’s `external-files` in `tree-sitter.json` so the CLI rebuilds its cached parser when either table changes.
150
+ The keyword header declares sorted arrays of ASCII strings. Use bytewise `strcmp` order within each array and size
151
+ `FUNCTION_MACRO_KEYWORD_MAX_LENGTH` for the longest spelling. The arrays have the following roles.
152
+
153
+ | Array | Words to include |
154
+ | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
155
+ | `function_macro_keywords` | All keyword spellings the scanner must distinguish from annotation names. |
156
+ | `function_macro_type_keywords` | Keywords that introduce a type specifier. |
157
+ | `function_macro_tagged_type_keywords` | Type introducers that admit a tag or a braced definition, such as C’s `struct`, `union`, and `enum`. |
158
+ | `function_macro_scalar_type_keywords` | Scalar primitive tokens recognized by this grammar, including typedef spellings such as `size_t` and `uint32_t` when the grammar treats them as primitives. |
159
+ | `function_macro_declaration_modifiers` | Qualifiers, attributes and calling-convention words in declarations. |
160
+ | `function_macro_type_prefix_modifiers` | Declaration modifiers and storage classes that can precede a type. |
161
+ | `function_macro_object_prefix_keywords` | Built-in type words, size modifiers, declaration modifiers, storage classes and typedef introducers that can start an object declaration. |
162
+ | `function_macro_group_modifiers` | Modifiers or type introducers whose following parenthesized group belongs to the same specifier. |
163
+
150
164
  The primitive keyword data shared by grammar generation and object-prefix classification is in `src/grammarKeywords.cjs`.
151
165
  The `_preproc_function_name` token ends before splices used to determine adjacency, so the `_preproc_lparen`
152
166
  scanner must skip those splices again to reach `(`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@willbooster/tree-sitter-c",
3
- "version": "48.0.0",
3
+ "version": "48.1.0",
4
4
  "description": "C grammar for tree-sitter",
5
5
  "keywords": [
6
6
  "c",
@@ -20,6 +20,7 @@
20
20
  "tree-sitter.json",
21
21
  "*.wasm",
22
22
  "src/grammarKeywords.cjs",
23
+ "script/buildIdentifierTables.mjs",
23
24
  "src/pragma.h",
24
25
  "src/identifier.h",
25
26
  "src/keywords.h",
@@ -0,0 +1,304 @@
1
+ // @ts-check
2
+ import assert from 'node:assert/strict';
3
+
4
+ /**
5
+ * @param {string} parserSource
6
+ */
7
+ export function buildIdentifierTables(parserSource) {
8
+ const symbolMatch = parserSource.match(/^\s*sym_identifier\s*=\s*(\d+),/m);
9
+ const tableMatch = parserSource.match(/static const uint16_t ts_lex_table\[\]\s*=\s*\{([\s\S]*?)\};/);
10
+ assert.ok(symbolMatch?.[1] && tableMatch?.[1], 'Missing sym_identifier or ts_lex_table in src/parser.c');
11
+ const identifierSymbol = Number(symbolMatch[1]);
12
+ const words = Uint16Array.from(tableMatch[1].match(/\d+/g) ?? [], Number);
13
+ const lex = createLexTableReader(words);
14
+ const { accepting, reachable } = statesReachingIdentifier(lex, identifierSymbol);
15
+ const startStates = new Set(
16
+ [...parserSource.matchAll(/\.lex_state(?:_after_extra)?\s*=\s*(\d+)/g)]
17
+ .map((match) => Number(match[1]))
18
+ .filter((state) => state < lex.stateCount)
19
+ );
20
+ assert.ok(startStates.size, 'Missing lexer modes in src/parser.c');
21
+ const startClasses = classifyIdentifierClasses(lex, [...startStates], reachable, true);
22
+ for (const char of [' ', '\t', '\v', '\f', '\r', '\n']) startClasses[lex.asciiClass(char.codePointAt(0) ?? 0)] = 0;
23
+ const continueClasses = classifyIdentifierClasses(lex, accepting, reachable, false);
24
+ return `${formatCharacterRanges('start', lex, startClasses)}${formatCharacterRanges('continue', lex, continueClasses)}${formatAsciiMask('start', lex, startClasses)}${formatAsciiMask('continue', lex, continueClasses)}\n`;
25
+ }
26
+
27
+ /**
28
+ * @param {ReturnType<typeof createLexTableReader>} lex
29
+ * @param {number} symbol
30
+ */
31
+ function statesReachingIdentifier(lex, symbol) {
32
+ const predecessors = identifierPredecessors(lex);
33
+ const reachable = Array.from({ length: lex.stateCount }, () => new Set());
34
+ /** @type {[number,number][]} */
35
+ const pending = [];
36
+ const accepting = [];
37
+ for (let state = 0; state < lex.stateCount; state++) {
38
+ const tag = lex.acceptTag(state, symbol);
39
+ if (tag === undefined) continue;
40
+ pending.push([state, tag]);
41
+ reachable[state]?.add(tag);
42
+ accepting.push(state);
43
+ }
44
+ assert.ok(accepting.length, 'Missing identifier accepting state');
45
+ while (pending.length > 0) {
46
+ const item = pending.pop();
47
+ assert.ok(item);
48
+ const [state, tag] = item;
49
+ for (const [action, origins] of predecessors[state] ?? []) {
50
+ const before = previousTag(action, tag);
51
+ if (before === undefined) continue;
52
+ for (const origin of unseenOrigins(origins, reachable, before)) {
53
+ reachable[origin]?.add(before);
54
+ pending.push([origin, before]);
55
+ }
56
+ }
57
+ }
58
+ return { accepting, reachable };
59
+ }
60
+
61
+ /**
62
+ * @param {Set<number>} origins
63
+ * @param {Set<number>[]} reachable
64
+ * @param {number} tag
65
+ */
66
+ function* unseenOrigins(origins, reachable, tag) {
67
+ for (const origin of origins) {
68
+ if (!reachable[origin]?.has(tag)) yield origin;
69
+ }
70
+ }
71
+
72
+ /** @param {ReturnType<typeof createLexTableReader>} lex */
73
+ function identifierPredecessors(lex) {
74
+ const predecessors = Array.from({ length: lex.stateCount }, () => new Map());
75
+ for (let state = 0; state < lex.stateCount; state++) {
76
+ for (let cls = 0; cls < lex.classCount; cls++) {
77
+ const action = lex.transition(state, cls);
78
+ if (!action) continue;
79
+ const from = predecessors[action.target];
80
+ assert.ok(from);
81
+ if (!from.has(action)) from.set(action, new Set());
82
+ from.get(action).add(state);
83
+ }
84
+ }
85
+ return predecessors;
86
+ }
87
+
88
+ /**
89
+ * @param {{tags: [number, number][]}} action
90
+ * @param {number} tag
91
+ */
92
+ function previousTag(action, tag) {
93
+ for (let i = action.tags.length - 1; i >= 0; i--) {
94
+ const assignment = action.tags[i];
95
+ if (assignment && assignment[0] === tag) {
96
+ if (assignment[1] === 0xff_ff) return;
97
+ tag = assignment[1];
98
+ }
99
+ }
100
+ return tag;
101
+ }
102
+
103
+ /**
104
+ * @param {ReturnType<typeof createLexTableReader>} lex
105
+ * @param {number[]} fromStates
106
+ * @param {Set<number>[]} reachable
107
+ * @param {boolean} atStart
108
+ */
109
+ function classifyIdentifierClasses(lex, fromStates, reachable, atStart) {
110
+ return Uint8Array.from({ length: lex.classCount }, (_, cls) =>
111
+ Number(
112
+ fromStates.some((state) => {
113
+ const action = lex.transition(state, cls);
114
+ if (!action) return false;
115
+ const tags = reachable[action.target];
116
+ return !!tags?.size && (atStart || [...tags].some((tag) => previousTag(action, tag) !== undefined));
117
+ })
118
+ )
119
+ );
120
+ }
121
+
122
+ /**
123
+ * @param {string} suffix
124
+ * @param {ReturnType<typeof createLexTableReader>} lex
125
+ * @param {Uint8Array} matchedClasses
126
+ */
127
+ function formatCharacterRanges(suffix, lex, matchedClasses) {
128
+ const entries = collectCharacterRanges(lex, matchedClasses);
129
+ let lines = `static const TSCharacterRange preproc_identifier_${suffix}[] = {\n`;
130
+ for (let i = 0; i < entries.length; i++) {
131
+ const column = i % 8;
132
+ lines += `${column ? ' ' : ' '}${entries[i]}${column === 7 || i === entries.length - 1 ? '\n' : ''}`;
133
+ }
134
+ return `${lines}};\n\n`;
135
+ }
136
+
137
+ /**
138
+ * @param {ReturnType<typeof createLexTableReader>} lex
139
+ * @param {Uint8Array} matchedClasses
140
+ */
141
+ function collectCharacterRanges(lex, matchedClasses) {
142
+ /** @type {string[]} */
143
+ const entries = [];
144
+ let rangeStart = -1;
145
+ const visit = (/** @type {number} */ start, /** @type {number} */ endExclusive, /** @type {number} */ cls) => {
146
+ if (matchedClasses[cls]) rangeStart = rangeStart < 0 ? start : rangeStart;
147
+ else if (rangeStart >= 0) {
148
+ entries.push(`{0x${rangeStart.toString(16)}, 0x${(start - 1).toString(16)}},`);
149
+ rangeStart = -1;
150
+ }
151
+ return endExclusive;
152
+ };
153
+ let cursor = 0;
154
+ for (let cp = 0; cp < 128; cp++) cursor = visit(cp, cp + 1, lex.asciiClass(cp));
155
+ for (let i = 0; i < lex.unicodeRanges; i++) cursor = visit(cursor, lex.unicodeEnd(i) + 1, lex.unicodeClass(i));
156
+ if (rangeStart >= 0) entries.push(`{0x${rangeStart.toString(16)}, 0x${(cursor - 1).toString(16)}},`);
157
+ return entries;
158
+ }
159
+
160
+ /**
161
+ * @param {string} suffix
162
+ * @param {ReturnType<typeof createLexTableReader>} lex
163
+ * @param {Uint8Array} matchedClasses
164
+ */
165
+ function formatAsciiMask(suffix, lex, matchedClasses) {
166
+ let low = 0n;
167
+ let high = 0n;
168
+ for (let cp = 0; cp < 64; cp++) {
169
+ if (matchedClasses[lex.asciiClass(cp)]) low |= 1n << BigInt(cp);
170
+ if (matchedClasses[lex.asciiClass(cp + 64)]) high |= 1n << BigInt(cp);
171
+ }
172
+ const lowHex = low.toString(16).padStart(16, '0');
173
+ const highHex = high.toString(16).padStart(16, '0');
174
+ return `static const uint64_t preproc_identifier_${suffix}_ascii[] = {0x${lowHex}ull, 0x${highHex}ull};\n`;
175
+ }
176
+
177
+ /**
178
+ * @param {Uint16Array} t
179
+ */
180
+ function createLexTableReader(t) {
181
+ const word = (/** @type {number} */ i) => t[i] ?? 0;
182
+ const readU32 = (/** @type {number} */ i) => (word(i) | (word(i + 1) << 16)) >>> 0;
183
+ const stateCount = word(2);
184
+ const classCount = word(4);
185
+ const unicodeRanges = word(5);
186
+ const wideBase = (word(6) & 0x40_00) !== 0;
187
+ const combLen = readU32(7);
188
+ const extTransLen = readU32(9);
189
+ const unicodeEndsOff = 141;
190
+ const unicodeClassesOff = unicodeEndsOff + unicodeRanges * 2;
191
+ const stateMetaOff = unicodeClassesOff + unicodeRanges;
192
+ const combOff = stateMetaOff + stateCount * (wideBase ? 5 : 4);
193
+ const extTransOff = combOff + combLen * 2;
194
+ const extAcceptsOff = extTransOff + extTransLen;
195
+ const layout = { word, readU32, wideBase, combLen, stateMetaOff, combOff, extTransOff, extAcceptsOff };
196
+ const asciiClass = (/** @type {number} */ cp) => word(13 + cp);
197
+ /** @type {Map<number, ReturnType<typeof decodeTransition>>} */
198
+ const actions = new Map();
199
+ function transition(/** @type {number} */ state, /** @type {number} */ cls) {
200
+ const action = readAction(layout, state, cls);
201
+ if (!actions.has(action)) actions.set(action, decodeTransition(layout, action));
202
+ return actions.get(action);
203
+ }
204
+ return {
205
+ stateCount,
206
+ classCount,
207
+ unicodeRanges,
208
+ asciiClass,
209
+ unicodeEnd: (/** @type {number} */ i) => readU32(unicodeEndsOff + i * 2),
210
+ unicodeClass: (/** @type {number} */ i) => word(unicodeClassesOff + i),
211
+ transition,
212
+ acceptTag: (/** @type {number} */ state, /** @type {number} */ symbol) => readAcceptTag(layout, state, symbol),
213
+ };
214
+ }
215
+
216
+ /**
217
+ * @typedef {{
218
+ * word: (i: number) => number,
219
+ * readU32: (i: number) => number,
220
+ * wideBase: boolean,
221
+ * combLen: number,
222
+ * stateMetaOff: number,
223
+ * combOff: number,
224
+ * extTransOff: number,
225
+ * extAcceptsOff: number,
226
+ * }} LexTableLayout
227
+ */
228
+
229
+ /**
230
+ * @param {LexTableLayout} layout
231
+ * @param {number} state
232
+ */
233
+ function readStateMeta(layout, state) {
234
+ const o = layout.stateMetaOff + state * (layout.wideBase ? 5 : 4);
235
+ return layout.wideBase
236
+ ? { base: layout.readU32(o), tmpl: layout.word(o + 2), def: layout.word(o + 3), acc: layout.word(o + 4) }
237
+ : { base: layout.word(o), tmpl: layout.word(o + 1), def: layout.word(o + 2), acc: layout.word(o + 3) };
238
+ }
239
+
240
+ /**
241
+ * @param {LexTableLayout} layout
242
+ * @param {number} state
243
+ * @param {number} cls
244
+ */
245
+ function readAction(layout, state, cls) {
246
+ const sm = readStateMeta(layout, state);
247
+ if (sm.tmpl === 0 || cls === 0xff_ff) return 0;
248
+ const idx = sm.base + cls;
249
+ const inComb = idx < layout.combLen && layout.word(layout.combOff + idx * 2) === sm.tmpl;
250
+ return inComb ? layout.word(layout.combOff + idx * 2 + 1) : sm.def;
251
+ }
252
+
253
+ /**
254
+ * @param {LexTableLayout} layout
255
+ * @param {number} act
256
+ */
257
+ function decodeTransition(layout, act) {
258
+ /** @type {[number,number][]} */
259
+ const tags = [];
260
+ if (!act) return;
261
+ if ((act & 0x80_00) === 0) {
262
+ if (act & 0x40_00) return;
263
+ if (act & 0x20_00) tags.push([0, 0xff_ff]);
264
+ return { target: (act & 0x1f_ff) - 1, tags };
265
+ }
266
+ const p = layout.extTransOff + (act & 0x7f_ff);
267
+ const count = layout.word(p + 1);
268
+ if (count & 0x80_00) return;
269
+ for (let i = 0; i < count; i++) tags.push([layout.word(p + 2 + i * 2), layout.word(p + 3 + i * 2)]);
270
+ return { target: layout.word(p), tags };
271
+ }
272
+
273
+ /**
274
+ * @param {LexTableLayout} layout
275
+ * @param {number} state
276
+ * @param {number} symbol
277
+ */
278
+ function readAcceptTag(layout, state, symbol) {
279
+ const acc = readStateMeta(layout, state).acc;
280
+ if (!acc) return;
281
+ if ((acc & 0x80_00) === 0) {
282
+ if ((acc & 0x3f_ff) - 1 !== symbol) return;
283
+ return acc & 0x40_00 ? 0 : -1;
284
+ }
285
+ return readExtendedAcceptTag(layout, layout.extAcceptsOff + (acc & 0x7f_ff), symbol);
286
+ }
287
+
288
+ /**
289
+ * @param {LexTableLayout} layout
290
+ * @param {number} p
291
+ * @param {number} symbol
292
+ */
293
+ function readExtendedAcceptTag(layout, p, symbol) {
294
+ const flags = layout.word(p++);
295
+ if (flags & 2) {
296
+ if (!(flags & 1) || layout.word(p) !== symbol) return;
297
+ const tag = layout.word(p + 3);
298
+ return tag === 0xff_ff ? -1 : tag;
299
+ }
300
+ if (flags & 1) p += 4;
301
+ if (!(flags & 4) || layout.word(p++) !== symbol) return;
302
+ if (flags & 8) p += 2;
303
+ return flags & 16 ? layout.word(p) : -1;
304
+ }
@@ -3,7 +3,10 @@
3
3
  #define TREE_SITTER_C_FUNCTION_MACRO_H_
4
4
 
5
5
  #include "pragma.h"
6
- #include "keywords.h"
6
+ #ifndef TREE_SITTER_C_KEYWORDS_HEADER
7
+ #define TREE_SITTER_C_KEYWORDS_HEADER "keywords.h"
8
+ #endif
9
+ #include TREE_SITTER_C_KEYWORDS_HEADER
7
10
  #include "macroProof.h"
8
11
 
9
12
  typedef struct {
@@ -328,7 +331,8 @@ static MacroTypePrefix function_macro_type_prefix_item(TSLexer *lexer, const Mac
328
331
 
329
332
  static MacroTypePrefix function_macro_known_type_item(TSLexer *lexer, const MacroName *name, const PragmaTrivia *trivia) {
330
333
  if (lexer->lookahead == '(' && (!function_macro_modifier_balanced(lexer, '(', ')', trivia) || !scan_pragma_spacing_with(lexer, trivia))) return MACRO_TYPE_PREFIX_INVALID;
331
- if (strcmp(name->word, "struct") == 0 || strcmp(name->word, "union") == 0 || strcmp(name->word, "enum") == 0) return MACRO_TYPE_PREFIX_TAGGED_TYPE;
334
+ if (function_macro_word_in(name->word, function_macro_tagged_type_keywords,
335
+ sizeof(function_macro_tagged_type_keywords) / sizeof(*function_macro_tagged_type_keywords))) return MACRO_TYPE_PREFIX_TAGGED_TYPE;
332
336
  return MACRO_TYPE_PREFIX_KNOWN_TYPE;
333
337
  }
334
338
 
@@ -430,8 +434,11 @@ static PeekExtrasKind peek_extras_first(uint16_t first, bool allow_directive, bo
430
434
  return object_possible || pragma_possible ? PEEK_EXTRAS_UNKNOWN : PEEK_EXTRAS_NONE;
431
435
  }
432
436
 
437
+ enum { PEEK_EXTRAS_WORD_CAPACITY = FUNCTION_MACRO_KEYWORD_MAX_LENGTH + 1 > sizeof pragma_word ?
438
+ FUNCTION_MACRO_KEYWORD_MAX_LENGTH + 1 : sizeof pragma_word };
439
+
433
440
  static PeekExtrasKind peek_extras_word(PeekUnitsView view, uint32_t i, bool allow_object, bool allow_pragma) {
434
- char word[12] = {0};
441
+ char word[PEEK_EXTRAS_WORD_CAPACITY] = {0};
435
442
  unsigned length = 0;
436
443
  while (i < view.count) {
437
444
  uint16_t c = peek_unit_at(view.units, view.size, i);
@@ -475,10 +482,16 @@ static uint32_t peek_skip_ident(PeekUnitsView view, uint32_t i, bool *non_plain)
475
482
  }
476
483
 
477
484
  static inline bool peek_object_starter(uint16_t c) {
478
- static const uint64_t starter_hi = (1ULL << ('_' - 64)) | (1ULL << ('b' - 64)) | (1ULL << ('c' - 64)) |
479
- (1ULL << ('d' - 64)) | (1ULL << ('f' - 64)) | (1ULL << ('i' - 64)) | (1ULL << ('m' - 64)) |
480
- (1ULL << ('n' - 64)) | (1ULL << ('p' - 64)) | (1ULL << ('s' - 64)) | (1ULL << ('u' - 64)) | (1ULL << ('v' - 64));
481
- return c >= 64 && ((starter_hi >> (c - 64)) & 1ULL) != 0;
485
+ unsigned low = 0, high = sizeof(function_macro_scalar_type_keywords) / sizeof(*function_macro_scalar_type_keywords);
486
+ if (c >= 128) return false;
487
+ while (low < high) {
488
+ unsigned mid = low + (high - low) / 2;
489
+ unsigned first = (unsigned char)function_macro_scalar_type_keywords[mid][0];
490
+ if (first == c) return true;
491
+ if (first < c) low = mid + 1;
492
+ else high = mid;
493
+ }
494
+ return false;
482
495
  }
483
496
 
484
497
  static inline uint16_t peek_unit_at(const char *units, uint32_t size, uint32_t index) {
package/src/keywords.h CHANGED
@@ -227,6 +227,11 @@ static const char *const function_macro_type_keywords[] = {
227
227
  "unsigned",
228
228
  "void",
229
229
  };
230
+ static const char *const function_macro_tagged_type_keywords[] = {
231
+ "enum",
232
+ "struct",
233
+ "union",
234
+ };
230
235
  static const char *const function_macro_scalar_type_keywords[] = {
231
236
  "_Bool",
232
237
  "_Decimal128",
package/src/pragma.h CHANGED
@@ -3,7 +3,10 @@
3
3
  #define TREE_SITTER_C_PRAGMA_H_
4
4
 
5
5
  #include "tree_sitter/parser.h"
6
- #include "identifier.h"
6
+ #ifndef TREE_SITTER_C_IDENTIFIER_HEADER
7
+ #define TREE_SITTER_C_IDENTIFIER_HEADER "identifier.h"
8
+ #endif
9
+ #include TREE_SITTER_C_IDENTIFIER_HEADER
7
10
  #include "gnuRawString.h"
8
11
  #include <string.h>
9
12
 
Binary file
package/tree-sitter.json CHANGED
@@ -28,7 +28,7 @@
28
28
  }
29
29
  ],
30
30
  "metadata": {
31
- "version": "48.0.0",
31
+ "version": "48.1.0",
32
32
  "license": "MIT",
33
33
  "description": "C grammar for tree-sitter",
34
34
  "authors": [