GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — node-tree-sitter/index.js at master · ddannyc/node-tree-sitter Expand file tree/ Copy pathindex.jsMore file actions 746 lines (633 loc) · 20.7 KB / Copy pathindex.jsFile metadata and controls746 lines (633 loc) · 20.7 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 let binding; try { binding = require('./build/Release/tree_sitter_runtime_binding'); } catch (e) { try { binding = require('./build/Debug/tree_sitter_runtime_binding'); } catch (_) { throw e; } } const util = require('util') const {Query, Parser, NodeMethods, Tree, TreeCursor} = binding; /* * Tree */ const {rootNode, edit} = Tree.prototype; Object.defineProperty(Tree.prototype, 'rootNode', { get() { /* Due to a race condition arising from Jest's worker pool, "this" has no knowledge of the native extension if the extension has not yet loaded when multiple Jest tests are being run simultaneously. If the extension has correctly loaded, "this" should be an instance of the class whose prototype we are acting on (in this case, Tree). Furthermore, the race condition sometimes results in the function in question being undefined even when the context is correct, so we also perform a null function check. */ if (this instanceof Tree && rootNode) { return unmarshalNode(rootNode.call(this), this); } }, // Jest worker pool may attempt to override property due to race condition, // we don't want to error on this configurable: true }); Tree.prototype.edit = function(arg) { if (this instanceof Tree && edit) { edit.call( this, arg.startPosition.row, arg.startPosition.column, arg.oldEndPosition.row, arg.oldEndPosition.column, arg.newEndPosition.row, arg.newEndPosition.column, arg.startIndex, arg.oldEndIndex, arg.newEndIndex ); } }; Tree.prototype.walk = function() { return this.rootNode.walk() }; /* * Node */ class SyntaxNode { constructor(tree) { this.tree = tree; } [util.inspect.custom]() { return this.constructor.name + ' {\n' + ' type: ' + this.type + ',\n' + ' startPosition: ' + pointToString(this.startPosition) + ',\n' + ' endPosition: ' + pointToString(this.endPosition) + ',\n' + ' childCount: ' + this.childCount + ',\n' + '}' } get type() { marshalNode(this); return NodeMethods.type(this.tree); } get typeId() { marshalNode(this); return NodeMethods.typeId(this.tree); } get isNamed() { marshalNode(this); return NodeMethods.isNamed(this.tree); } get text() { return this.tree.getText(this); } get startPosition() { marshalNode(this); NodeMethods.startPosition(this.tree); return unmarshalPoint(); } get endPosition() { marshalNode(this); NodeMethods.endPosition(this.tree); return unmarshalPoint(); } get startIndex() { marshalNode(this); return NodeMethods.startIndex(this.tree); } get endIndex() { marshalNode(this); return NodeMethods.endIndex(this.tree); } get parent() { marshalNode(this); return unmarshalNode(NodeMethods.parent(this.tree), this.tree); } get children() { marshalNode(this); return unmarshalNodes(NodeMethods.children(this.tree), this.tree); } get namedChildren() { marshalNode(this); return unmarshalNodes(NodeMethods.namedChildren(this.tree), this.tree); } get childCount() { marshalNode(this); return NodeMethods.childCount(this.tree); } get namedChildCount() { marshalNode(this); return NodeMethods.namedChildCount(this.tree); } get firstChild() { marshalNode(this); return unmarshalNode(NodeMethods.firstChild(this.tree), this.tree); } get firstNamedChild() { marshalNode(this); return unmarshalNode(NodeMethods.firstNamedChild(this.tree), this.tree); } get lastChild() { marshalNode(this); return unmarshalNode(NodeMethods.lastChild(this.tree), this.tree); } get lastNamedChild() { marshalNode(this); return unmarshalNode(NodeMethods.lastNamedChild(this.tree), this.tree); } get nextSibling() { marshalNode(this); return unmarshalNode(NodeMethods.nextSibling(this.tree), this.tree); } get nextNamedSibling() { marshalNode(this); return unmarshalNode(NodeMethods.nextNamedSibling(this.tree), this.tree); } get previousSibling() { marshalNode(this); return unmarshalNode(NodeMethods.previousSibling(this.tree), this.tree); } get previousNamedSibling() { marshalNode(this); return unmarshalNode(NodeMethods.previousNamedSibling(this.tree), this.tree); } hasChanges() { marshalNode(this); return NodeMethods.hasChanges(this.tree); } hasError() { marshalNode(this); return NodeMethods.hasError(this.tree); } isMissing() { marshalNode(this); return NodeMethods.isMissing(this.tree); } toString() { marshalNode(this); return NodeMethods.toString(this.tree); } child(index) { marshalNode(this); return unmarshalNode(NodeMethods.child(this.tree, index), this.tree); } namedChild(index) { marshalNode(this); return unmarshalNode(NodeMethods.namedChild(this.tree, index), this.tree); } firstChildForIndex(index) { marshalNode(this); return unmarshalNode(NodeMethods.firstChildForIndex(this.tree, index), this.tree); } firstNamedChildForIndex(index) { marshalNode(this); return unmarshalNode(NodeMethods.firstNamedChildForIndex(this.tree, index), this.tree); } namedDescendantForIndex(start, end) { marshalNode(this); if (end == null) end = start; return unmarshalNode(NodeMethods.namedDescendantForIndex(this.tree, start, end), this.tree); } descendantForIndex(start, end) { marshalNode(this); if (end == null) end = start; return unmarshalNode(NodeMethods.descendantForIndex(this.tree, start, end), this.tree); } descendantsOfType(types, start, end) { marshalNode(this); if (typeof types === 'string') types = [types] return unmarshalNodes(NodeMethods.descendantsOfType(this.tree, types, start, end), this.tree); } namedDescendantForPosition(start, end) { marshalNode(this); if (end == null) end = start; return unmarshalNode(NodeMethods.namedDescendantForPosition(this.tree, start, end), this.tree); } descendantForPosition(start, end) { marshalNode(this); if (end == null) end = start; return unmarshalNode(NodeMethods.descendantForPosition(this.tree, start, end), this.tree); } closest(types) { marshalNode(this); if (typeof types === 'string') types = [types] return unmarshalNode(NodeMethods.closest(this.tree, types), this.tree); } walk () { marshalNode(this); const cursor = NodeMethods.walk(this.tree); cursor.tree = this.tree; return cursor; } } /* * Parser */ const {parse, setLanguage} = Parser.prototype; const languageSymbol = Symbol('parser.language'); Parser.prototype.setLanguage = function(language) { if (this instanceof Parser && setLanguage) { setLanguage.call(this, language); } this[languageSymbol] = language; if (!language.nodeSubclasses) { initializeLanguageNodeClasses(language) } return this; }; Parser.prototype.getLanguage = function(language) { return this[languageSymbol] || null; }; Parser.prototype.parse = function(input, oldTree, {bufferSize, includedRanges}={}) { let getText, treeInput = input if (typeof input === 'string') { const inputString = input; input = (offset, position) => inputString.slice(offset) getText = getTextFromString } else { getText = getTextFromFunction } const tree = this instanceof Parser && parse ? parse.call( this, input, oldTree, bufferSize, includedRanges) : undefined; if (tree) { tree.input = treeInput tree.getText = getText tree.language = this.getLanguage() } return tree }; /* * TreeCursor */ const {startPosition, endPosition, currentNode, reset} = TreeCursor.prototype; Object.defineProperties(TreeCursor.prototype, { currentNode: { get() { if (this instanceof TreeCursor && currentNode) { return unmarshalNode(currentNode.call(this), this.tree); } }, configurable: true }, startPosition: { get() { if (this instanceof TreeCursor && startPosition) { startPosition.call(this); return unmarshalPoint(); } }, configurable: true }, endPosition: { get() { if (this instanceof TreeCursor && endPosition) { endPosition.call(this); return unmarshalPoint(); } }, configurable: true }, nodeText: { get() { return this.tree.getText(this) }, configurable: true } }); TreeCursor.prototype.reset = function(node) { marshalNode(node); if (this instanceof TreeCursor && reset) { reset.call(this); } } /* * Query */ const {_matches, _captures} = Query.prototype; const PREDICATE_STEP_TYPE = { DONE: 0, CAPTURE: 1, STRING: 2, } const ZERO_POINT = { row: 0, column: 0 }; Query.prototype._init = function() { /* * Initialize predicate functions * format: [type1, value1, type2, value2, ...] */ const predicateDescriptions = this._getPredicates(); const patternCount = predicateDescriptions.length; const setProperties = new Array(patternCount); const assertedProperties = new Array(patternCount); const refutedProperties = new Array(patternCount); const predicates = new Array(patternCount); const FIRST = 0 const SECOND = 2 const THIRD = 4 for (let i = 0; i < predicateDescriptions.length; i++) { predicates[i] = []; for (let j = 0; j < predicateDescriptions[i].length; j++) { const steps = predicateDescriptions[i][j]; const stepsLength = steps.length / 2; if (steps[FIRST] !== PREDICATE_STEP_TYPE.STRING) { throw new Error('Predicates must begin with a literal value'); } const operator = steps[FIRST + 1]; let isPositive = true; switch (operator) { case 'not-eq?': isPositive = false; case 'eq?': if (stepsLength !== 3) throw new Error( `Wrong number of arguments to \`#eq?\` predicate. Expected 2, got ${stepsLength - 1}` ); if (steps[SECOND] !== PREDICATE_STEP_TYPE.CAPTURE) throw new Error( `First argument of \`#eq?\` predicate must be a capture. Got "${steps[SECOND + 1]}"` ); if (steps[THIRD] === PREDICATE_STEP_TYPE.CAPTURE) { const captureName1 = steps[SECOND + 1]; const captureName2 = steps[THIRD + 1]; predicates[i].push(function(captures) { let node1, node2 for (const c of captures) { if (c.name === captureName1) node1 = c.node; if (c.name === captureName2) node2 = c.node; } if (node1 === undefined || node2 === undefined) return true; return (node1.text === node2.text) === isPositive; }); } else { const captureName = steps[SECOND + 1]; const stringValue = steps[THIRD + 1]; predicates[i].push(function(captures) { for (const c of captures) { if (c.name === captureName) { return (c.node.text === stringValue) === isPositive; }; } return true; }); } break; case 'not-match?': isPositive = false; case 'match?': if (stepsLength !== 3) throw new Error( `Wrong number of arguments to \`#match?\` predicate. Expected 2, got ${stepsLength - 1}.` ); if (steps[SECOND] !== PREDICATE_STEP_TYPE.CAPTURE) throw new Error( `First argument of \`#match?\` predicate must be a capture. Got "${steps[SECOND + 1]}".` ); if (steps[THIRD] !== PREDICATE_STEP_TYPE.STRING) throw new Error( `Second argument of \`#match?\` predicate must be a string. Got @${steps[THIRD + 1]}.` ); const captureName = steps[SECOND + 1]; const regex = new RegExp(steps[THIRD + 1]); predicates[i].push(function(captures) { for (const c of captures) { if (c.name === captureName) return regex.test(c.node.text) === isPositive } return true; }); break; case 'set!': if (stepsLength < 2 || stepsLength > 3) throw new Error( `Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${stepsLength - 1}.` ); if (steps.some((s, i) => (i % 2 !== 1) && s !== PREDICATE_STEP_TYPE.STRING)) throw new Error( `Arguments to \`#set!\` predicate must be a strings.".` ); if (!setProperties[i]) setProperties[i] = {}; setProperties[i][steps[SECOND + 1]] = steps[THIRD] ? steps[THIRD + 1] : null; break; case 'is?': case 'is-not?': if (stepsLength < 2 || stepsLength > 3) throw new Error( `Wrong number of arguments to \`#${operator}\` predicate. Expected 1 or 2. Got ${stepsLength - 1}.` ); if (steps.some((s, i) => (i % 2 !== 1) && s !== PREDICATE_STEP_TYPE.STRING)) throw new Error( `Arguments to \`#${operator}\` predicate must be a strings.".` ); const properties = operator === 'is?' ? assertedProperties : refutedProperties; if (!properties[i]) properties[i] = {}; properties[i][steps[SECOND + 1]] = steps[THIRD] ? steps[THIRD + 1] : null; break; default: throw new Error(`Unknown query predicate \`#${steps[FIRST + 1]}\``); } } } this.predicates = Object.freeze(predicates); this.setProperties = Object.freeze(setProperties); this.assertedProperties = Object.freeze(assertedProperties); this.refutedProperties = Object.freeze(refutedProperties); } Query.prototype.matches = function(rootNode, startPosition = ZERO_POINT, endPosition = ZERO_POINT) { marshalNode(rootNode); const [returnedMatches, returnedNodes] = _matches.call(this, rootNode.tree, startPosition.row, startPosition.column, endPosition.row, endPosition.column ); const nodes = unmarshalNodes(returnedNodes, rootNode.tree); const results = []; let i = 0 let nodeIndex = 0; while (i < returnedMatches.length) { const patternIndex = returnedMatches[i++]; const captures = []; while (i < returnedMatches.length && typeof returnedMatches[i] === 'string') { const captureName = returnedMatches[i++]; captures.push({ name: captureName, node: nodes[nodeIndex++], }) } if (this.predicates[patternIndex].every(p => p(captures))) { const result = {pattern: patternIndex, captures}; const setProperties = this.setProperties[patternIndex]; const assertedProperties = this.assertedProperties[patternIndex]; const refutedProperties = this.refutedProperties[patternIndex]; if (setProperties) result.setProperties = setProperties; if (assertedProperties) result.assertedProperties = assertedProperties; if (refutedProperties) result.refutedProperties = refutedProperties; results.push(result); } } return results; } Query.prototype.captures = function(rootNode, startPosition = ZERO_POINT, endPosition = ZERO_POINT) { marshalNode(rootNode); const [returnedMatches, returnedNodes] = _captures.call(this, rootNode.tree, startPosition.row, startPosition.column, endPosition.row, endPosition.column ); const nodes = unmarshalNodes(returnedNodes, rootNode.tree); const results = []; let i = 0 let nodeIndex = 0; while (i < returnedMatches.length) { const patternIndex = returnedMatches[i++]; const captureIndex = returnedMatches[i++]; const captures = []; while (i < returnedMatches.length && typeof returnedMatches[i] === 'string') { const captureName = returnedMatches[i++]; captures.push({ name: captureName, node: nodes[nodeIndex++], }) } if (this.predicates[patternIndex].every(p => p(captures))) { const result = captures[captureIndex]; const setProperties = this.setProperties[patternIndex]; const assertedProperties = this.assertedProperties[patternIndex]; const refutedProperties = this.refutedProperties[patternIndex]; if (setProperties) result.setProperties = setProperties; if (assertedProperties) result.assertedProperties = assertedProperties; if (refutedProperties) result.refutedProperties = refutedProperties; results.push(result); } } return results; } /* * Other functions */ function getTextFromString (node) { return this.input.substring(node.startIndex, node.endIndex); } function getTextFromFunction ({startIndex, endIndex}) { const {input} = this let result = ''; const goalLength = endIndex - startIndex; while (result.length < goalLength) { const text = input(startIndex + result.length); result += text; } return result.substr(0, goalLength); } const {pointTransferArray} = binding; const NODE_FIELD_COUNT = 6; const ERROR_TYPE_ID = 0xFFFF function getID(buffer, offset) { const low = BigInt(buffer[offset]); const high = BigInt(buffer[offset + 1]); return (high << 32n) + low; } function unmarshalNode(value, tree, offset = 0, cache = null) { /* case 1: node from the tree cache */ if (typeof value === 'object') { const node = value; return node; } /* case 2: node being transferred */ const nodeTypeId = value; const NodeClass = nodeTypeId === ERROR_TYPE_ID ? SyntaxNode : tree.language.nodeSubclasses[nodeTypeId]; const {nodeTransferArray} = binding; const id = getID(nodeTransferArray, offset) if (id === 0n) { return null } let cachedResult; if (cache && (cachedResult = cache.get(id))) return cachedResult; const result = new NodeClass(tree); for (let i = 0; i < NODE_FIELD_COUNT; i++) { result[i] = nodeTransferArray[offset + i]; } if (cache) cache.set(id, result); else tree._cacheNode(result); return result; } function unmarshalNodes(nodes, tree) { const cache = new Map(); let offset = 0; for (let i = 0, {length} = nodes; i < length; i++) { const node = unmarshalNode(nodes[i], tree, offset, cache); if (node !== nodes[i]) { nodes[i] = node; offset += NODE_FIELD_COUNT } } tree._cacheNodes(Array.from(cache.values())); return nodes; } function marshalNode(node) { if (!(node.tree instanceof Tree)){ throw new TypeError("SyntaxNode must belong to a Tree") } const {nodeTransferArray} = binding; for (let i = 0; i < NODE_FIELD_COUNT; i++) { nodeTransferArray[i] = node[i]; } } function unmarshalPoint() { return {row: pointTransferArray[0], column: pointTransferArray[1]}; } function pointToString(point) { return `{row: ${point.row}, column: ${point.column}}`; } function initializeLanguageNodeClasses(language) { const nodeTypeNamesById = binding.getNodeTypeNamesById(language); const nodeFieldNamesById = binding.getNodeFieldNamesById(language); const nodeTypeInfo = language.nodeTypeInfo || []; const nodeSubclasses = []; for (let id = 0, n = nodeTypeNamesById.length; id < n; id++) { nodeSubclasses[id] = SyntaxNode; const typeName = nodeTypeNamesById[id]; if (!typeName) continue; const typeInfo = nodeTypeInfo.find(info => info.named && info.type === typeName); if (!typeInfo) continue; const fieldNames = []; let classBody = '\n'; if (typeInfo.fields) { for (const fieldName in typeInfo.fields) { const fieldId = nodeFieldNamesById.indexOf(fieldName); if (fieldId === -1) continue; if (typeInfo.fields[fieldName].multiple) { const getterName = camelCase(fieldName) + 'Nodes'; fieldNames.push(getterName); classBody += ` get ${getterName}() { marshalNode(this); return unmarshalNodes(NodeMethods.childNodesForFieldId(this.tree, ${fieldId}), this.tree); } `.replace(/\s+/g, ' ') + '\n'; } else { const getterName = camelCase(fieldName, false) + 'Node'; fieldNames.push(getterName); classBody += ` get ${getterName}() { marshalNode(this); return unmarshalNode(NodeMethods.childNodeForFieldId(this.tree, ${fieldId}), this.tree); } `.replace(/\s+/g, ' ') + '\n'; } } } const className = camelCase(typeName, true) + 'Node'; const nodeSubclass = eval(`class ${className} extends SyntaxNode {${classBody}}; ${className}`); nodeSubclass.prototype.type = typeName; nodeSubclass.prototype.fields = Object.freeze(fieldNames.sort()) nodeSubclasses[id] = nodeSubclass; } language.nodeSubclasses = nodeSubclasses } function camelCase(name, upperCase) { name = name.replace(/_(\w)/g, (match, letter) => letter.toUpperCase()); if (upperCase) name = name[0].toUpperCase() + name.slice(1); return name; } module.exports = Parser; module.exports.Query = Query; module.exports.Tree = Tree; module.exports.SyntaxNode = SyntaxNode; module.exports.TreeCursor = TreeCursor; |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |