diff --git a/common/deps.json b/common/deps.json
index beb66a2e..80bcfa3e 100644
--- a/common/deps.json
+++ b/common/deps.json
@@ -103,6 +103,10 @@
"path": "modules/web-modules/sortable.min.js",
"provide": ["Sortable"],
"require": []
+ }, {
+ "path": "modules/web-modules/diff.min.js",
+ "provide": ["Diff"],
+ "require": []
}, {
"path": "modules/web-modules/store.modern.min.js",
"provide": ["store"],
diff --git a/common/modules/mixly-modules/common/editor-code.js b/common/modules/mixly-modules/common/editor-code.js
index adbf1437..8386af1a 100644
--- a/common/modules/mixly-modules/common/editor-code.js
+++ b/common/modules/mixly-modules/common/editor-code.js
@@ -1,7 +1,5 @@
goog.loadJs('common', () => {
-goog.require('ace');
-goog.require('ace.ExtLanguageTools');
goog.require('Mixly.Config');
goog.require('Mixly.XML');
goog.require('Mixly.Env');
@@ -11,6 +9,8 @@ goog.require('Mixly.Menu');
goog.require('Mixly.ContextMenu');
goog.require('Mixly.IdGenerator');
goog.require('Mixly.CodeFormatter');
+goog.require('Mixly.MonacoTheme');
+goog.require('Mixly.MonacoTreeSitter');
goog.require('Mixly.EditorMonaco');
goog.provide('Mixly.EditorCode');
@@ -24,12 +24,16 @@ const {
ContextMenu,
IdGenerator,
CodeFormatter,
+ MonacoTheme,
+ MonacoTreeSitter,
EditorMonaco
} = Mixly;
const { USER } = Config;
+
class EditorCode extends EditorMonaco {
#contextMenu_ = null;
+ #monacoTreeSitter_ = null;
constructor() {
super();
@@ -41,6 +45,7 @@ class EditorCode extends EditorMonaco {
this.setTabSize(4);
this.#addContextMenu_();
this.setTheme(USER.theme);
+ this.#monacoTreeSitter_ = new MonacoTreeSitter(this);
}
onMounted() {
@@ -113,40 +118,65 @@ class EditorCode extends EditorMonaco {
setValue(data, ext) {
this.disableChangeEvent();
- super.setValue(data, ext);
+ super.setValue(data);
const language = this.getLanguageByExt(ext);
+ if (MonacoTheme.supportThemes.includes(language)) {
+ this.setTheme(`${USER.theme}-${language}`);
+ } else {
+ this.setTheme(USER.theme);
+ }
this.setLanguage(language);
this.enableChangeEvent();
- CodeFormatter.activateFormatter(language)
- .then((formatter) => {
- const menu = this.#contextMenu_.getItem('code');
- if (!formatter) {
- menu.remove('sep-format');
- menu.remove('format');
- return;
+ this.setCodeFormatter(language, ext).catch(Debug.error);
+ }
+
+ diffEdits(data, ext) {
+ this.disableChangeEvent();
+ super.diffEdits(data);
+ const language = this.getLanguageByExt(ext);
+ this.setLanguage(language);
+ if (MonacoTheme.supportThemes.includes(language)) {
+ this.setTheme(`${USER.theme}-${language}`);
+ } else {
+ this.setTheme(USER.theme);
+ }
+ this.#monacoTreeSitter_.setValue(language, USER.theme, data);
+ this.enableChangeEvent();
+ this.setCodeFormatter(language, ext).catch(Debug.error);
+ }
+
+ async setCodeFormatter(language, ext) {
+ const formatter = await CodeFormatter.activateFormatter(language);
+ const menu = this.#contextMenu_.getItem('code');
+ if (!formatter) {
+ menu.remove('sep-format');
+ menu.remove('format');
+ return;
+ }
+ menu.add({
+ weight: 6,
+ id: 'sep-format',
+ data: '---------'
+ });
+ menu.add({
+ weight: 6,
+ id: 'format',
+ data: {
+ isHtmlName: true,
+ name: Menu.getItem(Msg.Lang['editor.contextMenu.formatDocument'], ''),
+ callback: () => {
+ CodeFormatter.format(language, this.getValue())
+ .then((data) => {
+ super.setValue(data, ext);
+ })
+ .catch(Debug.error);
}
- menu.add({
- weight: 6,
- id: 'sep-format',
- data: '---------'
- });
- menu.add({
- weight: 6,
- id: 'format',
- data: {
- isHtmlName: true,
- name: Menu.getItem(Msg.Lang['editor.contextMenu.formatDocument'], ''),
- callback: (key, opt) => {
- CodeFormatter.format(language, this.getValue())
- .then((data) => {
- super.setValue(data, ext);
- })
- .catch(Debug.error);
- }
- }
- });
- })
- .catch(Debug.error);
+ }
+ });
+ }
+
+ getTreeSitter() {
+ return this.#monacoTreeSitter_;
}
getLanguageByExt(ext) {
@@ -183,7 +213,10 @@ class EditorCode extends EditorMonaco {
#addChangeEventListenerExt_() {
this.offEvent('change');
- this.bind('change', () => this.addDirty());
+ this.bind('change', () => {
+ this.addDirty();
+ this.#monacoTreeSitter_.setValue(this.getLanguage(), USER.theme, this.getValue());
+ });
}
dispose() {
diff --git a/common/modules/mixly-modules/common/editor-mix.js b/common/modules/mixly-modules/common/editor-mix.js
index 307c9bd0..686c9f9b 100644
--- a/common/modules/mixly-modules/common/editor-mix.js
+++ b/common/modules/mixly-modules/common/editor-mix.js
@@ -39,7 +39,7 @@ const {
HTMLTemplate,
LayerExt
} = Mixly;
-const { BOARD, SOFTWARE } = Config;
+const { BOARD, SOFTWARE, USER } = Config;
const { form } = layui;
@@ -173,6 +173,7 @@ class EditorMix extends EditorBase {
codePage.offEvent('change');
codePage.bind('change', () => {
this.addDirty();
+ codePage.getTreeSitter().setValue(codePage.getLanguage(), USER.theme, codePage.getValue());
});
}
@@ -217,12 +218,12 @@ class EditorMix extends EditorBase {
&& typeof this.py2BlockEditor.updateBlock === 'function') {
this.py2BlockEditor.updateBlock();
} else {
- codePage.setValue(blockPage.getValue(), this.#language_);
+ codePage.diffEdits(blockPage.getValue(), this.#language_);
}
break;
case Drag.Extend.POSITIVE:
this.#temp_ = blockPage.getValue();
- codePage.setValue(this.#temp_, this.#language_);
+ codePage.diffEdits(this.#temp_, this.#language_);
break;
}
blockPage.resize();
@@ -363,7 +364,7 @@ class EditorMix extends EditorBase {
return;
}
this.#temp_ = code;
- codePage.setValue(code, this.#language_);
+ codePage.diffEdits(code, this.#language_);
});
this.#addCodeChangeEventListener_();
}
@@ -549,7 +550,7 @@ class EditorMix extends EditorBase {
return;
}
this.drag.full(Drag.Extend.NEGATIVE); // 完全显示代码编辑器
- codePage.setValue(code, this.#language_);
+ codePage.diffEdits(code, this.#language_);
endFunc('USE_CODE');
return;
}
@@ -585,7 +586,7 @@ class EditorMix extends EditorBase {
Blockly.hideChaff();
if (!useIncompleteBlocks && codeDom && xmlDom.attr('shown') === 'code') {
this.drag.full(Drag.Extend.NEGATIVE); // 完全显示代码编辑器
- codePage.setValue(code, this.#language_);
+ codePage.diffEdits(code, this.#language_);
endFunc();
return;
}
diff --git a/common/modules/mixly-modules/common/editor-monaco.js b/common/modules/mixly-modules/common/editor-monaco.js
index bac9c033..0c3180f4 100644
--- a/common/modules/mixly-modules/common/editor-monaco.js
+++ b/common/modules/mixly-modules/common/editor-monaco.js
@@ -1,5 +1,6 @@
goog.loadJs('common', () => {
+goog.require('Diff');
goog.require('monaco');
goog.require('Mixly.XML');
goog.require('Mixly.Env');
@@ -70,8 +71,8 @@ class EditorMonaco extends EditorBase {
}
});
- editor.onDidChangeModelContent(() => {
- this.events.run('change');
+ editor.onDidChangeModelContent((...args) => {
+ this.events.run('change', ...args);
});
}
@@ -121,6 +122,7 @@ class EditorMonaco extends EditorBase {
#state_ = null;
#tabSize_ = null;
#language_ = null;
+ #mode_ = null;
constructor() {
super();
@@ -132,6 +134,7 @@ class EditorMonaco extends EditorBase {
init() {
super.init();
this.#editor_ = monaco.editor.createModel('');
+ this.#editor_.setEOL(monaco.editor.EndOfLineSequence.LF);
}
onMounted() {
@@ -187,13 +190,21 @@ class EditorMonaco extends EditorBase {
}
setTheme(mode) {
+ if (this.#mode_ === mode) {
+ return;
+ }
const editor = EditorMonaco.getEditor();
editor.updateOptions({
theme: `vs-${mode}`
});
+ this.#mode_ = mode;
}
- setValue(data, ext) {
+ getTheme() {
+ return this.#mode_;
+ }
+
+ setValue(data) {
if (this.getValue() === data) {
return;
}
@@ -209,6 +220,72 @@ class EditorMonaco extends EditorBase {
return this.#editor_.getValue();
}
+ diffEdits(data) {
+ const prevData = this.getValue();
+ if (prevData === data) {
+ return;
+ }
+ const edits = this.buildDiffEdits(prevData, data);
+ if (!edits.length) {
+ return;
+ }
+ this.#editor_.pushEditOperations([], edits, () => null);
+ }
+
+ buildDiffEdits(prevData, nextData) {
+ if (prevData === nextData) {
+ return [];
+ }
+ const diffs = Diff.diffChars(prevData, nextData);
+ const edits = [];
+ const state = {
+ index: 0,
+ pendingStart: null,
+ pendingText: ''
+ };
+ for (const d of diffs) {
+ if (d.added) {
+ if (state.pendingStart == null) {
+ state.pendingStart = state.index;
+ }
+ state.pendingText += d.value;
+ }
+ else if (d.removed) {
+ if (state.pendingStart == null) {
+ state.pendingStart = state.index;
+ }
+ state.index += d.value.length;
+ }
+ else {
+ this.flushPendingEdit(state, edits);
+ state.index += d.value.length;
+ }
+ }
+ this.flushPendingEdit(state, edits);
+ return edits;
+ }
+
+ flushPendingEdit(state, edits) {
+ const { pendingStart, index, pendingText } = state;
+ if (pendingStart == null) {
+ return;
+ }
+ const startPos = this.#editor_.getPositionAt(pendingStart);
+ const endPos = this.#editor_.getPositionAt(index);
+ edits.push({
+ range: new monaco.Range(
+ startPos.lineNumber,
+ startPos.column,
+ endPos.lineNumber,
+ endPos.column
+ ),
+ text: pendingText,
+ forceMoveMarkers: true
+ });
+ state.pendingStart = null;
+ state.pendingText = '';
+ }
+
clear() {
this.setValue('', true);
}
@@ -242,7 +319,7 @@ class EditorMonaco extends EditorBase {
let selection = editor.getSelection();
let selectedText = this.#editor_.getValueInRange(selection);
if (selection) {
- editor.executeEdits("cut", [{ range: selection, text: '' }]);
+ editor.executeEdits('cut', [{ range: selection, text: '' }]);
navigator.clipboard.writeText(selectedText);
}
this.focus();
@@ -281,6 +358,10 @@ class EditorMonaco extends EditorBase {
monaco.editor.setModelLanguage(this.#editor_, language);
}
+ getLanguage() {
+ return this.#language_;
+ }
+
setTabSize(tabSize) {
if (this.#tabSize_ === tabSize) {
return;
diff --git a/common/modules/mixly-modules/common/monaco-theme.js b/common/modules/mixly-modules/common/monaco-theme.js
new file mode 100644
index 00000000..db5de20c
--- /dev/null
+++ b/common/modules/mixly-modules/common/monaco-theme.js
@@ -0,0 +1,119 @@
+goog.loadJs('common', () => {
+
+goog.require('monaco');
+goog.require('Mixly.Registry');
+goog.provide('Mixly.MonacoTheme');
+
+const { Registry } = Mixly;
+
+
+class MonacoTheme {
+ static {
+ this.cssClassNamePrefix = 'mts';
+ this.themesRegistry = new Registry();
+ this.supportThemes = [];
+ // this.supportThemes = ['cpp', 'python'];
+
+ this.getClassNameOfTerm = function (type, theme, term) {
+ return `${this.cssClassNamePrefix}-${type}-${theme}-${term}`;
+ }
+
+ /*this.themesRegistry.register('vs-dark-cpp', new MonacoTheme(
+ 'vs-dark-cpp',
+ 'cpp',
+ 'dark',
+ goog.readJsonSync('../common/templates/json/tree-sitter/themes/dark-cpp.json')
+ ));
+
+ this.themesRegistry.register('vs-light-cpp', new MonacoTheme(
+ 'vs-light-cpp',
+ 'cpp',
+ 'light',
+ goog.readJsonSync('../common/templates/json/tree-sitter/themes/light-cpp.json')
+ ));
+
+ this.themesRegistry.register('vs-dark-python', new MonacoTheme(
+ 'vs-dark-python',
+ 'python',
+ 'dark',
+ goog.readJsonSync('../common/templates/json/tree-sitter/themes/dark-python.json')
+ ));
+
+ this.themesRegistry.register('vs-light-python', new MonacoTheme(
+ 'vs-light-python',
+ 'python',
+ 'light',
+ goog.readJsonSync('../common/templates/json/tree-sitter/themes/light-python.json')
+ ));*/
+ }
+
+ #id_ = null;
+ #type_ = null;
+ #theme_ = null;
+ #$tag_ = null;
+ #config_ = null;
+
+ constructor(id, type, theme, config) {
+ this.#id_ = id;
+ this.#type_ = type;
+ this.#theme_ = theme;
+ this.load(config);
+ }
+
+ load(config) {
+ monaco.editor.defineTheme(this.#id_, config.base);
+ this.#config_ = config;
+
+ if (!this.#$tag_) {
+ let hasStyleNode = $('head').find(`style[style-id='${this.id_}']`).length;
+ if (hasStyleNode) {
+ return;
+ }
+ this.#$tag_ = $('');
+ this.#$tag_.attr('style-id', this.id);
+ this.#$tag_.attr('type', 'text/css')
+ $('head').append(this.#$tag_);
+ }
+
+ this.#$tag_.html(this.generateCss());
+ }
+
+ generateCss() {
+ return Object.keys(this.#config_.monacoTreeSitter)
+ .map(term =>
+ `span.${MonacoTheme.getClassNameOfTerm(this.#type_, this.#theme_, term)}{${this.generateStyleOfTerm(term)}}`
+ )
+ .join('');
+ }
+
+ generateStyleOfTerm(term) {
+ const style = this.#config_.monacoTreeSitter[term];
+ if (!style) {
+ return '';
+ }
+
+ if (typeof style === 'string') {
+ return `color:${style}`;
+ }
+
+ return `color:${style.color};${style.extraCssStyles || ''}`;
+ }
+
+ getColorOfTerm(term) {
+ const style = this.#config_.monacoTreeSitter[term];
+ if (!style) {
+ return undefined;
+ }
+ return typeof style === 'object' ? style.color : style;
+ }
+
+ dispose() {
+ this.#$tag_ && this.#$tag_.remove();
+ this.#$tag_ = null;
+ this.#config_ = null;
+ }
+}
+
+Mixly.MonacoTheme = MonacoTheme;
+
+});
\ No newline at end of file
diff --git a/common/modules/mixly-modules/common/monaco-tree-sitter.js b/common/modules/mixly-modules/common/monaco-tree-sitter.js
new file mode 100644
index 00000000..0aa5f7ae
--- /dev/null
+++ b/common/modules/mixly-modules/common/monaco-tree-sitter.js
@@ -0,0 +1,127 @@
+goog.loadJs('common', () => {
+
+goog.require('_');
+goog.require('monaco');
+goog.require('Mixly.Registry');
+goog.require('Mixly.MonacoTheme');
+goog.provide('Mixly.MonacoTreeSitter');
+
+const { Registry, MonacoTheme } = Mixly;
+
+
+class MonacoTreeSitter {
+ static {
+ this.workerPath = '../common/modules/mixly-modules/workers/common/tree-sitter/index.js';
+ this.supportTreeSitters_ = new Registry();
+ this.activeTreeSitters_ = new Registry();
+
+ /*this.supportTreeSitters_.register('python', {
+ workerName: 'pythonTreeSitterService',
+ wasm: 'tree-sitter-python.wasm'
+ });
+
+ this.supportTreeSitters_.register('cpp', {
+ workerName: 'cppTreeSitterService',
+ wasm: 'tree-sitter-cpp.wasm'
+ });*/
+
+ this.activateTreeSitter = async function (type) {
+ if (!this.supportTreeSitters_.hasKey(type)) return null;
+
+ const info = this.supportTreeSitters_.getItem(type);
+ if (this.activeTreeSitters_.hasKey(type)) {
+ const ts = this.activeTreeSitters_.getItem(type);
+ if (ts.loading) await ts.loading;
+ return ts;
+ }
+
+ const treeSitter = workerpool.pool(this.workerPath, {
+ workerOpts: { name: info.workerName },
+ workerType: 'web'
+ });
+
+ const grammar = await goog.readJson(
+ `../common/templates/json/tree-sitter/grammars/${type}.json`
+ );
+
+ treeSitter.loading = treeSitter.exec(
+ 'init',
+ [info.wasm, grammar]
+ );
+
+ this.activeTreeSitters_.register(type, treeSitter);
+ await treeSitter.loading;
+ treeSitter.loading = null;
+ return treeSitter;
+ };
+
+ this.treeSitterPostion = function (pos) {
+ return {
+ row: pos.lineNumber - 1,
+ column: pos.column - 1
+ };
+ };
+ }
+
+ constructor(editor, opts) {
+ this.editor = editor;
+
+ this.seq = 0;
+ this.decorations = [];
+
+ this.refresh = _.debounce(
+ this.refresh.bind(this),
+ opts?.debounceUpdate ?? 15
+ );
+ }
+
+ dispose() {
+ this.pool.terminate(true);
+ this.decorations = [];
+ }
+
+ async updateWorker(type, theme, text) {
+ const treeSitter = await MonacoTreeSitter.activateTreeSitter(type);
+ if (!treeSitter) {
+ return;
+ }
+ const id = ++this.seq;
+ const dto = await treeSitter.exec('update', [text]);
+ if (id !== this.seq) return;
+ this.applyDecorations(type, theme, dto);
+ }
+
+ applyDecorations(type, theme, dto) {
+ const decos = [];
+
+ for (const [term, ranges] of Object.entries(dto)) {
+ const className = MonacoTheme.getClassNameOfTerm(type, theme, term);
+ for (const r of ranges) {
+ decos.push({
+ range: new monaco.Range(
+ r.startLineNumber,
+ r.startColumn,
+ r.endLineNumber,
+ r.endColumn
+ ),
+ options: {
+ inlineClassName: className
+ }
+ });
+ }
+ }
+ this.decorations = this.editor.getEditor().deltaDecorations(this.decorations, decos);
+ }
+
+ refresh(type, theme, newText) {
+ this.updateWorker(type, theme, newText);
+ }
+
+ setValue(type, theme, newText) {
+ this.refresh(type, theme, newText);
+ }
+}
+
+Mixly.MonacoTreeSitter = MonacoTreeSitter;
+
+});
diff --git a/common/modules/mixly-modules/common/statusbar-serial.js b/common/modules/mixly-modules/common/statusbar-serial.js
index cae4749e..49f24a3f 100644
--- a/common/modules/mixly-modules/common/statusbar-serial.js
+++ b/common/modules/mixly-modules/common/statusbar-serial.js
@@ -9,6 +9,7 @@ goog.require('Mixly.Debug');
goog.require('Mixly.Config');
goog.require('Mixly.StatusBar');
goog.require('Mixly.SideBarsManager');
+goog.require('Mixly.RightSideBarsManager');
goog.require('Mixly.HTMLTemplate');
goog.require('Mixly.PageBase');
goog.require('Mixly.Menu');
diff --git a/common/modules/mixly-modules/common/statusbar.js b/common/modules/mixly-modules/common/statusbar.js
index 0cc2f19e..19ac0099 100644
--- a/common/modules/mixly-modules/common/statusbar.js
+++ b/common/modules/mixly-modules/common/statusbar.js
@@ -60,7 +60,7 @@ class StatusBar extends EditorAce {
} else {
editor.setOption('theme', 'ace/theme/xcode');
}
- editor.getSession().setMode("ace/mode/python");
+ editor.getSession().setMode('ace/mode/python');
editor.setReadOnly(true);
// editor.setScrollSpeed(0.3);
editor.setShowPrintMargin(false);
diff --git a/common/modules/mixly-modules/deps.json b/common/modules/mixly-modules/deps.json
index af213b79..f81b39e5 100644
--- a/common/modules/mixly-modules/deps.json
+++ b/common/modules/mixly-modules/deps.json
@@ -286,8 +286,6 @@
{
"path": "/common/editor-code.js",
"require": [
- "ace",
- "ace.ExtLanguageTools",
"Mixly.Config",
"Mixly.XML",
"Mixly.Env",
@@ -297,6 +295,8 @@
"Mixly.ContextMenu",
"Mixly.IdGenerator",
"Mixly.CodeFormatter",
+ "Mixly.MonacoTheme",
+ "Mixly.MonacoTreeSitter",
"Mixly.EditorMonaco"
],
"provide": [
@@ -351,6 +351,7 @@
{
"path": "/common/editor-monaco.js",
"require": [
+ "Diff",
"monaco",
"Mixly.XML",
"Mixly.Env",
@@ -778,6 +779,28 @@
"Mixly.MJson"
]
},
+ {
+ "path": "/common/monaco-theme.js",
+ "require": [
+ "monaco",
+ "Mixly.Registry"
+ ],
+ "provide": [
+ "Mixly.MonacoTheme"
+ ]
+ },
+ {
+ "path": "/common/monaco-tree-sitter.js",
+ "require": [
+ "_",
+ "monaco",
+ "Mixly.Registry",
+ "Mixly.MonacoTheme"
+ ],
+ "provide": [
+ "Mixly.MonacoTreeSitter"
+ ]
+ },
{
"path": "/common/msg.js",
"require": [
@@ -1115,6 +1138,7 @@
"Mixly.Config",
"Mixly.StatusBar",
"Mixly.SideBarsManager",
+ "Mixly.RightSideBarsManager",
"Mixly.HTMLTemplate",
"Mixly.PageBase",
"Mixly.Menu",
diff --git a/common/modules/mixly-modules/workers/common/tree-sitter/index.js b/common/modules/mixly-modules/workers/common/tree-sitter/index.js
new file mode 100644
index 00000000..51ac969a
--- /dev/null
+++ b/common/modules/mixly-modules/workers/common/tree-sitter/index.js
@@ -0,0 +1,141 @@
+importScripts('./tree-sitter.js');
+importScripts('../../../../web-modules/workerpool.min.js');
+
+
+const terms = [
+ 'type',
+ 'scope',
+ 'function',
+ 'variable',
+ 'number',
+ 'string',
+ 'comment',
+ 'constant',
+ 'directive',
+ 'control',
+ 'operator',
+ 'modifier',
+ 'punctuation'
+];
+
+let parser;
+let tree = null;
+let language = null;
+
+
+class Language {
+ constructor(grammarJson) {
+ this.simpleTerms = {};
+ this.complexTerms = [];
+ this.complexScopes = {};
+ for (const t in grammarJson.simpleTerms)
+ this.simpleTerms[t] = grammarJson.simpleTerms[t];
+ for (const t in grammarJson.complexTerms)
+ this.complexTerms[t] = grammarJson.complexTerms[t];
+ for (const t in grammarJson.complexScopes)
+ this.complexScopes[t] = grammarJson.complexScopes[t];
+ this.complexDepth = 0;
+ this.complexOrder = false;
+ for (const s in this.complexScopes) {
+ const depth = s.split('>').length;
+ if (depth > this.complexDepth)
+ this.complexDepth = depth;
+ if (s.indexOf('[') >= 0)
+ this.complexOrder = true;
+ }
+ this.complexDepth--;
+ }
+}
+
+async function init(languageWasmPath, grammarJson) {
+ await TreeSitter.init();
+
+ parser = new TreeSitter();
+ const lang = await TreeSitter.Language.load(languageWasmPath);
+ console.log(lang.version)
+ parser.setLanguage(lang);
+ language = new Language(grammarJson);
+
+ tree = null;
+}
+
+function buildDecorations(tree) {
+ const result = [];
+ const stack = [];
+ let node = tree.rootNode.firstChild;
+ while (stack.length > 0 || node) {
+ if (node) {
+ stack.push(node);
+ node = node.firstChild;
+ }
+ else {
+ node = stack.pop();
+ let type = node.type;
+ if (!node.isNamed())
+ type = '"' + type + '"';
+ let term = null;
+ if (!language.complexTerms.includes(type)) {
+ term = language.simpleTerms[type];
+ }
+ else {
+ let desc = type;
+ let scopes = [desc];
+ let parent = node.parent;
+ for (let i = 0; i < language.complexDepth && parent; i++) {
+ let parentType = parent.type;
+ if (!parent.isNamed())
+ parentType = '"' + parentType + '"';
+ desc = parentType + ' > ' + desc;
+ scopes.push(desc);
+ parent = parent.parent;
+ }
+ if (language.complexOrder) {
+ let index = 0;
+ let sibling = node.previousSibling;
+ while (sibling) {
+ if (sibling.type === node.type)
+ index++;
+ sibling = sibling.previousSibling;
+ }
+ let rindex = -1;
+ sibling = node.nextSibling;
+ while (sibling) {
+ if (sibling.type === node.type)
+ rindex--;
+ sibling = sibling.nextSibling;
+ }
+ const orderScopes = [];
+ for (let i = 0; i < scopes.length; i++)
+ orderScopes.push(scopes[i], scopes[i] + '[' + index + ']', scopes[i] + '[' + rindex + ']');
+ scopes = orderScopes;
+ }
+ for (const d of scopes)
+ if (d in language.complexScopes)
+ term = language.complexScopes[d];
+ }
+ if (terms.includes(term)) {
+ if (!result[term]) {
+ result[term] = [];
+ }
+ result[term].push({
+ startLineNumber: node.startPosition.row + 1,
+ startColumn: node.startPosition.column + 1,
+ endLineNumber: node.endPosition.row + 1,
+ endColumn: node.endPosition.column + 1
+ });
+ }
+ node = node.nextSibling;
+ }
+ }
+ return result;
+}
+
+function update(text) {
+ const tree = parser.parse(text);
+ return buildDecorations(tree);
+}
+
+workerpool.worker({
+ init,
+ update
+});
diff --git a/common/modules/mixly-modules/workers/common/tree-sitter/tree-sitter-cpp.wasm b/common/modules/mixly-modules/workers/common/tree-sitter/tree-sitter-cpp.wasm
new file mode 100644
index 00000000..6ada0a40
Binary files /dev/null and b/common/modules/mixly-modules/workers/common/tree-sitter/tree-sitter-cpp.wasm differ
diff --git a/common/modules/mixly-modules/workers/common/tree-sitter/tree-sitter-python.wasm b/common/modules/mixly-modules/workers/common/tree-sitter/tree-sitter-python.wasm
new file mode 100644
index 00000000..05fdeb2d
Binary files /dev/null and b/common/modules/mixly-modules/workers/common/tree-sitter/tree-sitter-python.wasm differ
diff --git a/common/modules/mixly-modules/workers/common/tree-sitter/tree-sitter.js b/common/modules/mixly-modules/workers/common/tree-sitter/tree-sitter.js
new file mode 100644
index 00000000..f6ee3112
--- /dev/null
+++ b/common/modules/mixly-modules/workers/common/tree-sitter/tree-sitter.js
@@ -0,0 +1 @@
+var Module=void 0!==Module?Module:{};!function(e,t){"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?module.exports=t():self.TreeSitter=t()}(0,function(){var e,t={};for(e in Module)Module.hasOwnProperty(e)&&(t[e]=Module[e]);var r,n,o=[],s=function(e,t){throw t},_=!1,a=!1;_="object"==typeof window,a="function"==typeof importScripts,r="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,n=!_&&!r&&!a;var u,i,l,d,c="";r?(c=a?require("path").dirname(c)+"/":__dirname+"/",u=function(e,t){return l||(l=require("fs")),d||(d=require("path")),e=d.normalize(e),l.readFileSync(e,t?null:"utf8")},i=function(e){var t=u(e,!0);return t.buffer||(t=new Uint8Array(t)),q(t.buffer),t},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),o=process.argv.slice(2),"undefined"!=typeof module&&(module.exports=Module),process.on("uncaughtException",function(e){if(!(e instanceof Ze))throw e}),process.on("unhandledRejection",de),s=function(e){process.exit(e)},Module.inspect=function(){return"[Emscripten Module object]"}):n?("undefined"!=typeof read&&(u=function(e){return read(e)}),i=function(e){var t;return"function"==typeof readbuffer?new Uint8Array(readbuffer(e)):(q("object"==typeof(t=read(e,"binary"))),t)},"undefined"!=typeof scriptArgs?o=scriptArgs:void 0!==arguments&&(o=arguments),"function"==typeof quit&&(s=function(e){quit(e)}),"undefined"!=typeof print&&("undefined"==typeof console&&(console={}),console.log=print,console.warn=console.error="undefined"!=typeof printErr?printErr:print)):(_||a)&&(a?c=self.location.href:document.currentScript&&(c=document.currentScript.src),c=0!==c.indexOf("blob:")?c.substr(0,c.lastIndexOf("/")+1):"",u=function(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},a&&(i=function(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)}),function(e,t,r){var n=new XMLHttpRequest;n.open("GET",e,!0),n.responseType="arraybuffer",n.onload=function(){200==n.status||0==n.status&&n.response?t(n.response):r()},n.onerror=r,n.send(null)});var m=Module.print||console.log.bind(console),f=Module.printErr||console.warn.bind(console);for(e in t)t.hasOwnProperty(e)&&(Module[e]=t[e]);t=null,Module.arguments&&(o=Module.arguments),Module.thisProgram&&Module.thisProgram,Module.quit&&(s=Module.quit);var p=16;function h(e){var t=D[K>>2],r=t+e+15&-16;return r>Ee()&&de(),D[K>>2]=r,t}function w(e,t){return t||(t=p),Math.ceil(e/t)*t}function g(e){switch(e){case"i1":case"i8":return 1;case"i16":return 2;case"i32":return 4;case"i64":return 8;case"float":return 4;case"double":return 8;default:if("*"===e[e.length-1])return 4;if("i"===e[0]){var t=parseInt(e.substr(1));return q(t%8==0,"getNativeTypeSize invalid bits "+t+", type "+e),t/8}return 0}}var M={nextHandle:1,loadedLibs:{"-1":{refcount:1/0,name:"__self__",module:Module,global:!0}},loadedLibNames:{__self__:-1}};function y(e,t){t=t||{global:!0,nodelete:!0};var r,n=M.loadedLibNames[e];if(n)return r=M.loadedLibs[n],t.global&&!r.global&&(r.global=!0,"loading"!==r.module&&a(r.module)),t.nodelete&&r.refcount!==1/0&&(r.refcount=1/0),r.refcount++,t.loadAsync?Promise.resolve(n):n;function o(){if(t.fs){var r=t.fs.readFile(e,{encoding:"binary"});return r instanceof Uint8Array||(r=new Uint8Array(lib_data)),t.loadAsync?Promise.resolve(r):r}return t.loadAsync?(n=e,fetch(n,{credentials:"same-origin"}).then(function(e){if(!e.ok)throw"failed to load binary file at '"+n+"'";return e.arrayBuffer()}).then(function(e){return new Uint8Array(e)})):i(e);var n}function s(e){return E(e,t)}function _(){if(void 0!==Module.preloadedWasm&&void 0!==Module.preloadedWasm[e]){var r=Module.preloadedWasm[e];return t.loadAsync?Promise.resolve(r):r}return t.loadAsync?o().then(function(e){return s(e)}):s(o())}function a(e){for(var t in e)if(e.hasOwnProperty(t)){var r;r="_"+t,Module.hasOwnProperty(r)||(Module[r]=e[t])}}function u(e){r.global&&a(e),r.module=e}return n=M.nextHandle++,r={refcount:t.nodelete?1/0:1,name:e,module:"loading",global:t.global},M.loadedLibNames[e]=n,M.loadedLibs[n]=r,t.loadAsync?_().then(function(e){return u(e),n}):(u(_()),n)}function b(e,t,r,n){var o={};for(var s in e){var _=e[s];"object"==typeof _&&(_=_.value),"number"==typeof _&&(_+=t),o[s]=_,n&&(n["_"+s]=_)}return o}function E(e,t){q(1836278016==new Uint32Array(new Uint8Array(e.subarray(0,24)).buffer)[0],"need to see wasm magic number"),q(0===e[8],"need the dylink section to be first");var r=9;function n(){for(var t=0,n=1;;){var o=e[r++];if(t+=(127&o)*n,n*=128,!(128&o))break}return t}n();q(6===e[r]),q(e[++r]==="d".charCodeAt(0)),q(e[++r]==="y".charCodeAt(0)),q(e[++r]==="l".charCodeAt(0)),q(e[++r]==="i".charCodeAt(0)),q(e[++r]==="n".charCodeAt(0)),q(e[++r]==="k".charCodeAt(0)),r++;for(var o=n(),s=n(),_=n(),a=n(),u=n(),i=[],l=0;l=0,a=0;return e[t]=function(){if(!a){var e=m(n,0,_);a=I(e,s)}return a}}return t.startsWith("invoke_")?e[t]=We:e[t]=function(){return m(t).apply(null,arguments)}}}),g={global:{NaN:NaN,Infinity:1/0},"global.Math":Math,env:h,wasi_snapshot_preview1:h};function M(e,t){var n=b(e.exports,r,0,t),o=n.__post_instantiate;return o&&(ee?o():Q.push(o)),n}return t.loadAsync?WebAssembly.instantiate(e,g).then(function(e){return M(e.instance,c)}):M(new WebAssembly.Instance(new WebAssembly.Module(e),g),c)}return t.loadAsync?Promise.all(i.map(function(e){return y(e,t)})).then(function(){return f()}):(i.forEach(function(e){y(e,t)}),f())}function v(e,t){var r=R,n=r.length;try{r.grow(1)}catch(e){if(!(e instanceof RangeError))throw e;throw"Unable to grow wasm table. Use a higher value for RESERVED_FUNCTION_POINTERS or set ALLOW_TABLE_GROWTH."}try{r.set(n,e)}catch(s){if(!(s instanceof TypeError))throw s;q(void 0!==t,"Missing signature argument to addFunction");var o=function(e,t){if("function"==typeof WebAssembly.Function){for(var r={i:"i32",j:"i64",f:"f32",d:"f64"},n={parameters:[],results:"v"==t[0]?[]:[r[t[0]]]},o=1;o>0]=t;break;case"i16":j[e>>1]=t;break;case"i32":D[e>>2]=t;break;case"i64":he=[t>>>0,(pe=t,+re(pe)>=1?pe>0?(0|se(+oe(pe/4294967296),4294967295))>>>0:~~+ne((pe-+(~~pe>>>0))/4294967296)>>>0:0)],D[e>>2]=he[0],D[e+4>>2]=he[1];break;case"float":B[e>>2]=t;break;case"double":H[e>>3]=t;break;default:de("invalid type for setValue: "+r)}}function P(e,t,r){switch("*"===(t=t||"i8").charAt(t.length-1)&&(t="i32"),t){case"i1":case"i8":return O[e>>0];case"i16":return j[e>>1];case"i32":case"i64":return D[e>>2];case"float":return B[e>>2];case"double":return H[e>>3];default:de("invalid type for getValue: "+t)}return null}A=w(A,1),Module.wasmBinary&&(S=Module.wasmBinary),Module.noExitRuntime&&(N=Module.noExitRuntime),"object"!=typeof WebAssembly&&f("no native wasm support detected");var R=new WebAssembly.Table({initial:12,element:"anyfunc"}),C=!1;function q(e,t){e||de("Assertion failed: "+t)}var T=3;function F(e){return ee?Pe(e):h(e)}var L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function $(e,t,r){for(var n=t+r,o=t;e[o]&&!(o>=n);)++o;if(o-t>16&&e.subarray&&L)return L.decode(e.subarray(t,o));for(var s="";t>10,56320|1023&i)}}else s+=String.fromCharCode((31&_)<<6|a)}else s+=String.fromCharCode(_)}return s}function W(e,t){return e?$(U,e,t):""}"undefined"!=typeof TextDecoder&&new TextDecoder("utf-16le");var Z,O,U,j,D,B,H;function z(e){Z=e,Module.HEAP8=O=new Int8Array(e),Module.HEAP16=j=new Int16Array(e),Module.HEAP32=D=new Int32Array(e),Module.HEAPU8=U=new Uint8Array(e),Module.HEAPU16=new Uint16Array(e),Module.HEAPU32=new Uint32Array(e),Module.HEAPF32=B=new Float32Array(e),Module.HEAPF64=H=new Float64Array(e)}var K=7984,G=Module.TOTAL_MEMORY||33554432;function V(e){for(;e.length>0;){var t=e.shift();if("function"!=typeof t){var r=t.func;"number"==typeof r?void 0===t.arg?Module.dynCall_v(r):Module.dynCall_vi(r,t.arg):r(void 0===t.arg?null:t.arg)}else t()}}(x=Module.wasmMemory?Module.wasmMemory:new WebAssembly.Memory({initial:G/65536}))&&(Z=x.buffer),G=Z.byteLength,z(Z),D[K>>2]=5251024;var X=[],Q=[],Y=[],J=[],ee=!1;function te(e){X.unshift(e)}var re=Math.abs,ne=Math.ceil,oe=Math.floor,se=Math.min,_e=0,ae=null,ue=null;function ie(e){_e++,Module.monitorRunDependencies&&Module.monitorRunDependencies(_e)}function le(e){if(_e--,Module.monitorRunDependencies&&Module.monitorRunDependencies(_e),0==_e&&(null!==ae&&(clearInterval(ae),ae=null),ue)){var t=ue;ue=null,t()}}function de(e){throw Module.onAbort&&Module.onAbort(e),m(e+=""),f(e),C=!0,1,e="abort("+e+"). Build with -s ASSERTIONS=1 for more info.",new WebAssembly.RuntimeError(e)}Module.preloadedImages={},Module.preloadedAudios={},Module.preloadedWasm={},te(function(){if(Module.dynamicLibraries&&Module.dynamicLibraries.length>0&&!i)return ie(),void Promise.all(Module.dynamicLibraries.map(function(e){return y(e,{loadAsync:!0,global:!0,nodelete:!0})})).then(function(){le()});var e;(e=Module.dynamicLibraries)&&e.forEach(function(e){y(e,{global:!0,nodelete:!0})})});var ce="data:application/octet-stream;base64,";function me(e){return String.prototype.startsWith?e.startsWith(ce):0===e.indexOf(ce)}var fe,pe,he,we="tree-sitter.wasm";function ge(){try{if(S)return new Uint8Array(S);if(i)return i(we);throw"both async and sync fetching of the wasm failed"}catch(e){de(e)}}function Me(){de()}function ye(){de()}me(we)||(fe=we,we=Module.locateFile?Module.locateFile(fe,c):c+fe),Q.push({func:function(){Fe()}},{func:function(){ke()}}),Module._abort=Me;var be=r||"undefined"!=typeof dateNow||1;function Ee(){return U.length}function ve(e){try{return x.grow(e-Z.byteLength+65535>>16),z(x.buffer),1}catch(e){}}function Ie(e,t,r){if(ot){const e=W(r);ot(e,0!==t)}}ye=r?function(){var e=process.hrtime();return 1e3*e[0]+e[1]/1e6}:"undefined"!=typeof dateNow?dateNow:function(){return performance.now()};var Se=A,Ne={__memory_base:1024,__stack_pointer:5251024,__table_base:1,abort:Me,clock_gettime:function(e,t){var r,n;if(0===e)r=Date.now();else{if(1!==e&&4!==e||!be)return n=28,Module.___errno_location&&(D[Module.___errno_location()>>2]=n),-1;r=ye()}return D[t>>2]=r/1e3|0,D[t+4>>2]=r%1e3*1e3*1e3|0,0},emscripten_memcpy_big:function(e,t,r){U.set(U.subarray(t,t+r),e)},emscripten_resize_heap:function(e){var t=Ee();if(e>2147418112)return!1;for(var r,n,o=1;o<=4;o*=2){var s=t*(1+.2/o);if(s=Math.min(s,e+100663296),ve(Math.min(2147418112,((r=Math.max(16777216,e,s))%(n=65536)>0&&(r+=n-r%n),r))))return!0}return!1},exit:function(e){Ue(e)},fp$tree_sitter_log_callback$viii:function(){return Module._fp$tree_sitter_log_callback$viii.apply(null,arguments)},g$TRANSFER_BUFFER:function(){return Module._TRANSFER_BUFFER},g$__THREW__:function(){return Module.___THREW__},g$__cxa_new_handler:function(){return Module.___cxa_new_handler},g$__threwValue:function(){return Module.___threwValue},memory:x,table:R,tree_sitter_parse_callback:function(e,t,r,n,o){var s=nt(t,{row:r,column:n});"string"==typeof s?(k(o,s.length,"i32"),function(e,t,r){if(void 0===r&&(r=2147483647),r<2)return 0;for(var n=(r-=2)<2*e.length?r/2:e.length,o=0;o>1]=s,t+=2}j[t>>1]=0}(s,e,10240)):k(o,0,"i32")}},xe=function(){var e={env:Ne,wasi_snapshot_preview1:Ne};function t(e,t){var r=e.exports;r=b(r,A),Module.asm=r,le()}function r(e){t(e.instance)}function n(t){return(S||!_&&!a||"function"!=typeof fetch?new Promise(function(e,t){e(ge())}):fetch(we,{credentials:"same-origin"}).then(function(e){if(!e.ok)throw"failed to load wasm binary file at '"+we+"'";return e.arrayBuffer()}).catch(function(){return ge()})).then(function(t){return WebAssembly.instantiate(t,e)}).then(t,function(e){f("failed to asynchronously prepare wasm: "+e),de(e)})}if(ie(),Module.instantiateWasm)try{return Module.instantiateWasm(e,t)}catch(e){return f("Module.instantiateWasm callback failed with error: "+e),!1}return function(){if(S||"function"!=typeof WebAssembly.instantiateStreaming||me(we)||"function"!=typeof fetch)return n(r);fetch(we,{credentials:"same-origin"}).then(function(t){return WebAssembly.instantiateStreaming(t,e).then(r,function(e){f("wasm streaming compile failed: "+e),f("falling back to ArrayBuffer instantiation"),n(r)})})}(),{}}();Module.asm=xe;var Ae,ke=Module.___wasm_call_ctors=function(){return(ke=Module.___wasm_call_ctors=Module.asm.__wasm_call_ctors).apply(null,arguments)},Pe=(Module._calloc=function(){return(Module._calloc=Module.asm.calloc).apply(null,arguments)},Module._ts_language_symbol_count=function(){return(Module._ts_language_symbol_count=Module.asm.ts_language_symbol_count).apply(null,arguments)},Module._ts_language_version=function(){return(Module._ts_language_version=Module.asm.ts_language_version).apply(null,arguments)},Module._ts_language_field_count=function(){return(Module._ts_language_field_count=Module.asm.ts_language_field_count).apply(null,arguments)},Module._ts_language_symbol_name=function(){return(Module._ts_language_symbol_name=Module.asm.ts_language_symbol_name).apply(null,arguments)},Module._ts_language_symbol_type=function(){return(Module._ts_language_symbol_type=Module.asm.ts_language_symbol_type).apply(null,arguments)},Module._ts_language_field_name_for_id=function(){return(Module._ts_language_field_name_for_id=Module.asm.ts_language_field_name_for_id).apply(null,arguments)},Module._memcpy=function(){return(Module._memcpy=Module.asm.memcpy).apply(null,arguments)},Module._free=function(){return(Module._free=Module.asm.free).apply(null,arguments)},Module._malloc=function(){return(Pe=Module._malloc=Module.asm.malloc).apply(null,arguments)}),Re=(Module._ts_parser_delete=function(){return(Module._ts_parser_delete=Module.asm.ts_parser_delete).apply(null,arguments)},Module._ts_parser_set_language=function(){return(Module._ts_parser_set_language=Module.asm.ts_parser_set_language).apply(null,arguments)},Module._memcmp=function(){return(Module._memcmp=Module.asm.memcmp).apply(null,arguments)},Module._ts_query_new=function(){return(Module._ts_query_new=Module.asm.ts_query_new).apply(null,arguments)},Module._iswspace=function(){return(Module._iswspace=Module.asm.iswspace).apply(null,arguments)},Module._ts_query_delete=function(){return(Module._ts_query_delete=Module.asm.ts_query_delete).apply(null,arguments)},Module._iswalnum=function(){return(Module._iswalnum=Module.asm.iswalnum).apply(null,arguments)},Module._ts_query_pattern_count=function(){return(Module._ts_query_pattern_count=Module.asm.ts_query_pattern_count).apply(null,arguments)},Module._ts_query_capture_count=function(){return(Module._ts_query_capture_count=Module.asm.ts_query_capture_count).apply(null,arguments)},Module._ts_query_string_count=function(){return(Module._ts_query_string_count=Module.asm.ts_query_string_count).apply(null,arguments)},Module._ts_query_capture_name_for_id=function(){return(Module._ts_query_capture_name_for_id=Module.asm.ts_query_capture_name_for_id).apply(null,arguments)},Module._ts_query_string_value_for_id=function(){return(Module._ts_query_string_value_for_id=Module.asm.ts_query_string_value_for_id).apply(null,arguments)},Module._ts_query_predicates_for_pattern=function(){return(Module._ts_query_predicates_for_pattern=Module.asm.ts_query_predicates_for_pattern).apply(null,arguments)},Module._ts_tree_delete=function(){return(Module._ts_tree_delete=Module.asm.ts_tree_delete).apply(null,arguments)},Module._ts_init=function(){return(Module._ts_init=Module.asm.ts_init).apply(null,arguments)},Module._ts_parser_new_wasm=function(){return(Module._ts_parser_new_wasm=Module.asm.ts_parser_new_wasm).apply(null,arguments)},Module._ts_parser_enable_logger_wasm=function(){return(Module._ts_parser_enable_logger_wasm=Module.asm.ts_parser_enable_logger_wasm).apply(null,arguments)},Module._ts_parser_parse_wasm=function(){return(Module._ts_parser_parse_wasm=Module.asm.ts_parser_parse_wasm).apply(null,arguments)},Module._ts_tree_root_node_wasm=function(){return(Module._ts_tree_root_node_wasm=Module.asm.ts_tree_root_node_wasm).apply(null,arguments)},Module._ts_tree_edit_wasm=function(){return(Module._ts_tree_edit_wasm=Module.asm.ts_tree_edit_wasm).apply(null,arguments)},Module._ts_tree_get_changed_ranges_wasm=function(){return(Module._ts_tree_get_changed_ranges_wasm=Module.asm.ts_tree_get_changed_ranges_wasm).apply(null,arguments)},Module._ts_tree_cursor_new_wasm=function(){return(Module._ts_tree_cursor_new_wasm=Module.asm.ts_tree_cursor_new_wasm).apply(null,arguments)},Module._ts_tree_cursor_delete_wasm=function(){return(Module._ts_tree_cursor_delete_wasm=Module.asm.ts_tree_cursor_delete_wasm).apply(null,arguments)},Module._ts_tree_cursor_reset_wasm=function(){return(Module._ts_tree_cursor_reset_wasm=Module.asm.ts_tree_cursor_reset_wasm).apply(null,arguments)},Module._ts_tree_cursor_goto_first_child_wasm=function(){return(Module._ts_tree_cursor_goto_first_child_wasm=Module.asm.ts_tree_cursor_goto_first_child_wasm).apply(null,arguments)},Module._ts_tree_cursor_goto_next_sibling_wasm=function(){return(Module._ts_tree_cursor_goto_next_sibling_wasm=Module.asm.ts_tree_cursor_goto_next_sibling_wasm).apply(null,arguments)},Module._ts_tree_cursor_goto_parent_wasm=function(){return(Module._ts_tree_cursor_goto_parent_wasm=Module.asm.ts_tree_cursor_goto_parent_wasm).apply(null,arguments)},Module._ts_tree_cursor_current_node_type_id_wasm=function(){return(Module._ts_tree_cursor_current_node_type_id_wasm=Module.asm.ts_tree_cursor_current_node_type_id_wasm).apply(null,arguments)},Module._ts_tree_cursor_current_node_is_named_wasm=function(){return(Module._ts_tree_cursor_current_node_is_named_wasm=Module.asm.ts_tree_cursor_current_node_is_named_wasm).apply(null,arguments)},Module._ts_tree_cursor_current_node_is_missing_wasm=function(){return(Module._ts_tree_cursor_current_node_is_missing_wasm=Module.asm.ts_tree_cursor_current_node_is_missing_wasm).apply(null,arguments)},Module._ts_tree_cursor_current_node_id_wasm=function(){return(Module._ts_tree_cursor_current_node_id_wasm=Module.asm.ts_tree_cursor_current_node_id_wasm).apply(null,arguments)},Module._ts_tree_cursor_start_position_wasm=function(){return(Module._ts_tree_cursor_start_position_wasm=Module.asm.ts_tree_cursor_start_position_wasm).apply(null,arguments)},Module._ts_tree_cursor_end_position_wasm=function(){return(Module._ts_tree_cursor_end_position_wasm=Module.asm.ts_tree_cursor_end_position_wasm).apply(null,arguments)},Module._ts_tree_cursor_start_index_wasm=function(){return(Module._ts_tree_cursor_start_index_wasm=Module.asm.ts_tree_cursor_start_index_wasm).apply(null,arguments)},Module._ts_tree_cursor_end_index_wasm=function(){return(Module._ts_tree_cursor_end_index_wasm=Module.asm.ts_tree_cursor_end_index_wasm).apply(null,arguments)},Module._ts_tree_cursor_current_field_id_wasm=function(){return(Module._ts_tree_cursor_current_field_id_wasm=Module.asm.ts_tree_cursor_current_field_id_wasm).apply(null,arguments)},Module._ts_tree_cursor_current_node_wasm=function(){return(Module._ts_tree_cursor_current_node_wasm=Module.asm.ts_tree_cursor_current_node_wasm).apply(null,arguments)},Module._ts_node_symbol_wasm=function(){return(Module._ts_node_symbol_wasm=Module.asm.ts_node_symbol_wasm).apply(null,arguments)},Module._ts_node_child_count_wasm=function(){return(Module._ts_node_child_count_wasm=Module.asm.ts_node_child_count_wasm).apply(null,arguments)},Module._ts_node_named_child_count_wasm=function(){return(Module._ts_node_named_child_count_wasm=Module.asm.ts_node_named_child_count_wasm).apply(null,arguments)},Module._ts_node_child_wasm=function(){return(Module._ts_node_child_wasm=Module.asm.ts_node_child_wasm).apply(null,arguments)},Module._ts_node_named_child_wasm=function(){return(Module._ts_node_named_child_wasm=Module.asm.ts_node_named_child_wasm).apply(null,arguments)},Module._ts_node_child_by_field_id_wasm=function(){return(Module._ts_node_child_by_field_id_wasm=Module.asm.ts_node_child_by_field_id_wasm).apply(null,arguments)},Module._ts_node_next_sibling_wasm=function(){return(Module._ts_node_next_sibling_wasm=Module.asm.ts_node_next_sibling_wasm).apply(null,arguments)},Module._ts_node_prev_sibling_wasm=function(){return(Module._ts_node_prev_sibling_wasm=Module.asm.ts_node_prev_sibling_wasm).apply(null,arguments)},Module._ts_node_next_named_sibling_wasm=function(){return(Module._ts_node_next_named_sibling_wasm=Module.asm.ts_node_next_named_sibling_wasm).apply(null,arguments)},Module._ts_node_prev_named_sibling_wasm=function(){return(Module._ts_node_prev_named_sibling_wasm=Module.asm.ts_node_prev_named_sibling_wasm).apply(null,arguments)},Module._ts_node_parent_wasm=function(){return(Module._ts_node_parent_wasm=Module.asm.ts_node_parent_wasm).apply(null,arguments)},Module._ts_node_descendant_for_index_wasm=function(){return(Module._ts_node_descendant_for_index_wasm=Module.asm.ts_node_descendant_for_index_wasm).apply(null,arguments)},Module._ts_node_named_descendant_for_index_wasm=function(){return(Module._ts_node_named_descendant_for_index_wasm=Module.asm.ts_node_named_descendant_for_index_wasm).apply(null,arguments)},Module._ts_node_descendant_for_position_wasm=function(){return(Module._ts_node_descendant_for_position_wasm=Module.asm.ts_node_descendant_for_position_wasm).apply(null,arguments)},Module._ts_node_named_descendant_for_position_wasm=function(){return(Module._ts_node_named_descendant_for_position_wasm=Module.asm.ts_node_named_descendant_for_position_wasm).apply(null,arguments)},Module._ts_node_start_point_wasm=function(){return(Module._ts_node_start_point_wasm=Module.asm.ts_node_start_point_wasm).apply(null,arguments)},Module._ts_node_end_point_wasm=function(){return(Module._ts_node_end_point_wasm=Module.asm.ts_node_end_point_wasm).apply(null,arguments)},Module._ts_node_start_index_wasm=function(){return(Module._ts_node_start_index_wasm=Module.asm.ts_node_start_index_wasm).apply(null,arguments)},Module._ts_node_end_index_wasm=function(){return(Module._ts_node_end_index_wasm=Module.asm.ts_node_end_index_wasm).apply(null,arguments)},Module._ts_node_to_string_wasm=function(){return(Module._ts_node_to_string_wasm=Module.asm.ts_node_to_string_wasm).apply(null,arguments)},Module._ts_node_children_wasm=function(){return(Module._ts_node_children_wasm=Module.asm.ts_node_children_wasm).apply(null,arguments)},Module._ts_node_named_children_wasm=function(){return(Module._ts_node_named_children_wasm=Module.asm.ts_node_named_children_wasm).apply(null,arguments)},Module._ts_node_descendants_of_type_wasm=function(){return(Module._ts_node_descendants_of_type_wasm=Module.asm.ts_node_descendants_of_type_wasm).apply(null,arguments)},Module._ts_node_is_named_wasm=function(){return(Module._ts_node_is_named_wasm=Module.asm.ts_node_is_named_wasm).apply(null,arguments)},Module._ts_node_has_changes_wasm=function(){return(Module._ts_node_has_changes_wasm=Module.asm.ts_node_has_changes_wasm).apply(null,arguments)},Module._ts_node_has_error_wasm=function(){return(Module._ts_node_has_error_wasm=Module.asm.ts_node_has_error_wasm).apply(null,arguments)},Module._ts_node_is_missing_wasm=function(){return(Module._ts_node_is_missing_wasm=Module.asm.ts_node_is_missing_wasm).apply(null,arguments)},Module._ts_query_matches_wasm=function(){return(Module._ts_query_matches_wasm=Module.asm.ts_query_matches_wasm).apply(null,arguments)},Module._ts_query_captures_wasm=function(){return(Module._ts_query_captures_wasm=Module.asm.ts_query_captures_wasm).apply(null,arguments)},Module._iswdigit=function(){return(Module._iswdigit=Module.asm.iswdigit).apply(null,arguments)},Module._iswalpha=function(){return(Module._iswalpha=Module.asm.iswalpha).apply(null,arguments)},Module._iswlower=function(){return(Module._iswlower=Module.asm.iswlower).apply(null,arguments)},Module._towupper=function(){return(Module._towupper=Module.asm.towupper).apply(null,arguments)},Module._memchr=function(){return(Module._memchr=Module.asm.memchr).apply(null,arguments)},Module._strlen=function(){return(Module._strlen=Module.asm.strlen).apply(null,arguments)},Module._setThrew=function(){return(Re=Module._setThrew=Module.asm.setThrew).apply(null,arguments)}),Ce=(Module.__Znwm=function(){return(Module.__Znwm=Module.asm._Znwm).apply(null,arguments)},Module.__ZdlPv=function(){return(Module.__ZdlPv=Module.asm._ZdlPv).apply(null,arguments)},Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm=function(){return(Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm=Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE6__initEPKcm).apply(null,arguments)},Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev=function(){return(Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev=Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEED2Ev).apply(null,arguments)},Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm=function(){return(Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm=Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9__grow_byEmmmmmm).apply(null,arguments)},Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm=function(){return(Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm=Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE7reserveEm).apply(null,arguments)},Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc=function(){return(Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc=Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE9push_backEc).apply(null,arguments)},Module.__ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm=function(){return(Module.__ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm=Module.asm._ZNKSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEE4copyEPcmm).apply(null,arguments)},Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev=function(){return(Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev=Module.asm._ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEED2Ev).apply(null,arguments)},Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw=function(){return(Module.__ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw=Module.asm._ZNSt3__212basic_stringIwNS_11char_traitsIwEENS_9allocatorIwEEE9push_backEw).apply(null,arguments)},Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEC1ERKS5_=function(){return(Module.__ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEC1ERKS5_=Module.asm._ZNSt3__212basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEC1ERKS5_).apply(null,arguments)},Module.__ZNKSt3__220__vector_base_commonILb1EE20__throw_length_errorEv=function(){return(Module.__ZNKSt3__220__vector_base_commonILb1EE20__throw_length_errorEv=Module.asm._ZNKSt3__220__vector_base_commonILb1EE20__throw_length_errorEv).apply(null,arguments)},Module.stackSave=function(){return(Ce=Module.stackSave=Module.asm.stackSave).apply(null,arguments)}),qe=Module.stackAlloc=function(){return(qe=Module.stackAlloc=Module.asm.stackAlloc).apply(null,arguments)},Te=Module.stackRestore=function(){return(Te=Module.stackRestore=Module.asm.stackRestore).apply(null,arguments)},Fe=Module.___assign_got_enties=function(){return(Fe=Module.___assign_got_enties=Module.asm.__assign_got_enties).apply(null,arguments)},Le=(Module.dynCall_vi=function(){return(Module.dynCall_vi=Module.asm.dynCall_vi).apply(null,arguments)},{__cxa_new_handler:6112,__data_end:6960,__THREW__:6952,TRANSFER_BUFFER:1472,__threwValue:6956});for(var $e in Le)Module["_"+$e]=Se+Le[$e];for(var $e in Module.NAMED_GLOBALS=Le,Le)!function(e){var t=Module["_"+e];Module["g$_"+e]=function(){return t}}($e);function We(){var e=Ce();try{var t=Array.prototype.slice.call(arguments);return R.get(t[0]).apply(null,t.slice(1))}catch(t){if(Te(e),t!==t+0&&"longjmp"!==t)throw t;Re(1,0)}}function Ze(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}Module._fp$tree_sitter_log_callback$viii=function(){q(Module._tree_sitter_log_callback||!0,"external function `tree_sitter_log_callback` is missing.perhaps a side module was not linked in? if this symbol was expected to arrive from a system library, try to build the MAIN_MODULE with EMCC_FORCE_STDLIBS=XX in the environment");var e=Module.asm.tree_sitter_log_callback;e||(e=Module._tree_sitter_log_callback),e||(e=Module._tree_sitter_log_callback),e||(e=Ie);var t=I(e,"viii");return Module._fp$tree_sitter_log_callback$viii=function(){return t},t},Module.asm=xe,Module.allocate=function(e,t,r,n){var o,s;"number"==typeof e?(o=!0,s=e):(o=!1,s=e.length);var _,a="string"==typeof t?t:null;if(_=r==T?n:[Pe,qe,h][r](Math.max(s,a?1:t.length)),o){var u;for(n=_,q(0==(3&_)),u=_+(-4&s);n>2]=0;for(u=_+s;n>0]=0;return _}if("i8"===a)return e.subarray||e.slice?U.set(e,_):U.set(new Uint8Array(e),_),_;for(var i,l,d,c=0;c0||(!function(){if(Module.preRun)for("function"==typeof Module.preRun&&(Module.preRun=[Module.preRun]);Module.preRun.length;)te(Module.preRun.shift());V(X)}(),_e>0||(Module.setStatus?(Module.setStatus("Running..."),setTimeout(function(){setTimeout(function(){Module.setStatus("")},1),t()},1)):t()))}function Ue(e,t){t&&N&&0===e||(N||(C=!0,e,!0,Module.onExit&&Module.onExit(e)),s(e,new Ze(e)))}if(ue=function e(){Ae||Oe(),Ae||(ue=e)},Module.run=Oe,Module.preInit)for("function"==typeof Module.preInit&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.pop()();var je=!0;Module.noInitialRun&&(je=!1),N=!0,Oe();const De=Module,Be={},He=4,ze=5*He,Ke=2*He,Ge=2*He+2*Ke,Ve={row:0,column:0},Xe=/[\w-.]*/g,Qe=1,Ye=2,Je=/^_?tree_sitter_\w+/;var et,tt,rt,nt,ot,st=new Promise(e=>{Module.onRuntimeInitialized=e}).then(()=>{rt=De._ts_init(),et=P(rt,"i32"),tt=P(rt+He,"i32")});class Parser{static init(){return st}constructor(){if(null==rt)throw new Error("You must first call Parser.init() and wait for it to resolve.");De._ts_parser_new_wasm(),this[0]=P(rt,"i32"),this[1]=P(rt+He,"i32")}delete(){De._ts_parser_delete(this[0]),De._free(this[1])}setLanguage(e){let t;if(e){if(e.constructor!==Language)throw new Error("Argument must be a Language");{t=e[0];const r=De._ts_language_version(t);if(re.slice(t,n));else{if("function"!=typeof e)throw new Error("Argument must be a string or a function");nt=e}this.logCallback?(ot=this.logCallback,De._ts_parser_enable_logger_wasm(this[0],1)):(ot=null,De._ts_parser_enable_logger_wasm(this[0],0));let n=0,o=0;if(r&&r.includedRanges){n=r.includedRanges.length;let e=o=De._calloc(n,Ge);for(let t=0;t0){let e=r;for(let r=0;r0){let r=t;for(let t=0;t0){let r=t;for(let t=0;t0){let e=a;for(let t=0;t<_;t++)u[t]=dt(this.tree,e),e+=ze}return De._free(a),De._free(s),u}get nextSibling(){return lt(this),De._ts_node_next_sibling_wasm(this.tree[0]),dt(this.tree)}get previousSibling(){return lt(this),De._ts_node_prev_sibling_wasm(this.tree[0]),dt(this.tree)}get nextNamedSibling(){return lt(this),De._ts_node_next_named_sibling_wasm(this.tree[0]),dt(this.tree)}get previousNamedSibling(){return lt(this),De._ts_node_prev_named_sibling_wasm(this.tree[0]),dt(this.tree)}get parent(){return lt(this),De._ts_node_parent_wasm(this.tree[0]),dt(this.tree)}descendantForIndex(e,t=e){if("number"!=typeof e||"number"!=typeof t)throw new Error("Arguments must be numbers");lt(this);let r=rt+ze;return k(r,e,"i32"),k(r+He,t,"i32"),De._ts_node_descendant_for_index_wasm(this.tree[0]),dt(this.tree)}namedDescendantForIndex(e,t=e){if("number"!=typeof e||"number"!=typeof t)throw new Error("Arguments must be numbers");lt(this);let r=rt+ze;return k(r,e,"i32"),k(r+He,t,"i32"),De._ts_node_named_descendant_for_index_wasm(this.tree[0]),dt(this.tree)}descendantForPosition(e,t=e){if(!it(e)||!it(t))throw new Error("Arguments must be {row, column} objects");lt(this);let r=rt+ze;return ft(r,e),ft(r+Ke,t),De._ts_node_descendant_for_position_wasm(this.tree[0]),dt(this.tree)}namedDescendantForPosition(e,t=e){if(!it(e)||!it(t))throw new Error("Arguments must be {row, column} objects");lt(this);let r=rt+ze;return ft(r,e),ft(r+Ke,t),De._ts_node_named_descendant_for_position_wasm(this.tree[0]),dt(this.tree)}walk(){return lt(this),De._ts_tree_cursor_new_wasm(this.tree[0]),new TreeCursor(Be,this.tree)}toString(){lt(this);const e=De._ts_node_to_string_wasm(this.tree[0]),t=function(e){for(var t="";;){var r=U[e++>>0];if(!r)return t;t+=String.fromCharCode(r)}}(e);return De._free(e),t}}class TreeCursor{constructor(e,t){ut(e),this.tree=t,mt(this)}delete(){ct(this),De._ts_tree_cursor_delete_wasm(this.tree[0])}reset(e){lt(e),ct(this,rt+ze),De._ts_tree_cursor_reset_wasm(this.tree[0]),mt(this)}get nodeType(){return this.tree.language.types[this.nodeTypeId]||"ERROR"}get nodeTypeId(){return ct(this),De._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeId(){return ct(this),De._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return ct(this),1===De._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])}get nodeIsMissing(){return ct(this),1===De._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])}get nodeText(){ct(this);const e=De._ts_tree_cursor_start_index_wasm(this.tree[0]),t=De._ts_tree_cursor_end_index_wasm(this.tree[0]);return _t(this.tree,e,t)}get startPosition(){return ct(this),De._ts_tree_cursor_start_position_wasm(this.tree[0]),pt(rt)}get endPosition(){return ct(this),De._ts_tree_cursor_end_position_wasm(this.tree[0]),pt(rt)}get startIndex(){return ct(this),De._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return ct(this),De._ts_tree_cursor_end_index_wasm(this.tree[0])}currentNode(){return ct(this),De._ts_tree_cursor_current_node_wasm(this.tree[0]),dt(this.tree)}currentFieldId(){return ct(this),De._ts_tree_cursor_current_field_id_wasm(this.tree[0])}currentFieldName(){return this.tree.language.fields[this.currentFieldId()]}gotoFirstChild(){ct(this);const e=De._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return mt(this),1===e}gotoNextSibling(){ct(this);const e=De._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return mt(this),1===e}gotoParent(){ct(this);const e=De._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return mt(this),1===e}}class Language{constructor(e,t){ut(e),this[0]=t,this.types=new Array(De._ts_language_symbol_count(this[0]));for(let e=0,t=this.types.length;e=55296&&n<=57343&&(n=65536+((1023&n)<<10)|1023&e.charCodeAt(++r)),n<=127?++t:t+=n<=2047?2:n<=65535?3:4}return t}(e),r=De._malloc(t+1);(function(e,t,r,n){if(!(n>0))return 0;for(var o=r,s=r+n-1,_=0;_=55296&&a<=57343&&(a=65536+((1023&a)<<10)|1023&e.charCodeAt(++_)),a<=127){if(r>=s)break;t[r++]=a}else if(a<=2047){if(r+1>=s)break;t[r++]=192|a>>6,t[r++]=128|63&a}else if(a<=65535){if(r+2>=s)break;t[r++]=224|a>>12,t[r++]=128|a>>6&63,t[r++]=128|63&a}else{if(r+3>=s)break;t[r++]=240|a>>18,t[r++]=128|a>>12&63,t[r++]=128|a>>6&63,t[r++]=128|63&a}}t[r]=0})(e,U,r,t+1);const n=De._ts_query_new(this[0],r,t,rt,rt+He);if(!n){const t=P(rt+He,"i32"),n=W(r,P(rt,"i32")).length,o=e.substr(n,100),s=o.match(Xe)[0];let _;switch(t){case 2:_=new RangeError(`Bad node name '${s}'`);break;case 3:_=new RangeError(`Bad field name '${s}'`);break;case 4:_=new RangeError(`Bad capture name @${s}`);break;default:_=new SyntaxError(`Bad syntax at offset ${n}: '${o}'...`)}throw _.index=n,_.length=s.length,De._free(r),_}const o=De._ts_query_string_count(n),s=De._ts_query_capture_count(n),_=De._ts_query_pattern_count(n),a=new Array(s),u=new Array(o);for(let e=0;e0){if("string"!==o[0].type)throw new Error("Predicates must begin with a literal value");const t=o[0].value;let r=!0;switch(t){case"not-eq?":r=!1;case"eq?":if(3!==o.length)throw new Error(`Wrong number of arguments to \`eq?\` predicate. Expected 2, got ${o.length-1}`);if("capture"!==o[1].type)throw new Error(`First argument of \`eq?\` predicate must be a capture. Got "${o[1].value}"`);if("capture"===o[2].type){const t=o[1].name,n=o[2].name;c[e].push(function(e){let o,s;for(const r of e)r.name===t&&(o=r.node),r.name===n&&(s=r.node);return o.text===s.text===r})}else{const t=o[1].name,n=o[2].value;c[e].push(function(e){for(const o of e)if(o.name===t)return o.node.text===n===r;return!1})}break;case"match?":if(3!==o.length)throw new Error(`Wrong number of arguments to \`match?\` predicate. Expected 2, got ${o.length-1}.`);if("capture"!==o[1].type)throw new Error(`First argument of \`match?\` predicate must be a capture. Got "${o[1].value}".`);if("string"!==o[2].type)throw new Error(`Second argument of \`match?\` predicate must be a string. Got @${o[2].value}.`);const n=o[1].name,s=new RegExp(o[2].value);c[e].push(function(e){for(const t of e)if(t.name===n)return s.test(t.node.text);return!1});break;case"set!":if(o.length<2||o.length>3)throw new Error(`Wrong number of arguments to \`set!\` predicate. Expected 1 or 2. Got ${o.length-1}.`);if(o.some(e=>"string"!==e.type))throw new Error('Arguments to `set!` predicate must be a strings.".');i[e]||(i[e]={}),i[e][o[1].value]=o[2]?o[2].value:null;break;case"is?":case"is-not?":if(o.length<2||o.length>3)throw new Error(`Wrong number of arguments to \`${t}\` predicate. Expected 1 or 2. Got ${o.length-1}.`);if(o.some(e=>"string"!==e.type))throw new Error(`Arguments to \`${t}\` predicate must be a strings.".`);const _="is?"===t?l:d;_[e]||(_[e]={}),_[e][o[1].value]=o[2]?o[2].value:null;break;default:throw new Error(`Unknown query predicate \`${o[0].value}\``)}o.length=0}}Object.freeze(i[e]),Object.freeze(l[e]),Object.freeze(d[e])}return De._free(r),new Query(Be,n,a,c,Object.freeze(i),Object.freeze(l),Object.freeze(d))}static load(e){let t;if("undefined"!=typeof process&&process.versions&&process.versions.node){const r=require("fs");t=Promise.resolve(r.readFileSync(e))}else t=fetch(e).then(e=>e.arrayBuffer().then(t=>{if(e.ok)return new Uint8Array(t);{const r=new TextDecoder("utf-8").decode(t);throw new Error(`Language.load failed with status ${e.status}.\n\n${r}`)}}));return t.then(e=>E(e,{loadAsync:!0})).then(e=>{const t=e[Object.keys(e).find(e=>Je.test(e)&&!e.includes("external_scanner_"))]();return new Language(Be,t)})}}class Query{constructor(e,t,r,n,o,s,_){ut(e),this[0]=t,this.captureNames=r,this.predicates=n,this.setProperties=o,this.assertedProperties=s,this.refutedProperties=_}delete(){De._ts_query_delete(this[0])}matches(e,t,r){t||(t=Ve),r||(r=Ve),lt(e),De._ts_query_matches_wasm(this[0],e.tree[0],t.row,t.column,r.row,r.column);const n=P(rt,"i32"),o=P(rt+He,"i32"),s=new Array(n);let _=o;for(let t=0;te(o))){s[t]={pattern:r,captures:o};const e=this.setProperties[r];e&&(s[t].setProperties=e);const n=this.assertedProperties[r];n&&(s[t].assertedProperties=n);const _=this.refutedProperties[r];_&&(s[t].refutedProperties=_)}}return De._free(o),s}captures(e,t,r){t||(t=Ve),r||(r=Ve),lt(e),De._ts_query_captures_wasm(this[0],e.tree[0],t.row,t.column,r.row,r.column);const n=P(rt,"i32"),o=P(rt+He,"i32"),s=[],_=[];let a=o;for(let t=0;te(_))){const e=_[n],r=this.setProperties[t];r&&(e.setProperties=r);const o=this.assertedProperties[t];o&&(e.assertedProperties=o);const a=this.refutedProperties[t];a&&(e.refutedProperties=a),s.push(e)}}return De._free(o),s}}function _t(e,t,r){const n=r-t;let o=e.textCallback(t,null,r);for(t+=o.length;t0))break;t+=n.length,o+=n}return t>r&&(o=o.slice(0,n)),o}function at(e,t,r,n){for(let o=0,s=n.length;o __defProp(target, "name", { value, configurable: true });
+
+// src/edit.ts
+var Edit = class {
+ static {
+ __name(this, "Edit");
+ }
+ /** The start position of the change. */
+ startPosition;
+ /** The end position of the change before the edit. */
+ oldEndPosition;
+ /** The end position of the change after the edit. */
+ newEndPosition;
+ /** The start index of the change. */
+ startIndex;
+ /** The end index of the change before the edit. */
+ oldEndIndex;
+ /** The end index of the change after the edit. */
+ newEndIndex;
+ constructor({
+ startIndex,
+ oldEndIndex,
+ newEndIndex,
+ startPosition,
+ oldEndPosition,
+ newEndPosition
+ }) {
+ this.startIndex = startIndex >>> 0;
+ this.oldEndIndex = oldEndIndex >>> 0;
+ this.newEndIndex = newEndIndex >>> 0;
+ this.startPosition = startPosition;
+ this.oldEndPosition = oldEndPosition;
+ this.newEndPosition = newEndPosition;
+ }
+ /**
+ * Edit a point and index to keep it in-sync with source code that has been edited.
+ *
+ * This function updates a single point's byte offset and row/column position
+ * based on an edit operation. This is useful for editing points without
+ * requiring a tree or node instance.
+ */
+ editPoint(point, index) {
+ let newIndex = index;
+ const newPoint = { ...point };
+ if (index >= this.oldEndIndex) {
+ newIndex = this.newEndIndex + (index - this.oldEndIndex);
+ const originalRow = point.row;
+ newPoint.row = this.newEndPosition.row + (point.row - this.oldEndPosition.row);
+ newPoint.column = originalRow === this.oldEndPosition.row ? this.newEndPosition.column + (point.column - this.oldEndPosition.column) : point.column;
+ } else if (index > this.startIndex) {
+ newIndex = this.newEndIndex;
+ newPoint.row = this.newEndPosition.row;
+ newPoint.column = this.newEndPosition.column;
+ }
+ return { point: newPoint, index: newIndex };
+ }
+ /**
+ * Edit a range to keep it in-sync with source code that has been edited.
+ *
+ * This function updates a range's start and end positions based on an edit
+ * operation. This is useful for editing ranges without requiring a tree
+ * or node instance.
+ */
+ editRange(range) {
+ const newRange = {
+ startIndex: range.startIndex,
+ startPosition: { ...range.startPosition },
+ endIndex: range.endIndex,
+ endPosition: { ...range.endPosition }
+ };
+ if (range.endIndex >= this.oldEndIndex) {
+ if (range.endIndex !== Number.MAX_SAFE_INTEGER) {
+ newRange.endIndex = this.newEndIndex + (range.endIndex - this.oldEndIndex);
+ newRange.endPosition = {
+ row: this.newEndPosition.row + (range.endPosition.row - this.oldEndPosition.row),
+ column: range.endPosition.row === this.oldEndPosition.row ? this.newEndPosition.column + (range.endPosition.column - this.oldEndPosition.column) : range.endPosition.column
+ };
+ if (newRange.endIndex < this.newEndIndex) {
+ newRange.endIndex = Number.MAX_SAFE_INTEGER;
+ newRange.endPosition = { row: Number.MAX_SAFE_INTEGER, column: Number.MAX_SAFE_INTEGER };
+ }
+ }
+ } else if (range.endIndex > this.startIndex) {
+ newRange.endIndex = this.startIndex;
+ newRange.endPosition = { ...this.startPosition };
+ }
+ if (range.startIndex >= this.oldEndIndex) {
+ newRange.startIndex = this.newEndIndex + (range.startIndex - this.oldEndIndex);
+ newRange.startPosition = {
+ row: this.newEndPosition.row + (range.startPosition.row - this.oldEndPosition.row),
+ column: range.startPosition.row === this.oldEndPosition.row ? this.newEndPosition.column + (range.startPosition.column - this.oldEndPosition.column) : range.startPosition.column
+ };
+ if (newRange.startIndex < this.newEndIndex) {
+ newRange.startIndex = Number.MAX_SAFE_INTEGER;
+ newRange.startPosition = { row: Number.MAX_SAFE_INTEGER, column: Number.MAX_SAFE_INTEGER };
+ }
+ } else if (range.startIndex > this.startIndex) {
+ newRange.startIndex = this.startIndex;
+ newRange.startPosition = { ...this.startPosition };
+ }
+ return newRange;
+ }
+};
+
+// src/constants.ts
+var SIZE_OF_SHORT = 2;
+var SIZE_OF_INT = 4;
+var SIZE_OF_CURSOR = 4 * SIZE_OF_INT;
+var SIZE_OF_NODE = 5 * SIZE_OF_INT;
+var SIZE_OF_POINT = 2 * SIZE_OF_INT;
+var SIZE_OF_RANGE = 2 * SIZE_OF_INT + 2 * SIZE_OF_POINT;
+var ZERO_POINT = { row: 0, column: 0 };
+var INTERNAL = /* @__PURE__ */ Symbol("INTERNAL");
+function assertInternal(x) {
+ if (x !== INTERNAL) throw new Error("Illegal constructor");
+}
+__name(assertInternal, "assertInternal");
+function isPoint(point) {
+ return !!point && typeof point.row === "number" && typeof point.column === "number";
+}
+__name(isPoint, "isPoint");
+function setModule(module2) {
+ C = module2;
+}
+__name(setModule, "setModule");
+var C;
+
+// src/lookahead_iterator.ts
+var LookaheadIterator = class {
+ static {
+ __name(this, "LookaheadIterator");
+ }
+ /** @internal */
+ [0] = 0;
+ // Internal handle for Wasm
+ /** @internal */
+ language;
+ /** @internal */
+ constructor(internal, address, language) {
+ assertInternal(internal);
+ this[0] = address;
+ this.language = language;
+ }
+ /** Get the current symbol of the lookahead iterator. */
+ get currentTypeId() {
+ return C._ts_lookahead_iterator_current_symbol(this[0]);
+ }
+ /** Get the current symbol name of the lookahead iterator. */
+ get currentType() {
+ return this.language.types[this.currentTypeId] || "ERROR";
+ }
+ /** Delete the lookahead iterator, freeing its resources. */
+ delete() {
+ C._ts_lookahead_iterator_delete(this[0]);
+ this[0] = 0;
+ }
+ /**
+ * Reset the lookahead iterator.
+ *
+ * This returns `true` if the language was set successfully and `false`
+ * otherwise.
+ */
+ reset(language, stateId) {
+ if (C._ts_lookahead_iterator_reset(this[0], language[0], stateId)) {
+ this.language = language;
+ return true;
+ }
+ return false;
+ }
+ /**
+ * Reset the lookahead iterator to another state.
+ *
+ * This returns `true` if the iterator was reset to the given state and
+ * `false` otherwise.
+ */
+ resetState(stateId) {
+ return Boolean(C._ts_lookahead_iterator_reset_state(this[0], stateId));
+ }
+ /**
+ * Returns an iterator that iterates over the symbols of the lookahead iterator.
+ *
+ * The iterator will yield the current symbol name as a string for each step
+ * until there are no more symbols to iterate over.
+ */
+ [Symbol.iterator]() {
+ return {
+ next: /* @__PURE__ */ __name(() => {
+ if (C._ts_lookahead_iterator_next(this[0])) {
+ return { done: false, value: this.currentType };
+ }
+ return { done: true, value: "" };
+ }, "next")
+ };
+ }
+};
+
+// src/tree.ts
+function getText(tree, startIndex, endIndex, startPosition) {
+ const length = endIndex - startIndex;
+ let result = tree.textCallback(startIndex, startPosition);
+ if (result) {
+ startIndex += result.length;
+ while (startIndex < endIndex) {
+ const string = tree.textCallback(startIndex, startPosition);
+ if (string && string.length > 0) {
+ startIndex += string.length;
+ result += string;
+ } else {
+ break;
+ }
+ }
+ if (startIndex > endIndex) {
+ result = result.slice(0, length);
+ }
+ }
+ return result ?? "";
+}
+__name(getText, "getText");
+var Tree = class _Tree {
+ static {
+ __name(this, "Tree");
+ }
+ /** @internal */
+ [0] = 0;
+ // Internal handle for Wasm
+ /** @internal */
+ textCallback;
+ /** The language that was used to parse the syntax tree. */
+ language;
+ /** @internal */
+ constructor(internal, address, language, textCallback) {
+ assertInternal(internal);
+ this[0] = address;
+ this.language = language;
+ this.textCallback = textCallback;
+ }
+ /** Create a shallow copy of the syntax tree. This is very fast. */
+ copy() {
+ const address = C._ts_tree_copy(this[0]);
+ return new _Tree(INTERNAL, address, this.language, this.textCallback);
+ }
+ /** Delete the syntax tree, freeing its resources. */
+ delete() {
+ C._ts_tree_delete(this[0]);
+ this[0] = 0;
+ }
+ /** Get the root node of the syntax tree. */
+ get rootNode() {
+ C._ts_tree_root_node_wasm(this[0]);
+ return unmarshalNode(this);
+ }
+ /**
+ * Get the root node of the syntax tree, but with its position shifted
+ * forward by the given offset.
+ */
+ rootNodeWithOffset(offsetBytes, offsetExtent) {
+ const address = TRANSFER_BUFFER + SIZE_OF_NODE;
+ C.setValue(address, offsetBytes, "i32");
+ marshalPoint(address + SIZE_OF_INT, offsetExtent);
+ C._ts_tree_root_node_with_offset_wasm(this[0]);
+ return unmarshalNode(this);
+ }
+ /**
+ * Edit the syntax tree to keep it in sync with source code that has been
+ * edited.
+ *
+ * You must describe the edit both in terms of byte offsets and in terms of
+ * row/column coordinates.
+ */
+ edit(edit) {
+ marshalEdit(edit);
+ C._ts_tree_edit_wasm(this[0]);
+ }
+ /** Create a new {@link TreeCursor} starting from the root of the tree. */
+ walk() {
+ return this.rootNode.walk();
+ }
+ /**
+ * Compare this old edited syntax tree to a new syntax tree representing
+ * the same document, returning a sequence of ranges whose syntactic
+ * structure has changed.
+ *
+ * For this to work correctly, this syntax tree must have been edited such
+ * that its ranges match up to the new tree. Generally, you'll want to
+ * call this method right after calling one of the [`Parser::parse`]
+ * functions. Call it on the old tree that was passed to parse, and
+ * pass the new tree that was returned from `parse`.
+ */
+ getChangedRanges(other) {
+ if (!(other instanceof _Tree)) {
+ throw new TypeError("Argument must be a Tree");
+ }
+ C._ts_tree_get_changed_ranges_wasm(this[0], other[0]);
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
+ const result = new Array(count);
+ if (count > 0) {
+ let address = buffer;
+ for (let i2 = 0; i2 < count; i2++) {
+ result[i2] = unmarshalRange(address);
+ address += SIZE_OF_RANGE;
+ }
+ C._free(buffer);
+ }
+ return result;
+ }
+ /** Get the included ranges that were used to parse the syntax tree. */
+ getIncludedRanges() {
+ C._ts_tree_included_ranges_wasm(this[0]);
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
+ const result = new Array(count);
+ if (count > 0) {
+ let address = buffer;
+ for (let i2 = 0; i2 < count; i2++) {
+ result[i2] = unmarshalRange(address);
+ address += SIZE_OF_RANGE;
+ }
+ C._free(buffer);
+ }
+ return result;
+ }
+};
+
+// src/tree_cursor.ts
+var TreeCursor = class _TreeCursor {
+ static {
+ __name(this, "TreeCursor");
+ }
+ /** @internal */
+ // @ts-expect-error: never read
+ [0] = 0;
+ // Internal handle for Wasm
+ /** @internal */
+ // @ts-expect-error: never read
+ [1] = 0;
+ // Internal handle for Wasm
+ /** @internal */
+ // @ts-expect-error: never read
+ [2] = 0;
+ // Internal handle for Wasm
+ /** @internal */
+ // @ts-expect-error: never read
+ [3] = 0;
+ // Internal handle for Wasm
+ /** @internal */
+ tree;
+ /** @internal */
+ constructor(internal, tree) {
+ assertInternal(internal);
+ this.tree = tree;
+ unmarshalTreeCursor(this);
+ }
+ /** Creates a deep copy of the tree cursor. This allocates new memory. */
+ copy() {
+ const copy = new _TreeCursor(INTERNAL, this.tree);
+ C._ts_tree_cursor_copy_wasm(this.tree[0]);
+ unmarshalTreeCursor(copy);
+ return copy;
+ }
+ /** Delete the tree cursor, freeing its resources. */
+ delete() {
+ marshalTreeCursor(this);
+ C._ts_tree_cursor_delete_wasm(this.tree[0]);
+ this[0] = this[1] = this[2] = 0;
+ }
+ /** Get the tree cursor's current {@link Node}. */
+ get currentNode() {
+ marshalTreeCursor(this);
+ C._ts_tree_cursor_current_node_wasm(this.tree[0]);
+ return unmarshalNode(this.tree);
+ }
+ /**
+ * Get the numerical field id of this tree cursor's current node.
+ *
+ * See also {@link TreeCursor#currentFieldName}.
+ */
+ get currentFieldId() {
+ marshalTreeCursor(this);
+ return C._ts_tree_cursor_current_field_id_wasm(this.tree[0]);
+ }
+ /** Get the field name of this tree cursor's current node. */
+ get currentFieldName() {
+ return this.tree.language.fields[this.currentFieldId];
+ }
+ /**
+ * Get the depth of the cursor's current node relative to the original
+ * node that the cursor was constructed with.
+ */
+ get currentDepth() {
+ marshalTreeCursor(this);
+ return C._ts_tree_cursor_current_depth_wasm(this.tree[0]);
+ }
+ /**
+ * Get the index of the cursor's current node out of all of the
+ * descendants of the original node that the cursor was constructed with.
+ */
+ get currentDescendantIndex() {
+ marshalTreeCursor(this);
+ return C._ts_tree_cursor_current_descendant_index_wasm(this.tree[0]);
+ }
+ /** Get the type of the cursor's current node. */
+ get nodeType() {
+ return this.tree.language.types[this.nodeTypeId] || "ERROR";
+ }
+ /** Get the type id of the cursor's current node. */
+ get nodeTypeId() {
+ marshalTreeCursor(this);
+ return C._ts_tree_cursor_current_node_type_id_wasm(this.tree[0]);
+ }
+ /** Get the state id of the cursor's current node. */
+ get nodeStateId() {
+ marshalTreeCursor(this);
+ return C._ts_tree_cursor_current_node_state_id_wasm(this.tree[0]);
+ }
+ /** Get the id of the cursor's current node. */
+ get nodeId() {
+ marshalTreeCursor(this);
+ return C._ts_tree_cursor_current_node_id_wasm(this.tree[0]);
+ }
+ /**
+ * Check if the cursor's current node is *named*.
+ *
+ * Named nodes correspond to named rules in the grammar, whereas
+ * *anonymous* nodes correspond to string literals in the grammar.
+ */
+ get nodeIsNamed() {
+ marshalTreeCursor(this);
+ return C._ts_tree_cursor_current_node_is_named_wasm(this.tree[0]) === 1;
+ }
+ /**
+ * Check if the cursor's current node is *missing*.
+ *
+ * Missing nodes are inserted by the parser in order to recover from
+ * certain kinds of syntax errors.
+ */
+ get nodeIsMissing() {
+ marshalTreeCursor(this);
+ return C._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0]) === 1;
+ }
+ /** Get the string content of the cursor's current node. */
+ get nodeText() {
+ marshalTreeCursor(this);
+ const startIndex = C._ts_tree_cursor_start_index_wasm(this.tree[0]);
+ const endIndex = C._ts_tree_cursor_end_index_wasm(this.tree[0]);
+ C._ts_tree_cursor_start_position_wasm(this.tree[0]);
+ const startPosition = unmarshalPoint(TRANSFER_BUFFER);
+ return getText(this.tree, startIndex, endIndex, startPosition);
+ }
+ /** Get the start position of the cursor's current node. */
+ get startPosition() {
+ marshalTreeCursor(this);
+ C._ts_tree_cursor_start_position_wasm(this.tree[0]);
+ return unmarshalPoint(TRANSFER_BUFFER);
+ }
+ /** Get the end position of the cursor's current node. */
+ get endPosition() {
+ marshalTreeCursor(this);
+ C._ts_tree_cursor_end_position_wasm(this.tree[0]);
+ return unmarshalPoint(TRANSFER_BUFFER);
+ }
+ /** Get the start index of the cursor's current node. */
+ get startIndex() {
+ marshalTreeCursor(this);
+ return C._ts_tree_cursor_start_index_wasm(this.tree[0]);
+ }
+ /** Get the end index of the cursor's current node. */
+ get endIndex() {
+ marshalTreeCursor(this);
+ return C._ts_tree_cursor_end_index_wasm(this.tree[0]);
+ }
+ /**
+ * Move this cursor to the first child of its current node.
+ *
+ * This returns `true` if the cursor successfully moved, and returns
+ * `false` if there were no children.
+ */
+ gotoFirstChild() {
+ marshalTreeCursor(this);
+ const result = C._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);
+ unmarshalTreeCursor(this);
+ return result === 1;
+ }
+ /**
+ * Move this cursor to the last child of its current node.
+ *
+ * This returns `true` if the cursor successfully moved, and returns
+ * `false` if there were no children.
+ *
+ * Note that this function may be slower than
+ * {@link TreeCursor#gotoFirstChild} because it needs to
+ * iterate through all the children to compute the child's position.
+ */
+ gotoLastChild() {
+ marshalTreeCursor(this);
+ const result = C._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);
+ unmarshalTreeCursor(this);
+ return result === 1;
+ }
+ /**
+ * Move this cursor to the parent of its current node.
+ *
+ * This returns `true` if the cursor successfully moved, and returns
+ * `false` if there was no parent node (the cursor was already on the
+ * root node).
+ *
+ * Note that the node the cursor was constructed with is considered the root
+ * of the cursor, and the cursor cannot walk outside this node.
+ */
+ gotoParent() {
+ marshalTreeCursor(this);
+ const result = C._ts_tree_cursor_goto_parent_wasm(this.tree[0]);
+ unmarshalTreeCursor(this);
+ return result === 1;
+ }
+ /**
+ * Move this cursor to the next sibling of its current node.
+ *
+ * This returns `true` if the cursor successfully moved, and returns
+ * `false` if there was no next sibling node.
+ *
+ * Note that the node the cursor was constructed with is considered the root
+ * of the cursor, and the cursor cannot walk outside this node.
+ */
+ gotoNextSibling() {
+ marshalTreeCursor(this);
+ const result = C._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);
+ unmarshalTreeCursor(this);
+ return result === 1;
+ }
+ /**
+ * Move this cursor to the previous sibling of its current node.
+ *
+ * This returns `true` if the cursor successfully moved, and returns
+ * `false` if there was no previous sibling node.
+ *
+ * Note that this function may be slower than
+ * {@link TreeCursor#gotoNextSibling} due to how node
+ * positions are stored. In the worst case, this will need to iterate
+ * through all the children up to the previous sibling node to recalculate
+ * its position. Also note that the node the cursor was constructed with is
+ * considered the root of the cursor, and the cursor cannot walk outside this node.
+ */
+ gotoPreviousSibling() {
+ marshalTreeCursor(this);
+ const result = C._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);
+ unmarshalTreeCursor(this);
+ return result === 1;
+ }
+ /**
+ * Move the cursor to the node that is the nth descendant of
+ * the original node that the cursor was constructed with, where
+ * zero represents the original node itself.
+ */
+ gotoDescendant(goalDescendantIndex) {
+ marshalTreeCursor(this);
+ C._ts_tree_cursor_goto_descendant_wasm(this.tree[0], goalDescendantIndex);
+ unmarshalTreeCursor(this);
+ }
+ /**
+ * Move this cursor to the first child of its current node that contains or
+ * starts after the given byte offset.
+ *
+ * This returns `true` if the cursor successfully moved to a child node, and returns
+ * `false` if no such child was found.
+ */
+ gotoFirstChildForIndex(goalIndex) {
+ marshalTreeCursor(this);
+ C.setValue(TRANSFER_BUFFER + SIZE_OF_CURSOR, goalIndex, "i32");
+ const result = C._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);
+ unmarshalTreeCursor(this);
+ return result === 1;
+ }
+ /**
+ * Move this cursor to the first child of its current node that contains or
+ * starts after the given byte offset.
+ *
+ * This returns the index of the child node if one was found, and returns
+ * `null` if no such child was found.
+ */
+ gotoFirstChildForPosition(goalPosition) {
+ marshalTreeCursor(this);
+ marshalPoint(TRANSFER_BUFFER + SIZE_OF_CURSOR, goalPosition);
+ const result = C._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);
+ unmarshalTreeCursor(this);
+ return result === 1;
+ }
+ /**
+ * Re-initialize this tree cursor to start at the original node that the
+ * cursor was constructed with.
+ */
+ reset(node) {
+ marshalNode(node);
+ marshalTreeCursor(this, TRANSFER_BUFFER + SIZE_OF_NODE);
+ C._ts_tree_cursor_reset_wasm(this.tree[0]);
+ unmarshalTreeCursor(this);
+ }
+ /**
+ * Re-initialize a tree cursor to the same position as another cursor.
+ *
+ * Unlike {@link TreeCursor#reset}, this will not lose parent
+ * information and allows reusing already created cursors.
+ */
+ resetTo(cursor) {
+ marshalTreeCursor(this, TRANSFER_BUFFER);
+ marshalTreeCursor(cursor, TRANSFER_BUFFER + SIZE_OF_CURSOR);
+ C._ts_tree_cursor_reset_to_wasm(this.tree[0], cursor.tree[0]);
+ unmarshalTreeCursor(this);
+ }
+};
+
+// src/node.ts
+var Node = class {
+ static {
+ __name(this, "Node");
+ }
+ /** @internal */
+ // @ts-expect-error: never read
+ [0] = 0;
+ // Internal handle for Wasm
+ /** @internal */
+ _children;
+ /** @internal */
+ _namedChildren;
+ /** @internal */
+ constructor(internal, {
+ id,
+ tree,
+ startIndex,
+ startPosition,
+ other
+ }) {
+ assertInternal(internal);
+ this[0] = other;
+ this.id = id;
+ this.tree = tree;
+ this.startIndex = startIndex;
+ this.startPosition = startPosition;
+ }
+ /**
+ * The numeric id for this node that is unique.
+ *
+ * Within a given syntax tree, no two nodes have the same id. However:
+ *
+ * * If a new tree is created based on an older tree, and a node from the old tree is reused in
+ * the process, then that node will have the same id in both trees.
+ *
+ * * A node not marked as having changes does not guarantee it was reused.
+ *
+ * * If a node is marked as having changed in the old tree, it will not be reused.
+ */
+ id;
+ /** The byte index where this node starts. */
+ startIndex;
+ /** The position where this node starts. */
+ startPosition;
+ /** The tree that this node belongs to. */
+ tree;
+ /** Get this node's type as a numerical id. */
+ get typeId() {
+ marshalNode(this);
+ return C._ts_node_symbol_wasm(this.tree[0]);
+ }
+ /**
+ * Get the node's type as a numerical id as it appears in the grammar,
+ * ignoring aliases.
+ */
+ get grammarId() {
+ marshalNode(this);
+ return C._ts_node_grammar_symbol_wasm(this.tree[0]);
+ }
+ /** Get this node's type as a string. */
+ get type() {
+ return this.tree.language.types[this.typeId] || "ERROR";
+ }
+ /**
+ * Get this node's symbol name as it appears in the grammar, ignoring
+ * aliases as a string.
+ */
+ get grammarType() {
+ return this.tree.language.types[this.grammarId] || "ERROR";
+ }
+ /**
+ * Check if this node is *named*.
+ *
+ * Named nodes correspond to named rules in the grammar, whereas
+ * *anonymous* nodes correspond to string literals in the grammar.
+ */
+ get isNamed() {
+ marshalNode(this);
+ return C._ts_node_is_named_wasm(this.tree[0]) === 1;
+ }
+ /**
+ * Check if this node is *extra*.
+ *
+ * Extra nodes represent things like comments, which are not required
+ * by the grammar, but can appear anywhere.
+ */
+ get isExtra() {
+ marshalNode(this);
+ return C._ts_node_is_extra_wasm(this.tree[0]) === 1;
+ }
+ /**
+ * Check if this node represents a syntax error.
+ *
+ * Syntax errors represent parts of the code that could not be incorporated
+ * into a valid syntax tree.
+ */
+ get isError() {
+ marshalNode(this);
+ return C._ts_node_is_error_wasm(this.tree[0]) === 1;
+ }
+ /**
+ * Check if this node is *missing*.
+ *
+ * Missing nodes are inserted by the parser in order to recover from
+ * certain kinds of syntax errors.
+ */
+ get isMissing() {
+ marshalNode(this);
+ return C._ts_node_is_missing_wasm(this.tree[0]) === 1;
+ }
+ /** Check if this node has been edited. */
+ get hasChanges() {
+ marshalNode(this);
+ return C._ts_node_has_changes_wasm(this.tree[0]) === 1;
+ }
+ /**
+ * Check if this node represents a syntax error or contains any syntax
+ * errors anywhere within it.
+ */
+ get hasError() {
+ marshalNode(this);
+ return C._ts_node_has_error_wasm(this.tree[0]) === 1;
+ }
+ /** Get the byte index where this node ends. */
+ get endIndex() {
+ marshalNode(this);
+ return C._ts_node_end_index_wasm(this.tree[0]);
+ }
+ /** Get the position where this node ends. */
+ get endPosition() {
+ marshalNode(this);
+ C._ts_node_end_point_wasm(this.tree[0]);
+ return unmarshalPoint(TRANSFER_BUFFER);
+ }
+ /** Get the string content of this node. */
+ get text() {
+ return getText(this.tree, this.startIndex, this.endIndex, this.startPosition);
+ }
+ /** Get this node's parse state. */
+ get parseState() {
+ marshalNode(this);
+ return C._ts_node_parse_state_wasm(this.tree[0]);
+ }
+ /** Get the parse state after this node. */
+ get nextParseState() {
+ marshalNode(this);
+ return C._ts_node_next_parse_state_wasm(this.tree[0]);
+ }
+ /** Check if this node is equal to another node. */
+ equals(other) {
+ return this.tree === other.tree && this.id === other.id;
+ }
+ /**
+ * Get the node's child at the given index, where zero represents the first child.
+ *
+ * This method is fairly fast, but its cost is technically log(n), so if
+ * you might be iterating over a long list of children, you should use
+ * {@link Node#children} instead.
+ */
+ child(index) {
+ marshalNode(this);
+ C._ts_node_child_wasm(this.tree[0], index);
+ return unmarshalNode(this.tree);
+ }
+ /**
+ * Get this node's *named* child at the given index.
+ *
+ * See also {@link Node#isNamed}.
+ * This method is fairly fast, but its cost is technically log(n), so if
+ * you might be iterating over a long list of children, you should use
+ * {@link Node#namedChildren} instead.
+ */
+ namedChild(index) {
+ marshalNode(this);
+ C._ts_node_named_child_wasm(this.tree[0], index);
+ return unmarshalNode(this.tree);
+ }
+ /**
+ * Get this node's child with the given numerical field id.
+ *
+ * See also {@link Node#childForFieldName}. You can
+ * convert a field name to an id using {@link Language#fieldIdForName}.
+ */
+ childForFieldId(fieldId) {
+ marshalNode(this);
+ C._ts_node_child_by_field_id_wasm(this.tree[0], fieldId);
+ return unmarshalNode(this.tree);
+ }
+ /**
+ * Get the first child with the given field name.
+ *
+ * If multiple children may have the same field name, access them using
+ * {@link Node#childrenForFieldName}.
+ */
+ childForFieldName(fieldName) {
+ const fieldId = this.tree.language.fields.indexOf(fieldName);
+ if (fieldId !== -1) return this.childForFieldId(fieldId);
+ return null;
+ }
+ /** Get the field name of this node's child at the given index. */
+ fieldNameForChild(index) {
+ marshalNode(this);
+ const address = C._ts_node_field_name_for_child_wasm(this.tree[0], index);
+ if (!address) return null;
+ return C.AsciiToString(address);
+ }
+ /** Get the field name of this node's named child at the given index. */
+ fieldNameForNamedChild(index) {
+ marshalNode(this);
+ const address = C._ts_node_field_name_for_named_child_wasm(this.tree[0], index);
+ if (!address) return null;
+ return C.AsciiToString(address);
+ }
+ /**
+ * Get an array of this node's children with a given field name.
+ *
+ * See also {@link Node#children}.
+ */
+ childrenForFieldName(fieldName) {
+ const fieldId = this.tree.language.fields.indexOf(fieldName);
+ if (fieldId !== -1 && fieldId !== 0) return this.childrenForFieldId(fieldId);
+ return [];
+ }
+ /**
+ * Get an array of this node's children with a given field id.
+ *
+ * See also {@link Node#childrenForFieldName}.
+ */
+ childrenForFieldId(fieldId) {
+ marshalNode(this);
+ C._ts_node_children_by_field_id_wasm(this.tree[0], fieldId);
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
+ const result = new Array(count);
+ if (count > 0) {
+ let address = buffer;
+ for (let i2 = 0; i2 < count; i2++) {
+ result[i2] = unmarshalNode(this.tree, address);
+ address += SIZE_OF_NODE;
+ }
+ C._free(buffer);
+ }
+ return result;
+ }
+ /** Get the node's first child that contains or starts after the given byte offset. */
+ firstChildForIndex(index) {
+ marshalNode(this);
+ const address = TRANSFER_BUFFER + SIZE_OF_NODE;
+ C.setValue(address, index, "i32");
+ C._ts_node_first_child_for_byte_wasm(this.tree[0]);
+ return unmarshalNode(this.tree);
+ }
+ /** Get the node's first named child that contains or starts after the given byte offset. */
+ firstNamedChildForIndex(index) {
+ marshalNode(this);
+ const address = TRANSFER_BUFFER + SIZE_OF_NODE;
+ C.setValue(address, index, "i32");
+ C._ts_node_first_named_child_for_byte_wasm(this.tree[0]);
+ return unmarshalNode(this.tree);
+ }
+ /** Get this node's number of children. */
+ get childCount() {
+ marshalNode(this);
+ return C._ts_node_child_count_wasm(this.tree[0]);
+ }
+ /**
+ * Get this node's number of *named* children.
+ *
+ * See also {@link Node#isNamed}.
+ */
+ get namedChildCount() {
+ marshalNode(this);
+ return C._ts_node_named_child_count_wasm(this.tree[0]);
+ }
+ /** Get this node's first child. */
+ get firstChild() {
+ return this.child(0);
+ }
+ /**
+ * Get this node's first named child.
+ *
+ * See also {@link Node#isNamed}.
+ */
+ get firstNamedChild() {
+ return this.namedChild(0);
+ }
+ /** Get this node's last child. */
+ get lastChild() {
+ return this.child(this.childCount - 1);
+ }
+ /**
+ * Get this node's last named child.
+ *
+ * See also {@link Node#isNamed}.
+ */
+ get lastNamedChild() {
+ return this.namedChild(this.namedChildCount - 1);
+ }
+ /**
+ * Iterate over this node's children.
+ *
+ * If you're walking the tree recursively, you may want to use the
+ * {@link TreeCursor} APIs directly instead.
+ */
+ get children() {
+ if (!this._children) {
+ marshalNode(this);
+ C._ts_node_children_wasm(this.tree[0]);
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
+ this._children = new Array(count);
+ if (count > 0) {
+ let address = buffer;
+ for (let i2 = 0; i2 < count; i2++) {
+ this._children[i2] = unmarshalNode(this.tree, address);
+ address += SIZE_OF_NODE;
+ }
+ C._free(buffer);
+ }
+ }
+ return this._children;
+ }
+ /**
+ * Iterate over this node's named children.
+ *
+ * See also {@link Node#children}.
+ */
+ get namedChildren() {
+ if (!this._namedChildren) {
+ marshalNode(this);
+ C._ts_node_named_children_wasm(this.tree[0]);
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
+ this._namedChildren = new Array(count);
+ if (count > 0) {
+ let address = buffer;
+ for (let i2 = 0; i2 < count; i2++) {
+ this._namedChildren[i2] = unmarshalNode(this.tree, address);
+ address += SIZE_OF_NODE;
+ }
+ C._free(buffer);
+ }
+ }
+ return this._namedChildren;
+ }
+ /**
+ * Get the descendants of this node that are the given type, or in the given types array.
+ *
+ * The types array should contain node type strings, which can be retrieved from {@link Language#types}.
+ *
+ * Additionally, a `startPosition` and `endPosition` can be passed in to restrict the search to a byte range.
+ */
+ descendantsOfType(types, startPosition = ZERO_POINT, endPosition = ZERO_POINT) {
+ if (!Array.isArray(types)) types = [types];
+ const symbols = [];
+ const typesBySymbol = this.tree.language.types;
+ for (const node_type of types) {
+ if (node_type == "ERROR") {
+ symbols.push(65535);
+ }
+ }
+ for (let i2 = 0, n = typesBySymbol.length; i2 < n; i2++) {
+ if (types.includes(typesBySymbol[i2])) {
+ symbols.push(i2);
+ }
+ }
+ const symbolsAddress = C._malloc(SIZE_OF_INT * symbols.length);
+ for (let i2 = 0, n = symbols.length; i2 < n; i2++) {
+ C.setValue(symbolsAddress + i2 * SIZE_OF_INT, symbols[i2], "i32");
+ }
+ marshalNode(this);
+ C._ts_node_descendants_of_type_wasm(
+ this.tree[0],
+ symbolsAddress,
+ symbols.length,
+ startPosition.row,
+ startPosition.column,
+ endPosition.row,
+ endPosition.column
+ );
+ const descendantCount = C.getValue(TRANSFER_BUFFER, "i32");
+ const descendantAddress = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
+ const result = new Array(descendantCount);
+ if (descendantCount > 0) {
+ let address = descendantAddress;
+ for (let i2 = 0; i2 < descendantCount; i2++) {
+ result[i2] = unmarshalNode(this.tree, address);
+ address += SIZE_OF_NODE;
+ }
+ }
+ C._free(descendantAddress);
+ C._free(symbolsAddress);
+ return result;
+ }
+ /** Get this node's next sibling. */
+ get nextSibling() {
+ marshalNode(this);
+ C._ts_node_next_sibling_wasm(this.tree[0]);
+ return unmarshalNode(this.tree);
+ }
+ /** Get this node's previous sibling. */
+ get previousSibling() {
+ marshalNode(this);
+ C._ts_node_prev_sibling_wasm(this.tree[0]);
+ return unmarshalNode(this.tree);
+ }
+ /**
+ * Get this node's next *named* sibling.
+ *
+ * See also {@link Node#isNamed}.
+ */
+ get nextNamedSibling() {
+ marshalNode(this);
+ C._ts_node_next_named_sibling_wasm(this.tree[0]);
+ return unmarshalNode(this.tree);
+ }
+ /**
+ * Get this node's previous *named* sibling.
+ *
+ * See also {@link Node#isNamed}.
+ */
+ get previousNamedSibling() {
+ marshalNode(this);
+ C._ts_node_prev_named_sibling_wasm(this.tree[0]);
+ return unmarshalNode(this.tree);
+ }
+ /** Get the node's number of descendants, including one for the node itself. */
+ get descendantCount() {
+ marshalNode(this);
+ return C._ts_node_descendant_count_wasm(this.tree[0]);
+ }
+ /**
+ * Get this node's immediate parent.
+ * Prefer {@link Node#childWithDescendant} for iterating over this node's ancestors.
+ */
+ get parent() {
+ marshalNode(this);
+ C._ts_node_parent_wasm(this.tree[0]);
+ return unmarshalNode(this.tree);
+ }
+ /**
+ * Get the node that contains `descendant`.
+ *
+ * Note that this can return `descendant` itself.
+ */
+ childWithDescendant(descendant) {
+ marshalNode(this);
+ marshalNode(descendant, 1);
+ C._ts_node_child_with_descendant_wasm(this.tree[0]);
+ return unmarshalNode(this.tree);
+ }
+ /** Get the smallest node within this node that spans the given byte range. */
+ descendantForIndex(start2, end = start2) {
+ if (typeof start2 !== "number" || typeof end !== "number") {
+ throw new Error("Arguments must be numbers");
+ }
+ marshalNode(this);
+ const address = TRANSFER_BUFFER + SIZE_OF_NODE;
+ C.setValue(address, start2, "i32");
+ C.setValue(address + SIZE_OF_INT, end, "i32");
+ C._ts_node_descendant_for_index_wasm(this.tree[0]);
+ return unmarshalNode(this.tree);
+ }
+ /** Get the smallest named node within this node that spans the given byte range. */
+ namedDescendantForIndex(start2, end = start2) {
+ if (typeof start2 !== "number" || typeof end !== "number") {
+ throw new Error("Arguments must be numbers");
+ }
+ marshalNode(this);
+ const address = TRANSFER_BUFFER + SIZE_OF_NODE;
+ C.setValue(address, start2, "i32");
+ C.setValue(address + SIZE_OF_INT, end, "i32");
+ C._ts_node_named_descendant_for_index_wasm(this.tree[0]);
+ return unmarshalNode(this.tree);
+ }
+ /** Get the smallest node within this node that spans the given point range. */
+ descendantForPosition(start2, end = start2) {
+ if (!isPoint(start2) || !isPoint(end)) {
+ throw new Error("Arguments must be {row, column} objects");
+ }
+ marshalNode(this);
+ const address = TRANSFER_BUFFER + SIZE_OF_NODE;
+ marshalPoint(address, start2);
+ marshalPoint(address + SIZE_OF_POINT, end);
+ C._ts_node_descendant_for_position_wasm(this.tree[0]);
+ return unmarshalNode(this.tree);
+ }
+ /** Get the smallest named node within this node that spans the given point range. */
+ namedDescendantForPosition(start2, end = start2) {
+ if (!isPoint(start2) || !isPoint(end)) {
+ throw new Error("Arguments must be {row, column} objects");
+ }
+ marshalNode(this);
+ const address = TRANSFER_BUFFER + SIZE_OF_NODE;
+ marshalPoint(address, start2);
+ marshalPoint(address + SIZE_OF_POINT, end);
+ C._ts_node_named_descendant_for_position_wasm(this.tree[0]);
+ return unmarshalNode(this.tree);
+ }
+ /**
+ * Create a new {@link TreeCursor} starting from this node.
+ *
+ * Note that the given node is considered the root of the cursor,
+ * and the cursor cannot walk outside this node.
+ */
+ walk() {
+ marshalNode(this);
+ C._ts_tree_cursor_new_wasm(this.tree[0]);
+ return new TreeCursor(INTERNAL, this.tree);
+ }
+ /**
+ * Edit this node to keep it in-sync with source code that has been edited.
+ *
+ * This function is only rarely needed. When you edit a syntax tree with
+ * the {@link Tree#edit} method, all of the nodes that you retrieve from
+ * the tree afterward will already reflect the edit. You only need to
+ * use {@link Node#edit} when you have a specific {@link Node} instance that
+ * you want to keep and continue to use after an edit.
+ */
+ edit(edit) {
+ if (this.startIndex >= edit.oldEndIndex) {
+ this.startIndex = edit.newEndIndex + (this.startIndex - edit.oldEndIndex);
+ let subbedPointRow;
+ let subbedPointColumn;
+ if (this.startPosition.row > edit.oldEndPosition.row) {
+ subbedPointRow = this.startPosition.row - edit.oldEndPosition.row;
+ subbedPointColumn = this.startPosition.column;
+ } else {
+ subbedPointRow = 0;
+ subbedPointColumn = this.startPosition.column;
+ if (this.startPosition.column >= edit.oldEndPosition.column) {
+ subbedPointColumn = this.startPosition.column - edit.oldEndPosition.column;
+ }
+ }
+ if (subbedPointRow > 0) {
+ this.startPosition.row += subbedPointRow;
+ this.startPosition.column = subbedPointColumn;
+ } else {
+ this.startPosition.column += subbedPointColumn;
+ }
+ } else if (this.startIndex > edit.startIndex) {
+ this.startIndex = edit.newEndIndex;
+ this.startPosition.row = edit.newEndPosition.row;
+ this.startPosition.column = edit.newEndPosition.column;
+ }
+ }
+ /** Get the S-expression representation of this node. */
+ toString() {
+ marshalNode(this);
+ const address = C._ts_node_to_string_wasm(this.tree[0]);
+ const result = C.AsciiToString(address);
+ C._free(address);
+ return result;
+ }
+};
+
+// src/marshal.ts
+function unmarshalCaptures(query, tree, address, patternIndex, result) {
+ for (let i2 = 0, n = result.length; i2 < n; i2++) {
+ const captureIndex = C.getValue(address, "i32");
+ address += SIZE_OF_INT;
+ const node = unmarshalNode(tree, address);
+ address += SIZE_OF_NODE;
+ result[i2] = { patternIndex, name: query.captureNames[captureIndex], node };
+ }
+ return address;
+}
+__name(unmarshalCaptures, "unmarshalCaptures");
+function marshalNode(node, index = 0) {
+ let address = TRANSFER_BUFFER + index * SIZE_OF_NODE;
+ C.setValue(address, node.id, "i32");
+ address += SIZE_OF_INT;
+ C.setValue(address, node.startIndex, "i32");
+ address += SIZE_OF_INT;
+ C.setValue(address, node.startPosition.row, "i32");
+ address += SIZE_OF_INT;
+ C.setValue(address, node.startPosition.column, "i32");
+ address += SIZE_OF_INT;
+ C.setValue(address, node[0], "i32");
+}
+__name(marshalNode, "marshalNode");
+function unmarshalNode(tree, address = TRANSFER_BUFFER) {
+ const id = C.getValue(address, "i32");
+ address += SIZE_OF_INT;
+ if (id === 0) return null;
+ const index = C.getValue(address, "i32");
+ address += SIZE_OF_INT;
+ const row = C.getValue(address, "i32");
+ address += SIZE_OF_INT;
+ const column = C.getValue(address, "i32");
+ address += SIZE_OF_INT;
+ const other = C.getValue(address, "i32");
+ const result = new Node(INTERNAL, {
+ id,
+ tree,
+ startIndex: index,
+ startPosition: { row, column },
+ other
+ });
+ return result;
+}
+__name(unmarshalNode, "unmarshalNode");
+function marshalTreeCursor(cursor, address = TRANSFER_BUFFER) {
+ C.setValue(address + 0 * SIZE_OF_INT, cursor[0], "i32");
+ C.setValue(address + 1 * SIZE_OF_INT, cursor[1], "i32");
+ C.setValue(address + 2 * SIZE_OF_INT, cursor[2], "i32");
+ C.setValue(address + 3 * SIZE_OF_INT, cursor[3], "i32");
+}
+__name(marshalTreeCursor, "marshalTreeCursor");
+function unmarshalTreeCursor(cursor) {
+ cursor[0] = C.getValue(TRANSFER_BUFFER + 0 * SIZE_OF_INT, "i32");
+ cursor[1] = C.getValue(TRANSFER_BUFFER + 1 * SIZE_OF_INT, "i32");
+ cursor[2] = C.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
+ cursor[3] = C.getValue(TRANSFER_BUFFER + 3 * SIZE_OF_INT, "i32");
+}
+__name(unmarshalTreeCursor, "unmarshalTreeCursor");
+function marshalPoint(address, point) {
+ C.setValue(address, point.row, "i32");
+ C.setValue(address + SIZE_OF_INT, point.column, "i32");
+}
+__name(marshalPoint, "marshalPoint");
+function unmarshalPoint(address) {
+ const result = {
+ row: C.getValue(address, "i32") >>> 0,
+ column: C.getValue(address + SIZE_OF_INT, "i32") >>> 0
+ };
+ return result;
+}
+__name(unmarshalPoint, "unmarshalPoint");
+function marshalRange(address, range) {
+ marshalPoint(address, range.startPosition);
+ address += SIZE_OF_POINT;
+ marshalPoint(address, range.endPosition);
+ address += SIZE_OF_POINT;
+ C.setValue(address, range.startIndex, "i32");
+ address += SIZE_OF_INT;
+ C.setValue(address, range.endIndex, "i32");
+ address += SIZE_OF_INT;
+}
+__name(marshalRange, "marshalRange");
+function unmarshalRange(address) {
+ const result = {};
+ result.startPosition = unmarshalPoint(address);
+ address += SIZE_OF_POINT;
+ result.endPosition = unmarshalPoint(address);
+ address += SIZE_OF_POINT;
+ result.startIndex = C.getValue(address, "i32") >>> 0;
+ address += SIZE_OF_INT;
+ result.endIndex = C.getValue(address, "i32") >>> 0;
+ return result;
+}
+__name(unmarshalRange, "unmarshalRange");
+function marshalEdit(edit, address = TRANSFER_BUFFER) {
+ marshalPoint(address, edit.startPosition);
+ address += SIZE_OF_POINT;
+ marshalPoint(address, edit.oldEndPosition);
+ address += SIZE_OF_POINT;
+ marshalPoint(address, edit.newEndPosition);
+ address += SIZE_OF_POINT;
+ C.setValue(address, edit.startIndex, "i32");
+ address += SIZE_OF_INT;
+ C.setValue(address, edit.oldEndIndex, "i32");
+ address += SIZE_OF_INT;
+ C.setValue(address, edit.newEndIndex, "i32");
+ address += SIZE_OF_INT;
+}
+__name(marshalEdit, "marshalEdit");
+function unmarshalLanguageMetadata(address) {
+ const major_version = C.getValue(address, "i32");
+ const minor_version = C.getValue(address += SIZE_OF_INT, "i32");
+ const patch_version = C.getValue(address += SIZE_OF_INT, "i32");
+ return { major_version, minor_version, patch_version };
+}
+__name(unmarshalLanguageMetadata, "unmarshalLanguageMetadata");
+
+// src/language.ts
+var LANGUAGE_FUNCTION_REGEX = /^tree_sitter_\w+$/;
+var Language = class _Language {
+ static {
+ __name(this, "Language");
+ }
+ /** @internal */
+ [0] = 0;
+ // Internal handle for Wasm
+ /**
+ * A list of all node types in the language. The index of each type in this
+ * array is its node type id.
+ */
+ types;
+ /**
+ * A list of all field names in the language. The index of each field name in
+ * this array is its field id.
+ */
+ fields;
+ /** @internal */
+ constructor(internal, address) {
+ assertInternal(internal);
+ this[0] = address;
+ this.types = new Array(C._ts_language_symbol_count(this[0]));
+ for (let i2 = 0, n = this.types.length; i2 < n; i2++) {
+ if (C._ts_language_symbol_type(this[0], i2) < 2) {
+ this.types[i2] = C.UTF8ToString(C._ts_language_symbol_name(this[0], i2));
+ }
+ }
+ this.fields = new Array(C._ts_language_field_count(this[0]) + 1);
+ for (let i2 = 0, n = this.fields.length; i2 < n; i2++) {
+ const fieldName = C._ts_language_field_name_for_id(this[0], i2);
+ if (fieldName !== 0) {
+ this.fields[i2] = C.UTF8ToString(fieldName);
+ } else {
+ this.fields[i2] = null;
+ }
+ }
+ }
+ /**
+ * Gets the name of the language.
+ */
+ get name() {
+ const ptr = C._ts_language_name(this[0]);
+ if (ptr === 0) return null;
+ return C.UTF8ToString(ptr);
+ }
+ /**
+ * Gets the ABI version of the language.
+ */
+ get abiVersion() {
+ return C._ts_language_abi_version(this[0]);
+ }
+ /**
+ * Get the metadata for this language. This information is generated by the
+ * CLI, and relies on the language author providing the correct metadata in
+ * the language's `tree-sitter.json` file.
+ */
+ get metadata() {
+ C._ts_language_metadata_wasm(this[0]);
+ const length = C.getValue(TRANSFER_BUFFER, "i32");
+ if (length === 0) return null;
+ return unmarshalLanguageMetadata(TRANSFER_BUFFER + SIZE_OF_INT);
+ }
+ /**
+ * Gets the number of fields in the language.
+ */
+ get fieldCount() {
+ return this.fields.length - 1;
+ }
+ /**
+ * Gets the number of states in the language.
+ */
+ get stateCount() {
+ return C._ts_language_state_count(this[0]);
+ }
+ /**
+ * Get the field id for a field name.
+ */
+ fieldIdForName(fieldName) {
+ const result = this.fields.indexOf(fieldName);
+ return result !== -1 ? result : null;
+ }
+ /**
+ * Get the field name for a field id.
+ */
+ fieldNameForId(fieldId) {
+ return this.fields[fieldId] ?? null;
+ }
+ /**
+ * Get the node type id for a node type name.
+ */
+ idForNodeType(type, named) {
+ const typeLength = C.lengthBytesUTF8(type);
+ const typeAddress = C._malloc(typeLength + 1);
+ C.stringToUTF8(type, typeAddress, typeLength + 1);
+ const result = C._ts_language_symbol_for_name(this[0], typeAddress, typeLength, named ? 1 : 0);
+ C._free(typeAddress);
+ return result || null;
+ }
+ /**
+ * Gets the number of node types in the language.
+ */
+ get nodeTypeCount() {
+ return C._ts_language_symbol_count(this[0]);
+ }
+ /**
+ * Get the node type name for a node type id.
+ */
+ nodeTypeForId(typeId) {
+ const name2 = C._ts_language_symbol_name(this[0], typeId);
+ return name2 ? C.UTF8ToString(name2) : null;
+ }
+ /**
+ * Check if a node type is named.
+ *
+ * @see {@link https://tree-sitter.github.io/tree-sitter/using-parsers/2-basic-parsing.html#named-vs-anonymous-nodes}
+ */
+ nodeTypeIsNamed(typeId) {
+ return C._ts_language_type_is_named_wasm(this[0], typeId) ? true : false;
+ }
+ /**
+ * Check if a node type is visible.
+ */
+ nodeTypeIsVisible(typeId) {
+ return C._ts_language_type_is_visible_wasm(this[0], typeId) ? true : false;
+ }
+ /**
+ * Get the supertypes ids of this language.
+ *
+ * @see {@link https://tree-sitter.github.io/tree-sitter/using-parsers/6-static-node-types.html?highlight=supertype#supertype-nodes}
+ */
+ get supertypes() {
+ C._ts_language_supertypes_wasm(this[0]);
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
+ const result = new Array(count);
+ if (count > 0) {
+ let address = buffer;
+ for (let i2 = 0; i2 < count; i2++) {
+ result[i2] = C.getValue(address, "i16");
+ address += SIZE_OF_SHORT;
+ }
+ }
+ return result;
+ }
+ /**
+ * Get the subtype ids for a given supertype node id.
+ */
+ subtypes(supertype) {
+ C._ts_language_subtypes_wasm(this[0], supertype);
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
+ const result = new Array(count);
+ if (count > 0) {
+ let address = buffer;
+ for (let i2 = 0; i2 < count; i2++) {
+ result[i2] = C.getValue(address, "i16");
+ address += SIZE_OF_SHORT;
+ }
+ }
+ return result;
+ }
+ /**
+ * Get the next state id for a given state id and node type id.
+ */
+ nextState(stateId, typeId) {
+ return C._ts_language_next_state(this[0], stateId, typeId);
+ }
+ /**
+ * Create a new lookahead iterator for this language and parse state.
+ *
+ * This returns `null` if state is invalid for this language.
+ *
+ * Iterating {@link LookaheadIterator} will yield valid symbols in the given
+ * parse state. Newly created lookahead iterators will return the `ERROR`
+ * symbol from {@link LookaheadIterator#currentType}.
+ *
+ * Lookahead iterators can be useful for generating suggestions and improving
+ * syntax error diagnostics. To get symbols valid in an `ERROR` node, use the
+ * lookahead iterator on its first leaf node state. For `MISSING` nodes, a
+ * lookahead iterator created on the previous non-extra leaf node may be
+ * appropriate.
+ */
+ lookaheadIterator(stateId) {
+ const address = C._ts_lookahead_iterator_new(this[0], stateId);
+ if (address) return new LookaheadIterator(INTERNAL, address, this);
+ return null;
+ }
+ /**
+ * Load a language from a WebAssembly module.
+ * The module can be provided as a path to a file or as a buffer.
+ */
+ static async load(input) {
+ let binary2;
+ if (input instanceof Uint8Array) {
+ binary2 = input;
+ } else if (globalThis.process?.versions.node) {
+ const fs2 = await import("fs/promises");
+ binary2 = await fs2.readFile(input);
+ } else {
+ const response = await fetch(input);
+ if (!response.ok) {
+ const body2 = await response.text();
+ throw new Error(`Language.load failed with status ${response.status}.
+
+${body2}`);
+ }
+ const retryResp = response.clone();
+ try {
+ binary2 = await WebAssembly.compileStreaming(response);
+ } catch (reason) {
+ console.error("wasm streaming compile failed:", reason);
+ console.error("falling back to ArrayBuffer instantiation");
+ binary2 = new Uint8Array(await retryResp.arrayBuffer());
+ }
+ }
+ const mod = await C.loadWebAssemblyModule(binary2, { loadAsync: true });
+ const symbolNames = Object.keys(mod);
+ const functionName = symbolNames.find((key) => LANGUAGE_FUNCTION_REGEX.test(key) && !key.includes("external_scanner_"));
+ if (!functionName) {
+ console.log(`Couldn't find language function in Wasm file. Symbols:
+${JSON.stringify(symbolNames, null, 2)}`);
+ throw new Error("Language.load failed: no language function found in Wasm file");
+ }
+ const languageAddress = mod[functionName]();
+ return new _Language(INTERNAL, languageAddress);
+ }
+};
+
+// lib/web-tree-sitter.mjs
+async function Module2(moduleArg = {}) {
+ var moduleRtn;
+ var Module = moduleArg;
+ // var ENVIRONMENT_IS_WEB = typeof window == "object";
+ // var ENVIRONMENT_IS_WORKER = typeof WorkerGlobalScope != "undefined";
+ // var ENVIRONMENT_IS_NODE = typeof process == "object" && process.versions?.node && process.type != "renderer";
+ var ENVIRONMENT_IS_WEB = false;
+ var ENVIRONMENT_IS_WORKER = true;
+ var ENVIRONMENT_IS_NODE = false;
+ // if (ENVIRONMENT_IS_NODE) {
+ // const { createRequire } = await import("module");
+ // var require = createRequire(import.meta.url);
+ // }
+ Module.currentQueryProgressCallback = null;
+ Module.currentProgressCallback = null;
+ Module.currentLogCallback = null;
+ Module.currentParseCallback = null;
+ var arguments_ = [];
+ var thisProgram = "./this.program";
+ var quit_ = /* @__PURE__ */ __name((status, toThrow) => {
+ throw toThrow;
+ }, "quit_");
+ var _scriptName = self.location.origin + self.location.pathname;
+ var scriptDirectory = "";
+ function locateFile(path) {
+ if (Module["locateFile"]) {
+ return Module["locateFile"](path, scriptDirectory);
+ }
+ return scriptDirectory + path;
+ }
+ __name(locateFile, "locateFile");
+ var readAsync, readBinary;
+ if (ENVIRONMENT_IS_NODE) {
+ var fs = require("fs");
+ if (_scriptName.startsWith("file:")) {
+ scriptDirectory = require("path").dirname(require("url").fileURLToPath(_scriptName)) + "/";
+ }
+ readBinary = /* @__PURE__ */ __name((filename) => {
+ filename = isFileURI(filename) ? new URL(filename) : filename;
+ var ret = fs.readFileSync(filename);
+ return ret;
+ }, "readBinary");
+ readAsync = /* @__PURE__ */ __name(async (filename, binary2 = true) => {
+ filename = isFileURI(filename) ? new URL(filename) : filename;
+ var ret = fs.readFileSync(filename, binary2 ? void 0 : "utf8");
+ return ret;
+ }, "readAsync");
+ if (process.argv.length > 1) {
+ thisProgram = process.argv[1].replace(/\\/g, "/");
+ }
+ arguments_ = process.argv.slice(2);
+ quit_ = /* @__PURE__ */ __name((status, toThrow) => {
+ process.exitCode = status;
+ throw toThrow;
+ }, "quit_");
+ } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) {
+ try {
+ scriptDirectory = new URL(".", _scriptName).href;
+ } catch {
+ }
+ {
+ if (ENVIRONMENT_IS_WORKER) {
+ readBinary = /* @__PURE__ */ __name((url) => {
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", url, false);
+ xhr.responseType = "arraybuffer";
+ xhr.send(null);
+ return new Uint8Array(
+ /** @type{!ArrayBuffer} */
+ xhr.response
+ );
+ }, "readBinary");
+ }
+ readAsync = /* @__PURE__ */ __name(async (url) => {
+ if (isFileURI(url)) {
+ return new Promise((resolve, reject) => {
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", url, true);
+ xhr.responseType = "arraybuffer";
+ xhr.onload = () => {
+ if (xhr.status == 200 || xhr.status == 0 && xhr.response) {
+ resolve(xhr.response);
+ return;
+ }
+ reject(xhr.status);
+ };
+ xhr.onerror = reject;
+ xhr.send(null);
+ });
+ }
+ var response = await fetch(url, {
+ credentials: "same-origin"
+ });
+ if (response.ok) {
+ return response.arrayBuffer();
+ }
+ throw new Error(response.status + " : " + response.url);
+ }, "readAsync");
+ }
+ } else {
+ }
+ var out = console.log.bind(console);
+ var err = console.error.bind(console);
+ var dynamicLibraries = [];
+ var wasmBinary;
+ var ABORT = false;
+ var EXITSTATUS;
+ var isFileURI = /* @__PURE__ */ __name((filename) => filename.startsWith("file://"), "isFileURI");
+ var readyPromiseResolve, readyPromiseReject;
+ var wasmMemory;
+ var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAPF64;
+ var HEAP64, HEAPU64;
+ var HEAP_DATA_VIEW;
+ var runtimeInitialized = false;
+ function updateMemoryViews() {
+ var b = wasmMemory.buffer;
+ Module["HEAP8"] = HEAP8 = new Int8Array(b);
+ Module["HEAP16"] = HEAP16 = new Int16Array(b);
+ Module["HEAPU8"] = HEAPU8 = new Uint8Array(b);
+ Module["HEAPU16"] = HEAPU16 = new Uint16Array(b);
+ Module["HEAP32"] = HEAP32 = new Int32Array(b);
+ Module["HEAPU32"] = HEAPU32 = new Uint32Array(b);
+ Module["HEAPF32"] = HEAPF32 = new Float32Array(b);
+ Module["HEAPF64"] = HEAPF64 = new Float64Array(b);
+ Module["HEAP64"] = HEAP64 = new BigInt64Array(b);
+ Module["HEAPU64"] = HEAPU64 = new BigUint64Array(b);
+ Module["HEAP_DATA_VIEW"] = HEAP_DATA_VIEW = new DataView(b);
+ LE_HEAP_UPDATE();
+ }
+ __name(updateMemoryViews, "updateMemoryViews");
+ function initMemory() {
+ if (Module["wasmMemory"]) {
+ wasmMemory = Module["wasmMemory"];
+ } else {
+ var INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 33554432;
+ wasmMemory = new WebAssembly.Memory({
+ "initial": INITIAL_MEMORY / 65536,
+ // In theory we should not need to emit the maximum if we want "unlimited"
+ // or 4GB of memory, but VMs error on that atm, see
+ // https://github.com/emscripten-core/emscripten/issues/14130
+ // And in the pthreads case we definitely need to emit a maximum. So
+ // always emit one.
+ "maximum": 32768
+ });
+ }
+ updateMemoryViews();
+ }
+ __name(initMemory, "initMemory");
+ var __RELOC_FUNCS__ = [];
+ function preRun() {
+ if (Module["preRun"]) {
+ if (typeof Module["preRun"] == "function") Module["preRun"] = [Module["preRun"]];
+ while (Module["preRun"].length) {
+ addOnPreRun(Module["preRun"].shift());
+ }
+ }
+ callRuntimeCallbacks(onPreRuns);
+ }
+ __name(preRun, "preRun");
+ function initRuntime() {
+ runtimeInitialized = true;
+ callRuntimeCallbacks(__RELOC_FUNCS__);
+ wasmExports["__wasm_call_ctors"]();
+ callRuntimeCallbacks(onPostCtors);
+ }
+ __name(initRuntime, "initRuntime");
+ function preMain() {
+ }
+ __name(preMain, "preMain");
+ function postRun() {
+ if (Module["postRun"]) {
+ if (typeof Module["postRun"] == "function") Module["postRun"] = [Module["postRun"]];
+ while (Module["postRun"].length) {
+ addOnPostRun(Module["postRun"].shift());
+ }
+ }
+ callRuntimeCallbacks(onPostRuns);
+ }
+ __name(postRun, "postRun");
+ function abort(what) {
+ Module["onAbort"]?.(what);
+ what = "Aborted(" + what + ")";
+ err(what);
+ ABORT = true;
+ what += ". Build with -sASSERTIONS for more info.";
+ var e = new WebAssembly.RuntimeError(what);
+ readyPromiseReject?.(e);
+ throw e;
+ }
+ __name(abort, "abort");
+ var wasmBinaryFile;
+ function findWasmBinary() {
+ if (Module["locateFile"]) {
+ return locateFile("web-tree-sitter.wasm");
+ }
+ return new URL("web-tree-sitter.wasm", self.location.origin + self.location.pathname).href;
+ }
+ __name(findWasmBinary, "findWasmBinary");
+ function getBinarySync(file) {
+ if (file == wasmBinaryFile && wasmBinary) {
+ return new Uint8Array(wasmBinary);
+ }
+ if (readBinary) {
+ return readBinary(file);
+ }
+ throw "both async and sync fetching of the wasm failed";
+ }
+ __name(getBinarySync, "getBinarySync");
+ async function getWasmBinary(binaryFile) {
+ if (!wasmBinary) {
+ try {
+ var response = await readAsync(binaryFile);
+ return new Uint8Array(response);
+ } catch {
+ }
+ }
+ return getBinarySync(binaryFile);
+ }
+ __name(getWasmBinary, "getWasmBinary");
+ async function instantiateArrayBuffer(binaryFile, imports) {
+ try {
+ var binary2 = await getWasmBinary(binaryFile);
+ var instance2 = await WebAssembly.instantiate(binary2, imports);
+ return instance2;
+ } catch (reason) {
+ err(`failed to asynchronously prepare wasm: ${reason}`);
+ abort(reason);
+ }
+ }
+ __name(instantiateArrayBuffer, "instantiateArrayBuffer");
+ async function instantiateAsync(binary2, binaryFile, imports) {
+ if (!binary2 && !isFileURI(binaryFile) && !ENVIRONMENT_IS_NODE) {
+ try {
+ var response = fetch(binaryFile, {
+ credentials: "same-origin"
+ });
+ var instantiationResult = await WebAssembly.instantiateStreaming(response, imports);
+ return instantiationResult;
+ } catch (reason) {
+ err(`wasm streaming compile failed: ${reason}`);
+ err("falling back to ArrayBuffer instantiation");
+ }
+ }
+ return instantiateArrayBuffer(binaryFile, imports);
+ }
+ __name(instantiateAsync, "instantiateAsync");
+ function getWasmImports() {
+ return {
+ "env": wasmImports,
+ "wasi_snapshot_preview1": wasmImports,
+ "GOT.mem": new Proxy(wasmImports, GOTHandler),
+ "GOT.func": new Proxy(wasmImports, GOTHandler)
+ };
+ }
+ __name(getWasmImports, "getWasmImports");
+ async function createWasm() {
+ function receiveInstance(instance2, module2) {
+ wasmExports = instance2.exports;
+ wasmExports = relocateExports(wasmExports, 1024);
+ var metadata2 = getDylinkMetadata(module2);
+ if (metadata2.neededDynlibs) {
+ dynamicLibraries = metadata2.neededDynlibs.concat(dynamicLibraries);
+ }
+ mergeLibSymbols(wasmExports, "main");
+ LDSO.init();
+ loadDylibs();
+ __RELOC_FUNCS__.push(wasmExports["__wasm_apply_data_relocs"]);
+ assignWasmExports(wasmExports);
+ return wasmExports;
+ }
+ __name(receiveInstance, "receiveInstance");
+ function receiveInstantiationResult(result2) {
+ return receiveInstance(result2["instance"], result2["module"]);
+ }
+ __name(receiveInstantiationResult, "receiveInstantiationResult");
+ var info2 = getWasmImports();
+ if (Module["instantiateWasm"]) {
+ return new Promise((resolve, reject) => {
+ Module["instantiateWasm"](info2, (mod, inst) => {
+ resolve(receiveInstance(mod, inst));
+ });
+ });
+ }
+ wasmBinaryFile ??= findWasmBinary();
+ var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info2);
+ var exports = receiveInstantiationResult(result);
+ return exports;
+ }
+ __name(createWasm, "createWasm");
+ class ExitStatus {
+ static {
+ __name(this, "ExitStatus");
+ }
+ name = "ExitStatus";
+ constructor(status) {
+ this.message = `Program terminated with exit(${status})`;
+ this.status = status;
+ }
+ }
+ var GOT = {};
+ var currentModuleWeakSymbols = /* @__PURE__ */ new Set([]);
+ var GOTHandler = {
+ get(obj, symName) {
+ var rtn = GOT[symName];
+ if (!rtn) {
+ rtn = GOT[symName] = new WebAssembly.Global({
+ "value": "i32",
+ "mutable": true
+ });
+ }
+ if (!currentModuleWeakSymbols.has(symName)) {
+ rtn.required = true;
+ }
+ return rtn;
+ }
+ };
+ var LE_ATOMICS_NATIVE_BYTE_ORDER = [];
+ var LE_HEAP_LOAD_F32 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getFloat32(byteOffset, true), "LE_HEAP_LOAD_F32");
+ var LE_HEAP_LOAD_F64 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getFloat64(byteOffset, true), "LE_HEAP_LOAD_F64");
+ var LE_HEAP_LOAD_I16 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getInt16(byteOffset, true), "LE_HEAP_LOAD_I16");
+ var LE_HEAP_LOAD_I32 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getInt32(byteOffset, true), "LE_HEAP_LOAD_I32");
+ var LE_HEAP_LOAD_I64 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getBigInt64(byteOffset, true), "LE_HEAP_LOAD_I64");
+ var LE_HEAP_LOAD_U32 = /* @__PURE__ */ __name((byteOffset) => HEAP_DATA_VIEW.getUint32(byteOffset, true), "LE_HEAP_LOAD_U32");
+ var LE_HEAP_STORE_F32 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setFloat32(byteOffset, value, true), "LE_HEAP_STORE_F32");
+ var LE_HEAP_STORE_F64 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setFloat64(byteOffset, value, true), "LE_HEAP_STORE_F64");
+ var LE_HEAP_STORE_I16 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setInt16(byteOffset, value, true), "LE_HEAP_STORE_I16");
+ var LE_HEAP_STORE_I32 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setInt32(byteOffset, value, true), "LE_HEAP_STORE_I32");
+ var LE_HEAP_STORE_I64 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setBigInt64(byteOffset, value, true), "LE_HEAP_STORE_I64");
+ var LE_HEAP_STORE_U32 = /* @__PURE__ */ __name((byteOffset, value) => HEAP_DATA_VIEW.setUint32(byteOffset, value, true), "LE_HEAP_STORE_U32");
+ var callRuntimeCallbacks = /* @__PURE__ */ __name((callbacks) => {
+ while (callbacks.length > 0) {
+ callbacks.shift()(Module);
+ }
+ }, "callRuntimeCallbacks");
+ var onPostRuns = [];
+ var addOnPostRun = /* @__PURE__ */ __name((cb) => onPostRuns.push(cb), "addOnPostRun");
+ var onPreRuns = [];
+ var addOnPreRun = /* @__PURE__ */ __name((cb) => onPreRuns.push(cb), "addOnPreRun");
+ var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder() : void 0;
+ var findStringEnd = /* @__PURE__ */ __name((heapOrArray, idx, maxBytesToRead, ignoreNul) => {
+ var maxIdx = idx + maxBytesToRead;
+ if (ignoreNul) return maxIdx;
+ while (heapOrArray[idx] && !(idx >= maxIdx)) ++idx;
+ return idx;
+ }, "findStringEnd");
+ var UTF8ArrayToString = /* @__PURE__ */ __name((heapOrArray, idx = 0, maxBytesToRead, ignoreNul) => {
+ var endPtr = findStringEnd(heapOrArray, idx, maxBytesToRead, ignoreNul);
+ if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
+ return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
+ }
+ var str = "";
+ while (idx < endPtr) {
+ var u0 = heapOrArray[idx++];
+ if (!(u0 & 128)) {
+ str += String.fromCharCode(u0);
+ continue;
+ }
+ var u1 = heapOrArray[idx++] & 63;
+ if ((u0 & 224) == 192) {
+ str += String.fromCharCode((u0 & 31) << 6 | u1);
+ continue;
+ }
+ var u2 = heapOrArray[idx++] & 63;
+ if ((u0 & 240) == 224) {
+ u0 = (u0 & 15) << 12 | u1 << 6 | u2;
+ } else {
+ u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63;
+ }
+ if (u0 < 65536) {
+ str += String.fromCharCode(u0);
+ } else {
+ var ch = u0 - 65536;
+ str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
+ }
+ }
+ return str;
+ }, "UTF8ArrayToString");
+ var getDylinkMetadata = /* @__PURE__ */ __name((binary2) => {
+ var offset = 0;
+ var end = 0;
+ function getU8() {
+ return binary2[offset++];
+ }
+ __name(getU8, "getU8");
+ function getLEB() {
+ var ret = 0;
+ var mul = 1;
+ while (1) {
+ var byte = binary2[offset++];
+ ret += (byte & 127) * mul;
+ mul *= 128;
+ if (!(byte & 128)) break;
+ }
+ return ret;
+ }
+ __name(getLEB, "getLEB");
+ function getString() {
+ var len = getLEB();
+ offset += len;
+ return UTF8ArrayToString(binary2, offset - len, len);
+ }
+ __name(getString, "getString");
+ function getStringList() {
+ var count2 = getLEB();
+ var rtn = [];
+ while (count2--) rtn.push(getString());
+ return rtn;
+ }
+ __name(getStringList, "getStringList");
+ function failIf(condition, message) {
+ if (condition) throw new Error(message);
+ }
+ __name(failIf, "failIf");
+ if (binary2 instanceof WebAssembly.Module) {
+ var dylinkSection = WebAssembly.Module.customSections(binary2, "dylink.0");
+ failIf(dylinkSection.length === 0, "need dylink section");
+ binary2 = new Uint8Array(dylinkSection[0]);
+ end = binary2.length;
+ } else {
+ var int32View = new Uint32Array(new Uint8Array(binary2.subarray(0, 24)).buffer);
+ var magicNumberFound = int32View[0] == 1836278016 || int32View[0] == 6386541;
+ failIf(!magicNumberFound, "need to see wasm magic number");
+ failIf(binary2[8] !== 0, "need the dylink section to be first");
+ offset = 9;
+ var section_size = getLEB();
+ end = offset + section_size;
+ var name2 = getString();
+ failIf(name2 !== "dylink.0");
+ }
+ var customSection = {
+ neededDynlibs: [],
+ tlsExports: /* @__PURE__ */ new Set(),
+ weakImports: /* @__PURE__ */ new Set(),
+ runtimePaths: []
+ };
+ var WASM_DYLINK_MEM_INFO = 1;
+ var WASM_DYLINK_NEEDED = 2;
+ var WASM_DYLINK_EXPORT_INFO = 3;
+ var WASM_DYLINK_IMPORT_INFO = 4;
+ var WASM_DYLINK_RUNTIME_PATH = 5;
+ var WASM_SYMBOL_TLS = 256;
+ var WASM_SYMBOL_BINDING_MASK = 3;
+ var WASM_SYMBOL_BINDING_WEAK = 1;
+ while (offset < end) {
+ var subsectionType = getU8();
+ var subsectionSize = getLEB();
+ if (subsectionType === WASM_DYLINK_MEM_INFO) {
+ customSection.memorySize = getLEB();
+ customSection.memoryAlign = getLEB();
+ customSection.tableSize = getLEB();
+ customSection.tableAlign = getLEB();
+ } else if (subsectionType === WASM_DYLINK_NEEDED) {
+ customSection.neededDynlibs = getStringList();
+ } else if (subsectionType === WASM_DYLINK_EXPORT_INFO) {
+ var count = getLEB();
+ while (count--) {
+ var symname = getString();
+ var flags2 = getLEB();
+ if (flags2 & WASM_SYMBOL_TLS) {
+ customSection.tlsExports.add(symname);
+ }
+ }
+ } else if (subsectionType === WASM_DYLINK_IMPORT_INFO) {
+ var count = getLEB();
+ while (count--) {
+ var modname = getString();
+ var symname = getString();
+ var flags2 = getLEB();
+ if ((flags2 & WASM_SYMBOL_BINDING_MASK) == WASM_SYMBOL_BINDING_WEAK) {
+ customSection.weakImports.add(symname);
+ }
+ }
+ } else if (subsectionType === WASM_DYLINK_RUNTIME_PATH) {
+ customSection.runtimePaths = getStringList();
+ } else {
+ offset += subsectionSize;
+ }
+ }
+ return customSection;
+ }, "getDylinkMetadata");
+ function getValue(ptr, type = "i8") {
+ if (type.endsWith("*")) type = "*";
+ switch (type) {
+ case "i1":
+ return HEAP8[ptr];
+ case "i8":
+ return HEAP8[ptr];
+ case "i16":
+ return LE_HEAP_LOAD_I16((ptr >> 1) * 2);
+ case "i32":
+ return LE_HEAP_LOAD_I32((ptr >> 2) * 4);
+ case "i64":
+ return LE_HEAP_LOAD_I64((ptr >> 3) * 8);
+ case "float":
+ return LE_HEAP_LOAD_F32((ptr >> 2) * 4);
+ case "double":
+ return LE_HEAP_LOAD_F64((ptr >> 3) * 8);
+ case "*":
+ return LE_HEAP_LOAD_U32((ptr >> 2) * 4);
+ default:
+ abort(`invalid type for getValue: ${type}`);
+ }
+ }
+ __name(getValue, "getValue");
+ var newDSO = /* @__PURE__ */ __name((name2, handle2, syms) => {
+ var dso = {
+ refcount: Infinity,
+ name: name2,
+ exports: syms,
+ global: true
+ };
+ LDSO.loadedLibsByName[name2] = dso;
+ if (handle2 != void 0) {
+ LDSO.loadedLibsByHandle[handle2] = dso;
+ }
+ return dso;
+ }, "newDSO");
+ var LDSO = {
+ loadedLibsByName: {},
+ loadedLibsByHandle: {},
+ init() {
+ newDSO("__main__", 0, wasmImports);
+ }
+ };
+ var ___heap_base = 78240;
+ var alignMemory = /* @__PURE__ */ __name((size, alignment) => Math.ceil(size / alignment) * alignment, "alignMemory");
+ var getMemory = /* @__PURE__ */ __name((size) => {
+ if (runtimeInitialized) {
+ return _calloc(size, 1);
+ }
+ var ret = ___heap_base;
+ var end = ret + alignMemory(size, 16);
+ ___heap_base = end;
+ GOT["__heap_base"].value = end;
+ return ret;
+ }, "getMemory");
+ var isInternalSym = /* @__PURE__ */ __name((symName) => ["__cpp_exception", "__c_longjmp", "__wasm_apply_data_relocs", "__dso_handle", "__tls_size", "__tls_align", "__set_stack_limits", "_emscripten_tls_init", "__wasm_init_tls", "__wasm_call_ctors", "__start_em_asm", "__stop_em_asm", "__start_em_js", "__stop_em_js"].includes(symName) || symName.startsWith("__em_js__"), "isInternalSym");
+ var uleb128EncodeWithLen = /* @__PURE__ */ __name((arr) => {
+ const n = arr.length;
+ return [n % 128 | 128, n >> 7, ...arr];
+ }, "uleb128EncodeWithLen");
+ var wasmTypeCodes = {
+ "i": 127,
+ // i32
+ "p": 127,
+ // i32
+ "j": 126,
+ // i64
+ "f": 125,
+ // f32
+ "d": 124,
+ // f64
+ "e": 111
+ };
+ var generateTypePack = /* @__PURE__ */ __name((types) => uleb128EncodeWithLen(Array.from(types, (type) => {
+ var code = wasmTypeCodes[type];
+ return code;
+ })), "generateTypePack");
+ var convertJsFunctionToWasm = /* @__PURE__ */ __name((func2, sig) => {
+ var bytes = Uint8Array.of(
+ 0,
+ 97,
+ 115,
+ 109,
+ // magic ("\0asm")
+ 1,
+ 0,
+ 0,
+ 0,
+ // version: 1
+ 1,
+ ...uleb128EncodeWithLen([
+ 1,
+ // count: 1
+ 96,
+ // param types
+ ...generateTypePack(sig.slice(1)),
+ // return types (for now only supporting [] if `void` and single [T] otherwise)
+ ...generateTypePack(sig[0] === "v" ? "" : sig[0])
+ ]),
+ // The rest of the module is static
+ 2,
+ 7,
+ // import section
+ // (import "e" "f" (func 0 (type 0)))
+ 1,
+ 1,
+ 101,
+ 1,
+ 102,
+ 0,
+ 0,
+ 7,
+ 5,
+ // export section
+ // (export "f" (func 0 (type 0)))
+ 1,
+ 1,
+ 102,
+ 0,
+ 0
+ );
+ var module2 = new WebAssembly.Module(bytes);
+ var instance2 = new WebAssembly.Instance(module2, {
+ "e": {
+ "f": func2
+ }
+ });
+ var wrappedFunc = instance2.exports["f"];
+ return wrappedFunc;
+ }, "convertJsFunctionToWasm");
+ var wasmTableMirror = [];
+ var wasmTable = new WebAssembly.Table({
+ "initial": 31,
+ "element": "anyfunc"
+ });
+ var getWasmTableEntry = /* @__PURE__ */ __name((funcPtr) => {
+ var func2 = wasmTableMirror[funcPtr];
+ if (!func2) {
+ wasmTableMirror[funcPtr] = func2 = wasmTable.get(funcPtr);
+ }
+ return func2;
+ }, "getWasmTableEntry");
+ var updateTableMap = /* @__PURE__ */ __name((offset, count) => {
+ if (functionsInTableMap) {
+ for (var i2 = offset; i2 < offset + count; i2++) {
+ var item = getWasmTableEntry(i2);
+ if (item) {
+ functionsInTableMap.set(item, i2);
+ }
+ }
+ }
+ }, "updateTableMap");
+ var functionsInTableMap;
+ var getFunctionAddress = /* @__PURE__ */ __name((func2) => {
+ if (!functionsInTableMap) {
+ functionsInTableMap = /* @__PURE__ */ new WeakMap();
+ updateTableMap(0, wasmTable.length);
+ }
+ return functionsInTableMap.get(func2) || 0;
+ }, "getFunctionAddress");
+ var freeTableIndexes = [];
+ var getEmptyTableSlot = /* @__PURE__ */ __name(() => {
+ if (freeTableIndexes.length) {
+ return freeTableIndexes.pop();
+ }
+ return wasmTable["grow"](1);
+ }, "getEmptyTableSlot");
+ var setWasmTableEntry = /* @__PURE__ */ __name((idx, func2) => {
+ wasmTable.set(idx, func2);
+ wasmTableMirror[idx] = wasmTable.get(idx);
+ }, "setWasmTableEntry");
+ var addFunction = /* @__PURE__ */ __name((func2, sig) => {
+ var rtn = getFunctionAddress(func2);
+ if (rtn) {
+ return rtn;
+ }
+ var ret = getEmptyTableSlot();
+ try {
+ setWasmTableEntry(ret, func2);
+ } catch (err2) {
+ if (!(err2 instanceof TypeError)) {
+ throw err2;
+ }
+ var wrapped = convertJsFunctionToWasm(func2, sig);
+ setWasmTableEntry(ret, wrapped);
+ }
+ functionsInTableMap.set(func2, ret);
+ return ret;
+ }, "addFunction");
+ var updateGOT = /* @__PURE__ */ __name((exports, replace) => {
+ for (var symName in exports) {
+ if (isInternalSym(symName)) {
+ continue;
+ }
+ var value = exports[symName];
+ GOT[symName] ||= new WebAssembly.Global({
+ "value": "i32",
+ "mutable": true
+ });
+ if (replace || GOT[symName].value == 0) {
+ if (typeof value == "function") {
+ GOT[symName].value = addFunction(value);
+ } else if (typeof value == "number") {
+ GOT[symName].value = value;
+ } else {
+ err(`unhandled export type for '${symName}': ${typeof value}`);
+ }
+ }
+ }
+ }, "updateGOT");
+ var relocateExports = /* @__PURE__ */ __name((exports, memoryBase2, replace) => {
+ var relocated = {};
+ for (var e in exports) {
+ var value = exports[e];
+ if (typeof value == "object") {
+ value = value.value;
+ }
+ if (typeof value == "number") {
+ value += memoryBase2;
+ }
+ relocated[e] = value;
+ }
+ updateGOT(relocated, replace);
+ return relocated;
+ }, "relocateExports");
+ var isSymbolDefined = /* @__PURE__ */ __name((symName) => {
+ var existing = wasmImports[symName];
+ if (!existing || existing.stub) {
+ return false;
+ }
+ return true;
+ }, "isSymbolDefined");
+ var dynCall = /* @__PURE__ */ __name((sig, ptr, args2 = [], promising = false) => {
+ var func2 = getWasmTableEntry(ptr);
+ var rtn = func2(...args2);
+ function convert(rtn2) {
+ return rtn2;
+ }
+ __name(convert, "convert");
+ return convert(rtn);
+ }, "dynCall");
+ var stackSave = /* @__PURE__ */ __name(() => _emscripten_stack_get_current(), "stackSave");
+ var stackRestore = /* @__PURE__ */ __name((val) => __emscripten_stack_restore(val), "stackRestore");
+ var createInvokeFunction = /* @__PURE__ */ __name((sig) => (ptr, ...args2) => {
+ var sp = stackSave();
+ try {
+ return dynCall(sig, ptr, args2);
+ } catch (e) {
+ stackRestore(sp);
+ if (e !== e + 0) throw e;
+ _setThrew(1, 0);
+ if (sig[0] == "j") return 0n;
+ }
+ }, "createInvokeFunction");
+ var resolveGlobalSymbol = /* @__PURE__ */ __name((symName, direct = false) => {
+ var sym;
+ if (isSymbolDefined(symName)) {
+ sym = wasmImports[symName];
+ } else if (symName.startsWith("invoke_")) {
+ sym = wasmImports[symName] = createInvokeFunction(symName.split("_")[1]);
+ }
+ return {
+ sym,
+ name: symName
+ };
+ }, "resolveGlobalSymbol");
+ var onPostCtors = [];
+ var addOnPostCtor = /* @__PURE__ */ __name((cb) => onPostCtors.push(cb), "addOnPostCtor");
+ var UTF8ToString = /* @__PURE__ */ __name((ptr, maxBytesToRead, ignoreNul) => ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead, ignoreNul) : "", "UTF8ToString");
+ var loadWebAssemblyModule = /* @__PURE__ */ __name((binary, flags, libName, localScope, handle) => {
+ var metadata = getDylinkMetadata(binary);
+ function loadModule() {
+ var memAlign = Math.pow(2, metadata.memoryAlign);
+ var memoryBase = metadata.memorySize ? alignMemory(getMemory(metadata.memorySize + memAlign), memAlign) : 0;
+ var tableBase = metadata.tableSize ? wasmTable.length : 0;
+ if (handle) {
+ HEAP8[handle + 8] = 1;
+ LE_HEAP_STORE_U32((handle + 12 >> 2) * 4, memoryBase);
+ LE_HEAP_STORE_I32((handle + 16 >> 2) * 4, metadata.memorySize);
+ LE_HEAP_STORE_U32((handle + 20 >> 2) * 4, tableBase);
+ LE_HEAP_STORE_I32((handle + 24 >> 2) * 4, metadata.tableSize);
+ }
+ if (metadata.tableSize) {
+ wasmTable.grow(metadata.tableSize);
+ }
+ var moduleExports;
+ function resolveSymbol(sym) {
+ var resolved = resolveGlobalSymbol(sym).sym;
+ if (!resolved && localScope) {
+ resolved = localScope[sym];
+ }
+ if (!resolved) {
+ resolved = moduleExports[sym];
+ }
+ return resolved;
+ }
+ __name(resolveSymbol, "resolveSymbol");
+ var proxyHandler = {
+ get(stubs, prop) {
+ switch (prop) {
+ case "__memory_base":
+ return memoryBase;
+ case "__table_base":
+ return tableBase;
+ }
+ if (prop in wasmImports && !wasmImports[prop].stub) {
+ var res = wasmImports[prop];
+ return res;
+ }
+ if (!(prop in stubs)) {
+ var resolved;
+ stubs[prop] = (...args2) => {
+ resolved ||= resolveSymbol(prop);
+ return resolved(...args2);
+ };
+ }
+ return stubs[prop];
+ }
+ };
+ var proxy = new Proxy({}, proxyHandler);
+ currentModuleWeakSymbols = metadata.weakImports;
+ var info = {
+ "GOT.mem": new Proxy({}, GOTHandler),
+ "GOT.func": new Proxy({}, GOTHandler),
+ "env": proxy,
+ "wasi_snapshot_preview1": proxy
+ };
+ function postInstantiation(module, instance) {
+ updateTableMap(tableBase, metadata.tableSize);
+ moduleExports = relocateExports(instance.exports, memoryBase);
+ if (!flags.allowUndefined) {
+ reportUndefinedSymbols();
+ }
+ function addEmAsm(addr, body) {
+ var args = [];
+ var arity = 0;
+ for (; arity < 16; arity++) {
+ if (body.indexOf("$" + arity) != -1) {
+ args.push("$" + arity);
+ } else {
+ break;
+ }
+ }
+ args = args.join(",");
+ var func = `(${args}) => { ${body} };`;
+ ASM_CONSTS[start] = eval(func);
+ }
+ __name(addEmAsm, "addEmAsm");
+ if ("__start_em_asm" in moduleExports) {
+ var start = moduleExports["__start_em_asm"];
+ var stop = moduleExports["__stop_em_asm"];
+ while (start < stop) {
+ var jsString = UTF8ToString(start);
+ addEmAsm(start, jsString);
+ start = HEAPU8.indexOf(0, start) + 1;
+ }
+ }
+ function addEmJs(name, cSig, body) {
+ var jsArgs = [];
+ cSig = cSig.slice(1, -1);
+ if (cSig != "void") {
+ cSig = cSig.split(",");
+ for (var i in cSig) {
+ var jsArg = cSig[i].split(" ").pop();
+ jsArgs.push(jsArg.replace("*", ""));
+ }
+ }
+ var func = `(${jsArgs}) => ${body};`;
+ moduleExports[name] = eval(func);
+ }
+ __name(addEmJs, "addEmJs");
+ for (var name in moduleExports) {
+ if (name.startsWith("__em_js__")) {
+ var start = moduleExports[name];
+ var jsString = UTF8ToString(start);
+ var parts = jsString.split("<::>");
+ addEmJs(name.replace("__em_js__", ""), parts[0], parts[1]);
+ delete moduleExports[name];
+ }
+ }
+ var applyRelocs = moduleExports["__wasm_apply_data_relocs"];
+ if (applyRelocs) {
+ if (runtimeInitialized) {
+ applyRelocs();
+ } else {
+ __RELOC_FUNCS__.push(applyRelocs);
+ }
+ }
+ var init = moduleExports["__wasm_call_ctors"];
+ if (init) {
+ if (runtimeInitialized) {
+ init();
+ } else {
+ addOnPostCtor(init);
+ }
+ }
+ return moduleExports;
+ }
+ __name(postInstantiation, "postInstantiation");
+ if (flags.loadAsync) {
+ return (async () => {
+ var instance2;
+ if (binary instanceof WebAssembly.Module) {
+ instance2 = new WebAssembly.Instance(binary, info);
+ } else {
+ ({ module: binary, instance: instance2 } = await WebAssembly.instantiate(binary, info));
+ }
+ return postInstantiation(binary, instance2);
+ })();
+ }
+ var module = binary instanceof WebAssembly.Module ? binary : new WebAssembly.Module(binary);
+ var instance = new WebAssembly.Instance(module, info);
+ return postInstantiation(module, instance);
+ }
+ __name(loadModule, "loadModule");
+ flags = {
+ ...flags,
+ rpath: {
+ parentLibPath: libName,
+ paths: metadata.runtimePaths
+ }
+ };
+ if (flags.loadAsync) {
+ return metadata.neededDynlibs.reduce((chain, dynNeeded) => chain.then(() => loadDynamicLibrary(dynNeeded, flags, localScope)), Promise.resolve()).then(loadModule);
+ }
+ metadata.neededDynlibs.forEach((needed) => loadDynamicLibrary(needed, flags, localScope));
+ return loadModule();
+ }, "loadWebAssemblyModule");
+ var mergeLibSymbols = /* @__PURE__ */ __name((exports, libName2) => {
+ for (var [sym, exp] of Object.entries(exports)) {
+ const setImport = /* @__PURE__ */ __name((target) => {
+ if (!isSymbolDefined(target)) {
+ wasmImports[target] = exp;
+ }
+ }, "setImport");
+ setImport(sym);
+ const main_alias = "__main_argc_argv";
+ if (sym == "main") {
+ setImport(main_alias);
+ }
+ if (sym == main_alias) {
+ setImport("main");
+ }
+ }
+ }, "mergeLibSymbols");
+ var asyncLoad = /* @__PURE__ */ __name(async (url) => {
+ var arrayBuffer = await readAsync(url);
+ return new Uint8Array(arrayBuffer);
+ }, "asyncLoad");
+ function loadDynamicLibrary(libName2, flags2 = {
+ global: true,
+ nodelete: true
+ }, localScope2, handle2) {
+ var dso = LDSO.loadedLibsByName[libName2];
+ if (dso) {
+ if (!flags2.global) {
+ if (localScope2) {
+ Object.assign(localScope2, dso.exports);
+ }
+ } else if (!dso.global) {
+ dso.global = true;
+ mergeLibSymbols(dso.exports, libName2);
+ }
+ if (flags2.nodelete && dso.refcount !== Infinity) {
+ dso.refcount = Infinity;
+ }
+ dso.refcount++;
+ if (handle2) {
+ LDSO.loadedLibsByHandle[handle2] = dso;
+ }
+ return flags2.loadAsync ? Promise.resolve(true) : true;
+ }
+ dso = newDSO(libName2, handle2, "loading");
+ dso.refcount = flags2.nodelete ? Infinity : 1;
+ dso.global = flags2.global;
+ function loadLibData() {
+ if (handle2) {
+ var data = LE_HEAP_LOAD_U32((handle2 + 28 >> 2) * 4);
+ var dataSize = LE_HEAP_LOAD_U32((handle2 + 32 >> 2) * 4);
+ if (data && dataSize) {
+ var libData = HEAP8.slice(data, data + dataSize);
+ return flags2.loadAsync ? Promise.resolve(libData) : libData;
+ }
+ }
+ var libFile = locateFile(libName2);
+ if (flags2.loadAsync) {
+ return asyncLoad(libFile);
+ }
+ if (!readBinary) {
+ throw new Error(`${libFile}: file not found, and synchronous loading of external files is not available`);
+ }
+ return readBinary(libFile);
+ }
+ __name(loadLibData, "loadLibData");
+ function getExports() {
+ if (flags2.loadAsync) {
+ return loadLibData().then((libData) => loadWebAssemblyModule(libData, flags2, libName2, localScope2, handle2));
+ }
+ return loadWebAssemblyModule(loadLibData(), flags2, libName2, localScope2, handle2);
+ }
+ __name(getExports, "getExports");
+ function moduleLoaded(exports) {
+ if (dso.global) {
+ mergeLibSymbols(exports, libName2);
+ } else if (localScope2) {
+ Object.assign(localScope2, exports);
+ }
+ dso.exports = exports;
+ }
+ __name(moduleLoaded, "moduleLoaded");
+ if (flags2.loadAsync) {
+ return getExports().then((exports) => {
+ moduleLoaded(exports);
+ return true;
+ });
+ }
+ moduleLoaded(getExports());
+ return true;
+ }
+ __name(loadDynamicLibrary, "loadDynamicLibrary");
+ var reportUndefinedSymbols = /* @__PURE__ */ __name(() => {
+ for (var [symName, entry] of Object.entries(GOT)) {
+ if (entry.value == 0) {
+ var value = resolveGlobalSymbol(symName, true).sym;
+ if (!value && !entry.required) {
+ continue;
+ }
+ if (typeof value == "function") {
+ entry.value = addFunction(value, value.sig);
+ } else if (typeof value == "number") {
+ entry.value = value;
+ } else {
+ throw new Error(`bad export type for '${symName}': ${typeof value}`);
+ }
+ }
+ }
+ }, "reportUndefinedSymbols");
+ var runDependencies = 0;
+ var dependenciesFulfilled = null;
+ var removeRunDependency = /* @__PURE__ */ __name((id) => {
+ runDependencies--;
+ Module["monitorRunDependencies"]?.(runDependencies);
+ if (runDependencies == 0) {
+ if (dependenciesFulfilled) {
+ var callback = dependenciesFulfilled;
+ dependenciesFulfilled = null;
+ callback();
+ }
+ }
+ }, "removeRunDependency");
+ var addRunDependency = /* @__PURE__ */ __name((id) => {
+ runDependencies++;
+ Module["monitorRunDependencies"]?.(runDependencies);
+ }, "addRunDependency");
+ var loadDylibs = /* @__PURE__ */ __name(async () => {
+ if (!dynamicLibraries.length) {
+ reportUndefinedSymbols();
+ return;
+ }
+ addRunDependency("loadDylibs");
+ for (var lib of dynamicLibraries) {
+ await loadDynamicLibrary(lib, {
+ loadAsync: true,
+ global: true,
+ nodelete: true,
+ allowUndefined: true
+ });
+ }
+ reportUndefinedSymbols();
+ removeRunDependency("loadDylibs");
+ }, "loadDylibs");
+ var noExitRuntime = true;
+ function setValue(ptr, value, type = "i8") {
+ if (type.endsWith("*")) type = "*";
+ switch (type) {
+ case "i1":
+ HEAP8[ptr] = value;
+ break;
+ case "i8":
+ HEAP8[ptr] = value;
+ break;
+ case "i16":
+ LE_HEAP_STORE_I16((ptr >> 1) * 2, value);
+ break;
+ case "i32":
+ LE_HEAP_STORE_I32((ptr >> 2) * 4, value);
+ break;
+ case "i64":
+ LE_HEAP_STORE_I64((ptr >> 3) * 8, BigInt(value));
+ break;
+ case "float":
+ LE_HEAP_STORE_F32((ptr >> 2) * 4, value);
+ break;
+ case "double":
+ LE_HEAP_STORE_F64((ptr >> 3) * 8, value);
+ break;
+ case "*":
+ LE_HEAP_STORE_U32((ptr >> 2) * 4, value);
+ break;
+ default:
+ abort(`invalid type for setValue: ${type}`);
+ }
+ }
+ __name(setValue, "setValue");
+ var ___memory_base = new WebAssembly.Global({
+ "value": "i32",
+ "mutable": false
+ }, 1024);
+ var ___stack_high = 78240;
+ var ___stack_low = 12704;
+ var ___stack_pointer = new WebAssembly.Global({
+ "value": "i32",
+ "mutable": true
+ }, 78240);
+ var ___table_base = new WebAssembly.Global({
+ "value": "i32",
+ "mutable": false
+ }, 1);
+ var __abort_js = /* @__PURE__ */ __name(() => abort(""), "__abort_js");
+ __abort_js.sig = "v";
+ var getHeapMax = /* @__PURE__ */ __name(() => (
+ // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate
+ // full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side
+ // for any code that deals with heap sizes, which would require special
+ // casing all heap size related code to treat 0 specially.
+ 2147483648
+ ), "getHeapMax");
+ var growMemory = /* @__PURE__ */ __name((size) => {
+ var oldHeapSize = wasmMemory.buffer.byteLength;
+ var pages = (size - oldHeapSize + 65535) / 65536 | 0;
+ try {
+ wasmMemory.grow(pages);
+ updateMemoryViews();
+ return 1;
+ } catch (e) {
+ }
+ }, "growMemory");
+ var _emscripten_resize_heap = /* @__PURE__ */ __name((requestedSize) => {
+ var oldSize = HEAPU8.length;
+ requestedSize >>>= 0;
+ var maxHeapSize = getHeapMax();
+ if (requestedSize > maxHeapSize) {
+ return false;
+ }
+ for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
+ var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
+ overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
+ var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));
+ var replacement = growMemory(newSize);
+ if (replacement) {
+ return true;
+ }
+ }
+ return false;
+ }, "_emscripten_resize_heap");
+ _emscripten_resize_heap.sig = "ip";
+ var _fd_close = /* @__PURE__ */ __name((fd) => 52, "_fd_close");
+ _fd_close.sig = "ii";
+ var INT53_MAX = 9007199254740992;
+ var INT53_MIN = -9007199254740992;
+ var bigintToI53Checked = /* @__PURE__ */ __name((num) => num < INT53_MIN || num > INT53_MAX ? NaN : Number(num), "bigintToI53Checked");
+ function _fd_seek(fd, offset, whence, newOffset) {
+ offset = bigintToI53Checked(offset);
+ return 70;
+ }
+ __name(_fd_seek, "_fd_seek");
+ _fd_seek.sig = "iijip";
+ var printCharBuffers = [null, [], []];
+ var printChar = /* @__PURE__ */ __name((stream, curr) => {
+ var buffer = printCharBuffers[stream];
+ if (curr === 0 || curr === 10) {
+ (stream === 1 ? out : err)(UTF8ArrayToString(buffer));
+ buffer.length = 0;
+ } else {
+ buffer.push(curr);
+ }
+ }, "printChar");
+ var _fd_write = /* @__PURE__ */ __name((fd, iov, iovcnt, pnum) => {
+ var num = 0;
+ for (var i2 = 0; i2 < iovcnt; i2++) {
+ var ptr = LE_HEAP_LOAD_U32((iov >> 2) * 4);
+ var len = LE_HEAP_LOAD_U32((iov + 4 >> 2) * 4);
+ iov += 8;
+ for (var j = 0; j < len; j++) {
+ printChar(fd, HEAPU8[ptr + j]);
+ }
+ num += len;
+ }
+ LE_HEAP_STORE_U32((pnum >> 2) * 4, num);
+ return 0;
+ }, "_fd_write");
+ _fd_write.sig = "iippp";
+ function _tree_sitter_log_callback(isLexMessage, messageAddress) {
+ if (Module.currentLogCallback) {
+ const message = UTF8ToString(messageAddress);
+ Module.currentLogCallback(message, isLexMessage !== 0);
+ }
+ }
+ __name(_tree_sitter_log_callback, "_tree_sitter_log_callback");
+ function _tree_sitter_parse_callback(inputBufferAddress, index, row, column, lengthAddress) {
+ const INPUT_BUFFER_SIZE = 10 * 1024;
+ const string = Module.currentParseCallback(index, {
+ row,
+ column
+ });
+ if (typeof string === "string") {
+ setValue(lengthAddress, string.length, "i32");
+ stringToUTF16(string, inputBufferAddress, INPUT_BUFFER_SIZE);
+ } else {
+ setValue(lengthAddress, 0, "i32");
+ }
+ }
+ __name(_tree_sitter_parse_callback, "_tree_sitter_parse_callback");
+ function _tree_sitter_progress_callback(currentOffset, hasError) {
+ if (Module.currentProgressCallback) {
+ return Module.currentProgressCallback({
+ currentOffset,
+ hasError
+ });
+ }
+ return false;
+ }
+ __name(_tree_sitter_progress_callback, "_tree_sitter_progress_callback");
+ function _tree_sitter_query_progress_callback(currentOffset) {
+ if (Module.currentQueryProgressCallback) {
+ return Module.currentQueryProgressCallback({
+ currentOffset
+ });
+ }
+ return false;
+ }
+ __name(_tree_sitter_query_progress_callback, "_tree_sitter_query_progress_callback");
+ var runtimeKeepaliveCounter = 0;
+ var keepRuntimeAlive = /* @__PURE__ */ __name(() => noExitRuntime || runtimeKeepaliveCounter > 0, "keepRuntimeAlive");
+ var _proc_exit = /* @__PURE__ */ __name((code) => {
+ EXITSTATUS = code;
+ if (!keepRuntimeAlive()) {
+ Module["onExit"]?.(code);
+ ABORT = true;
+ }
+ quit_(code, new ExitStatus(code));
+ }, "_proc_exit");
+ _proc_exit.sig = "vi";
+ var exitJS = /* @__PURE__ */ __name((status, implicit) => {
+ EXITSTATUS = status;
+ _proc_exit(status);
+ }, "exitJS");
+ var handleException = /* @__PURE__ */ __name((e) => {
+ if (e instanceof ExitStatus || e == "unwind") {
+ return EXITSTATUS;
+ }
+ quit_(1, e);
+ }, "handleException");
+ var lengthBytesUTF8 = /* @__PURE__ */ __name((str) => {
+ var len = 0;
+ for (var i2 = 0; i2 < str.length; ++i2) {
+ var c = str.charCodeAt(i2);
+ if (c <= 127) {
+ len++;
+ } else if (c <= 2047) {
+ len += 2;
+ } else if (c >= 55296 && c <= 57343) {
+ len += 4;
+ ++i2;
+ } else {
+ len += 3;
+ }
+ }
+ return len;
+ }, "lengthBytesUTF8");
+ var stringToUTF8Array = /* @__PURE__ */ __name((str, heap, outIdx, maxBytesToWrite) => {
+ if (!(maxBytesToWrite > 0)) return 0;
+ var startIdx = outIdx;
+ var endIdx = outIdx + maxBytesToWrite - 1;
+ for (var i2 = 0; i2 < str.length; ++i2) {
+ var u = str.codePointAt(i2);
+ if (u <= 127) {
+ if (outIdx >= endIdx) break;
+ heap[outIdx++] = u;
+ } else if (u <= 2047) {
+ if (outIdx + 1 >= endIdx) break;
+ heap[outIdx++] = 192 | u >> 6;
+ heap[outIdx++] = 128 | u & 63;
+ } else if (u <= 65535) {
+ if (outIdx + 2 >= endIdx) break;
+ heap[outIdx++] = 224 | u >> 12;
+ heap[outIdx++] = 128 | u >> 6 & 63;
+ heap[outIdx++] = 128 | u & 63;
+ } else {
+ if (outIdx + 3 >= endIdx) break;
+ heap[outIdx++] = 240 | u >> 18;
+ heap[outIdx++] = 128 | u >> 12 & 63;
+ heap[outIdx++] = 128 | u >> 6 & 63;
+ heap[outIdx++] = 128 | u & 63;
+ i2++;
+ }
+ }
+ heap[outIdx] = 0;
+ return outIdx - startIdx;
+ }, "stringToUTF8Array");
+ var stringToUTF8 = /* @__PURE__ */ __name((str, outPtr, maxBytesToWrite) => stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite), "stringToUTF8");
+ var stackAlloc = /* @__PURE__ */ __name((sz) => __emscripten_stack_alloc(sz), "stackAlloc");
+ var stringToUTF8OnStack = /* @__PURE__ */ __name((str) => {
+ var size = lengthBytesUTF8(str) + 1;
+ var ret = stackAlloc(size);
+ stringToUTF8(str, ret, size);
+ return ret;
+ }, "stringToUTF8OnStack");
+ var AsciiToString = /* @__PURE__ */ __name((ptr) => {
+ var str = "";
+ while (1) {
+ var ch = HEAPU8[ptr++];
+ if (!ch) return str;
+ str += String.fromCharCode(ch);
+ }
+ }, "AsciiToString");
+ var stringToUTF16 = /* @__PURE__ */ __name((str, outPtr, maxBytesToWrite) => {
+ maxBytesToWrite ??= 2147483647;
+ if (maxBytesToWrite < 2) return 0;
+ maxBytesToWrite -= 2;
+ var startPtr = outPtr;
+ var numCharsToWrite = maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length;
+ for (var i2 = 0; i2 < numCharsToWrite; ++i2) {
+ var codeUnit = str.charCodeAt(i2);
+ LE_HEAP_STORE_I16((outPtr >> 1) * 2, codeUnit);
+ outPtr += 2;
+ }
+ LE_HEAP_STORE_I16((outPtr >> 1) * 2, 0);
+ return outPtr - startPtr;
+ }, "stringToUTF16");
+ LE_ATOMICS_NATIVE_BYTE_ORDER = new Int8Array(new Int16Array([1]).buffer)[0] === 1 ? [
+ /* little endian */
+ ((x) => x),
+ ((x) => x),
+ void 0,
+ ((x) => x)
+ ] : [
+ /* big endian */
+ ((x) => x),
+ ((x) => ((x & 65280) << 8 | (x & 255) << 24) >> 16),
+ void 0,
+ ((x) => x >> 24 & 255 | x >> 8 & 65280 | (x & 65280) << 8 | (x & 255) << 24)
+ ];
+ function LE_HEAP_UPDATE() {
+ HEAPU16.unsigned = ((x) => x & 65535);
+ HEAPU32.unsigned = ((x) => x >>> 0);
+ }
+ __name(LE_HEAP_UPDATE, "LE_HEAP_UPDATE");
+ {
+ initMemory();
+ if (Module["noExitRuntime"]) noExitRuntime = Module["noExitRuntime"];
+ if (Module["print"]) out = Module["print"];
+ if (Module["printErr"]) err = Module["printErr"];
+ if (Module["dynamicLibraries"]) dynamicLibraries = Module["dynamicLibraries"];
+ if (Module["wasmBinary"]) wasmBinary = Module["wasmBinary"];
+ if (Module["arguments"]) arguments_ = Module["arguments"];
+ if (Module["thisProgram"]) thisProgram = Module["thisProgram"];
+ if (Module["preInit"]) {
+ if (typeof Module["preInit"] == "function") Module["preInit"] = [Module["preInit"]];
+ while (Module["preInit"].length > 0) {
+ Module["preInit"].shift()();
+ }
+ }
+ }
+ Module["setValue"] = setValue;
+ Module["getValue"] = getValue;
+ Module["UTF8ToString"] = UTF8ToString;
+ Module["stringToUTF8"] = stringToUTF8;
+ Module["lengthBytesUTF8"] = lengthBytesUTF8;
+ Module["AsciiToString"] = AsciiToString;
+ Module["stringToUTF16"] = stringToUTF16;
+ Module["loadWebAssemblyModule"] = loadWebAssemblyModule;
+ Module["LE_HEAP_STORE_I64"] = LE_HEAP_STORE_I64;
+ var ASM_CONSTS = {};
+ var _malloc, _calloc, _realloc, _free, _ts_range_edit, _memcmp, _ts_language_symbol_count, _ts_language_state_count, _ts_language_abi_version, _ts_language_name, _ts_language_field_count, _ts_language_next_state, _ts_language_symbol_name, _ts_language_symbol_for_name, _strncmp, _ts_language_symbol_type, _ts_language_field_name_for_id, _ts_lookahead_iterator_new, _ts_lookahead_iterator_delete, _ts_lookahead_iterator_reset_state, _ts_lookahead_iterator_reset, _ts_lookahead_iterator_next, _ts_lookahead_iterator_current_symbol, _ts_point_edit, _ts_parser_delete, _ts_parser_reset, _ts_parser_set_language, _ts_parser_set_included_ranges, _ts_query_new, _ts_query_delete, _iswspace, _iswalnum, _ts_query_pattern_count, _ts_query_capture_count, _ts_query_string_count, _ts_query_capture_name_for_id, _ts_query_capture_quantifier_for_id, _ts_query_string_value_for_id, _ts_query_predicates_for_pattern, _ts_query_start_byte_for_pattern, _ts_query_end_byte_for_pattern, _ts_query_is_pattern_rooted, _ts_query_is_pattern_non_local, _ts_query_is_pattern_guaranteed_at_step, _ts_query_disable_capture, _ts_query_disable_pattern, _ts_tree_copy, _ts_tree_delete, _ts_init, _ts_parser_new_wasm, _ts_parser_enable_logger_wasm, _ts_parser_parse_wasm, _ts_parser_included_ranges_wasm, _ts_language_type_is_named_wasm, _ts_language_type_is_visible_wasm, _ts_language_metadata_wasm, _ts_language_supertypes_wasm, _ts_language_subtypes_wasm, _ts_tree_root_node_wasm, _ts_tree_root_node_with_offset_wasm, _ts_tree_edit_wasm, _ts_tree_included_ranges_wasm, _ts_tree_get_changed_ranges_wasm, _ts_tree_cursor_new_wasm, _ts_tree_cursor_copy_wasm, _ts_tree_cursor_delete_wasm, _ts_tree_cursor_reset_wasm, _ts_tree_cursor_reset_to_wasm, _ts_tree_cursor_goto_first_child_wasm, _ts_tree_cursor_goto_last_child_wasm, _ts_tree_cursor_goto_first_child_for_index_wasm, _ts_tree_cursor_goto_first_child_for_position_wasm, _ts_tree_cursor_goto_next_sibling_wasm, _ts_tree_cursor_goto_previous_sibling_wasm, _ts_tree_cursor_goto_descendant_wasm, _ts_tree_cursor_goto_parent_wasm, _ts_tree_cursor_current_node_type_id_wasm, _ts_tree_cursor_current_node_state_id_wasm, _ts_tree_cursor_current_node_is_named_wasm, _ts_tree_cursor_current_node_is_missing_wasm, _ts_tree_cursor_current_node_id_wasm, _ts_tree_cursor_start_position_wasm, _ts_tree_cursor_end_position_wasm, _ts_tree_cursor_start_index_wasm, _ts_tree_cursor_end_index_wasm, _ts_tree_cursor_current_field_id_wasm, _ts_tree_cursor_current_depth_wasm, _ts_tree_cursor_current_descendant_index_wasm, _ts_tree_cursor_current_node_wasm, _ts_node_symbol_wasm, _ts_node_field_name_for_child_wasm, _ts_node_field_name_for_named_child_wasm, _ts_node_children_by_field_id_wasm, _ts_node_first_child_for_byte_wasm, _ts_node_first_named_child_for_byte_wasm, _ts_node_grammar_symbol_wasm, _ts_node_child_count_wasm, _ts_node_named_child_count_wasm, _ts_node_child_wasm, _ts_node_named_child_wasm, _ts_node_child_by_field_id_wasm, _ts_node_next_sibling_wasm, _ts_node_prev_sibling_wasm, _ts_node_next_named_sibling_wasm, _ts_node_prev_named_sibling_wasm, _ts_node_descendant_count_wasm, _ts_node_parent_wasm, _ts_node_child_with_descendant_wasm, _ts_node_descendant_for_index_wasm, _ts_node_named_descendant_for_index_wasm, _ts_node_descendant_for_position_wasm, _ts_node_named_descendant_for_position_wasm, _ts_node_start_point_wasm, _ts_node_end_point_wasm, _ts_node_start_index_wasm, _ts_node_end_index_wasm, _ts_node_to_string_wasm, _ts_node_children_wasm, _ts_node_named_children_wasm, _ts_node_descendants_of_type_wasm, _ts_node_is_named_wasm, _ts_node_has_changes_wasm, _ts_node_has_error_wasm, _ts_node_is_error_wasm, _ts_node_is_missing_wasm, _ts_node_is_extra_wasm, _ts_node_parse_state_wasm, _ts_node_next_parse_state_wasm, _ts_query_matches_wasm, _ts_query_captures_wasm, _memset, _memcpy, _memmove, _iswalpha, _iswblank, _iswdigit, _iswlower, _iswupper, _iswxdigit, _memchr, _strlen, _strcmp, _strncat, _strncpy, _towlower, _towupper, _setThrew, __emscripten_stack_restore, __emscripten_stack_alloc, _emscripten_stack_get_current, ___wasm_apply_data_relocs;
+ function assignWasmExports(wasmExports2) {
+ Module["_malloc"] = _malloc = wasmExports2["malloc"];
+ Module["_calloc"] = _calloc = wasmExports2["calloc"];
+ Module["_realloc"] = _realloc = wasmExports2["realloc"];
+ Module["_free"] = _free = wasmExports2["free"];
+ Module["_ts_range_edit"] = _ts_range_edit = wasmExports2["ts_range_edit"];
+ Module["_memcmp"] = _memcmp = wasmExports2["memcmp"];
+ Module["_ts_language_symbol_count"] = _ts_language_symbol_count = wasmExports2["ts_language_symbol_count"];
+ Module["_ts_language_state_count"] = _ts_language_state_count = wasmExports2["ts_language_state_count"];
+ Module["_ts_language_abi_version"] = _ts_language_abi_version = wasmExports2["ts_language_abi_version"];
+ Module["_ts_language_name"] = _ts_language_name = wasmExports2["ts_language_name"];
+ Module["_ts_language_field_count"] = _ts_language_field_count = wasmExports2["ts_language_field_count"];
+ Module["_ts_language_next_state"] = _ts_language_next_state = wasmExports2["ts_language_next_state"];
+ Module["_ts_language_symbol_name"] = _ts_language_symbol_name = wasmExports2["ts_language_symbol_name"];
+ Module["_ts_language_symbol_for_name"] = _ts_language_symbol_for_name = wasmExports2["ts_language_symbol_for_name"];
+ Module["_strncmp"] = _strncmp = wasmExports2["strncmp"];
+ Module["_ts_language_symbol_type"] = _ts_language_symbol_type = wasmExports2["ts_language_symbol_type"];
+ Module["_ts_language_field_name_for_id"] = _ts_language_field_name_for_id = wasmExports2["ts_language_field_name_for_id"];
+ Module["_ts_lookahead_iterator_new"] = _ts_lookahead_iterator_new = wasmExports2["ts_lookahead_iterator_new"];
+ Module["_ts_lookahead_iterator_delete"] = _ts_lookahead_iterator_delete = wasmExports2["ts_lookahead_iterator_delete"];
+ Module["_ts_lookahead_iterator_reset_state"] = _ts_lookahead_iterator_reset_state = wasmExports2["ts_lookahead_iterator_reset_state"];
+ Module["_ts_lookahead_iterator_reset"] = _ts_lookahead_iterator_reset = wasmExports2["ts_lookahead_iterator_reset"];
+ Module["_ts_lookahead_iterator_next"] = _ts_lookahead_iterator_next = wasmExports2["ts_lookahead_iterator_next"];
+ Module["_ts_lookahead_iterator_current_symbol"] = _ts_lookahead_iterator_current_symbol = wasmExports2["ts_lookahead_iterator_current_symbol"];
+ Module["_ts_point_edit"] = _ts_point_edit = wasmExports2["ts_point_edit"];
+ Module["_ts_parser_delete"] = _ts_parser_delete = wasmExports2["ts_parser_delete"];
+ Module["_ts_parser_reset"] = _ts_parser_reset = wasmExports2["ts_parser_reset"];
+ Module["_ts_parser_set_language"] = _ts_parser_set_language = wasmExports2["ts_parser_set_language"];
+ Module["_ts_parser_set_included_ranges"] = _ts_parser_set_included_ranges = wasmExports2["ts_parser_set_included_ranges"];
+ Module["_ts_query_new"] = _ts_query_new = wasmExports2["ts_query_new"];
+ Module["_ts_query_delete"] = _ts_query_delete = wasmExports2["ts_query_delete"];
+ Module["_iswspace"] = _iswspace = wasmExports2["iswspace"];
+ Module["_iswalnum"] = _iswalnum = wasmExports2["iswalnum"];
+ Module["_ts_query_pattern_count"] = _ts_query_pattern_count = wasmExports2["ts_query_pattern_count"];
+ Module["_ts_query_capture_count"] = _ts_query_capture_count = wasmExports2["ts_query_capture_count"];
+ Module["_ts_query_string_count"] = _ts_query_string_count = wasmExports2["ts_query_string_count"];
+ Module["_ts_query_capture_name_for_id"] = _ts_query_capture_name_for_id = wasmExports2["ts_query_capture_name_for_id"];
+ Module["_ts_query_capture_quantifier_for_id"] = _ts_query_capture_quantifier_for_id = wasmExports2["ts_query_capture_quantifier_for_id"];
+ Module["_ts_query_string_value_for_id"] = _ts_query_string_value_for_id = wasmExports2["ts_query_string_value_for_id"];
+ Module["_ts_query_predicates_for_pattern"] = _ts_query_predicates_for_pattern = wasmExports2["ts_query_predicates_for_pattern"];
+ Module["_ts_query_start_byte_for_pattern"] = _ts_query_start_byte_for_pattern = wasmExports2["ts_query_start_byte_for_pattern"];
+ Module["_ts_query_end_byte_for_pattern"] = _ts_query_end_byte_for_pattern = wasmExports2["ts_query_end_byte_for_pattern"];
+ Module["_ts_query_is_pattern_rooted"] = _ts_query_is_pattern_rooted = wasmExports2["ts_query_is_pattern_rooted"];
+ Module["_ts_query_is_pattern_non_local"] = _ts_query_is_pattern_non_local = wasmExports2["ts_query_is_pattern_non_local"];
+ Module["_ts_query_is_pattern_guaranteed_at_step"] = _ts_query_is_pattern_guaranteed_at_step = wasmExports2["ts_query_is_pattern_guaranteed_at_step"];
+ Module["_ts_query_disable_capture"] = _ts_query_disable_capture = wasmExports2["ts_query_disable_capture"];
+ Module["_ts_query_disable_pattern"] = _ts_query_disable_pattern = wasmExports2["ts_query_disable_pattern"];
+ Module["_ts_tree_copy"] = _ts_tree_copy = wasmExports2["ts_tree_copy"];
+ Module["_ts_tree_delete"] = _ts_tree_delete = wasmExports2["ts_tree_delete"];
+ Module["_ts_init"] = _ts_init = wasmExports2["ts_init"];
+ Module["_ts_parser_new_wasm"] = _ts_parser_new_wasm = wasmExports2["ts_parser_new_wasm"];
+ Module["_ts_parser_enable_logger_wasm"] = _ts_parser_enable_logger_wasm = wasmExports2["ts_parser_enable_logger_wasm"];
+ Module["_ts_parser_parse_wasm"] = _ts_parser_parse_wasm = wasmExports2["ts_parser_parse_wasm"];
+ Module["_ts_parser_included_ranges_wasm"] = _ts_parser_included_ranges_wasm = wasmExports2["ts_parser_included_ranges_wasm"];
+ Module["_ts_language_type_is_named_wasm"] = _ts_language_type_is_named_wasm = wasmExports2["ts_language_type_is_named_wasm"];
+ Module["_ts_language_type_is_visible_wasm"] = _ts_language_type_is_visible_wasm = wasmExports2["ts_language_type_is_visible_wasm"];
+ Module["_ts_language_metadata_wasm"] = _ts_language_metadata_wasm = wasmExports2["ts_language_metadata_wasm"];
+ Module["_ts_language_supertypes_wasm"] = _ts_language_supertypes_wasm = wasmExports2["ts_language_supertypes_wasm"];
+ Module["_ts_language_subtypes_wasm"] = _ts_language_subtypes_wasm = wasmExports2["ts_language_subtypes_wasm"];
+ Module["_ts_tree_root_node_wasm"] = _ts_tree_root_node_wasm = wasmExports2["ts_tree_root_node_wasm"];
+ Module["_ts_tree_root_node_with_offset_wasm"] = _ts_tree_root_node_with_offset_wasm = wasmExports2["ts_tree_root_node_with_offset_wasm"];
+ Module["_ts_tree_edit_wasm"] = _ts_tree_edit_wasm = wasmExports2["ts_tree_edit_wasm"];
+ Module["_ts_tree_included_ranges_wasm"] = _ts_tree_included_ranges_wasm = wasmExports2["ts_tree_included_ranges_wasm"];
+ Module["_ts_tree_get_changed_ranges_wasm"] = _ts_tree_get_changed_ranges_wasm = wasmExports2["ts_tree_get_changed_ranges_wasm"];
+ Module["_ts_tree_cursor_new_wasm"] = _ts_tree_cursor_new_wasm = wasmExports2["ts_tree_cursor_new_wasm"];
+ Module["_ts_tree_cursor_copy_wasm"] = _ts_tree_cursor_copy_wasm = wasmExports2["ts_tree_cursor_copy_wasm"];
+ Module["_ts_tree_cursor_delete_wasm"] = _ts_tree_cursor_delete_wasm = wasmExports2["ts_tree_cursor_delete_wasm"];
+ Module["_ts_tree_cursor_reset_wasm"] = _ts_tree_cursor_reset_wasm = wasmExports2["ts_tree_cursor_reset_wasm"];
+ Module["_ts_tree_cursor_reset_to_wasm"] = _ts_tree_cursor_reset_to_wasm = wasmExports2["ts_tree_cursor_reset_to_wasm"];
+ Module["_ts_tree_cursor_goto_first_child_wasm"] = _ts_tree_cursor_goto_first_child_wasm = wasmExports2["ts_tree_cursor_goto_first_child_wasm"];
+ Module["_ts_tree_cursor_goto_last_child_wasm"] = _ts_tree_cursor_goto_last_child_wasm = wasmExports2["ts_tree_cursor_goto_last_child_wasm"];
+ Module["_ts_tree_cursor_goto_first_child_for_index_wasm"] = _ts_tree_cursor_goto_first_child_for_index_wasm = wasmExports2["ts_tree_cursor_goto_first_child_for_index_wasm"];
+ Module["_ts_tree_cursor_goto_first_child_for_position_wasm"] = _ts_tree_cursor_goto_first_child_for_position_wasm = wasmExports2["ts_tree_cursor_goto_first_child_for_position_wasm"];
+ Module["_ts_tree_cursor_goto_next_sibling_wasm"] = _ts_tree_cursor_goto_next_sibling_wasm = wasmExports2["ts_tree_cursor_goto_next_sibling_wasm"];
+ Module["_ts_tree_cursor_goto_previous_sibling_wasm"] = _ts_tree_cursor_goto_previous_sibling_wasm = wasmExports2["ts_tree_cursor_goto_previous_sibling_wasm"];
+ Module["_ts_tree_cursor_goto_descendant_wasm"] = _ts_tree_cursor_goto_descendant_wasm = wasmExports2["ts_tree_cursor_goto_descendant_wasm"];
+ Module["_ts_tree_cursor_goto_parent_wasm"] = _ts_tree_cursor_goto_parent_wasm = wasmExports2["ts_tree_cursor_goto_parent_wasm"];
+ Module["_ts_tree_cursor_current_node_type_id_wasm"] = _ts_tree_cursor_current_node_type_id_wasm = wasmExports2["ts_tree_cursor_current_node_type_id_wasm"];
+ Module["_ts_tree_cursor_current_node_state_id_wasm"] = _ts_tree_cursor_current_node_state_id_wasm = wasmExports2["ts_tree_cursor_current_node_state_id_wasm"];
+ Module["_ts_tree_cursor_current_node_is_named_wasm"] = _ts_tree_cursor_current_node_is_named_wasm = wasmExports2["ts_tree_cursor_current_node_is_named_wasm"];
+ Module["_ts_tree_cursor_current_node_is_missing_wasm"] = _ts_tree_cursor_current_node_is_missing_wasm = wasmExports2["ts_tree_cursor_current_node_is_missing_wasm"];
+ Module["_ts_tree_cursor_current_node_id_wasm"] = _ts_tree_cursor_current_node_id_wasm = wasmExports2["ts_tree_cursor_current_node_id_wasm"];
+ Module["_ts_tree_cursor_start_position_wasm"] = _ts_tree_cursor_start_position_wasm = wasmExports2["ts_tree_cursor_start_position_wasm"];
+ Module["_ts_tree_cursor_end_position_wasm"] = _ts_tree_cursor_end_position_wasm = wasmExports2["ts_tree_cursor_end_position_wasm"];
+ Module["_ts_tree_cursor_start_index_wasm"] = _ts_tree_cursor_start_index_wasm = wasmExports2["ts_tree_cursor_start_index_wasm"];
+ Module["_ts_tree_cursor_end_index_wasm"] = _ts_tree_cursor_end_index_wasm = wasmExports2["ts_tree_cursor_end_index_wasm"];
+ Module["_ts_tree_cursor_current_field_id_wasm"] = _ts_tree_cursor_current_field_id_wasm = wasmExports2["ts_tree_cursor_current_field_id_wasm"];
+ Module["_ts_tree_cursor_current_depth_wasm"] = _ts_tree_cursor_current_depth_wasm = wasmExports2["ts_tree_cursor_current_depth_wasm"];
+ Module["_ts_tree_cursor_current_descendant_index_wasm"] = _ts_tree_cursor_current_descendant_index_wasm = wasmExports2["ts_tree_cursor_current_descendant_index_wasm"];
+ Module["_ts_tree_cursor_current_node_wasm"] = _ts_tree_cursor_current_node_wasm = wasmExports2["ts_tree_cursor_current_node_wasm"];
+ Module["_ts_node_symbol_wasm"] = _ts_node_symbol_wasm = wasmExports2["ts_node_symbol_wasm"];
+ Module["_ts_node_field_name_for_child_wasm"] = _ts_node_field_name_for_child_wasm = wasmExports2["ts_node_field_name_for_child_wasm"];
+ Module["_ts_node_field_name_for_named_child_wasm"] = _ts_node_field_name_for_named_child_wasm = wasmExports2["ts_node_field_name_for_named_child_wasm"];
+ Module["_ts_node_children_by_field_id_wasm"] = _ts_node_children_by_field_id_wasm = wasmExports2["ts_node_children_by_field_id_wasm"];
+ Module["_ts_node_first_child_for_byte_wasm"] = _ts_node_first_child_for_byte_wasm = wasmExports2["ts_node_first_child_for_byte_wasm"];
+ Module["_ts_node_first_named_child_for_byte_wasm"] = _ts_node_first_named_child_for_byte_wasm = wasmExports2["ts_node_first_named_child_for_byte_wasm"];
+ Module["_ts_node_grammar_symbol_wasm"] = _ts_node_grammar_symbol_wasm = wasmExports2["ts_node_grammar_symbol_wasm"];
+ Module["_ts_node_child_count_wasm"] = _ts_node_child_count_wasm = wasmExports2["ts_node_child_count_wasm"];
+ Module["_ts_node_named_child_count_wasm"] = _ts_node_named_child_count_wasm = wasmExports2["ts_node_named_child_count_wasm"];
+ Module["_ts_node_child_wasm"] = _ts_node_child_wasm = wasmExports2["ts_node_child_wasm"];
+ Module["_ts_node_named_child_wasm"] = _ts_node_named_child_wasm = wasmExports2["ts_node_named_child_wasm"];
+ Module["_ts_node_child_by_field_id_wasm"] = _ts_node_child_by_field_id_wasm = wasmExports2["ts_node_child_by_field_id_wasm"];
+ Module["_ts_node_next_sibling_wasm"] = _ts_node_next_sibling_wasm = wasmExports2["ts_node_next_sibling_wasm"];
+ Module["_ts_node_prev_sibling_wasm"] = _ts_node_prev_sibling_wasm = wasmExports2["ts_node_prev_sibling_wasm"];
+ Module["_ts_node_next_named_sibling_wasm"] = _ts_node_next_named_sibling_wasm = wasmExports2["ts_node_next_named_sibling_wasm"];
+ Module["_ts_node_prev_named_sibling_wasm"] = _ts_node_prev_named_sibling_wasm = wasmExports2["ts_node_prev_named_sibling_wasm"];
+ Module["_ts_node_descendant_count_wasm"] = _ts_node_descendant_count_wasm = wasmExports2["ts_node_descendant_count_wasm"];
+ Module["_ts_node_parent_wasm"] = _ts_node_parent_wasm = wasmExports2["ts_node_parent_wasm"];
+ Module["_ts_node_child_with_descendant_wasm"] = _ts_node_child_with_descendant_wasm = wasmExports2["ts_node_child_with_descendant_wasm"];
+ Module["_ts_node_descendant_for_index_wasm"] = _ts_node_descendant_for_index_wasm = wasmExports2["ts_node_descendant_for_index_wasm"];
+ Module["_ts_node_named_descendant_for_index_wasm"] = _ts_node_named_descendant_for_index_wasm = wasmExports2["ts_node_named_descendant_for_index_wasm"];
+ Module["_ts_node_descendant_for_position_wasm"] = _ts_node_descendant_for_position_wasm = wasmExports2["ts_node_descendant_for_position_wasm"];
+ Module["_ts_node_named_descendant_for_position_wasm"] = _ts_node_named_descendant_for_position_wasm = wasmExports2["ts_node_named_descendant_for_position_wasm"];
+ Module["_ts_node_start_point_wasm"] = _ts_node_start_point_wasm = wasmExports2["ts_node_start_point_wasm"];
+ Module["_ts_node_end_point_wasm"] = _ts_node_end_point_wasm = wasmExports2["ts_node_end_point_wasm"];
+ Module["_ts_node_start_index_wasm"] = _ts_node_start_index_wasm = wasmExports2["ts_node_start_index_wasm"];
+ Module["_ts_node_end_index_wasm"] = _ts_node_end_index_wasm = wasmExports2["ts_node_end_index_wasm"];
+ Module["_ts_node_to_string_wasm"] = _ts_node_to_string_wasm = wasmExports2["ts_node_to_string_wasm"];
+ Module["_ts_node_children_wasm"] = _ts_node_children_wasm = wasmExports2["ts_node_children_wasm"];
+ Module["_ts_node_named_children_wasm"] = _ts_node_named_children_wasm = wasmExports2["ts_node_named_children_wasm"];
+ Module["_ts_node_descendants_of_type_wasm"] = _ts_node_descendants_of_type_wasm = wasmExports2["ts_node_descendants_of_type_wasm"];
+ Module["_ts_node_is_named_wasm"] = _ts_node_is_named_wasm = wasmExports2["ts_node_is_named_wasm"];
+ Module["_ts_node_has_changes_wasm"] = _ts_node_has_changes_wasm = wasmExports2["ts_node_has_changes_wasm"];
+ Module["_ts_node_has_error_wasm"] = _ts_node_has_error_wasm = wasmExports2["ts_node_has_error_wasm"];
+ Module["_ts_node_is_error_wasm"] = _ts_node_is_error_wasm = wasmExports2["ts_node_is_error_wasm"];
+ Module["_ts_node_is_missing_wasm"] = _ts_node_is_missing_wasm = wasmExports2["ts_node_is_missing_wasm"];
+ Module["_ts_node_is_extra_wasm"] = _ts_node_is_extra_wasm = wasmExports2["ts_node_is_extra_wasm"];
+ Module["_ts_node_parse_state_wasm"] = _ts_node_parse_state_wasm = wasmExports2["ts_node_parse_state_wasm"];
+ Module["_ts_node_next_parse_state_wasm"] = _ts_node_next_parse_state_wasm = wasmExports2["ts_node_next_parse_state_wasm"];
+ Module["_ts_query_matches_wasm"] = _ts_query_matches_wasm = wasmExports2["ts_query_matches_wasm"];
+ Module["_ts_query_captures_wasm"] = _ts_query_captures_wasm = wasmExports2["ts_query_captures_wasm"];
+ Module["_memset"] = _memset = wasmExports2["memset"];
+ Module["_memcpy"] = _memcpy = wasmExports2["memcpy"];
+ Module["_memmove"] = _memmove = wasmExports2["memmove"];
+ Module["_iswalpha"] = _iswalpha = wasmExports2["iswalpha"];
+ Module["_iswblank"] = _iswblank = wasmExports2["iswblank"];
+ Module["_iswdigit"] = _iswdigit = wasmExports2["iswdigit"];
+ Module["_iswlower"] = _iswlower = wasmExports2["iswlower"];
+ Module["_iswupper"] = _iswupper = wasmExports2["iswupper"];
+ Module["_iswxdigit"] = _iswxdigit = wasmExports2["iswxdigit"];
+ Module["_memchr"] = _memchr = wasmExports2["memchr"];
+ Module["_strlen"] = _strlen = wasmExports2["strlen"];
+ Module["_strcmp"] = _strcmp = wasmExports2["strcmp"];
+ Module["_strncat"] = _strncat = wasmExports2["strncat"];
+ Module["_strncpy"] = _strncpy = wasmExports2["strncpy"];
+ Module["_towlower"] = _towlower = wasmExports2["towlower"];
+ Module["_towupper"] = _towupper = wasmExports2["towupper"];
+ _setThrew = wasmExports2["setThrew"];
+ __emscripten_stack_restore = wasmExports2["_emscripten_stack_restore"];
+ __emscripten_stack_alloc = wasmExports2["_emscripten_stack_alloc"];
+ _emscripten_stack_get_current = wasmExports2["emscripten_stack_get_current"];
+ ___wasm_apply_data_relocs = wasmExports2["__wasm_apply_data_relocs"];
+ }
+ __name(assignWasmExports, "assignWasmExports");
+ var wasmImports = {
+ /** @export */
+ __heap_base: ___heap_base,
+ /** @export */
+ __indirect_function_table: wasmTable,
+ /** @export */
+ __memory_base: ___memory_base,
+ /** @export */
+ __stack_high: ___stack_high,
+ /** @export */
+ __stack_low: ___stack_low,
+ /** @export */
+ __stack_pointer: ___stack_pointer,
+ /** @export */
+ __table_base: ___table_base,
+ /** @export */
+ _abort_js: __abort_js,
+ /** @export */
+ emscripten_resize_heap: _emscripten_resize_heap,
+ /** @export */
+ fd_close: _fd_close,
+ /** @export */
+ fd_seek: _fd_seek,
+ /** @export */
+ fd_write: _fd_write,
+ /** @export */
+ memory: wasmMemory,
+ /** @export */
+ tree_sitter_log_callback: _tree_sitter_log_callback,
+ /** @export */
+ tree_sitter_parse_callback: _tree_sitter_parse_callback,
+ /** @export */
+ tree_sitter_progress_callback: _tree_sitter_progress_callback,
+ /** @export */
+ tree_sitter_query_progress_callback: _tree_sitter_query_progress_callback
+ };
+ function callMain(args2 = []) {
+ var entryFunction = resolveGlobalSymbol("main").sym;
+ if (!entryFunction) return;
+ args2.unshift(thisProgram);
+ var argc = args2.length;
+ var argv = stackAlloc((argc + 1) * 4);
+ var argv_ptr = argv;
+ args2.forEach((arg) => {
+ LE_HEAP_STORE_U32((argv_ptr >> 2) * 4, stringToUTF8OnStack(arg));
+ argv_ptr += 4;
+ });
+ LE_HEAP_STORE_U32((argv_ptr >> 2) * 4, 0);
+ try {
+ var ret = entryFunction(argc, argv);
+ exitJS(
+ ret,
+ /* implicit = */
+ true
+ );
+ return ret;
+ } catch (e) {
+ return handleException(e);
+ }
+ }
+ __name(callMain, "callMain");
+ function run(args2 = arguments_) {
+ if (runDependencies > 0) {
+ dependenciesFulfilled = run;
+ return;
+ }
+ preRun();
+ if (runDependencies > 0) {
+ dependenciesFulfilled = run;
+ return;
+ }
+ function doRun() {
+ Module["calledRun"] = true;
+ if (ABORT) return;
+ initRuntime();
+ preMain();
+ readyPromiseResolve?.(Module);
+ Module["onRuntimeInitialized"]?.();
+ var noInitialRun = Module["noInitialRun"] || false;
+ if (!noInitialRun) callMain(args2);
+ postRun();
+ }
+ __name(doRun, "doRun");
+ if (Module["setStatus"]) {
+ Module["setStatus"]("Running...");
+ setTimeout(() => {
+ setTimeout(() => Module["setStatus"](""), 1);
+ doRun();
+ }, 1);
+ } else {
+ doRun();
+ }
+ }
+ __name(run, "run");
+ var wasmExports;
+ wasmExports = await createWasm();
+ run();
+ if (runtimeInitialized) {
+ moduleRtn = Module;
+ } else {
+ moduleRtn = new Promise((resolve, reject) => {
+ readyPromiseResolve = resolve;
+ readyPromiseReject = reject;
+ });
+ }
+ return moduleRtn;
+}
+__name(Module2, "Module");
+var web_tree_sitter_default = Module2;
+
+// src/bindings.ts
+var Module3 = null;
+async function initializeBinding(moduleOptions) {
+ return Module3 ??= await web_tree_sitter_default(moduleOptions);
+}
+__name(initializeBinding, "initializeBinding");
+function checkModule() {
+ return !!Module3;
+}
+__name(checkModule, "checkModule");
+
+// src/parser.ts
+var TRANSFER_BUFFER;
+var LANGUAGE_VERSION;
+var MIN_COMPATIBLE_VERSION;
+var Parser = class {
+ static {
+ __name(this, "Parser");
+ }
+ /** @internal */
+ [0] = 0;
+ // Internal handle for Wasm
+ /** @internal */
+ [1] = 0;
+ // Internal handle for Wasm
+ /** @internal */
+ logCallback = null;
+ /** The parser's current language. */
+ language = null;
+ /**
+ * This must always be called before creating a Parser.
+ *
+ * You can optionally pass in options to configure the Wasm module, the most common
+ * one being `locateFile` to help the module find the `.wasm` file.
+ */
+ static async init(moduleOptions) {
+ setModule(await initializeBinding(moduleOptions));
+ TRANSFER_BUFFER = C._ts_init();
+ LANGUAGE_VERSION = C.getValue(TRANSFER_BUFFER, "i32");
+ MIN_COMPATIBLE_VERSION = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
+ }
+ /**
+ * Create a new parser.
+ */
+ constructor() {
+ this.initialize();
+ }
+ /** @internal */
+ initialize() {
+ if (!checkModule()) {
+ throw new Error("cannot construct a Parser before calling `init()`");
+ }
+ C._ts_parser_new_wasm();
+ this[0] = C.getValue(TRANSFER_BUFFER, "i32");
+ this[1] = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
+ }
+ /** Delete the parser, freeing its resources. */
+ delete() {
+ C._ts_parser_delete(this[0]);
+ C._free(this[1]);
+ this[0] = 0;
+ this[1] = 0;
+ }
+ /**
+ * Set the language that the parser should use for parsing.
+ *
+ * If the language was not successfully assigned, an error will be thrown.
+ * This happens if the language was generated with an incompatible
+ * version of the Tree-sitter CLI. Check the language's version using
+ * {@link Language#version} and compare it to this library's
+ * {@link LANGUAGE_VERSION} and {@link MIN_COMPATIBLE_VERSION} constants.
+ */
+ setLanguage(language) {
+ let address;
+ if (!language) {
+ address = 0;
+ this.language = null;
+ } else if (language.constructor === Language) {
+ address = language[0];
+ const version = C._ts_language_abi_version(address);
+ if (version < MIN_COMPATIBLE_VERSION || LANGUAGE_VERSION < version) {
+ throw new Error(
+ `Incompatible language version ${version}. Compatibility range ${MIN_COMPATIBLE_VERSION} through ${LANGUAGE_VERSION}.`
+ );
+ }
+ this.language = language;
+ } else {
+ throw new Error("Argument must be a Language");
+ }
+ C._ts_parser_set_language(this[0], address);
+ return this;
+ }
+ /**
+ * Parse a slice of UTF8 text.
+ *
+ * @param {string | ParseCallback} callback - The UTF8-encoded text to parse or a callback function.
+ *
+ * @param {Tree | null} [oldTree] - A previous syntax tree parsed from the same document. If the text of the
+ * document has changed since `oldTree` was created, then you must edit `oldTree` to match
+ * the new text using {@link Tree#edit}.
+ *
+ * @param {ParseOptions} [options] - Options for parsing the text.
+ * This can be used to set the included ranges, or a progress callback.
+ *
+ * @returns {Tree | null} A {@link Tree} if parsing succeeded, or `null` if:
+ * - The parser has not yet had a language assigned with {@link Parser#setLanguage}.
+ * - The progress callback returned true.
+ */
+ parse(callback, oldTree, options) {
+ if (typeof callback === "string") {
+ C.currentParseCallback = (index) => callback.slice(index);
+ } else if (typeof callback === "function") {
+ C.currentParseCallback = callback;
+ } else {
+ throw new Error("Argument must be a string or a function");
+ }
+ if (options?.progressCallback) {
+ C.currentProgressCallback = options.progressCallback;
+ } else {
+ C.currentProgressCallback = null;
+ }
+ if (this.logCallback) {
+ C.currentLogCallback = this.logCallback;
+ C._ts_parser_enable_logger_wasm(this[0], 1);
+ } else {
+ C.currentLogCallback = null;
+ C._ts_parser_enable_logger_wasm(this[0], 0);
+ }
+ let rangeCount = 0;
+ let rangeAddress = 0;
+ if (options?.includedRanges) {
+ rangeCount = options.includedRanges.length;
+ rangeAddress = C._calloc(rangeCount, SIZE_OF_RANGE);
+ let address = rangeAddress;
+ for (let i2 = 0; i2 < rangeCount; i2++) {
+ marshalRange(address, options.includedRanges[i2]);
+ address += SIZE_OF_RANGE;
+ }
+ }
+ const treeAddress = C._ts_parser_parse_wasm(
+ this[0],
+ this[1],
+ oldTree ? oldTree[0] : 0,
+ rangeAddress,
+ rangeCount
+ );
+ if (!treeAddress) {
+ C.currentParseCallback = null;
+ C.currentLogCallback = null;
+ C.currentProgressCallback = null;
+ return null;
+ }
+ if (!this.language) {
+ throw new Error("Parser must have a language to parse");
+ }
+ const result = new Tree(INTERNAL, treeAddress, this.language, C.currentParseCallback);
+ C.currentParseCallback = null;
+ C.currentLogCallback = null;
+ C.currentProgressCallback = null;
+ return result;
+ }
+ /**
+ * Instruct the parser to start the next parse from the beginning.
+ *
+ * If the parser previously failed because of a callback,
+ * then by default, it will resume where it left off on the
+ * next call to {@link Parser#parse} or other parsing functions.
+ * If you don't want to resume, and instead intend to use this parser to
+ * parse some other document, you must call `reset` first.
+ */
+ reset() {
+ C._ts_parser_reset(this[0]);
+ }
+ /** Get the ranges of text that the parser will include when parsing. */
+ getIncludedRanges() {
+ C._ts_parser_included_ranges_wasm(this[0]);
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
+ const buffer = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
+ const result = new Array(count);
+ if (count > 0) {
+ let address = buffer;
+ for (let i2 = 0; i2 < count; i2++) {
+ result[i2] = unmarshalRange(address);
+ address += SIZE_OF_RANGE;
+ }
+ C._free(buffer);
+ }
+ return result;
+ }
+ /** Set the logging callback that a parser should use during parsing. */
+ setLogger(callback) {
+ if (!callback) {
+ this.logCallback = null;
+ } else if (typeof callback !== "function") {
+ throw new Error("Logger callback must be a function");
+ } else {
+ this.logCallback = callback;
+ }
+ return this;
+ }
+ /** Get the parser's current logger. */
+ getLogger() {
+ return this.logCallback;
+ }
+};
+
+// src/query.ts
+var PREDICATE_STEP_TYPE_CAPTURE = 1;
+var PREDICATE_STEP_TYPE_STRING = 2;
+var QUERY_WORD_REGEX = /[\w-]+/g;
+var CaptureQuantifier = {
+ Zero: 0,
+ ZeroOrOne: 1,
+ ZeroOrMore: 2,
+ One: 3,
+ OneOrMore: 4
+};
+var isCaptureStep = /* @__PURE__ */ __name((step) => step.type === "capture", "isCaptureStep");
+var isStringStep = /* @__PURE__ */ __name((step) => step.type === "string", "isStringStep");
+var QueryErrorKind = {
+ Syntax: 1,
+ NodeName: 2,
+ FieldName: 3,
+ CaptureName: 4,
+ PatternStructure: 5
+};
+var QueryError = class _QueryError extends Error {
+ constructor(kind, info2, index, length) {
+ super(_QueryError.formatMessage(kind, info2));
+ this.kind = kind;
+ this.info = info2;
+ this.index = index;
+ this.length = length;
+ this.name = "QueryError";
+ }
+ static {
+ __name(this, "QueryError");
+ }
+ /** Formats an error message based on the error kind and info */
+ static formatMessage(kind, info2) {
+ switch (kind) {
+ case QueryErrorKind.NodeName:
+ return `Bad node name '${info2.word}'`;
+ case QueryErrorKind.FieldName:
+ return `Bad field name '${info2.word}'`;
+ case QueryErrorKind.CaptureName:
+ return `Bad capture name @${info2.word}`;
+ case QueryErrorKind.PatternStructure:
+ return `Bad pattern structure at offset ${info2.suffix}`;
+ case QueryErrorKind.Syntax:
+ return `Bad syntax at offset ${info2.suffix}`;
+ }
+ }
+};
+function parseAnyPredicate(steps, index, operator, textPredicates) {
+ if (steps.length !== 3) {
+ throw new Error(
+ `Wrong number of arguments to \`#${operator}\` predicate. Expected 2, got ${steps.length - 1}`
+ );
+ }
+ if (!isCaptureStep(steps[1])) {
+ throw new Error(
+ `First argument of \`#${operator}\` predicate must be a capture. Got "${steps[1].value}"`
+ );
+ }
+ const isPositive = operator === "eq?" || operator === "any-eq?";
+ const matchAll = !operator.startsWith("any-");
+ if (isCaptureStep(steps[2])) {
+ const captureName1 = steps[1].name;
+ const captureName2 = steps[2].name;
+ textPredicates[index].push((captures) => {
+ const nodes1 = [];
+ const nodes2 = [];
+ for (const c of captures) {
+ if (c.name === captureName1) nodes1.push(c.node);
+ if (c.name === captureName2) nodes2.push(c.node);
+ }
+ const compare = /* @__PURE__ */ __name((n1, n2, positive) => {
+ return positive ? n1.text === n2.text : n1.text !== n2.text;
+ }, "compare");
+ return matchAll ? nodes1.every((n1) => nodes2.some((n2) => compare(n1, n2, isPositive))) : nodes1.some((n1) => nodes2.some((n2) => compare(n1, n2, isPositive)));
+ });
+ } else {
+ const captureName = steps[1].name;
+ const stringValue = steps[2].value;
+ const matches = /* @__PURE__ */ __name((n) => n.text === stringValue, "matches");
+ const doesNotMatch = /* @__PURE__ */ __name((n) => n.text !== stringValue, "doesNotMatch");
+ textPredicates[index].push((captures) => {
+ const nodes = [];
+ for (const c of captures) {
+ if (c.name === captureName) nodes.push(c.node);
+ }
+ const test = isPositive ? matches : doesNotMatch;
+ return matchAll ? nodes.every(test) : nodes.some(test);
+ });
+ }
+}
+__name(parseAnyPredicate, "parseAnyPredicate");
+function parseMatchPredicate(steps, index, operator, textPredicates) {
+ if (steps.length !== 3) {
+ throw new Error(
+ `Wrong number of arguments to \`#${operator}\` predicate. Expected 2, got ${steps.length - 1}.`
+ );
+ }
+ if (steps[1].type !== "capture") {
+ throw new Error(
+ `First argument of \`#${operator}\` predicate must be a capture. Got "${steps[1].value}".`
+ );
+ }
+ if (steps[2].type !== "string") {
+ throw new Error(
+ `Second argument of \`#${operator}\` predicate must be a string. Got @${steps[2].name}.`
+ );
+ }
+ const isPositive = operator === "match?" || operator === "any-match?";
+ const matchAll = !operator.startsWith("any-");
+ const captureName = steps[1].name;
+ const regex = new RegExp(steps[2].value);
+ textPredicates[index].push((captures) => {
+ const nodes = [];
+ for (const c of captures) {
+ if (c.name === captureName) nodes.push(c.node.text);
+ }
+ const test = /* @__PURE__ */ __name((text, positive) => {
+ return positive ? regex.test(text) : !regex.test(text);
+ }, "test");
+ if (nodes.length === 0) return !isPositive;
+ return matchAll ? nodes.every((text) => test(text, isPositive)) : nodes.some((text) => test(text, isPositive));
+ });
+}
+__name(parseMatchPredicate, "parseMatchPredicate");
+function parseAnyOfPredicate(steps, index, operator, textPredicates) {
+ if (steps.length < 2) {
+ throw new Error(
+ `Wrong number of arguments to \`#${operator}\` predicate. Expected at least 1. Got ${steps.length - 1}.`
+ );
+ }
+ if (steps[1].type !== "capture") {
+ throw new Error(
+ `First argument of \`#${operator}\` predicate must be a capture. Got "${steps[1].value}".`
+ );
+ }
+ const isPositive = operator === "any-of?";
+ const captureName = steps[1].name;
+ const stringSteps = steps.slice(2);
+ if (!stringSteps.every(isStringStep)) {
+ throw new Error(
+ `Arguments to \`#${operator}\` predicate must be strings.".`
+ );
+ }
+ const values = stringSteps.map((s) => s.value);
+ textPredicates[index].push((captures) => {
+ const nodes = [];
+ for (const c of captures) {
+ if (c.name === captureName) nodes.push(c.node.text);
+ }
+ if (nodes.length === 0) return !isPositive;
+ return nodes.every((text) => values.includes(text)) === isPositive;
+ });
+}
+__name(parseAnyOfPredicate, "parseAnyOfPredicate");
+function parseIsPredicate(steps, index, operator, assertedProperties, refutedProperties) {
+ if (steps.length < 2 || steps.length > 3) {
+ throw new Error(
+ `Wrong number of arguments to \`#${operator}\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`
+ );
+ }
+ if (!steps.every(isStringStep)) {
+ throw new Error(
+ `Arguments to \`#${operator}\` predicate must be strings.".`
+ );
+ }
+ const properties = operator === "is?" ? assertedProperties : refutedProperties;
+ if (!properties[index]) properties[index] = {};
+ properties[index][steps[1].value] = steps[2]?.value ?? null;
+}
+__name(parseIsPredicate, "parseIsPredicate");
+function parseSetDirective(steps, index, setProperties) {
+ if (steps.length < 2 || steps.length > 3) {
+ throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${steps.length - 1}.`);
+ }
+ if (!steps.every(isStringStep)) {
+ throw new Error(`Arguments to \`#set!\` predicate must be strings.".`);
+ }
+ if (!setProperties[index]) setProperties[index] = {};
+ setProperties[index][steps[1].value] = steps[2]?.value ?? null;
+}
+__name(parseSetDirective, "parseSetDirective");
+function parsePattern(index, stepType, stepValueId, captureNames, stringValues, steps, textPredicates, predicates, setProperties, assertedProperties, refutedProperties) {
+ if (stepType === PREDICATE_STEP_TYPE_CAPTURE) {
+ const name2 = captureNames[stepValueId];
+ steps.push({ type: "capture", name: name2 });
+ } else if (stepType === PREDICATE_STEP_TYPE_STRING) {
+ steps.push({ type: "string", value: stringValues[stepValueId] });
+ } else if (steps.length > 0) {
+ if (steps[0].type !== "string") {
+ throw new Error("Predicates must begin with a literal value");
+ }
+ const operator = steps[0].value;
+ switch (operator) {
+ case "any-not-eq?":
+ case "not-eq?":
+ case "any-eq?":
+ case "eq?":
+ parseAnyPredicate(steps, index, operator, textPredicates);
+ break;
+ case "any-not-match?":
+ case "not-match?":
+ case "any-match?":
+ case "match?":
+ parseMatchPredicate(steps, index, operator, textPredicates);
+ break;
+ case "not-any-of?":
+ case "any-of?":
+ parseAnyOfPredicate(steps, index, operator, textPredicates);
+ break;
+ case "is?":
+ case "is-not?":
+ parseIsPredicate(steps, index, operator, assertedProperties, refutedProperties);
+ break;
+ case "set!":
+ parseSetDirective(steps, index, setProperties);
+ break;
+ default:
+ predicates[index].push({ operator, operands: steps.slice(1) });
+ }
+ steps.length = 0;
+ }
+}
+__name(parsePattern, "parsePattern");
+var Query = class {
+ static {
+ __name(this, "Query");
+ }
+ /** @internal */
+ [0] = 0;
+ // Internal handle for Wasm
+ /** @internal */
+ exceededMatchLimit;
+ /** @internal */
+ textPredicates;
+ /** The names of the captures used in the query. */
+ captureNames;
+ /** The quantifiers of the captures used in the query. */
+ captureQuantifiers;
+ /**
+ * The other user-defined predicates associated with the given index.
+ *
+ * This includes predicates with operators other than:
+ * - `match?`
+ * - `eq?` and `not-eq?`
+ * - `any-of?` and `not-any-of?`
+ * - `is?` and `is-not?`
+ * - `set!`
+ */
+ predicates;
+ /** The properties for predicates with the operator `set!`. */
+ setProperties;
+ /** The properties for predicates with the operator `is?`. */
+ assertedProperties;
+ /** The properties for predicates with the operator `is-not?`. */
+ refutedProperties;
+ /** The maximum number of in-progress matches for this cursor. */
+ matchLimit;
+ /**
+ * Create a new query from a string containing one or more S-expression
+ * patterns.
+ *
+ * The query is associated with a particular language, and can only be run
+ * on syntax nodes parsed with that language. References to Queries can be
+ * shared between multiple threads.
+ *
+ * @link {@see https://tree-sitter.github.io/tree-sitter/using-parsers/queries}
+ */
+ constructor(language, source) {
+ const sourceLength = C.lengthBytesUTF8(source);
+ const sourceAddress = C._malloc(sourceLength + 1);
+ C.stringToUTF8(source, sourceAddress, sourceLength + 1);
+ const address = C._ts_query_new(
+ language[0],
+ sourceAddress,
+ sourceLength,
+ TRANSFER_BUFFER,
+ TRANSFER_BUFFER + SIZE_OF_INT
+ );
+ if (!address) {
+ const errorId = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
+ const errorByte = C.getValue(TRANSFER_BUFFER, "i32");
+ const errorIndex = C.UTF8ToString(sourceAddress, errorByte).length;
+ const suffix = source.slice(errorIndex, errorIndex + 100).split("\n")[0];
+ const word = suffix.match(QUERY_WORD_REGEX)?.[0] ?? "";
+ C._free(sourceAddress);
+ switch (errorId) {
+ case QueryErrorKind.Syntax:
+ throw new QueryError(QueryErrorKind.Syntax, { suffix: `${errorIndex}: '${suffix}'...` }, errorIndex, 0);
+ case QueryErrorKind.NodeName:
+ throw new QueryError(errorId, { word }, errorIndex, word.length);
+ case QueryErrorKind.FieldName:
+ throw new QueryError(errorId, { word }, errorIndex, word.length);
+ case QueryErrorKind.CaptureName:
+ throw new QueryError(errorId, { word }, errorIndex, word.length);
+ case QueryErrorKind.PatternStructure:
+ throw new QueryError(errorId, { suffix: `${errorIndex}: '${suffix}'...` }, errorIndex, 0);
+ }
+ }
+ const stringCount = C._ts_query_string_count(address);
+ const captureCount = C._ts_query_capture_count(address);
+ const patternCount = C._ts_query_pattern_count(address);
+ const captureNames = new Array(captureCount);
+ const captureQuantifiers = new Array(patternCount);
+ const stringValues = new Array(stringCount);
+ for (let i2 = 0; i2 < captureCount; i2++) {
+ const nameAddress = C._ts_query_capture_name_for_id(
+ address,
+ i2,
+ TRANSFER_BUFFER
+ );
+ const nameLength = C.getValue(TRANSFER_BUFFER, "i32");
+ captureNames[i2] = C.UTF8ToString(nameAddress, nameLength);
+ }
+ for (let i2 = 0; i2 < patternCount; i2++) {
+ const captureQuantifiersArray = new Array(captureCount);
+ for (let j = 0; j < captureCount; j++) {
+ const quantifier = C._ts_query_capture_quantifier_for_id(address, i2, j);
+ captureQuantifiersArray[j] = quantifier;
+ }
+ captureQuantifiers[i2] = captureQuantifiersArray;
+ }
+ for (let i2 = 0; i2 < stringCount; i2++) {
+ const valueAddress = C._ts_query_string_value_for_id(
+ address,
+ i2,
+ TRANSFER_BUFFER
+ );
+ const nameLength = C.getValue(TRANSFER_BUFFER, "i32");
+ stringValues[i2] = C.UTF8ToString(valueAddress, nameLength);
+ }
+ const setProperties = new Array(patternCount);
+ const assertedProperties = new Array(patternCount);
+ const refutedProperties = new Array(patternCount);
+ const predicates = new Array(patternCount);
+ const textPredicates = new Array(patternCount);
+ for (let i2 = 0; i2 < patternCount; i2++) {
+ const predicatesAddress = C._ts_query_predicates_for_pattern(address, i2, TRANSFER_BUFFER);
+ const stepCount = C.getValue(TRANSFER_BUFFER, "i32");
+ predicates[i2] = [];
+ textPredicates[i2] = [];
+ const steps = new Array();
+ let stepAddress = predicatesAddress;
+ for (let j = 0; j < stepCount; j++) {
+ const stepType = C.getValue(stepAddress, "i32");
+ stepAddress += SIZE_OF_INT;
+ const stepValueId = C.getValue(stepAddress, "i32");
+ stepAddress += SIZE_OF_INT;
+ parsePattern(
+ i2,
+ stepType,
+ stepValueId,
+ captureNames,
+ stringValues,
+ steps,
+ textPredicates,
+ predicates,
+ setProperties,
+ assertedProperties,
+ refutedProperties
+ );
+ }
+ Object.freeze(textPredicates[i2]);
+ Object.freeze(predicates[i2]);
+ Object.freeze(setProperties[i2]);
+ Object.freeze(assertedProperties[i2]);
+ Object.freeze(refutedProperties[i2]);
+ }
+ C._free(sourceAddress);
+ this[0] = address;
+ this.captureNames = captureNames;
+ this.captureQuantifiers = captureQuantifiers;
+ this.textPredicates = textPredicates;
+ this.predicates = predicates;
+ this.setProperties = setProperties;
+ this.assertedProperties = assertedProperties;
+ this.refutedProperties = refutedProperties;
+ this.exceededMatchLimit = false;
+ }
+ /** Delete the query, freeing its resources. */
+ delete() {
+ C._ts_query_delete(this[0]);
+ this[0] = 0;
+ }
+ /**
+ * Iterate over all of the matches in the order that they were found.
+ *
+ * Each match contains the index of the pattern that matched, and a list of
+ * captures. Because multiple patterns can match the same set of nodes,
+ * one match may contain captures that appear *before* some of the
+ * captures from a previous match.
+ *
+ * @param {Node} node - The node to execute the query on.
+ *
+ * @param {QueryOptions} options - Options for query execution.
+ */
+ matches(node, options = {}) {
+ const startPosition = options.startPosition ?? ZERO_POINT;
+ const endPosition = options.endPosition ?? ZERO_POINT;
+ const startIndex = options.startIndex ?? 0;
+ const endIndex = options.endIndex ?? 0;
+ const startContainingPosition = options.startContainingPosition ?? ZERO_POINT;
+ const endContainingPosition = options.endContainingPosition ?? ZERO_POINT;
+ const startContainingIndex = options.startContainingIndex ?? 0;
+ const endContainingIndex = options.endContainingIndex ?? 0;
+ const matchLimit = options.matchLimit ?? 4294967295;
+ const maxStartDepth = options.maxStartDepth ?? 4294967295;
+ const progressCallback = options.progressCallback;
+ if (typeof matchLimit !== "number") {
+ throw new Error("Arguments must be numbers");
+ }
+ this.matchLimit = matchLimit;
+ if (endIndex !== 0 && startIndex > endIndex) {
+ throw new Error("`startIndex` cannot be greater than `endIndex`");
+ }
+ if (endPosition !== ZERO_POINT && (startPosition.row > endPosition.row || startPosition.row === endPosition.row && startPosition.column > endPosition.column)) {
+ throw new Error("`startPosition` cannot be greater than `endPosition`");
+ }
+ if (endContainingIndex !== 0 && startContainingIndex > endContainingIndex) {
+ throw new Error("`startContainingIndex` cannot be greater than `endContainingIndex`");
+ }
+ if (endContainingPosition !== ZERO_POINT && (startContainingPosition.row > endContainingPosition.row || startContainingPosition.row === endContainingPosition.row && startContainingPosition.column > endContainingPosition.column)) {
+ throw new Error("`startContainingPosition` cannot be greater than `endContainingPosition`");
+ }
+ if (progressCallback) {
+ C.currentQueryProgressCallback = progressCallback;
+ }
+ marshalNode(node);
+ C._ts_query_matches_wasm(
+ this[0],
+ node.tree[0],
+ startPosition.row,
+ startPosition.column,
+ endPosition.row,
+ endPosition.column,
+ startIndex,
+ endIndex,
+ startContainingPosition.row,
+ startContainingPosition.column,
+ endContainingPosition.row,
+ endContainingPosition.column,
+ startContainingIndex,
+ endContainingIndex,
+ matchLimit,
+ maxStartDepth
+ );
+ const rawCount = C.getValue(TRANSFER_BUFFER, "i32");
+ const startAddress = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
+ const didExceedMatchLimit = C.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
+ const result = new Array(rawCount);
+ this.exceededMatchLimit = Boolean(didExceedMatchLimit);
+ let filteredCount = 0;
+ let address = startAddress;
+ for (let i2 = 0; i2 < rawCount; i2++) {
+ const patternIndex = C.getValue(address, "i32");
+ address += SIZE_OF_INT;
+ const captureCount = C.getValue(address, "i32");
+ address += SIZE_OF_INT;
+ const captures = new Array(captureCount);
+ address = unmarshalCaptures(this, node.tree, address, patternIndex, captures);
+ if (this.textPredicates[patternIndex].every((p) => p(captures))) {
+ result[filteredCount] = { patternIndex, captures };
+ const setProperties = this.setProperties[patternIndex];
+ result[filteredCount].setProperties = setProperties;
+ const assertedProperties = this.assertedProperties[patternIndex];
+ result[filteredCount].assertedProperties = assertedProperties;
+ const refutedProperties = this.refutedProperties[patternIndex];
+ result[filteredCount].refutedProperties = refutedProperties;
+ filteredCount++;
+ }
+ }
+ result.length = filteredCount;
+ C._free(startAddress);
+ C.currentQueryProgressCallback = null;
+ return result;
+ }
+ /**
+ * Iterate over all of the individual captures in the order that they
+ * appear.
+ *
+ * This is useful if you don't care about which pattern matched, and just
+ * want a single, ordered sequence of captures.
+ *
+ * @param {Node} node - The node to execute the query on.
+ *
+ * @param {QueryOptions} options - Options for query execution.
+ */
+ captures(node, options = {}) {
+ const startPosition = options.startPosition ?? ZERO_POINT;
+ const endPosition = options.endPosition ?? ZERO_POINT;
+ const startIndex = options.startIndex ?? 0;
+ const endIndex = options.endIndex ?? 0;
+ const startContainingPosition = options.startContainingPosition ?? ZERO_POINT;
+ const endContainingPosition = options.endContainingPosition ?? ZERO_POINT;
+ const startContainingIndex = options.startContainingIndex ?? 0;
+ const endContainingIndex = options.endContainingIndex ?? 0;
+ const matchLimit = options.matchLimit ?? 4294967295;
+ const maxStartDepth = options.maxStartDepth ?? 4294967295;
+ const progressCallback = options.progressCallback;
+ if (typeof matchLimit !== "number") {
+ throw new Error("Arguments must be numbers");
+ }
+ this.matchLimit = matchLimit;
+ if (endIndex !== 0 && startIndex > endIndex) {
+ throw new Error("`startIndex` cannot be greater than `endIndex`");
+ }
+ if (endPosition !== ZERO_POINT && (startPosition.row > endPosition.row || startPosition.row === endPosition.row && startPosition.column > endPosition.column)) {
+ throw new Error("`startPosition` cannot be greater than `endPosition`");
+ }
+ if (endContainingIndex !== 0 && startContainingIndex > endContainingIndex) {
+ throw new Error("`startContainingIndex` cannot be greater than `endContainingIndex`");
+ }
+ if (endContainingPosition !== ZERO_POINT && (startContainingPosition.row > endContainingPosition.row || startContainingPosition.row === endContainingPosition.row && startContainingPosition.column > endContainingPosition.column)) {
+ throw new Error("`startContainingPosition` cannot be greater than `endContainingPosition`");
+ }
+ if (progressCallback) {
+ C.currentQueryProgressCallback = progressCallback;
+ }
+ marshalNode(node);
+ C._ts_query_captures_wasm(
+ this[0],
+ node.tree[0],
+ startPosition.row,
+ startPosition.column,
+ endPosition.row,
+ endPosition.column,
+ startIndex,
+ endIndex,
+ startContainingPosition.row,
+ startContainingPosition.column,
+ endContainingPosition.row,
+ endContainingPosition.column,
+ startContainingIndex,
+ endContainingIndex,
+ matchLimit,
+ maxStartDepth
+ );
+ const count = C.getValue(TRANSFER_BUFFER, "i32");
+ const startAddress = C.getValue(TRANSFER_BUFFER + SIZE_OF_INT, "i32");
+ const didExceedMatchLimit = C.getValue(TRANSFER_BUFFER + 2 * SIZE_OF_INT, "i32");
+ const result = new Array();
+ this.exceededMatchLimit = Boolean(didExceedMatchLimit);
+ const captures = new Array();
+ let address = startAddress;
+ for (let i2 = 0; i2 < count; i2++) {
+ const patternIndex = C.getValue(address, "i32");
+ address += SIZE_OF_INT;
+ const captureCount = C.getValue(address, "i32");
+ address += SIZE_OF_INT;
+ const captureIndex = C.getValue(address, "i32");
+ address += SIZE_OF_INT;
+ captures.length = captureCount;
+ address = unmarshalCaptures(this, node.tree, address, patternIndex, captures);
+ if (this.textPredicates[patternIndex].every((p) => p(captures))) {
+ const capture = captures[captureIndex];
+ const setProperties = this.setProperties[patternIndex];
+ capture.setProperties = setProperties;
+ const assertedProperties = this.assertedProperties[patternIndex];
+ capture.assertedProperties = assertedProperties;
+ const refutedProperties = this.refutedProperties[patternIndex];
+ capture.refutedProperties = refutedProperties;
+ result.push(capture);
+ }
+ }
+ C._free(startAddress);
+ C.currentQueryProgressCallback = null;
+ return result;
+ }
+ /** Get the predicates for a given pattern. */
+ predicatesForPattern(patternIndex) {
+ return this.predicates[patternIndex];
+ }
+ /**
+ * Disable a certain capture within a query.
+ *
+ * This prevents the capture from being returned in matches, and also
+ * avoids any resource usage associated with recording the capture.
+ */
+ disableCapture(captureName) {
+ const captureNameLength = C.lengthBytesUTF8(captureName);
+ const captureNameAddress = C._malloc(captureNameLength + 1);
+ C.stringToUTF8(captureName, captureNameAddress, captureNameLength + 1);
+ C._ts_query_disable_capture(this[0], captureNameAddress, captureNameLength);
+ C._free(captureNameAddress);
+ }
+ /**
+ * Disable a certain pattern within a query.
+ *
+ * This prevents the pattern from matching, and also avoids any resource
+ * usage associated with the pattern. This throws an error if the pattern
+ * index is out of bounds.
+ */
+ disablePattern(patternIndex) {
+ if (patternIndex >= this.predicates.length) {
+ throw new Error(
+ `Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
+ );
+ }
+ C._ts_query_disable_pattern(this[0], patternIndex);
+ }
+ /**
+ * Check if, on its last execution, this cursor exceeded its maximum number
+ * of in-progress matches.
+ */
+ didExceedMatchLimit() {
+ return this.exceededMatchLimit;
+ }
+ /** Get the byte offset where the given pattern starts in the query's source. */
+ startIndexForPattern(patternIndex) {
+ if (patternIndex >= this.predicates.length) {
+ throw new Error(
+ `Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
+ );
+ }
+ return C._ts_query_start_byte_for_pattern(this[0], patternIndex);
+ }
+ /** Get the byte offset where the given pattern ends in the query's source. */
+ endIndexForPattern(patternIndex) {
+ if (patternIndex >= this.predicates.length) {
+ throw new Error(
+ `Pattern index is ${patternIndex} but the pattern count is ${this.predicates.length}`
+ );
+ }
+ return C._ts_query_end_byte_for_pattern(this[0], patternIndex);
+ }
+ /** Get the number of patterns in the query. */
+ patternCount() {
+ return C._ts_query_pattern_count(this[0]);
+ }
+ /** Get the index for a given capture name. */
+ captureIndexForName(captureName) {
+ return this.captureNames.indexOf(captureName);
+ }
+ /** Check if a given pattern within a query has a single root node. */
+ isPatternRooted(patternIndex) {
+ return C._ts_query_is_pattern_rooted(this[0], patternIndex) === 1;
+ }
+ /** Check if a given pattern within a query has a single root node. */
+ isPatternNonLocal(patternIndex) {
+ return C._ts_query_is_pattern_non_local(this[0], patternIndex) === 1;
+ }
+ /**
+ * Check if a given step in a query is 'definite'.
+ *
+ * A query step is 'definite' if its parent pattern will be guaranteed to
+ * match successfully once it reaches the step.
+ */
+ isPatternGuaranteedAtStep(byteIndex) {
+ return C._ts_query_is_pattern_guaranteed_at_step(this[0], byteIndex) === 1;
+ }
+};
+
+// export {
+// CaptureQuantifier,
+// Edit,
+// LANGUAGE_VERSION,
+// Language,
+// LookaheadIterator,
+// MIN_COMPATIBLE_VERSION,
+// Node,
+// Parser,
+// Query,
+// Tree,
+// TreeCursor
+// };
diff --git a/common/modules/mixly-modules/workers/common/tree-sitter/web-tree-sitter.wasm b/common/modules/mixly-modules/workers/common/tree-sitter/web-tree-sitter.wasm
new file mode 100644
index 00000000..30ec4312
Binary files /dev/null and b/common/modules/mixly-modules/workers/common/tree-sitter/web-tree-sitter.wasm differ
diff --git a/common/modules/web-modules/diff.min.js b/common/modules/web-modules/diff.min.js
new file mode 100644
index 00000000..6fd5d020
--- /dev/null
+++ b/common/modules/web-modules/diff.min.js
@@ -0,0 +1 @@
+((global,factory)=>{"object"==typeof exports&&"undefined"!=typeof module?factory(exports):"function"==typeof define&&define.amd?define(["exports"],factory):factory((global="undefined"!=typeof globalThis?globalThis:global||self).Diff={})})(this,function(exports){class Diff{diff(oldStr,newStr,options={}){let callback;"function"==typeof options?(callback=options,options={}):"callback"in options&&(callback=options.callback);oldStr=this.castInput(oldStr,options),newStr=this.castInput(newStr,options),oldStr=this.removeEmpty(this.tokenize(oldStr,options)),newStr=this.removeEmpty(this.tokenize(newStr,options));return this.diffWithOptionsObj(oldStr,newStr,options,callback)}diffWithOptionsObj(oldTokens,newTokens,options,callback){let _a,done=value=>{if(value=this.postProcess(value,options),!callback)return value;setTimeout(function(){callback(value)},0)},newLen=newTokens.length,oldLen=oldTokens.length,editLength=1,maxEditLength=newLen+oldLen;null!=options.maxEditLength&&(maxEditLength=Math.min(maxEditLength,options.maxEditLength));var maxExecutionTime=null!=(_a=options.timeout)?_a:1/0;let abortAfterTimestamp=Date.now()+maxExecutionTime,bestPath=[{oldPos:-1,lastComponent:void 0}],newPos=this.extractCommon(bestPath[0],newTokens,oldTokens,0,options);if(bestPath[0].oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(bestPath[0].lastComponent,newTokens,oldTokens));let minDiagonalToConsider=-1/0,maxDiagonalToConsider=1/0,execEditLength=()=>{for(let diagonalPath=Math.max(minDiagonalToConsider,-editLength);diagonalPath<=Math.min(maxDiagonalToConsider,editLength);diagonalPath+=2){let basePath;var removePath=bestPath[diagonalPath-1],addPath=bestPath[diagonalPath+1];removePath&&(bestPath[diagonalPath-1]=void 0);let canAdd=!1;addPath&&(addPathNewPos=addPath.oldPos-diagonalPath,canAdd=addPath&&0<=addPathNewPos&&addPathNewPos=oldLen&&newPos+1>=newLen)return done(this.buildValues(basePath.lastComponent,newTokens,oldTokens))||!0;(bestPath[diagonalPath]=basePath).oldPos+1>=oldLen&&(maxDiagonalToConsider=Math.min(maxDiagonalToConsider,diagonalPath-1)),newPos+1>=newLen&&(minDiagonalToConsider=Math.max(minDiagonalToConsider,diagonalPath+1))}else bestPath[diagonalPath]=void 0}editLength++};if(callback)!function exec(){setTimeout(function(){if(editLength>maxEditLength||Date.now()>abortAfterTimestamp)return callback(void 0);execEditLength()||exec()},0)}();else for(;editLength<=maxEditLength&&Date.now()<=abortAfterTimestamp;){var ret=execEditLength();if(ret)return ret}}addToPath(path,added,removed,oldPosInc,options){var last=path.lastComponent;return last&&!options.oneChangePerToken&&last.added===added&&last.removed===removed?{oldPos:path.oldPos+oldPosInc,lastComponent:{count:last.count+1,added:added,removed:removed,previousComponent:last.previousComponent}}:{oldPos:path.oldPos+oldPosInc,lastComponent:{count:1,added:added,removed:removed,previousComponent:last}}}extractCommon(basePath,newTokens,oldTokens,diagonalPath,options){var newLen=newTokens.length,oldLen=oldTokens.length;let oldPos=basePath.oldPos,newPos=oldPos-diagonalPath,commonCount=0;for(;newPos+1value.length?i:value}),component.value=this.join(value)}else component.value=this.join(newTokens.slice(newPos,newPos+component.count));newPos+=component.count,component.added||(oldPos+=component.count)}}return components}}class CharacterDiff extends Diff{}let characterDiff=new CharacterDiff;function longestCommonPrefix(str1,str2){let i;for(i=0;i{let startA=0,endB=(a.length>b.length&&(startA=a.length-b.length),b.length),map=(a.lengthsegment.segment)}else parts=value.match(tokenizeIncludingWhitespace)||[];let tokens=[],prevPart=null;return parts.forEach(part=>{/\s/.test(part)?null==prevPart?tokens.push(part):tokens.push(tokens.pop()+part):null!=prevPart&&/\s/.test(prevPart)?tokens[tokens.length-1]==prevPart?tokens.push(tokens.pop()+part):tokens.push(prevPart+part):tokens.push(part),prevPart=part}),tokens}join(tokens){return tokens.map((token,i)=>0==i?token:token.replace(/^\s+/,"")).join("")}postProcess(changes,options){if(changes&&!options.oneChangePerToken){let lastKeep=null,insertion=null,deletion=null;changes.forEach(change=>{change.added?insertion=change:deletion=change.removed?change:((insertion||deletion)&&dedupeWhitespaceInChangeObjects(lastKeep,deletion,insertion,change),lastKeep=change,insertion=null)}),(insertion||deletion)&&dedupeWhitespaceInChangeObjects(lastKeep,deletion,insertion,null)}return changes}}let wordDiff=new WordDiff;function dedupeWhitespaceInChangeObjects(startKeep,deletion,insertion,endKeep){if(deletion&&insertion){var oldWsPrefix=leadingWs(deletion.value),oldWsSuffix=trailingWs(deletion.value),newWsPrefix=leadingWs(insertion.value),newWsSuffix=trailingWs(insertion.value);startKeep&&(oldWsPrefix=longestCommonPrefix(oldWsPrefix,newWsPrefix),startKeep.value=replaceSuffix(startKeep.value,newWsPrefix,oldWsPrefix),deletion.value=removePrefix(deletion.value,oldWsPrefix),insertion.value=removePrefix(insertion.value,oldWsPrefix)),endKeep&&(newWsPrefix=longestCommonSuffix(oldWsSuffix,newWsSuffix),endKeep.value=replacePrefix(endKeep.value,newWsSuffix,newWsPrefix),deletion.value=removeSuffix(deletion.value,newWsPrefix),insertion.value=removeSuffix(insertion.value,newWsPrefix))}else if(insertion){if(startKeep&&(oldWsPrefix=leadingWs(insertion.value),insertion.value=insertion.value.substring(oldWsPrefix.length)),endKeep){let ws=leadingWs(endKeep.value);endKeep.value=endKeep.value.substring(ws.length)}}else if(startKeep&&endKeep){oldWsSuffix=leadingWs(endKeep.value),newWsSuffix=leadingWs(deletion.value),newWsPrefix=trailingWs(deletion.value),insertion=longestCommonPrefix(oldWsSuffix,newWsSuffix),oldWsPrefix=(deletion.value=removePrefix(deletion.value,insertion),longestCommonSuffix(removePrefix(oldWsSuffix,insertion),newWsPrefix));deletion.value=removeSuffix(deletion.value,oldWsPrefix),endKeep.value=replacePrefix(endKeep.value,oldWsSuffix,oldWsPrefix),startKeep.value=replaceSuffix(startKeep.value,oldWsSuffix,oldWsSuffix.slice(0,oldWsSuffix.length-oldWsPrefix.length))}else if(endKeep){newWsSuffix=leadingWs(endKeep.value),insertion=maximumOverlap(trailingWs(deletion.value),newWsSuffix);deletion.value=removeSuffix(deletion.value,insertion)}else if(startKeep){let overlap=maximumOverlap(trailingWs(startKeep.value),leadingWs(deletion.value));deletion.value=removePrefix(deletion.value,overlap)}}class WordsWithSpaceDiff extends Diff{tokenize(value){var regex=new RegExp(`(\\r?\\n)|[${extendedWordChars}]+|[^\\S\\n\\r]+|[^${extendedWordChars}]`,"ug");return value.match(regex)||[]}}let wordsWithSpaceDiff=new WordsWithSpaceDiff;function diffWordsWithSpace(oldStr,newStr,options){return wordsWithSpaceDiff.diff(oldStr,newStr,options)}class LineDiff extends Diff{constructor(){super(...arguments),this.tokenize=tokenize}equals(left,right,options){return options.ignoreWhitespace?(options.newlineIsToken&&left.includes("\n")||(left=left.trim()),options.newlineIsToken&&right.includes("\n")||(right=right.trim())):options.ignoreNewlineAtEof&&!options.newlineIsToken&&(left.endsWith("\n")&&(left=left.slice(0,-1)),right.endsWith("\n"))&&(right=right.slice(0,-1)),super.equals(left,right,options)}}let lineDiff=new LineDiff;function diffLines(oldStr,newStr,options){return lineDiff.diff(oldStr,newStr,options)}function tokenize(value,options){var retLines=[],linesAndNewlines=(value=options.stripTrailingCr?value.replace(/\r\n/g,"\n"):value).split(/(\n|\r\n)/);linesAndNewlines[linesAndNewlines.length-1]||linesAndNewlines.pop();for(let i=0;ivoid 0===v?undefinedReplacement:v}=options;return"string"==typeof value?value:JSON.stringify(canonicalize(value,null,null,stringifyReplacer),null," ")}equals(left,right,options){return super.equals(left.replace(/,([\r\n])/g,"$1"),right.replace(/,([\r\n])/g,"$1"),options)}}let jsonDiff=new JsonDiff;function canonicalize(obj,stack,replacementStack,replacer,key){stack=stack||[],replacementStack=replacementStack||[],replacer&&(obj=replacer(void 0===key?"":key,obj));let i;for(i=0;i{var chunkHeaderIndex=i,chunkHeaderLine=diffstr[i++],hunk={oldStart:+(chunkHeaderLine=chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/))[1],oldLines:void 0===chunkHeaderLine[2]?1:+chunkHeaderLine[2],newStart:+chunkHeaderLine[3],newLines:void 0===chunkHeaderLine[4]?1:+chunkHeaderLine[4],lines:[]};0===hunk.oldLines&&(hunk.oldStart+=1),0===hunk.newLines&&(hunk.newStart+=1);let addCount=0,removeCount=0;for(;i{!options.autoConvertLineEndings&&null!=options.autoConvertLineEndings||((string=>string.includes("\r\n")&&!string.startsWith("\n")&&!string.match(/[^\r]\n/))(source)&&(patch=>!(patch=Array.isArray(patch)?patch:[patch]).some(index=>index.hunks.some(hunk=>hunk.lines.some(line=>!line.startsWith("\\")&&line.endsWith("\r")))))(patch)?patch=function unixToWin(patch){return Array.isArray(patch)?patch.map(p=>unixToWin(p)):Object.assign(Object.assign({},patch),{hunks:patch.hunks.map(hunk=>Object.assign(Object.assign({},hunk),{lines:hunk.lines.map((line,i)=>line.startsWith("\\")||line.endsWith("\r")||null!=(i=hunk.lines[i+1])&&i.startsWith("\\")?line:line+"\r")}))})}(patch):(string=>!string.includes("\r\n")&&string.includes("\n"))(source)&&(patch=>(patch=Array.isArray(patch)?patch:[patch]).some(index=>index.hunks.some(hunk=>hunk.lines.some(line=>line.endsWith("\r"))))&&patch.every(index=>index.hunks.every(hunk=>hunk.lines.every((line,i)=>line.startsWith("\\")||line.endsWith("\r")||(null==(line=hunk.lines[i+1])?void 0:line.startsWith("\\"))))))(patch)&&(patch=function winToUnix(patch){return Array.isArray(patch)?patch.map(p=>winToUnix(p)):Object.assign(Object.assign({},patch),{hunks:patch.hunks.map(hunk=>Object.assign(Object.assign({},hunk),{lines:hunk.lines.map(line=>line.endsWith("\r")?line.substring(0,line.length-1):line)}))})}(patch)));let lines=source.split("\n"),hunks=patch.hunks,compareLine=options.compareLine||((lineNumber,line,operation,patchContent)=>line===patchContent),fuzzFactor=options.fuzzFactor||0,minLine=0;if(fuzzFactor<0||!Number.isInteger(fuzzFactor))throw new Error("fuzzFactor must be a non-negative integer");if(!hunks.length)return source;let prevLine="",removeEOFNL=!1,addEOFNL=!1;for(let i=0;i{let wantForward=!0,backwardExhausted=!1,forwardExhausted=!1,localOffset=1;return function iterator(){if(wantForward&&!forwardExhausted){if(backwardExhausted?localOffset++:wantForward=!1,start+localOffset<=maxLine)return start+localOffset;forwardExhausted=!0}if(!backwardExhausted)return forwardExhausted||(wantForward=!0),minLine<=start-localOffset?start-localOffset++:(backwardExhausted=!0,iterator())}})(toPos=hunk.oldStart+prevHunkOffset-1,minLine,maxLine);void 0!==toPos&&!(hunkResult=function applyHunk(hunkLines,toPos,maxErrors,hunkLinesI=0,lastContextLineMatched=!0,patchedLines=[],patchedLinesLength=0){let nConsecutiveOldContextLines=0,nextContextLineMustMatch=!1;for(;hunkLinesI{diff=diffLinesResultToPatch(diff);callback(diff)}}))}function diffLinesResultToPatch(diff){if(diff){diff.push({value:"",lines:[]});var hunks=[];let oldRangeStart=0,newRangeStart=0,curRange=[],oldLine=1,newLine=1;for(let i=0;i{var hasTrailingNl=text.endsWith("\n"),text=text.split("\n").map(line=>line+"\n");return hasTrailingNl?text.pop():text.push(text.pop().slice(0,-1)),text})(current.value);if(current.lines=lines,current.added||current.removed){oldRangeStart||(prev=diff[i-1],oldRangeStart=oldLine,newRangeStart=newLine,prev&&(curRange=0{patchObj?callback(formatPatch(patchObj)):callback(void 0)}}))}else{oldFileName=structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options);if(oldFileName)return formatPatch(oldFileName)}}exports.Diff=Diff,exports.applyPatch=applyPatch,exports.applyPatches=function(uniDiff,options){let spDiff="string"==typeof uniDiff?parsePatch(uniDiff):uniDiff,currentIndex=0;!function processIndex(){let index=spDiff[currentIndex++];if(!index)return options.complete();options.loadFile(index,function(err,data){if(err)return options.complete(err);err=applyPatch(data,index,options),options.patched(index,err,function(err){if(err)return options.complete(err);processIndex()})})}()},exports.arrayDiff=arrayDiff,exports.canonicalize=canonicalize,exports.characterDiff=characterDiff,exports.convertChangesToDMP=function(changes){var ret=[];let change,operation;for(let i=0;i"):change.removed&&ret.push(""),ret.push((s=>{let n=s;return n=(n=(n=(n=n.replace(/&/g,"&")).replace(//g,">")).replace(/"/g,""")})(change.value)),change.added?ret.push(""):change.removed&&ret.push("")}return ret.join("")},exports.createPatch=function(fileName,oldStr,newStr,oldHeader,newHeader,options){return createTwoFilesPatch(fileName,fileName,oldStr,newStr,oldHeader,newHeader,options)},exports.createTwoFilesPatch=createTwoFilesPatch,exports.cssDiff=cssDiff,exports.diffArrays=function(oldArr,newArr,options){return arrayDiff.diff(oldArr,newArr,options)},exports.diffChars=function(oldStr,newStr,options){return characterDiff.diff(oldStr,newStr,options)},exports.diffCss=function(oldStr,newStr,options){return cssDiff.diff(oldStr,newStr,options)},exports.diffJson=function(oldStr,newStr,options){return jsonDiff.diff(oldStr,newStr,options)},exports.diffLines=diffLines,exports.diffSentences=function(oldStr,newStr,options){return sentenceDiff.diff(oldStr,newStr,options)},exports.diffTrimmedLines=function(oldStr,newStr,options){return options=((options,defaults)=>{if("function"==typeof options)defaults.callback=options;else if(options)for(var name in options)Object.prototype.hasOwnProperty.call(options,name)&&(defaults[name]=options[name]);return defaults})(options,{ignoreWhitespace:!0}),lineDiff.diff(oldStr,newStr,options)},exports.diffWords=function(oldStr,newStr,options){return null==(null==options?void 0:options.ignoreWhitespace)||options.ignoreWhitespace?wordDiff.diff(oldStr,newStr,options):diffWordsWithSpace(oldStr,newStr,options)},exports.diffWordsWithSpace=diffWordsWithSpace,exports.formatPatch=formatPatch,exports.jsonDiff=jsonDiff,exports.lineDiff=lineDiff,exports.parsePatch=parsePatch,exports.reversePatch=function reversePatch(structuredPatch){return Array.isArray(structuredPatch)?structuredPatch.map(patch=>reversePatch(patch)).reverse():Object.assign(Object.assign({},structuredPatch),{oldFileName:structuredPatch.newFileName,oldHeader:structuredPatch.newHeader,newFileName:structuredPatch.oldFileName,newHeader:structuredPatch.oldHeader,hunks:structuredPatch.hunks.map(hunk=>({oldLines:hunk.newLines,oldStart:hunk.newStart,newLines:hunk.oldLines,newStart:hunk.oldStart,lines:hunk.lines.map(l=>l.startsWith("-")?"+"+l.slice(1):l.startsWith("+")?"-"+l.slice(1):l)}))})},exports.sentenceDiff=sentenceDiff,exports.structuredPatch=structuredPatch,exports.wordDiff=wordDiff,exports.wordsWithSpaceDiff=wordsWithSpaceDiff});
\ No newline at end of file
diff --git a/common/templates/json/tree-sitter/grammars/c.json b/common/templates/json/tree-sitter/grammars/c.json
new file mode 100644
index 00000000..c58a3e6b
--- /dev/null
+++ b/common/templates/json/tree-sitter/grammars/c.json
@@ -0,0 +1,123 @@
+{
+ "simpleTerms": {
+ "type_identifier": "type",
+ "primitive_type": "type",
+ "\"signed\"": "type",
+ "\"unsigned\"": "type",
+ "\"short\"": "type",
+ "\"long\"": "type",
+
+ "statement_identifier": "variable",
+
+ "\"const\"": "modifier",
+ "\"static\"": "modifier",
+ "\"auto\"": "modifier",
+ "\"extern\"": "modifier",
+ "\"inline\"": "modifier",
+ "\"register\"": "modifier",
+ "\"volatile\"": "modifier",
+ "\"restrict\"": "modifier",
+ "\"_Atomic\"": "modifier",
+ "\"__attribute__\"": "modifier",
+ "function_specifier": "modifier",
+
+ "number_literal": "number",
+ "char_literal": "string",
+ "string_literal": "string",
+ "system_lib_string": "string",
+ "escape_sequence": "string",
+ "comment": "comment",
+
+ "null": "constant",
+ "true": "constant",
+ "false": "constant",
+
+ "\"if\"": "control",
+ "\"else\"": "control",
+ "\"do\"": "control",
+ "\"for\"": "control",
+ "\"while\"": "control",
+ "\"break\"": "control",
+ "\"continue\"": "control",
+ "\"return\"": "control",
+ "\"switch\"": "control",
+ "\"case\"": "control",
+ "\"default\"": "control",
+ "\"goto\"": "control",
+ "\"struct\"": "control",
+ "\"enum\"": "control",
+ "\"union\"": "control",
+ "\"typedef\"": "control",
+
+ "\"sizeof\"": "operator",
+ "\".\"": "operator",
+ "\"->\"": "operator",
+ "\"*\"": "operator",
+ "\"-\"": "operator",
+ "\"+\"": "operator",
+ "\"/\"": "operator",
+ "\"%\"": "operator",
+ "\"++\"": "operator",
+ "\"--\"": "operator",
+ "\"==\"": "operator",
+ "\"!\"": "operator",
+ "\"!=\"": "operator",
+ "\"<\"": "operator",
+ "\">\"": "operator",
+ "\">=\"": "operator",
+ "\"<=\"": "operator",
+ "\"&&\"": "operator",
+ "\"||\"": "operator",
+ "\"&\"": "operator",
+ "\"|\"": "operator",
+ "\"^\"": "operator",
+ "\"~\"": "operator",
+ "\"<<\"": "operator",
+ "\">>\"": "operator",
+ "\"=\"": "operator",
+ "\"+=\"": "operator",
+ "\"-=\"": "operator",
+ "\"*=\"": "operator",
+ "\"/=\"": "operator",
+ "\"%=\"": "operator",
+ "\"<<=\"": "operator",
+ "\">>=\"": "operator",
+ "\"&=\"": "operator",
+ "\"^=\"": "operator",
+ "\"|=\"": "operator",
+ "\"?\"": "operator",
+ "\":\"": "operator",
+
+ "\"#if\"": "directive",
+ "\"#ifdef\"": "directive",
+ "\"#ifndef\"": "directive",
+ "\"#elif\"": "directive",
+ "\"#else\"": "directive",
+ "\"#endif\"": "directive",
+ "\"#define\"": "directive",
+ "\"#include\"": "directive",
+ "preproc_directive": "directive",
+ "preproc_arg": "directive",
+
+ "\";\"": "punctuation",
+ "\"[\"": "punctuation",
+ "\"]\"": "punctuation",
+ "\",\"": "punctuation",
+ "\"{\"": "punctuation",
+ "\"}\"": "punctuation",
+ "\"(\"": "punctuation",
+ "\")\"": "punctuation"
+ },
+
+ "complexTerms": ["identifier", "field_identifier"],
+
+ "complexScopes": {
+ "identifier": "variable",
+ "field_identifier": "variable",
+
+ "call_expression > identifier" : "function",
+ "call_expression > field_expression > field_identifier" : "function",
+ "function_declarator > identifier" : "function"
+ }
+
+}
diff --git a/common/templates/json/tree-sitter/grammars/cpp.json b/common/templates/json/tree-sitter/grammars/cpp.json
new file mode 100644
index 00000000..4bf46886
--- /dev/null
+++ b/common/templates/json/tree-sitter/grammars/cpp.json
@@ -0,0 +1,156 @@
+{
+ "simpleTerms": {
+ "type_identifier": "type",
+ "primitive_type": "type",
+ "\"unsigned\"": "type",
+ "\"signed\"": "type",
+ "\"short\"": "type",
+ "\"long\"": "type",
+ "auto": "type",
+
+ "namespace_identifier": "scope",
+
+ "operator_name": "function",
+
+ "\"public\"": "modifier",
+ "\"protected\"": "modifier",
+ "\"private\"": "modifier",
+ "\"virtual\"": "modifier",
+ "\"override\"": "modifier",
+ "\"default\"": "modifier",
+ "\"final\"": "modifier",
+ "\"const\"": "modifier",
+ "\"constexpr\"": "modifier",
+ "\"static\"": "modifier",
+ "\"extern\"": "modifier",
+ "\"inline\"": "modifier",
+ "\"noexcept\"": "modifier",
+ "\"explicit\"": "modifier",
+ "\"friend\"": "modifier",
+ "\"register\"": "modifier",
+ "\"volatile\"": "modifier",
+ "\"restrict\"": "modifier",
+ "\"_Atomic\"": "modifier",
+ "\"__attribute__\"": "modifier",
+ "function_specifier": "modifier",
+
+ "number_literal": "number",
+ "char_literal": "string",
+ "string_literal": "string",
+ "system_lib_string": "string",
+ "raw_string_literal": "string",
+ "escape_sequence": "string",
+ "comment": "comment",
+
+ "null": "constant",
+ "nullptr": "constant",
+ "true": "constant",
+ "false": "constant",
+
+ "\"if\"": "control",
+ "\"else\"": "control",
+ "\"do\"": "control",
+ "\"for\"": "control",
+ "\"while\"": "control",
+ "\"break\"": "control",
+ "\"continue\"": "control",
+ "\"return\"": "control",
+ "\"switch\"": "control",
+ "\"case\"": "control",
+ "\"goto\"": "control",
+
+ "\"struct\"": "control",
+ "\"enum\"": "control",
+ "\"union\"": "control",
+ "\"typedef\"": "control",
+ "\"class\"": "control",
+ "\"using\"": "control",
+ "\"namespace\"": "control",
+ "\"template\"": "control",
+ "\"typename\"": "control",
+ "\"try\"": "control",
+ "\"catch\"": "control",
+ "\"throw\"": "control",
+
+ "\"sizeof\"": "operator",
+ "\"new\"": "operator",
+ "\".\"": "operator",
+ "\"->\"": "operator",
+ "\"*\"": "operator",
+ "\"-\"": "operator",
+ "\"+\"": "operator",
+ "\"/\"": "operator",
+ "\"%\"": "operator",
+ "\"++\"": "operator",
+ "\"--\"": "operator",
+ "\"==\"": "operator",
+ "\"!\"": "operator",
+ "\"!=\"": "operator",
+ "\"<\"": "operator",
+ "\">\"": "operator",
+ "\">=\"": "operator",
+ "\"<=\"": "operator",
+ "\"&&\"": "operator",
+ "\"||\"": "operator",
+ "\"&\"": "operator",
+ "\"|\"": "operator",
+ "\"^\"": "operator",
+ "\"~\"": "operator",
+ "\"<<\"": "operator",
+ "\">>\"": "operator",
+ "\"=\"": "operator",
+ "\"+=\"": "operator",
+ "\"-=\"": "operator",
+ "\"*=\"": "operator",
+ "\"/=\"": "operator",
+ "\"%=\"": "operator",
+ "\"<<=\"": "operator",
+ "\">>=\"": "operator",
+ "\"&=\"": "operator",
+ "\"^=\"": "operator",
+ "\"|=\"": "operator",
+ "\"?\"": "operator",
+ "\"::\"": "operator",
+
+ "\"#if\"": "directive",
+ "\"#ifdef\"": "directive",
+ "\"#ifndef\"": "directive",
+ "\"#elif\"": "directive",
+ "\"#else\"": "directive",
+ "\"#endif\"": "directive",
+ "\"#define\"": "directive",
+ "\"#include\"": "directive",
+ "preproc_directive": "directive",
+
+ "\";\"": "punctuation",
+ "\":\"": "punctuation",
+ "\",\"": "punctuation",
+ "\"[\"": "punctuation",
+ "\"]\"": "punctuation",
+ "\"{\"": "punctuation",
+ "\"}\"": "punctuation",
+ "\"(\"": "punctuation",
+ "\")\"": "punctuation"
+ },
+
+ "complexTerms": ["identifier", "field_identifier", "\"delete\""],
+
+ "complexScopes": {
+ "identifier": "variable",
+ "field_identifier": "variable",
+
+ "call_expression > identifier": "function",
+ "call_expression > field_expression > field_identifier": "function",
+ "call_expression > scoped_identifier > identifier": "function",
+ "template_function > identifier": "function",
+ "template_function > scoped_identifier > identifier": "function",
+ "template_method > field_identifier": "function",
+ "function_declarator > identifier": "function",
+ "function_declarator > field_identifier": "function",
+ "function_declarator > scoped_identifier > identifier": "function",
+ "destructor_name > identifier": "function",
+
+ "\"delete\"": "operator",
+ "delete_method_clause > \"delete\"": "modifier"
+ }
+}
diff --git a/common/templates/json/tree-sitter/grammars/go.json b/common/templates/json/tree-sitter/grammars/go.json
new file mode 100644
index 00000000..20c455ae
--- /dev/null
+++ b/common/templates/json/tree-sitter/grammars/go.json
@@ -0,0 +1,108 @@
+{
+ "simpleTerms": {
+ "type_identifier": "type",
+ "package_identifier": "scope",
+
+ "\"var\"": "modifier",
+ "\"const\"": "modifier",
+
+ "interpreted_string_literal": "string",
+ "raw_string_literal": "string",
+ "escape_sequence": "string",
+ "rune_literal": "number",
+ "int_literal": "number",
+ "float_literal": "number",
+ "imaginary_literal": "number",
+ "comment": "comment",
+
+ "nil": "constant",
+ "false": "constant",
+ "true": "constant",
+
+ "\"if\"": "control",
+ "\"for\"": "control",
+ "\"else\"": "control",
+ "\"case\"": "control",
+ "\"break\"": "control",
+ "\"switch\"": "control",
+ "\"select\"": "control",
+ "\"return\"": "control",
+ "\"default\"": "control",
+ "\"continue\"": "control",
+ "\"goto\"": "control",
+ "\"fallthrough\"": "control",
+ "\"defer\"": "control",
+ "\"range\"": "control",
+ "\"go\"": "control",
+
+ "\"type\"": "operator",
+ "\"struct\"": "operator",
+ "\"import\"": "operator",
+ "\"package\"": "operator",
+ "\"func\"": "operator",
+ "\"interface\"": "operator",
+ "\"map\"": "operator",
+ "\"chan\"": "operator",
+
+ "\"+\"": "operator",
+ "\"-\"": "operator",
+ "\"*\"": "operator",
+ "\"/\"": "operator",
+ "\"%\"": "operator",
+ "\"++\"": "operator",
+ "\"--\"": "operator",
+ "\"==\"": "operator",
+ "\"!=\"": "operator",
+ "\">\"": "operator",
+ "\"<\"": "operator",
+ "\">=\"": "operator",
+ "\"<=\"": "operator",
+ "\"!\"": "operator",
+ "\"|\"": "operator",
+ "\"^\"": "operator",
+ "\"<<\"": "operator",
+ "\">>\"": "operator",
+ "\"=\"": "operator",
+ "\"+=\"": "operator",
+ "\"-=\"": "operator",
+ "\"*=\"": "operator",
+ "\"/=\"": "operator",
+ "\"%=\"": "operator",
+ "\"<<=\"": "operator",
+ "\">>=\"": "operator",
+ "\"&=\"": "operator",
+ "\"^=\"": "operator",
+ "\"|=\"": "operator",
+ "\":=\"": "operator",
+ "\"&\"": "operator",
+ "\"&&\"": "operator",
+ "\"&^\"": "operator",
+ "\"&^=\"": "operator",
+ "\"||\"": "operator",
+ "\"...\"": "operator",
+ "\"<-\"": "operator",
+ "\"[\"": "operator",
+ "\"]\"": "operator",
+
+ "\"(\"": "punctuation",
+ "\")\"": "punctuation",
+ "\"{\"": "punctuation",
+ "\"}\"": "punctuation",
+ "\",\"": "punctuation",
+ "\";\"": "punctuation",
+ "\".\"": "punctuation",
+ "\":\"": "punctuation"
+ },
+
+ "complexTerms": ["identifier", "field_identifier"],
+
+ "complexScopes": {
+ "identifier": "variable",
+ "field_identifier": "variable",
+
+ "call_expression > identifier": "function",
+ "function_declaration > identifier": "function",
+ "method_declaration > field_identifier": "function",
+ "call_expression > selector_expression > field_identifier": "function"
+ }
+}
diff --git a/common/templates/json/tree-sitter/grammars/javascript.json b/common/templates/json/tree-sitter/grammars/javascript.json
new file mode 100644
index 00000000..95ed2c27
--- /dev/null
+++ b/common/templates/json/tree-sitter/grammars/javascript.json
@@ -0,0 +1,136 @@
+{
+ "simpleTerms": {
+ "shorthand_property_identifier": "variable",
+
+ "\"var\"": "modifier",
+ "\"let\"": "modifier",
+ "\"extends\"": "modifier",
+ "\"const\"": "modifier",
+ "\"static\"": "modifier",
+
+ "number": "number",
+ "string": "string",
+ "escape_sequence": "string",
+ "template_string": "string",
+ "regex": "string",
+ "comment": "comment",
+ "hash_bang_line": "comment",
+
+ "true": "constant",
+ "false": "constant",
+ "null": "constant",
+ "undefined": "constant",
+
+ "\"as\"": "control",
+ "\"if\"": "control",
+ "\"do\"": "control",
+ "\"else\"": "control",
+ "\"while\"": "control",
+ "\"for\"": "control",
+ "\"return\"": "control",
+ "\"break\"": "control",
+ "\"continue\"": "control",
+ "\"throw\"": "control",
+ "\"try\"": "control",
+ "\"catch\"": "control",
+ "\"finally\"": "control",
+ "\"switch\"": "control",
+ "\"case\"": "control",
+ "\"default\"": "control",
+ "\"export\"": "control",
+ "\"import\"": "control",
+ "\"from\"": "control",
+ "\"yield\"": "control",
+ "\"async\"": "control",
+ "\"await\"": "control",
+ "\"debugger\"": "control",
+ "\"delete\"": "control",
+
+ "this": "operator",
+ "\"class\"": "operator",
+ "\"function\"": "operator",
+
+ "\"in\"": "operator",
+ "\"instanceof\"": "operator",
+ "\"of\"": "operator",
+ "\"new\"": "operator",
+ "\"typeof\"": "operator",
+ "\"get\"": "operator",
+ "\"set\"": "operator",
+
+ "\"=\"": "operator",
+ "\"+=\"": "operator",
+ "\"-=\"": "operator",
+ "\"*=\"": "operator",
+ "\"/=\"": "operator",
+ "\"%=\"": "operator",
+ "\"<<=\"": "operator",
+ "\">>=\"": "operator",
+ "\">>>=\"": "operator",
+ "\"&=\"": "operator",
+ "\"^=\"": "operator",
+ "\"|=\"": "operator",
+ "\"!\"": "operator",
+ "\"+\"": "operator",
+ "\"-\"": "operator",
+ "\"*\"": "operator",
+ "\"/\"": "operator",
+ "\"%\"": "operator",
+ "\"==\"": "operator",
+ "\"===\"": "operator",
+ "\"!=\"": "operator",
+ "\"!==\"": "operator",
+ "\">=\"": "operator",
+ "\"<=\"": "operator",
+ "\"=>\"": "operator",
+ "\">\"": "operator",
+ "\"<\"": "operator",
+ "\":\"": "operator",
+ "\"?\"": "operator",
+ "\"&&\"": "operator",
+ "\"||\"": "operator",
+ "\"&\"": "operator",
+ "\"~\"": "operator",
+ "\"^\"": "operator",
+ "\">>\"": "operator",
+ "\">>>\"": "operator",
+ "\"<<\"": "operator",
+ "\"|\"": "operator",
+ "\"++\"": "operator",
+ "\"--\"": "operator",
+ "\"...\"": "operator",
+
+ "\"(\"": "punctuation",
+ "\")\"": "punctuation",
+ "\"{\"": "punctuation",
+ "\"}\"": "punctuation",
+ "\";\"": "punctuation",
+ "\"[\"": "punctuation",
+ "\"]\"": "punctuation",
+ "\".\"": "punctuation",
+ "\",\"": "punctuation",
+ "\"${\"": "punctuation"
+ },
+
+ "complexTerms": ["identifier", "field_identifier", "property_identifier", "super"],
+
+ "complexScopes": {
+ "identifier": "variable",
+ "property_identifier": "variable",
+ "formal_parameters > identifier": "variable",
+ "jsx_attribute > property_identifier": "variable",
+
+ "class > identifier": "type",
+ "new_expression > identifier": "type",
+ "jsx_opening_element > identifier": "type",
+ "jsx_closing_element > identifier": "type",
+ "jsx_self_closing_element > identifier": "type",
+
+ "call_expression > identifier": "function",
+ "call_expression > super": "function",
+ "function > identifier": "function",
+ "generator_function > identifier": "function",
+ "method_definition > property_identifier": "function",
+ "call_expression > member_expression > property_identifier": "function"
+ }
+}
diff --git a/common/templates/json/tree-sitter/grammars/lua.json b/common/templates/json/tree-sitter/grammars/lua.json
new file mode 100644
index 00000000..3003e387
--- /dev/null
+++ b/common/templates/json/tree-sitter/grammars/lua.json
@@ -0,0 +1,87 @@
+{
+ "simpleTerms": {
+
+ "method": "function",
+
+ "\"local\"": "modifier",
+ "\"function\"": "modifier",
+
+ "number": "number",
+ "string": "string",
+ "comment": "comment",
+
+ "true": "constant",
+ "false": "constant",
+ "nil": "constant",
+ "global_variable": "constant",
+
+ "\"while\"": "control",
+ "\"do\"": "control",
+ "\"until\"": "control",
+ "\"break\"": "control",
+ "\"for\"": "control",
+ "\"if\"": "control",
+ "\"else\"": "control",
+ "\"elseif\"": "control",
+ "\"then\"": "control",
+ "\"end\"": "control",
+ "\"goto\"": "control",
+ "\"repeat\"": "control",
+ "\"return\"": "control",
+
+ "self": "operator",
+ "\"and\"": "operator",
+ "\"or\"": "operator",
+ "\"not\"": "operator",
+ "\"in\"": "operator",
+ "\"next\"": "operator",
+ "\"spread\"": "operator",
+
+ "\"+\"": "operator",
+ "\"-\"": "operator",
+ "\"*\"": "operator",
+ "\"/\"": "operator",
+ "\"%\"": "operator",
+ "\"^\"": "operator",
+ "\"#\"": "operator",
+ "\"&\"": "operator",
+ "\"~\"": "operator",
+ "\"|\"": "operator",
+ "\"//\"": "operator",
+ "\"<<\"": "operator",
+ "\">>\"": "operator",
+ "\"==\"": "operator",
+ "\"~=\"": "operator",
+ "\"<=\"": "operator",
+ "\">=\"": "operator",
+ "\"<\"": "operator",
+ "\">\"": "operator",
+ "\"=\"": "operator",
+ "\"::\"": "operator",
+ "\":\"": "operator",
+ "\".\"": "operator",
+ "\"..\"": "operator",
+
+ "\"{\"": "punctuation",
+ "\"}\"": "punctuation",
+ "\"[\"": "punctuation",
+ "\"]\"": "punctuation",
+ "\"(\"": "punctuation",
+ "\")\"": "punctuation",
+ "\";\"": "punctuation",
+ "\",\"": "punctuation"
+ },
+
+ "complexTerms": ["identifier", "property_identifier"],
+
+ "complexScopes": {
+ "identifier": "variable",
+ "property_identifier": "variable",
+
+ "function_call > identifier": "function",
+ "function_call > property_identifier": "function",
+ "function_name > identifier": "function",
+ "function_name > property_identifier": "function",
+ "local_function > identifier": "function"
+ }
+}
diff --git a/common/templates/json/tree-sitter/grammars/php.json b/common/templates/json/tree-sitter/grammars/php.json
new file mode 100644
index 00000000..71746aa6
--- /dev/null
+++ b/common/templates/json/tree-sitter/grammars/php.json
@@ -0,0 +1,164 @@
+{
+ "simpleTerms": {
+
+ "variable_name": "variable",
+
+ "__construct": "function",
+ "\"echo\"": "function",
+ "\"print\"": "function",
+ "\"unset\"": "function",
+ "\"isset\"": "function",
+ "\"eval\"": "function",
+ "\"array\"": "function",
+ "\"list\"": "function",
+ "\"empty\"": "function",
+
+ "require_once": "function",
+ "require": "function",
+ "include_once": "function",
+ "include": "function",
+
+ "\"callable\"": "modifier",
+ "\"var\"": "modifier",
+ "\"trait\"": "modifier",
+ "\"class\"": "modifier",
+ "\"interface\"": "modifier",
+ "\"function\"": "modifier",
+ "\"type\"": "modifier",
+
+ "\"static\"": "modifier",
+ "\"public\"": "modifier",
+ "\"private\"": "modifier",
+ "\"protected\"": "modifier",
+ "\"global\"": "modifier",
+ "\"const\"": "modifier",
+ "\"abstract\"": "modifier",
+ "\"extends\"": "modifier",
+ "\"implements\"": "modifier",
+ "\"final\"": "modifier",
+
+ "integer": "number",
+ "float": "number",
+ "string": "string",
+ "regex": "string",
+
+ "true": "constant",
+ "false": "constant",
+
+ "comment": "comment",
+
+ "\"if\"": "control",
+ "\"do\"": "control",
+ "\"else\"": "control",
+ "\"elseif\"": "control",
+ "\"endif\"": "control",
+ "\"while\"": "control",
+ "\"endwhile\"": "control",
+ "\"for\"": "control",
+ "\"endfor\"": "control",
+ "\"foreach\"": "control",
+ "\"endforeach\"": "control",
+ "\"declare\"": "control",
+ "\"enddeclare\"": "control",
+ "\"return\"": "control",
+ "\"break\"": "control",
+ "\"continue\"": "control",
+ "\"throw\"": "control",
+ "\"try\"": "control",
+ "\"catch\"": "control",
+ "\"finally\"": "control",
+ "\"switch\"": "control",
+ "\"endswitch\"": "control",
+ "\"case\"": "control",
+ "\"default\"": "control",
+ "\"yield\"": "control",
+ "\"goto\"": "control",
+ "\"exit\"": "control",
+ "\"die\"": "control",
+
+ "\"new\"": "operator",
+ "\"clone\"": "operator",
+ "\"insteadof\"": "operator",
+ "\"instanceof\"": "operator",
+
+ "\"+\"": "operator",
+ "\"-\"": "operator",
+ "\"*\"": "operator",
+ "\"/\"": "operator",
+ "\"%\"": "operator",
+ "\"**\"": "operator",
+ "\"=\"": "operator",
+ "\"==\"": "operator",
+ "\"===\"": "operator",
+ "\"!=\"": "operator",
+ "\"!==\"": "operator",
+ "\"<\"": "operator",
+ "\">\"": "operator",
+ "\"<>\"": "operator",
+ "\"<=\"": "operator",
+ "\"=>\"": "operator",
+ "\">=\"": "operator",
+ "\"<=>\"": "operator",
+ "\"&\"": "operator",
+ "\"$\"": "operator",
+ "\"|\"": "operator",
+ "\"^\"": "operator",
+ "\"~\"": "operator",
+ "\"<<\"": "operator",
+ "\">>\"": "operator",
+ "\"++\"": "operator",
+ "\"--\"": "operator",
+ "\"and\"": "operator",
+ "\"or\"": "operator",
+ "\"xor\"": "operator",
+ "\"!\"": "operator",
+ "\"&&\"": "operator",
+ "\"||\"": "operator",
+ "\".\"": "operator",
+ "\"?\"": "operator",
+ "\":\"": "operator",
+ "\"??\"": "operator",
+ "\"->\"": "operator",
+ "\"as\"": "operator",
+
+ "\"use\"": "directive",
+ "\"namespace\"": "directive",
+
+ "\"(\"": "punctuation",
+ "\")\"": "punctuation",
+ "\"{\"": "punctuation",
+ "\"}\"": "punctuation",
+ "\"[\"": "punctuation",
+ "\"]\"": "punctuation",
+ "\";\"": "punctuation",
+ "\",\"": "punctuation"
+ },
+
+ "complexTerms": ["name", "simple_variable"],
+
+ "complexScopes": {
+ "class_declaration > name": "type",
+ "catch_clause > qualified_name > name": "type",
+ "class_base_clause > qualified_name > name": "type",
+ "interface_declaration > name": "type",
+ "class_interface_clause > qualified_name > name": "type",
+ "object_creation_expression > qualified_name > name": "type",
+ "cast_expression > cast_type": "type",
+ "object_creation_expression > new_variable > simple_variable": "type",
+
+ "name": "variable",
+ "member_access_expression > name": "variable",
+
+ "function_definition > name": "function",
+ "function_call_expression > name": "function",
+ "function_call_expression > qualified_name": "function",
+ "method_declaration > name": "function",
+ "method_declaration > function_definition > name": "function",
+ "scoped_call_expression > name": "function",
+ "member_call_expression > name": "function",
+
+ "const_element > name": "constant",
+ "class_constant_access_expression > name": "constant",
+ "qualified_name > name": "constant"
+ }
+}
diff --git a/common/templates/json/tree-sitter/grammars/python.json b/common/templates/json/tree-sitter/grammars/python.json
new file mode 100644
index 00000000..e594a222
--- /dev/null
+++ b/common/templates/json/tree-sitter/grammars/python.json
@@ -0,0 +1,117 @@
+{
+ "simpleTerms": {
+ "module": "scope",
+
+ "\"global\"": "modifier",
+ "\"nonlocal\"": "modifier",
+
+ "decorator": "function",
+ "\"print\"": "function",
+ "\"assert\"": "function",
+ "\"exec\"": "function",
+ "\"del\"": "function",
+
+ "integer" : "number",
+ "float" : "number",
+ "string": "string",
+ "escape_sequence": "string",
+ "interpolation": "string",
+ "comment": "comment",
+
+ "none": "constant",
+ "true": "constant",
+ "false": "constant",
+
+ "\"if\"": "control",
+ "\"else\"": "control",
+ "\"elif\"": "control",
+ "\"while\"": "control",
+ "\"for\"": "control",
+ "\"return\"": "control",
+ "\"break\"": "control",
+ "\"continue\"": "control",
+ "\"pass\"": "control",
+ "\"raise\"": "control",
+ "\"yield\"": "control",
+ "\"await\"": "control",
+ "\"async\"": "control",
+ "\"try\"": "control",
+ "\"except\"": "control",
+ "\"with\"": "control",
+ "\"as\"": "control",
+ "\"finally\"": "control",
+
+ "\"+\"": "operator",
+ "\"-\"": "operator",
+ "\"*\"": "operator",
+ "\"/\"": "operator",
+ "\"%\"": "operator",
+ "\"@\"": "operator",
+ "\"**\"": "operator",
+ "\"//\"": "operator",
+ "\"==\"": "operator",
+ "\"!=\"": "operator",
+ "\"<>\"": "operator",
+ "\">\"": "operator",
+ "\"<\"": "operator",
+ "\">=\"": "operator",
+ "\"<=\"": "operator",
+ "\"=\"": "operator",
+ "\"+=\"": "operator",
+ "\"-=\"": "operator",
+ "\"*=\"": "operator",
+ "\"/=\"": "operator",
+ "\"%=\"": "operator",
+ "\"@=\"": "operator",
+ "\"**=\"": "operator",
+ "\"//=\"": "operator",
+ "\"&\"": "operator",
+ "\"|\"": "operator",
+ "\"^\"": "operator",
+ "\"~\"": "operator",
+ "\"<<\"": "operator",
+ "\">>\"": "operator",
+
+ "\"in\"": "operator",
+ "\"and\"": "operator",
+ "\"or\"": "operator",
+ "\"not\"": "operator",
+ "\"is\"": "operator",
+
+ "\"import\"": "directive",
+ "\"from\"": "directive",
+ "\"class\"": "directive",
+ "\"def\"": "directive",
+ "\"lambda\"": "directive",
+
+ "\"[\"": "punctuation",
+ "\"]\"": "punctuation",
+ "\"{\"": "punctuation",
+ "\"}\"": "punctuation",
+ "\"(\"": "punctuation",
+ "\")\"": "punctuation"
+ },
+
+ "complexTerms": ["identifier", "attribute"],
+
+ "complexScopes": {
+ "type > identifier": "type",
+ "class_definition > identifier": "type",
+ "class_definition > argument_list > attribute": "type",
+ "class_definition > argument_list > identifier": "type",
+ "class_definition > argument_list > keyword_argument > attribute": "type",
+ "class_definition > argument_list > keyword_argument > identifier": "type",
+
+ "identifier": "variable",
+ "attribute > identifier": "variable",
+ "keyword_argument > identifier": "variable",
+ "default_parameter > identifier": "variable",
+ "parameters > identifier": "variable",
+ "parameters > list_splat > identifier": "variable",
+ "parameters > dictionary_splat > identifier": "variable",
+
+ "call > identifier": "function",
+ "call > attribute > identifier[-1]": "function",
+ "function_definition > identifier": "function"
+ }
+}
diff --git a/common/templates/json/tree-sitter/grammars/ruby.json b/common/templates/json/tree-sitter/grammars/ruby.json
new file mode 100644
index 00000000..bfebf42b
--- /dev/null
+++ b/common/templates/json/tree-sitter/grammars/ruby.json
@@ -0,0 +1,117 @@
+{
+ "simpleTerms": {
+ "constant": "type",
+
+ "class_variable": "variable",
+ "instance_variable": "variable",
+
+ "string": "string",
+ "bare_string": "string",
+ "subshell": "string",
+ "heredoc_beginning": "string",
+ "heredoc_body": "string",
+ "regex": "string",
+ "escape_sequence": "string",
+ "symbol": "string",
+ "bare_symbol": "string",
+ "interpolation": "string",
+ "float": "number",
+ "integer": "number",
+ "complex": "number",
+ "rational": "number",
+ "comment": "comment",
+
+ "nil": "constant",
+ "true": "constant",
+ "false": "constant",
+
+ "\"if\"": "control",
+ "\"unless\"": "control",
+ "\"def\"": "control",
+ "\"do\"": "control",
+ "\"end\"": "control",
+ "\"else\"": "control",
+ "\"elsif\"": "control",
+ "\"class\"": "control",
+ "\"module\"": "control",
+ "\"alias\"": "control",
+ "\"begin\"": "control",
+ "\"rescue\"": "control",
+ "\"ensure\"": "control",
+ "\"return\"": "control",
+ "\"yield\"": "control",
+ "\"case\"": "control",
+ "\"when\"": "control",
+ "\"then\"": "control",
+ "\"for\"": "control",
+ "\"break\"": "control",
+ "\"next\"": "control",
+ "\"retry\"": "control",
+ "\"while\"": "control",
+ "\"in\"": "control",
+ "\"until\"": "control",
+
+ "self": "control",
+ "super": "control",
+
+ "\"and\"": "operator",
+ "\"or\"": "operator",
+ "\"not\"": "operator",
+ "\"||\"": "operator",
+ "\"&&\"": "operator",
+ "\"!\"": "operator",
+ "\"~\"": "operator",
+ "\"<<\"": "operator",
+ "\">>\"": "operator",
+ "\"=\"": "operator",
+ "\"==\"": "operator",
+ "\"!=\"": "operator",
+ "\"===\"": "operator",
+ "\"<=>\"": "operator",
+ "\"=~\"": "operator",
+ "\"!~\"": "operator",
+ "\"<\"": "operator",
+ "\"<=\"": "operator",
+ "\">\"": "operator",
+ "\">=\"": "operator",
+ "\"&\"": "operator",
+ "\"|\"": "operator",
+ "\"^\"": "operator",
+ "\"+\"": "operator",
+ "\"-\"": "operator",
+ "\"/\"": "operator",
+ "\"%\"": "operator",
+ "\"*\"": "operator",
+ "\"**\"": "operator",
+ "\"+@\"": "operator",
+ "\"-@\"": "operator",
+ "\"..\"": "operator",
+ "\"[]\"": "operator",
+ "\"[]=\"": "operator",
+ "\"defined?\"": "operator",
+
+ "\",\"": "punctuation",
+ "\"%w(\"": "punctuation",
+ "\"%i(\"": "punctuation",
+ "\"(\"": "punctuation",
+ "\")\"": "punctuation",
+ "\"{\"": "punctuation",
+ "\"}\"": "punctuation",
+ "\"#{\"": "punctuation"
+ },
+
+ "complexTerms": ["identifier"],
+
+ "complexScopes": {
+ "identifier": "variable",
+ "block_parameters > identifier": "variable",
+ "keyword_parameter > identifier": "constant",
+
+ "method > identifier": "function",
+ "setter > identifier": "function",
+ "call > identifier": "function",
+ "method_call > identifier": "function",
+ "singleton_method > identifier": "function",
+ "method_parameters > identifier": "function"
+ },
+}
diff --git a/common/templates/json/tree-sitter/grammars/rust.json b/common/templates/json/tree-sitter/grammars/rust.json
new file mode 100644
index 00000000..321e650a
--- /dev/null
+++ b/common/templates/json/tree-sitter/grammars/rust.json
@@ -0,0 +1,168 @@
+{
+ "simpleTerms": {
+
+ "primitive_type": "type",
+
+ "inner_attribute_item": "variable",
+ "shorthand_field_identifier": "variable",
+ "\"_\"": "variable",
+
+ "boolean_literal": "number",
+ "integer_literal": "number",
+ "float_literal": "number",
+ "char_literal": "string",
+ "string_literal": "string",
+ "raw_string_literal": "string",
+ "escape_sequence": "string",
+ "line_comment": "comment",
+ "block_comment": "comment",
+
+ "\"let\"": "modifier",
+ "\"const\"": "modifier",
+ "\"static\"": "modifier",
+ "\"extern\"": "modifier",
+ "\"dyn\"": "modifier",
+ "\"trait\"": "modifier",
+ "\"mod\"": "modifier",
+ "\"pub\"": "modifier",
+ "\"default\"": "modifier",
+ "\"ref\"": "modifier",
+ "mutable_specifier": "modifier",
+
+ "\"fn\"": "control",
+ "\"type\"": "control",
+ "\"struct\"": "control",
+ "\"enum\"": "control",
+ "\"union\"": "control",
+ "\"impl\"": "control",
+
+ "\"unsafe\"": "control",
+ "\"match\"": "control",
+ "\"if\"": "control",
+ "\"in\"": "control",
+ "\"else\"": "control",
+ "\"move\"": "control",
+ "\"while\"": "control",
+ "\"loop\"": "control",
+ "\"for\"": "control",
+ "\"return\"": "control",
+ "\"continue\"": "control",
+ "\"break\"": "control",
+ "\"where\"": "control",
+ "\"macro_rules!\"": "control",
+
+ "self": "control",
+ "super": "control",
+ "crate": "control",
+
+ "\".\"": "operator",
+ "\"->\"": "operator",
+ "\"=>\"": "operator",
+ "\"-\"": "operator",
+ "\"+\"": "operator",
+ "\"/\"": "operator",
+ "\"%\"": "operator",
+ "\"++\"": "operator",
+ "\"--\"": "operator",
+ "\"==\"": "operator",
+ "\"!\"": "operator",
+ "\"!=\"": "operator",
+ "\"<\"": "operator",
+ "\">\"": "operator",
+ "\">=\"": "operator",
+ "\"<=\"": "operator",
+ "\"&&\"": "operator",
+ "\"||\"": "operator",
+ "\"&\"": "operator",
+ "\"|\"": "operator",
+ "\"^\"": "operator",
+ "\"~\"": "operator",
+ "\"<<\"": "operator",
+ "\">>\"": "operator",
+ "\"=\"": "operator",
+ "\"+=\"": "operator",
+ "\"-=\"": "operator",
+ "\"*=\"": "operator",
+ "\"/=\"": "operator",
+ "\"%=\"": "operator",
+ "\"<<=\"": "operator",
+ "\">>=\"": "operator",
+ "\"&=\"": "operator",
+ "\"^=\"": "operator",
+ "\"|=\"": "operator",
+ "\"?\"": "operator",
+ "\"::\"": "operator",
+ "\"..\"": "operator",
+ "\"as\"": "operator",
+
+ "\"use\"": "directive",
+ "\"#\"": "directive",
+
+ "\";\"": "punctuation",
+ "\":\"": "punctuation",
+ "\",\"": "punctuation",
+ "\"{\"": "punctuation",
+ "\"}\"": "punctuation"
+ },
+
+ "complexTerms": [
+ "identifier", "field_identifier", "type_identifier",
+ "\"(\"", "\")\"", "\"[\"", "\"]\"", "\"*\""],
+
+ "complexScopes": {
+ "type_identifier": "type",
+ "scoped_type_identifier > type_identifier": "type",
+ "use_declaration > identifier": "type",
+ "use_declaration > scoped_identifier > identifier[-1]": "type",
+ "use_list > identifier": "type",
+ "use_list > scoped_identifier > identifier": "type",
+ "use_wildcard > \"*\"": "type",
+ "use_as_clause > identifier": "type",
+ "tuple_struct_pattern > identifier": "type",
+ "tuple_struct_pattern > scoped_identifier > identifier[-1]": "type",
+ "enum_variant > identifier": "type",
+ "match_pattern > scoped_identifier > identifier[-1]": "type",
+ "unit_type > \"(\"": "type",
+ "unit_type > \")\"": "type",
+
+ "scoped_identifier > identifier": "scope",
+ "scoped_type_identifier > identifier": "scope",
+ "scoped_type_identifier > scoped_identifier > identifier": "scope",
+ "scoped_identifier > scoped_identifier > identifier": "scope",
+ "scoped_use_list > scoped_identifier > identifier": "scope",
+ "scoped_use_list > identifier": "scope",
+ "use_wildcard > scoped_identifier > identifier": "scope",
+ "use_wildcard > identifier": "scope",
+ "struct_pattern > scoped_type_identifier > identifier": "scope",
+ "struct_expression > scoped_type_identifier > identifier": "scope",
+
+ "identifier": "variable",
+ "field_identifier": "variable",
+ "scoped_identifier > identifier[-1]": "variable",
+
+ "call_expression > identifier": "function",
+ "call_expression > field_expression > field_identifier[-1]": "function",
+ "call_expression > scoped_identifier > identifier[-1]": "function",
+ "macro_invocation > identifier": "function",
+ "macro_definition > identifier": "function",
+ "generic_function > identifier": "function",
+ "generic_function > field_expression > field_identifier": "function",
+ "generic_function > scoped_identifier > identifier": "function",
+ "function_item > identifier": "function",
+ "function_signature_item > identifier": "function",
+
+ "lifetime > identifier": "modifier",
+
+ "meta_item > identifier": "directive",
+
+ "\"*\"": "operator",
+ "\"(\"": "punctuation",
+ "\")\"": "punctuation",
+ "\"[\"": "punctuation",
+ "\"]\"": "punctuation",
+ "unit_expression > \"(\"": "constant",
+ "unit_expression > \")\"": "constant",
+ "attribute_item > \"[\"": "directive",
+ "attribute_item > \"]\"": "directive"
+ }
+}
diff --git a/common/templates/json/tree-sitter/grammars/typescript.json b/common/templates/json/tree-sitter/grammars/typescript.json
new file mode 100644
index 00000000..7f5420fb
--- /dev/null
+++ b/common/templates/json/tree-sitter/grammars/typescript.json
@@ -0,0 +1,156 @@
+{
+ "simpleTerms": {
+ "type_identifier": "type",
+ "predefined_type": "type",
+
+ "namespace": "scope",
+ "\"module\"": "scope",
+
+ "shorthand_property_identifier": "variable",
+
+ "\"var\"": "modifier",
+ "\"let\"": "modifier",
+ "\"extends\"": "modifier",
+ "\"const\"": "modifier",
+ "\"static\"": "modifier",
+ "\"public\"": "modifier",
+ "\"private\"": "modifier",
+ "\"protected\"": "modifier",
+ "\"readonly\"": "modifier",
+
+ "number": "number",
+ "string": "string",
+ "escape_sequence": "string",
+ "template_string": "string",
+ "template_substitution": "string",
+ "regex": "string",
+ "comment": "comment",
+ "hash_bang_line": "comment",
+
+ "true": "constant",
+ "false": "constant",
+ "null": "constant",
+ "undefined": "constant",
+
+ "\"as\"": "control",
+ "\"if\"": "control",
+ "\"do\"": "control",
+ "\"else\"": "control",
+ "\"while\"": "control",
+ "\"for\"": "control",
+ "\"return\"": "control",
+ "\"break\"": "control",
+ "\"continue\"": "control",
+ "\"throw\"": "control",
+ "\"try\"": "control",
+ "\"catch\"": "control",
+ "\"finally\"": "control",
+ "\"switch\"": "control",
+ "\"case\"": "control",
+ "\"default\"": "control",
+ "\"export\"": "control",
+ "\"import\"": "control",
+ "\"from\"": "control",
+ "\"yield\"": "control",
+ "\"async\"": "control",
+ "\"await\"": "control",
+ "\"debugger\"": "control",
+
+ "this": "operator",
+ "\"class\"": "operator",
+ "\"type\"": "operator",
+ "\"enum\"": "operator",
+ "\"function\"": "operator",
+ "\"interface\"": "operator",
+ "\"implements\"": "operator",
+ "\"declare\"": "operator",
+
+ "\"in\"": "operator",
+ "\"instanceof\"": "operator",
+ "\"of\"": "operator",
+ "\"new\"": "operator",
+ "\"delete\"": "operator",
+ "\"typeof\"": "operator",
+ "\"get\"": "operator",
+ "\"set\"": "operator",
+
+ "\"=\"": "operator",
+ "\"+=\"": "operator",
+ "\"-=\"": "operator",
+ "\"*=\"": "operator",
+ "\"/=\"": "operator",
+ "\"%=\"": "operator",
+ "\"<<=\"": "operator",
+ "\">>=\"": "operator",
+ "\">>>=\"": "operator",
+ "\"&=\"": "operator",
+ "\"^=\"": "operator",
+ "\"|=\"": "operator",
+ "\"!\"": "operator",
+ "\"+\"": "operator",
+ "\"-\"": "operator",
+ "\"*\"": "operator",
+ "\"/\"": "operator",
+ "\"%\"": "operator",
+ "\"==\"": "operator",
+ "\"===\"": "operator",
+ "\"!=\"": "operator",
+ "\"!==\"": "operator",
+ "\">=\"": "operator",
+ "\"<=\"": "operator",
+ "\"=>\"": "operator",
+ "\">\"": "operator",
+ "\"<\"": "operator",
+ "\":\"": "operator",
+ "\"?\"": "operator",
+ "\"&&\"": "operator",
+ "\"||\"": "operator",
+ "\"&\"": "operator",
+ "\"~\"": "operator",
+ "\"^\"": "operator",
+ "\">>\"": "operator",
+ "\">>>\"": "operator",
+ "\"<<\"": "operator",
+ "\"|\"": "operator",
+ "\"++\"": "operator",
+ "\"--\"": "operator",
+ "\"...\"": "operator",
+
+ "\"(\"": "punctuation",
+ "\")\"": "punctuation",
+ "\"{\"": "punctuation",
+ "\"}\"": "punctuation",
+ "\";\"": "punctuation",
+ "\"[\"": "punctuation",
+ "\"]\"": "punctuation",
+ "\".\"": "punctuation",
+ "\",\"": "punctuation",
+ "\"${\"": "punctuation"
+ },
+
+ "complexTerms": ["identifier", "property_identifier", "super"],
+
+ "complexScopes": {
+ "class > identifier": "type",
+ "new_expression > call_expression > identifier": "type",
+ "jsx_opening_element > identifier": "type",
+ "jsx_closing_element > identifier": "type",
+ "jsx_self_closing_element > identifier": "type",
+
+ "nested_type_identifier > identifier": "scope",
+
+ "identifier": "variable",
+ "property_identifier": "variable",
+ "member_expression > property_identifier": "variable",
+ "jsx_attribute > property_identifier": "variable",
+
+ "call_expression > identifier": "function",
+ "call_expression > super": "function",
+ "function > identifier": "function",
+ "generator_function > identifier": "function",
+ "method_definition > property_identifier": "function",
+ "call_expression > member_expression > property_identifier": "function",
+ "method_signature > property_identifier": "function",
+ "function_signature > identifier": "function"
+ }
+}
diff --git a/common/templates/json/tree-sitter/themes/dark-cpp.json b/common/templates/json/tree-sitter/themes/dark-cpp.json
new file mode 100644
index 00000000..156a96cb
--- /dev/null
+++ b/common/templates/json/tree-sitter/themes/dark-cpp.json
@@ -0,0 +1,124 @@
+{
+ "monacoTreeSitter": {
+ "type": "#4EC9B0",
+ "scope": "#D4D4D4",
+ "function": "#E5C07B",
+ "variable": "#9CDCFE",
+ "number": "#B5CEA8",
+ "string": "#D19A66",
+ "comment": "#5C6370",
+ "constant": "#56B6C2",
+ "directive": "#C586C0",
+ "control": "#569CD6",
+ "operator": "#D4D4D4",
+ "modifier": "#569CD6",
+ "punctuation": "#D4D4D4"
+ },
+ "base": {
+ "base": "vs-dark",
+ "inherit": true,
+ "rules": [
+ {
+ "token": "comment",
+ "foreground": "5C6370",
+ "fontStyle": "italic"
+ },
+ {
+ "token": "keyword",
+ "foreground": "569CD6",
+ "fontStyle": "bold"
+ },
+ {
+ "token": "keyword.control",
+ "foreground": "569CD6",
+ "fontStyle": "bold"
+ },
+ {
+ "token": "storage",
+ "foreground": "569CD6",
+ "fontStyle": "bold"
+ },
+ {
+ "token": "storage.type",
+ "foreground": "569CD6",
+ "fontStyle": "bold"
+ },
+ {
+ "token": "entity.name.type",
+ "foreground": "4EC9B0"
+ },
+ {
+ "token": "support.type",
+ "foreground": "4EC9B0"
+ },
+ {
+ "token": "entity.name.function",
+ "foreground": "E5C07B",
+ "fontStyle": "bold"
+ },
+ {
+ "token": "support.function",
+ "foreground": "E5C07B",
+ "fontStyle": "bold"
+ },
+ {
+ "token": "meta.function-call",
+ "foreground": "E5C07B",
+ "fontStyle": "bold"
+ },
+ {
+ "token": "variable",
+ "foreground": "9CDCFE"
+ },
+ {
+ "token": "variable.parameter",
+ "foreground": "9CDCFE"
+ },
+ {
+ "token": "constant.numeric",
+ "foreground": "B5CEA8"
+ },
+ {
+ "token": "constant.language",
+ "foreground": "56B6C2",
+ "fontStyle": "bold"
+ },
+ {
+ "token": "support.constant",
+ "foreground": "56B6C2",
+ "fontStyle": "bold"
+ },
+ {
+ "token": "string",
+ "foreground": "D19A66"
+ },
+ {
+ "token": "meta.preprocessor",
+ "foreground": "C586C0",
+ "fontStyle": "bold"
+ },
+ {
+ "token": "keyword.control.directive",
+ "foreground": "C586C0",
+ "fontStyle": "bold"
+ },
+ {
+ "token": "operator",
+ "foreground": "D4D4D4"
+ },
+ {
+ "token": "invalid",
+ "foreground": "FFFFFF",
+ "background": "F44747"
+ }
+ ],
+ "colors": {
+ "editor.foreground": "#D4D4D4",
+ "editor.background": "#1E1E1E",
+ "editor.selectionBackground": "#2C313A",
+ "editor.lineHighlightBackground": "#2A2D2E",
+ "editorCursor.foreground": "#AEAFAD",
+ "editorWhitespace.foreground": "#404040"
+ }
+ }
+}
\ No newline at end of file
diff --git a/common/templates/json/tree-sitter/themes/dark-python.json b/common/templates/json/tree-sitter/themes/dark-python.json
new file mode 100644
index 00000000..c30ac88f
--- /dev/null
+++ b/common/templates/json/tree-sitter/themes/dark-python.json
@@ -0,0 +1,116 @@
+{
+ "monacoTreeSitter": {
+ "type": "#0ca1a6",
+ "scope": "#dae3e3",
+ "function": "#F39C12",
+ "variable": "#dae3e3",
+ "number": "#7fcbcd",
+ "string": "#7fcbcd",
+ "comment": "#7f8c8d",
+ "constant": "#7fcbcd",
+ "directive": "#C586C0",
+ "control": "#0ca1a6",
+ "operator": "#dae3e3",
+ "modifier": "#0ca1a6",
+ "punctuation": "#dae3e3"
+ },
+ "base": {
+ "base": "vs-dark",
+ "inherit": true,
+ "rules": [
+ {
+ "token": "comment",
+ "foreground": "7f8c8d"
+ },
+ {
+ "token": "keyword",
+ "foreground": "0ca1a6"
+ },
+ {
+ "token": "keyword.control",
+ "foreground": "0ca1a6"
+ },
+ {
+ "token": "storage",
+ "foreground": "0ca1a6"
+ },
+ {
+ "token": "storage.type",
+ "foreground": "0ca1a6"
+ },
+ {
+ "token": "entity.name.type",
+ "foreground": "7fcbcd"
+ },
+ {
+ "token": "support.type",
+ "foreground": "7fcbcd"
+ },
+ {
+ "token": "entity.name.function",
+ "foreground": "F39C12"
+ },
+ {
+ "token": "support.function",
+ "foreground": "F39C12"
+ },
+ {
+ "token": "meta.function-call",
+ "foreground": "F39C12"
+ },
+ {
+ "token": "variable",
+ "foreground": "dae3e3"
+ },
+ {
+ "token": "variable.parameter",
+ "foreground": "dae3e3"
+ },
+ {
+ "token": "constant.numeric",
+ "foreground": "7fcbcd"
+ },
+ {
+ "token": "constant.language",
+ "foreground": "7fcbcd"
+ },
+ {
+ "token": "support.constant",
+ "foreground": "7fcbcd"
+ },
+ {
+ "token": "string",
+ "foreground": "7fcbcd"
+ },
+ {
+ "token": "meta.preprocessor",
+ "foreground": "C586C0"
+ },
+ {
+ "token": "keyword.control.directive",
+ "foreground": "C586C0"
+ },
+ {
+ "token": "operator",
+ "foreground": "dae3e3"
+ },
+ {
+ "token": "punctuation",
+ "foreground": "dae3e3"
+ },
+ {
+ "token": "invalid",
+ "foreground": "ffffff",
+ "background": "df7365"
+ }
+ ],
+ "colors": {
+ "editor.background": "#1f272a",
+ "editor.foreground": "#dae3e3",
+ "editor.selectionBackground": "#00818480",
+ "editor.lineHighlightBackground": "#434f5410",
+ "editorCursor.foreground": "#dae3e3",
+ "editorWhitespace.foreground": "#374146"
+ }
+ }
+}
\ No newline at end of file
diff --git a/common/templates/json/tree-sitter/themes/light-cpp.json b/common/templates/json/tree-sitter/themes/light-cpp.json
new file mode 100644
index 00000000..b5d9724b
--- /dev/null
+++ b/common/templates/json/tree-sitter/themes/light-cpp.json
@@ -0,0 +1,113 @@
+{
+ "monacoTreeSitter": {
+ "type": "#005C5F",
+ "scope": "#4e5b61",
+ "function": "#D35400",
+ "variable": "#4e5b61",
+ "number": "#005C5F",
+ "string": "#005C5F",
+ "comment": "#95a5a6cc",
+ "constant": "#005C5F",
+ "directive": "#728E00",
+ "control": "#00979D",
+ "operator": "#4e5b61",
+ "modifier": "#00979D",
+ "punctuation": "#4e5b61"
+ },
+ "base": {
+ "base": "vs",
+ "inherit": true,
+ "rules": [
+ {
+ "token": "comment",
+ "foreground": "95a5a6"
+ },
+ {
+ "token": "keyword",
+ "foreground": "00979D"
+ },
+ {
+ "token": "keyword.control",
+ "foreground": "00979D"
+ },
+ {
+ "token": "storage",
+ "foreground": "00979D"
+ },
+ {
+ "token": "storage.type",
+ "foreground": "005C5F"
+ },
+ {
+ "token": "entity.name.type",
+ "foreground": "005C5F"
+ },
+ {
+ "token": "support.type",
+ "foreground": "005C5F"
+ },
+ {
+ "token": "entity.name.function",
+ "foreground": "D35400"
+ },
+ {
+ "token": "support.function",
+ "foreground": "D35400"
+ },
+ {
+ "token": "meta.function-call",
+ "foreground": "D35400"
+ },
+ {
+ "token": "variable",
+ "foreground": "4e5b61"
+ },
+ {
+ "token": "variable.parameter",
+ "foreground": "4e5b61"
+ },
+ {
+ "token": "constant.numeric",
+ "foreground": "005C5F"
+ },
+ {
+ "token": "constant.language",
+ "foreground": "005C5F",
+ "fontStyle": "bold"
+ },
+ {
+ "token": "support.constant",
+ "foreground": "005C5F"
+ },
+ {
+ "token": "string",
+ "foreground": "005C5F"
+ },
+ {
+ "token": "meta.preprocessor",
+ "foreground": "728E00"
+ },
+ {
+ "token": "keyword.control.directive",
+ "foreground": "728E00"
+ },
+ {
+ "token": "operator",
+ "foreground": "4e5b61"
+ },
+ {
+ "token": "invalid",
+ "foreground": "ffffff",
+ "background": "df7365"
+ }
+ ],
+ "colors": {
+ "editor.foreground": "#4e5b61",
+ "editor.background": "#ffffff",
+ "editor.selectionBackground": "#7fcbcdb3",
+ "editor.lineHighlightBackground": "#434f5410",
+ "editorCursor.foreground": "#4e5b61",
+ "editorWhitespace.foreground": "#bfbfbf"
+ }
+ }
+}
\ No newline at end of file
diff --git a/common/templates/json/tree-sitter/themes/light-python.json b/common/templates/json/tree-sitter/themes/light-python.json
new file mode 100644
index 00000000..97ba5cec
--- /dev/null
+++ b/common/templates/json/tree-sitter/themes/light-python.json
@@ -0,0 +1,104 @@
+{
+ "monacoTreeSitter": {
+ "type": "#267F99",
+ "scope": "#333333",
+ "function": "#795E26",
+ "variable": "#333333",
+ "number": "#098658",
+ "string": "#A31515",
+ "comment": "#008000",
+ "constant": "#0451A5",
+ "directive": "#AF00DB",
+ "control": "#AF00DB",
+ "operator": "#333333",
+ "modifier": "#AF00DB",
+ "punctuation": "#333333"
+ },
+ "base": {
+ "base": "vs",
+ "inherit": true,
+ "rules": [
+ {
+ "token": "comment",
+ "foreground": "008000"
+ },
+ {
+ "token": "keyword",
+ "foreground": "AF00DB"
+ },
+ {
+ "token": "keyword.control",
+ "foreground": "AF00DB"
+ },
+ {
+ "token": "entity.name.class",
+ "foreground": "267F99"
+ },
+ {
+ "token": "entity.name.type",
+ "foreground": "267F99"
+ },
+ {
+ "token": "entity.name.function",
+ "foreground": "795E26"
+ },
+ {
+ "token": "support.function.builtin",
+ "foreground": "0451A5"
+ },
+ {
+ "token": "variable.parameter",
+ "foreground": "001080"
+ },
+ {
+ "token": "variable.language.self",
+ "foreground": "001080"
+ },
+ {
+ "token": "entity.name.function.magic",
+ "foreground": "001080"
+ },
+ {
+ "token": "meta.decorator",
+ "foreground": "AF00DB"
+ },
+ {
+ "token": "string",
+ "foreground": "A31515"
+ },
+ {
+ "token": "string.doc",
+ "foreground": "008000"
+ },
+ {
+ "token": "constant.numeric",
+ "foreground": "098658"
+ },
+ {
+ "token": "constant.language",
+ "foreground": "0451A5"
+ },
+ {
+ "token": "punctuation",
+ "foreground": "333333"
+ },
+ {
+ "token": "keyword.operator",
+ "foreground": "333333"
+ },
+ {
+ "token": "invalid",
+ "foreground": "FFFFFF",
+ "background": "E51400"
+ }
+ ],
+ "colors": {
+ "editor.background": "#FFFFFF",
+ "editor.foreground": "#333333",
+ "editor.selectionBackground": "#ADD6FF",
+ "editor.lineHighlightBackground": "#FFFFFF",
+ "editorCursor.foreground": "#000000",
+ "editorWhitespace.foreground": "#BFBFBF"
+ }
+ }
+}
\ No newline at end of file