├── .devcontainer ├── Dockerfile └── devcontainer.json ├── .eslintignore ├── .eslintrc.json ├── .gitignore ├── .prettierrc ├── .vscode ├── launch.json └── settings.json ├── LICENSE ├── README.md ├── jest.config.js ├── package-lock.json ├── package.json ├── src ├── __test__ │ ├── Tagger.test.ts │ ├── codefixture.ts │ ├── highlighter.test.ts │ ├── index.node.test.ts │ ├── outliner.test.ts │ └── ranker.test.ts ├── highlighter │ ├── CodeHighlighter.ts │ ├── CodelineScoper.ts │ ├── Highlighter.ts │ ├── Highlights.ts │ ├── LineScoper.ts │ ├── common.ts │ └── index.ts ├── index.browser.ts ├── index.continue.ts ├── index.node.ts ├── index.shared.ts ├── outliner │ ├── Outliner.ts │ ├── Outlines.ts │ └── index.ts ├── parser │ ├── AST.ts │ ├── ContentPath.browser.ts │ ├── ContentPath.continue.ts │ ├── ContentPath.node.ts │ ├── TreeSitter.ts │ ├── common.ts │ ├── index.ts │ └── lang-utils.ts ├── ranker │ ├── RankedTags.ts │ ├── TagRanker.ts │ └── index.ts ├── tag-qry │ ├── tree-sitter-c-tags.scm │ ├── tree-sitter-c_sharp-tags.scm │ ├── tree-sitter-cpp-tags.scm │ ├── tree-sitter-elisp-tags.scm │ ├── tree-sitter-elixir-tags.scm │ ├── tree-sitter-elm-tags.scm │ ├── tree-sitter-go-tags.scm │ ├── tree-sitter-java-tags.scm │ ├── tree-sitter-javascript-tags.scm │ ├── tree-sitter-ocaml-tags.scm │ ├── tree-sitter-php-tags.scm │ ├── tree-sitter-python-tags.scm │ ├── tree-sitter-ql-tags.scm │ ├── tree-sitter-ruby-tags.scm │ ├── tree-sitter-rust-tags.scm │ └── tree-sitter-typescript-tags.scm ├── tagger │ ├── AllTags.ts │ ├── CachedFileTagExtractor.ts │ ├── CodeTagExtractor.ts │ ├── DefRef.ts │ ├── DefRefs.node.ts │ ├── DefRefs.ts │ ├── TagQuery.ts │ ├── Tagger.ts │ ├── common.ts │ └── index.ts └── webpack.d.ts ├── tsconfig.json └── webpack.config.ts /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:18.19.0-bookworm 2 | 3 | RUN apt-get update && apt-get install -y git 4 | 5 | RUN npm install -g jest typescript 6 | 7 | WORKDIR /workspace 8 | 9 | COPY . . 10 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "llm-code-highlighter", 3 | "dockerFile": "Dockerfile", 4 | "forwardPorts": [3000], 5 | "customizations": { 6 | "vscode": { 7 | "settings": { 8 | "terminal.integrated.shell.linux": "/bin/bash" 9 | }, 10 | "extensions": [ 11 | "dbaeumer.vscode-eslint", 12 | "ms-vscode.vscode-typescript-tslint-plugin", 13 | "esbenp.prettier-vscode", 14 | "eamodio.gitlens", 15 | "redhat.vscode-yaml", 16 | "sourcegraph.cody-ai" 17 | ] 18 | } 19 | }, 20 | "remoteUser": "node" 21 | } 22 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | .pnpm-store/ 2 | node_modules/ 3 | dist/ 4 | *.min.js -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["airbnb", "@typescript-eslint/recommended", "prettier"], 3 | "parser": "@typescript-eslint/parser", 4 | "plugins": ["@typescript-eslint"], 5 | "rules": {} 6 | } 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | .cache 106 | 107 | # Docusaurus cache and generated files 108 | .docusaurus 109 | 110 | # Serverless directories 111 | .serverless/ 112 | 113 | # FuseBox cache 114 | .fusebox/ 115 | 116 | # DynamoDB Local files 117 | .dynamodb/ 118 | 119 | # TernJS port file 120 | .tern-port 121 | 122 | # Stores VSCode versions used for testing VSCode extensions 123 | .vscode-test 124 | 125 | # yarn v2 126 | .yarn/cache 127 | .yarn/unplugged 128 | .yarn/build-state.yml 129 | .yarn/install-state.gz 130 | .pnp.* 131 | 132 | .pnpm-store 133 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 100, 3 | "tabWidth": 2, 4 | "useTabs": false, 5 | "semi": true, 6 | "singleQuote": true, 7 | "trailingComma": "es5", 8 | "bracketSpacing": true, 9 | "jsxBracketSameLine": false, 10 | "arrowParens": "avoid" 11 | } 12 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "type": "node", 6 | "request": "launch", 7 | "name": "Launch Program", 8 | "skipFiles": ["/**"], 9 | "program": "${workspaceFolder}/src/index.node.ts", 10 | "preLaunchTask": "tsc: build - tsconfig.json", 11 | "outFiles": ["${workspaceFolder}/dist/**/*.js"] 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.defaultFormatter": "esbenp.prettier-vscode", 3 | "editor.codeActionsOnSave": { 4 | "source.fixAll": "explicit" 5 | }, 6 | "editor.formatOnSave": true 7 | } 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # llm-code-highlighter 2 | 3 | **llm-code-highlighter** is a TypeScript library for creating succinct repository highlights, based on a simplified version of Paul Gauthier's repomap technique as outlined in the [Aider Chat docs](https://aider.chat/docs/repomap.html) and implemented by the code in the [aider](https://github.com/paul-gauthier/aider) and [grep-ast](https://github.com/paul-gauthier/grep-ast) repos. 4 | 5 | This typescript version of the original python code was created with assistance from ChatGPT 4. Every line of code was manually curated (by me, @restlessronin 😇). 6 | 7 | ## Installation 8 | 9 | At the moment, this plugin is only being actively developed against the [Continue repository](https://github.com/continuedev/continue). If you are interested in other use cases, please [file an issue on the repository](https://github.com/restlessronin/llm-code-highlighter/issues) and I'll see what I can do to accommodate. 10 | 11 | To install llm-code-highlighter, you can use npm or yarn: 12 | 13 | ```bash 14 | npm install llm-code-highlighter 15 | ``` 16 | 17 | ### Usage 18 | 19 | To use llm-code-highlighter in your TypeScript project, you need to import the required functions: 20 | 21 | ```typescript 22 | import { getHighlightsThatFit, getOutlines, ILLMContextSizer } from 'llm-code-highlighter'; 23 | ``` 24 | 25 | `getHighlightsThatFit` 26 | 27 | This function identifies highlights within the code by selecting high-ranked tags from "chat" and "other" source files. It then determines and returns the maximum number of highlighted lines, exclusively from "other" sources, that can be included within the token budget defined by the ContextSizer. 28 | 29 | ```typescript 30 | const contextSizer = { 31 | fits(content: string): boolean { 32 | return content.length <= 100; 33 | }, 34 | } as ILLMContextSizer; 35 | 36 | const chatSources = [ 37 | { 38 | relPath: 'chat1.js', 39 | code: ` 40 | console.log(add(1, 2)); 41 | `, 42 | }, 43 | { 44 | relPath: 'chat2.js', 45 | code: ` 46 | console.log(multiply(3, 1)); 47 | `, 48 | }, 49 | ]; 50 | 51 | const otherSources = [ 52 | { 53 | relPath: 'file1.js', 54 | code: ` 55 | function add(a, b) { 56 | return a + b; 57 | } 58 | console.log(add(1, 2)); 59 | `, 60 | }, 61 | { 62 | relPath: 'file2.js', 63 | code: ` 64 | function subtract(a, b) { 65 | return a - b; 66 | } 67 | console.log(subtract(3, 1)); 68 | `, 69 | }, 70 | { 71 | relPath: 'file3.js', 72 | code: ` 73 | function multiply(a, b) { 74 | return a * b; 75 | } 76 | console.log(multiply(2, 3)); 77 | `, 78 | }, 79 | ]; 80 | 81 | const result = await getHighlightsThatFit(contextSizer, chatSources, otherSources); 82 | console.log(result); 83 | // Output: 84 | // file1.js 85 | // ⋮... 86 | // █function add(a, b) { 87 | // ⋮... 88 | // 89 | // file3.js 90 | // ⋮... 91 | // █function multiply(a, b) { 92 | // ⋮... 93 | ``` 94 | 95 | `getOutlines` 96 | 97 | This function generates an outline for a set of files by only displaying the definition lines. It takes an array of objects, each containing the path and source code for a file. The function generates outlines for each of the files, concatenates all of them, and returns the result as a single string. 98 | 99 | ```typescript 100 | const sources = [ 101 | { 102 | relPath: 'file1.js', 103 | code: ` 104 | function add(a, b) { 105 | return a + b; 106 | }`, 107 | }, 108 | { 109 | relPath: 'file2.js', 110 | code: ` 111 | function subtract(a, b) { 112 | return a - b; 113 | }`, 114 | }, 115 | ]; 116 | 117 | const outlines = await getOutlines(sources); 118 | 119 | console.log(outlines); 120 | // Output: 121 | // file1.js 122 | // █function add(a, b) { 123 | // ⋮... 124 | // 125 | // file2.js 126 | // █function subtract(a, b) { 127 | // ⋮... 128 | ``` 129 | 130 | Please refer to the source code for more details and options. 131 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | roots: ['/src'], 3 | transform: { 4 | '^.+\\.tsx?$': 'ts-jest', 5 | }, 6 | testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$', 7 | moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], 8 | }; 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "llm-code-highlighter", 3 | "version": "0.0.14", 4 | "description": "Condense source code for LLM analysis by extracting essential highlights, utilizing a simplified version of Paul Gauthier's repomap technique from Aider Chat.", 5 | "repository": { 6 | "type": "git", 7 | "url": "git+https://github.com/restlessronin/llm-code-highlighter.git" 8 | }, 9 | "bugs": { 10 | "url": "https://github.com/restlessronin/llm-code-highlighter/issues" 11 | }, 12 | "homepage": "https://github.com/restlessronin/llm-code-highlighter#readme", 13 | "main": "dist/index.node.js", 14 | "browser": { 15 | "entry-point": "dist/index.browser.js", 16 | "fs": false, 17 | "path": false 18 | }, 19 | "scripts": { 20 | "test": "jest", 21 | "copy:scheme": "cpy 'src/tag-qry/**/*' 'dist/tag-qry/' --parents", 22 | "build:tsc": "tsc", 23 | "build:webpack": "webpack --config webpack.config.ts", 24 | "build": "npm run copy:scheme && npm run build:tsc && npm run build:webpack" 25 | }, 26 | "keywords": [], 27 | "author": "restlessronin", 28 | "license": "Apache-2.0", 29 | "devDependencies": { 30 | "@babel/register": "^7.23.7", 31 | "@swc/register": "^0.1.10", 32 | "@types/jest": "^29.5.11", 33 | "@types/lodash": "^4.14.202", 34 | "@types/node": "^20.11.24", 35 | "@types/webpack": "^5.28.5", 36 | "@typescript-eslint/eslint-plugin": "^7.1.0", 37 | "@typescript-eslint/parser": "^7.1.0", 38 | "cpy-cli": "^5.0.0", 39 | "esbuild-register": "^3.5.0", 40 | "eslint": "^8.56.0", 41 | "eslint-config-airbnb": "^19.0.4", 42 | "eslint-config-prettier": "^9.1.0", 43 | "jest": "^29.7.0", 44 | "raw-loader": "^4.0.2", 45 | "sucrase": "^3.35.0", 46 | "ts-jest": "^29.1.1", 47 | "ts-loader": "^9.5.1", 48 | "ts-node": "^10.9.2", 49 | "typescript": "^5.3.3", 50 | "webpack": "^5.90.3", 51 | "webpack-cli": "^5.1.4" 52 | }, 53 | "dependencies": { 54 | "graphology": "^0.25.4", 55 | "graphology-metrics": "^2.2.0", 56 | "lodash": "^4.17.21", 57 | "tree-sitter-wasms": "^0.1.6", 58 | "web-tree-sitter": "^0.21.0" 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/__test__/Tagger.test.ts: -------------------------------------------------------------------------------- 1 | import { AST } from '../parser/AST'; 2 | import { NodeContentPath } from '../parser/ContentPath.node'; 3 | import { Tagger } from '../tagger/Tagger'; 4 | 5 | describe('Tagger', () => { 6 | const jsQueryScm = ` 7 | ( 8 | (comment)* @doc 9 | . 10 | (method_definition 11 | name: (property_identifier) @name.definition.method) @definition.method 12 | (#not-eq? @name.definition.method "constructor") 13 | (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") 14 | (#select-adjacent! @doc @definition.method) 15 | ) 16 | 17 | ( 18 | (comment)* @doc 19 | . 20 | [ 21 | (class 22 | name: (_) @name.definition.class) 23 | (class_declaration 24 | name: (_) @name.definition.class) 25 | ] @definition.class 26 | (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") 27 | (#select-adjacent! @doc @definition.class) 28 | ) 29 | 30 | ( 31 | (comment)* @doc 32 | . 33 | [ 34 | (function 35 | name: (identifier) @name.definition.function) 36 | (function_declaration 37 | name: (identifier) @name.definition.function) 38 | (generator_function 39 | name: (identifier) @name.definition.function) 40 | (generator_function_declaration 41 | name: (identifier) @name.definition.function) 42 | ] @definition.function 43 | (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") 44 | (#select-adjacent! @doc @definition.function) 45 | ) 46 | 47 | ( 48 | (comment)* @doc 49 | . 50 | (lexical_declaration 51 | (variable_declarator 52 | name: (identifier) @name.definition.function 53 | value: [(arrow_function) (function)]) @definition.function) 54 | (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") 55 | (#select-adjacent! @doc @definition.function) 56 | ) 57 | 58 | ( 59 | (comment)* @doc 60 | . 61 | (variable_declaration 62 | (variable_declarator 63 | name: (identifier) @name.definition.function 64 | value: [(arrow_function) (function)]) @definition.function) 65 | (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") 66 | (#select-adjacent! @doc @definition.function) 67 | ) 68 | 69 | (assignment_expression 70 | left: [ 71 | (identifier) @name.definition.function 72 | (member_expression 73 | property: (property_identifier) @name.definition.function) 74 | ] 75 | right: [(arrow_function) (function)] 76 | ) @definition.function 77 | 78 | (pair 79 | key: (property_identifier) @name.definition.function 80 | value: [(arrow_function) (function)]) @definition.function 81 | 82 | ( 83 | (call_expression 84 | function: (identifier) @name.reference.call) @reference.call 85 | (#not-match? @name.reference.call "^(require)$") 86 | ) 87 | 88 | (call_expression 89 | function: (member_expression 90 | property: (property_identifier) @name.reference.call) 91 | arguments: (_) @reference.call) 92 | 93 | (new_expression 94 | constructor: (_) @name.reference.class) @reference.class 95 | 96 | `; 97 | describe('read for JavaScript file contents', () => { 98 | it('should return an empty array when there are no captures', async () => { 99 | const contentPath = new NodeContentPath(); 100 | const language = 'JavaScript'; 101 | const ast = await AST.createFromCode( 102 | { relPath: 'test.js', code: 'let x = 1;' }, 103 | contentPath.getWasmURL(language), 104 | language 105 | ); 106 | const tagger = Tagger.create(ast, jsQueryScm); 107 | const result = tagger?.read(); 108 | expect(result).toEqual([]); 109 | }); 110 | 111 | it('should return a single reference', async () => { 112 | const contentPath = new NodeContentPath(); 113 | const language = 'JavaScript'; 114 | const ast = await AST.createFromCode( 115 | { 116 | relPath: 'test.js', 117 | code: `let x = 1; 118 | console.log(x);`, 119 | }, 120 | contentPath.getWasmURL(language), 121 | language 122 | ); 123 | const tagger = Tagger.create(ast, jsQueryScm); 124 | const result = tagger?.read(); 125 | expect(result).toEqual([ 126 | { 127 | relPath: 'test.js', 128 | text: 'log', 129 | kind: 'ref', 130 | start: { 131 | ln: 1, 132 | col: 14, 133 | }, 134 | end: { 135 | ln: 1, 136 | col: 17, 137 | }, 138 | }, 139 | ]); 140 | }); 141 | }); 142 | }); 143 | -------------------------------------------------------------------------------- /src/__test__/codefixture.ts: -------------------------------------------------------------------------------- 1 | const test_file_with_identifiers = { 2 | relPath: 'test_file_with_identifiers.py', 3 | code: `class MyClass: 4 | def my_method(self, arg1, arg2): 5 | return arg1 + arg2 6 | 7 | def my_function(arg1, arg2): 8 | return arg1 * arg2 9 | `, 10 | }; 11 | 12 | const test_file_pass = { 13 | relPath: 'test_file_pass.py', 14 | code: `pass`, 15 | }; 16 | 17 | const test_file_import = { 18 | relPath: 'test_file_import.py', 19 | code: `from test_file_with_identifiers import MyClass 20 | 21 | obj = MyClass() 22 | print(obj.my_method(1, 2)) 23 | print(my_function(3, 4)) 24 | `, 25 | }; 26 | 27 | export const test_typescript_code = { 28 | relPath: 'test_typescript_code.ts', 29 | code: `import { Tag } from '../tagger'; 30 | 31 | export class RankedTags { 32 | constructor( 33 | readonly definitions: Map>, 34 | readonly rankedFiles: [string, number][], 35 | readonly rankedDefinitions: [string, number][] 36 | ) {} 37 | 38 | without(chatRelPaths: string[]) { 39 | const filteredFiles = this.rankedFiles.filter( 40 | ([relPath, _]) => !chatRelPaths.includes(relPath) 41 | ); 42 | const filteredDefinitions = this.rankedDefinitions.filter(([key, _]) => { 43 | const [relPath, _ident] = key.split(','); 44 | return !chatRelPaths.includes(relPath); 45 | }); 46 | return new RankedTags(this.definitions, filteredFiles, filteredDefinitions); 47 | } 48 | 49 | toTags() { 50 | return this.rankedDefinitions.reduce((acc: Tag[], [key, _rank]: [string, number]) => { 51 | return [...acc, ...Array.from(this.definitions.get(key) as Set)]; 52 | }, []); 53 | } 54 | 55 | toRankedFiles(files: string[]) { 56 | const missingFiles = files.filter( 57 | file => !this.rankedFiles.some(([relPath, _]) => relPath === file) 58 | ); 59 | return [...this.rankedFiles.map(([relPath, _rank]) => relPath), ...missingFiles]; 60 | } 61 | } 62 | `, 63 | }; 64 | 65 | export const expected_outlines_typescript = ` 66 | test_typescript_code.ts 67 | ⋮... 68 | █export class RankedTags { 69 | ⋮... 70 | █ without(chatRelPaths: string[]) { 71 | ⋮... 72 | █ toTags() { 73 | ⋮... 74 | █ toRankedFiles(files: string[]) { 75 | ⋮... 76 | `; 77 | 78 | export const test_python_code = { 79 | relPath: 'test_python_code.py', 80 | code: `def greet(name): 81 | return f"Hello, {name}!" 82 | 83 | def calculate_area(length, width): 84 | return length * width 85 | 86 | class Point: 87 | def __init__(self, x, y): 88 | self.x = x 89 | self.y = y 90 | 91 | def distance_to(self, other): 92 | dx = self.x - other.x 93 | dy = self.y - other.y 94 | return (dx**2 + dy**2)**0.5 95 | 96 | # Example usage 97 | print(greet("Alice")) 98 | print(calculate_area(5, 3)) 99 | point1 = Point(2, 3) 100 | point2 = Point(4, 5) 101 | print(point1.distance_to(point2)) 102 | `, 103 | }; 104 | 105 | export const expected_outlines_python = ` 106 | test_python_code.py 107 | █def greet(name): 108 | ⋮... 109 | █def calculate_area(length, width): 110 | ⋮... 111 | █class Point: 112 | █ def __init__(self, x, y): 113 | ⋮... 114 | █ def distance_to(self, other): 115 | ⋮... 116 | `; 117 | 118 | export const pythonSources = [test_file_with_identifiers, test_file_import, test_file_pass]; 119 | -------------------------------------------------------------------------------- /src/__test__/highlighter.test.ts: -------------------------------------------------------------------------------- 1 | import { Highlighter } from '../highlighter/Highlighter'; 2 | import { LineOfInterest } from '../highlighter/common'; 3 | import { IContentPath, Source } from '../parser'; 4 | import { NodeContentPath } from '../parser/ContentPath.node'; 5 | 6 | async function generateFileHighlights( 7 | source: Source, 8 | linesOfInterest: LineOfInterest[], 9 | contentPath: IContentPath 10 | ) { 11 | const highlighter = await Highlighter.createFromLOI(linesOfInterest, source, contentPath); 12 | if (!highlighter) return; 13 | return highlighter.toHighlights(); 14 | } 15 | 16 | describe('CodeHighlighter', () => { 17 | it('should format python code correctly', async () => { 18 | const repomap = await generateFileHighlights( 19 | { 20 | relPath: 'test.py', 21 | code: `class MyClass: 22 | def my_method(self, arg1, arg2): 23 | return arg1 + arg2 24 | 25 | def my_function(arg1, arg2): 26 | return arg1 * arg2`, 27 | }, 28 | [1, 4], 29 | new NodeContentPath() 30 | ); 31 | const expectedOutput = ` 32 | test.py 33 | │class MyClass: 34 | █ def my_method(self, arg1, arg2): 35 | ⋮... 36 | █def my_function(arg1, arg2): 37 | ⋮... 38 | `; 39 | expect(repomap).toBe(expectedOutput); 40 | }); 41 | }); 42 | -------------------------------------------------------------------------------- /src/__test__/index.node.test.ts: -------------------------------------------------------------------------------- 1 | import { getHighlightsThatFit, getOutlines, ILLMContextSizer } from '../index.node'; 2 | 3 | class NumCharsSizer implements ILLMContextSizer { 4 | constructor(readonly sizeInChars: number) {} 5 | fits(content: string): boolean { 6 | return content.length <= this.sizeInChars; 7 | } 8 | } 9 | 10 | describe('getHighlightsThatFit', () => { 11 | it('should return the concatenated highlights for the top percentile of non-chat tags', async () => { 12 | const contextSizer = new NumCharsSizer(100); 13 | const chatSources = [ 14 | { 15 | relPath: 'chat1.js', 16 | code: ` 17 | console.log(add(1, 2)); 18 | `, 19 | }, 20 | { 21 | relPath: 'chat2.js', 22 | code: ` 23 | console.log(multiply(3, 1)); 24 | `, 25 | }, 26 | ]; 27 | 28 | const otherSources = [ 29 | { 30 | relPath: 'file1.js', 31 | code: ` 32 | function add(a, b) { 33 | return a + b; 34 | } 35 | console.log(add(1, 2)); 36 | `, 37 | }, 38 | { 39 | relPath: 'file2.js', 40 | code: ` 41 | function subtract(a, b) { 42 | return a - b; 43 | } 44 | console.log(subtract(3, 1)); 45 | `, 46 | }, 47 | { 48 | relPath: 'file3.js', 49 | code: ` 50 | function multiply(a, b) { 51 | return a * b; 52 | } 53 | console.log(multiply(2, 3)); 54 | `, 55 | }, 56 | ]; 57 | 58 | const result = await getHighlightsThatFit(contextSizer, chatSources, otherSources); 59 | 60 | expect(result).toBe(` 61 | file1.js 62 | ⋮... 63 | █function add(a, b) { 64 | ⋮... 65 | 66 | file3.js 67 | ⋮... 68 | █function multiply(a, b) { 69 | ⋮... 70 | `); 71 | }); 72 | }); 73 | 74 | describe('getFileOutlineHighlights', () => { 75 | it('should return the concatenated outlines for all the files', async () => { 76 | const sources = [ 77 | { 78 | relPath: 'file1.js', 79 | code: `function add(a, b) { 80 | return a + b; 81 | }`, 82 | }, 83 | { 84 | relPath: 'file2.js', 85 | code: `function subtract(a, b) { 86 | return a - b; 87 | }`, 88 | }, 89 | ]; 90 | 91 | const result = await getOutlines(sources); 92 | 93 | expect(result).toBe(` 94 | file1.js 95 | █function add(a, b) { 96 | ⋮... 97 | 98 | file2.js 99 | █function subtract(a, b) { 100 | ⋮... 101 | `); 102 | }); 103 | }); 104 | -------------------------------------------------------------------------------- /src/__test__/outliner.test.ts: -------------------------------------------------------------------------------- 1 | import { CodeTagExtractor } from '../tagger/CodeTagExtractor'; 2 | import { NodeContentPath } from '../parser/ContentPath.node'; 3 | import { DefRef } from '../tagger/DefRef'; 4 | import { 5 | test_typescript_code, 6 | expected_outlines_typescript, 7 | test_python_code, 8 | expected_outlines_python, 9 | } from './codefixture'; 10 | import { Outliner } from '../outliner/Outliner'; 11 | import { Tag } from '../tagger'; 12 | 13 | async function generateFileOutlineFromTags(fileTags: Tag[], code: string) { 14 | const highlighter = await Outliner.create(fileTags, code); 15 | if (!highlighter) return; 16 | return highlighter.toHighlights(); 17 | } 18 | 19 | describe('outliner', () => { 20 | let extractor: CodeTagExtractor; 21 | let contentPath: NodeContentPath; 22 | 23 | beforeEach(async () => { 24 | contentPath = new NodeContentPath(); 25 | extractor = new CodeTagExtractor('', contentPath); 26 | }); 27 | 28 | describe('create', () => { 29 | it('should create a new DefRef instance', async () => { 30 | const defRef = await DefRef.create(extractor, test_typescript_code); 31 | expect(defRef).toBeInstanceOf(DefRef); 32 | }); 33 | }); 34 | 35 | describe('highlight outline', () => { 36 | it('should return python definitions', async () => { 37 | const defRef = await DefRef.create(extractor, test_python_code); 38 | const defs = defRef.defs; 39 | const outline = await generateFileOutlineFromTags(defs, test_python_code.code); 40 | expect(outline).toBe(expected_outlines_python); 41 | }); 42 | 43 | it('should return typescript definitions', async () => { 44 | const defRef = await DefRef.create(extractor, test_typescript_code); 45 | const defs = defRef.defs; 46 | if (!defs || defs.length === 0) return; 47 | const outline = await generateFileOutlineFromTags(defs, test_typescript_code.code); 48 | expect(outline).toBe(expected_outlines_typescript); 49 | }); 50 | }); 51 | }); 52 | -------------------------------------------------------------------------------- /src/__test__/ranker.test.ts: -------------------------------------------------------------------------------- 1 | import { CodeTagExtractor } from '../tagger/CodeTagExtractor'; 2 | import { NodeContentPath } from '../parser/ContentPath.node'; 3 | import { DefRefs } from '../tagger/DefRefs'; 4 | import { TagRanker } from '../ranker/TagRanker'; 5 | import { pythonSources } from './codefixture'; 6 | 7 | describe('TagRanker', () => { 8 | let tagRanker: TagRanker; 9 | 10 | beforeEach(async () => { 11 | const extractor = new CodeTagExtractor('', new NodeContentPath()); 12 | const defRefs = await DefRefs.create(extractor, pythonSources); 13 | const tags = defRefs!.createTags(); 14 | tagRanker = new TagRanker(tags!); 15 | }); 16 | 17 | describe('create', () => { 18 | it('should create a new TagRanker instance', async () => { 19 | expect(tagRanker).toBeInstanceOf(TagRanker); 20 | }); 21 | }); 22 | 23 | describe('pagerank', () => { 24 | it('should return ranked definitions', () => { 25 | const rankedTagRanker = tagRanker.pagerank(); 26 | expect(rankedTagRanker!.rankedDefinitions).toEqual(expect.any(Array)); 27 | }); 28 | }); 29 | }); 30 | -------------------------------------------------------------------------------- /src/highlighter/CodeHighlighter.ts: -------------------------------------------------------------------------------- 1 | import { LineOfInterest } from './common'; 2 | 3 | export class CodeHighlighter { 4 | constructor( 5 | readonly codeLines: string[], 6 | readonly linesOfInterest: LineOfInterest[], 7 | readonly showLines: LineOfInterest[] 8 | ) {} 9 | 10 | withSmallGapsClosed(): CodeHighlighter { 11 | const closedShow = new Set(); 12 | const sortedShow = Array.from(this.showLines).sort((a, b) => a - b); 13 | for (let i = 0; i < sortedShow.length - 1; i++) { 14 | closedShow.add(sortedShow[i]); 15 | if (sortedShow[i + 1] - sortedShow[i] === 2) { 16 | closedShow.add(sortedShow[i] + 1); 17 | } 18 | } 19 | if (sortedShow.length > 0) { 20 | closedShow.add(sortedShow[sortedShow.length - 1]); 21 | } 22 | return new CodeHighlighter(this.codeLines, this.linesOfInterest, Array.from(closedShow)); 23 | } 24 | 25 | toFormattedString(): string { 26 | return this.codeLines.reduce((acc, line, i) => { 27 | return acc + this.formatLine(line, i); 28 | }, ''); 29 | } 30 | 31 | private formatLine(lineContent: string, i: number) { 32 | const isLineOfInterest = this.linesOfInterest.includes(i); 33 | const shouldShowLine = this.showLines.includes(i); 34 | if (shouldShowLine) { 35 | const linePrefix = isLineOfInterest ? '█' : '│'; 36 | return `${linePrefix}${lineContent}\n`; 37 | } else { 38 | return i === 0 || this.showLines.includes(i - 1) ? '⋮...\n' : ''; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/highlighter/CodelineScoper.ts: -------------------------------------------------------------------------------- 1 | import { Parser } from '../parser/TreeSitter'; 2 | import { LineScoper } from './LineScoper'; 3 | import { LineRange, ScopeStarts, Scopes } from './common'; 4 | 5 | export class CodelineScoper { 6 | static create(numLines: number) { 7 | const scopes: [number, number, number][][] = new Array<[number, number, number][]>(numLines) 8 | .fill([]) 9 | .map(() => []); 10 | return new CodelineScoper(numLines, scopes); 11 | } 12 | 13 | constructor(readonly numLines: number, readonly scopes: Scopes[]) {} 14 | 15 | withScopeDataInitialized(node: Parser.SyntaxNode, depth: number = 0) { 16 | const startLine = node.startPosition.row; 17 | const endLine = node.endPosition.row; 18 | const size = endLine - startLine; 19 | if (size) { 20 | this.scopes[startLine].push([size, startLine, endLine]); 21 | } 22 | node.children.forEach(child => this.withScopeDataInitialized(child, depth + 1)); 23 | return this; 24 | } 25 | 26 | toDominantScopes(codeLines: string[]) { 27 | const scopes = new Array(this.numLines); 28 | for (let i = 0; i < this.numLines; i++) { 29 | const scopesI = this.scopes[i].sort((a, b) => { 30 | for (let i = 0; i < 3; i++) { 31 | if (a[i] < b[i]) return -1; 32 | else if (a[i] > b[i]) return 1; 33 | } 34 | return 0; 35 | }); 36 | scopes[i] = scopesI.length > 1 ? (scopesI[0].slice(1) as LineRange) : [0, -1]; 37 | } 38 | const scopeStarts: ScopeStarts[] = new Array(this.numLines).fill(new Set()); 39 | scopes.forEach(([startLine, endLine]) => { 40 | for (let i = startLine; i <= endLine; i++) { 41 | scopeStarts[i].add(startLine); 42 | } 43 | }); 44 | return new LineScoper(codeLines, scopeStarts); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/highlighter/Highlighter.ts: -------------------------------------------------------------------------------- 1 | import { IContentPath, Source, AST } from '../parser'; 2 | import { Tag, createAST } from '../tagger'; 3 | import { LineOfInterest } from './common'; 4 | import { CodelineScoper } from './CodelineScoper'; 5 | 6 | export class Highlighter { 7 | static async create(fileTags: Tag[], code: string, contentPath: IContentPath) { 8 | const relPath = fileTags[0].relPath; 9 | const linesOfInterest = fileTags.map(tag => tag.start.ln); 10 | const source = { relPath: relPath, code: code }; 11 | return await Highlighter.createFromLOI(linesOfInterest, source, contentPath); 12 | } 13 | 14 | static async createFromLOI( 15 | linesOfInterest: LineOfInterest[], 16 | source: Source, 17 | contentPath: IContentPath 18 | ) { 19 | const ast = await createAST(source, contentPath); 20 | if (!ast) return; 21 | return new Highlighter(source, linesOfInterest, ast); 22 | } 23 | 24 | constructor( 25 | readonly source: Source, 26 | readonly linesOfInterest: LineOfInterest[], 27 | readonly ast: AST 28 | ) {} 29 | 30 | toHighlights() { 31 | const codeLines = this.source.code.split('\n'); 32 | const scopeTracker = CodelineScoper.create(codeLines.length).withScopeDataInitialized( 33 | this.ast.tree.rootNode 34 | ); 35 | const scopes = scopeTracker.toDominantScopes(codeLines); 36 | const highlighter = scopes.toCodeHighlighter(this.linesOfInterest); 37 | if (!highlighter) return; 38 | const highlights = highlighter.withSmallGapsClosed().toFormattedString(); 39 | return `\n${this.source.relPath}\n${highlights}`; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/highlighter/Highlights.ts: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | import { IContentPath, Source } from '../parser'; 3 | import { createRankedTags } from '../ranker'; 4 | import { RankedTags } from '../ranker/RankedTags'; 5 | import { Highlighter } from './Highlighter'; 6 | 7 | export class Highlights { 8 | static async create(chatSources: Source[], otherSources: Source[], contentPath: IContentPath) { 9 | const allSources = [...chatSources, ...otherSources]; 10 | const rankedTags = await createRankedTags({ sources: allSources, contentPath: contentPath }); 11 | if (!rankedTags) return; 12 | const chatRelPaths = chatSources.map(source => source.relPath); 13 | return new Highlights(rankedTags.without(chatRelPaths), allSources, contentPath); 14 | } 15 | 16 | constructor( 17 | readonly rankedTags: RankedTags, 18 | readonly allSources: Source[], 19 | readonly contentPath: IContentPath 20 | ) {} 21 | 22 | async toCodeHighlights(percentile: number) { 23 | const topTags = this.rankedTags.toTags(); 24 | const maxTags = _.round(percentile * topTags.length); 25 | const mapTags = topTags.slice(0, maxTags); 26 | const sortedTags = _.orderBy(mapTags, ['relPath', 'start.ln'], ['asc', 'asc']); 27 | const groupedTags = _.groupBy(sortedTags, tag => tag.relPath); 28 | const fileHighlights = await Promise.all( 29 | _.values(groupedTags).map(async tags => { 30 | const relPath = tags[0].relPath; 31 | const code = this.allSources.find(source => source.relPath === relPath)!.code; 32 | const highlighter = await Highlighter.create(tags, code, this.contentPath); 33 | if (!highlighter) return; 34 | return highlighter.toHighlights(); 35 | }) 36 | ); 37 | return _.join(fileHighlights, ''); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/highlighter/LineScoper.ts: -------------------------------------------------------------------------------- 1 | import { CodeHighlighter } from './CodeHighlighter'; 2 | import { ScopeStarts } from './common'; 3 | 4 | export class LineScoper { 5 | constructor(readonly codeLines: string[], readonly scopeStarts: ScopeStarts[]) {} 6 | 7 | parentScopes(lineNumbers: number[]) { 8 | return Array.from(lineNumbers) 9 | .map(lineOfInterest => this.scopeStarts[lineOfInterest]) 10 | .filter(scopeStarts => scopeStarts.size > 0) 11 | .reduce((acc, scopeStarts) => { 12 | return new Set([...acc, ...scopeStarts]); 13 | }, new Set()); 14 | } 15 | 16 | toCodeHighlighter(lineNumbers: number[]) { 17 | if (lineNumbers.length === 0) return; 18 | const parentScopes = this.parentScopes(lineNumbers); 19 | const allLines = Array.from(new Set([...parentScopes, ...new Set(lineNumbers)])); 20 | const linesOfInterest = [...lineNumbers].sort((a, b) => a - b); 21 | const showLines = [...allLines].sort((a, b) => a - b); 22 | return new CodeHighlighter(this.codeLines, linesOfInterest, showLines); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/highlighter/common.ts: -------------------------------------------------------------------------------- 1 | export type LineOfInterest = number; 2 | export type ScopeStarts = Set; 3 | export type Scopes = [number, number, number][]; 4 | export type LineRange = [number, number]; 5 | -------------------------------------------------------------------------------- /src/highlighter/index.ts: -------------------------------------------------------------------------------- 1 | export { Highlights } from './Highlights'; 2 | -------------------------------------------------------------------------------- /src/index.browser.ts: -------------------------------------------------------------------------------- 1 | import { ILLMContextSizer, outlines, highlightsThatFit } from './index.shared'; 2 | import { Source } from './parser'; 3 | import { BrowserContentPath } from './parser/ContentPath.browser'; 4 | 5 | export async function getHighlightsThatFit( 6 | contextSizer: ILLMContextSizer, 7 | chatSources: { relPath: string; code: string }[], 8 | otherSources: { relPath: string; code: string }[] 9 | ) { 10 | return highlightsThatFit(contextSizer, chatSources, otherSources, new BrowserContentPath()); 11 | } 12 | 13 | export async function getOutlines(sources: Source[]) { 14 | return outlines({ sources: sources, contentPath: new BrowserContentPath() }); 15 | } 16 | 17 | export { ILLMContextSizer }; 18 | -------------------------------------------------------------------------------- /src/index.continue.ts: -------------------------------------------------------------------------------- 1 | import { ILLMContextSizer, outlines, highlightsThatFit } from './index.shared'; 2 | import { Source } from './parser'; 3 | import { ContinueContentPath } from './parser/ContentPath.continue'; 4 | 5 | export async function getHighlightsThatFit( 6 | contextSizer: ILLMContextSizer, 7 | chatSources: { relPath: string; code: string }[], 8 | otherSources: { relPath: string; code: string }[] 9 | ) { 10 | return highlightsThatFit(contextSizer, chatSources, otherSources, new ContinueContentPath()); 11 | } 12 | 13 | export async function getOutlines(sources: Source[]) { 14 | return outlines({ sources: sources, contentPath: new ContinueContentPath() }); 15 | } 16 | 17 | export { ILLMContextSizer }; 18 | -------------------------------------------------------------------------------- /src/index.node.ts: -------------------------------------------------------------------------------- 1 | import { ILLMContextSizer, outlines, highlightsThatFit } from './index.shared'; 2 | import { Source } from './parser'; 3 | import { NodeContentPath } from './parser/ContentPath.node'; 4 | 5 | /** 6 | * Generates highlights for a source set by selecting the top ranked tags from non-chat sources, 7 | * that will fit in the context. 8 | * 9 | * It ranks all tags across the source set using PageRank, filters out tags from chat sources, 10 | * groups them by file, and generates highlights for each file. 11 | * 12 | * If the concatenated highlights do not fit in context a binary search on percentile is carried out 13 | * until a result is found that fits. 14 | * 15 | * @param contextSizer: - The context sizer that determines if the highlights will fit in the context. 16 | * @param chatSources - The source code files that are from chat. 17 | * @param otherSources - The source code files that are not from chat. 18 | * @returns The concatenated highlights for the top percentile of non-chat tags. 19 | */ 20 | export async function getHighlightsThatFit( 21 | contextSizer: ILLMContextSizer, 22 | chatSources: { relPath: string; code: string }[], 23 | otherSources: { relPath: string; code: string }[] 24 | ) { 25 | return highlightsThatFit(contextSizer, chatSources, otherSources, new NodeContentPath()); 26 | } 27 | 28 | /** 29 | * Generates an outline for a set of files by only displaying the definition lines. 30 | * 31 | * The outlines are concatenated and returned. 32 | * 33 | * @param sources - An array of objects, each having the path and source code for a file 34 | * @returns The concatenated outlines for all the files. 35 | */ 36 | export async function getOutlines(sources: Source[]) { 37 | return outlines({ sources: sources, contentPath: new NodeContentPath() }); 38 | } 39 | 40 | export { ILLMContextSizer }; 41 | -------------------------------------------------------------------------------- /src/index.shared.ts: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | import { IContentPath, Source, SourceSet } from './parser'; 3 | import { Highlights } from './highlighter'; 4 | import { Outlines } from './outliner'; 5 | 6 | export interface ILLMContextSizer { 7 | fits(content: string): boolean; 8 | } 9 | 10 | export async function highlightsThatFit( 11 | contextSizer: ILLMContextSizer, 12 | chatSources: Source[], 13 | otherSources: Source[], 14 | contentPath: IContentPath 15 | ) { 16 | const highlights = await Highlights.create(chatSources, otherSources, contentPath); 17 | if (!highlights) return; 18 | let loPercentile = 0; 19 | let hiPercentile = 1; 20 | let percentile = 1; 21 | let highlightedCode; 22 | while (0.001 <= Math.abs(hiPercentile - loPercentile)) { 23 | highlightedCode = await highlights.toCodeHighlights(percentile); 24 | const fits = !highlightedCode || contextSizer.fits(highlightedCode); 25 | loPercentile = fits ? percentile : loPercentile; 26 | hiPercentile = fits ? hiPercentile : percentile; 27 | percentile = (loPercentile + hiPercentile) / 2; 28 | } 29 | return highlightedCode; 30 | } 31 | 32 | export async function outlines(sourceSet: SourceSet) { 33 | const outlines = await Outlines.create(sourceSet); 34 | if (!outlines) return; 35 | return outlines.toCodeOutlines(); 36 | } 37 | -------------------------------------------------------------------------------- /src/outliner/Outliner.ts: -------------------------------------------------------------------------------- 1 | import { Source } from '../parser'; 2 | import { Tag } from '../tagger'; 3 | import { LineOfInterest } from '../highlighter/common'; 4 | import { CodeHighlighter } from '../highlighter/CodeHighlighter'; 5 | 6 | export class Outliner { 7 | static async create(fileTags: Tag[], code: string) { 8 | const relPath = fileTags[0].relPath; 9 | const linesOfInterest = fileTags.map(tag => tag.start.ln); 10 | const source = { relPath: relPath, code: code }; 11 | return Outliner.createFromLOI(linesOfInterest, source); 12 | } 13 | 14 | static async createFromLOI(linesOfInterest: LineOfInterest[], source: Source) { 15 | return new Outliner(source, linesOfInterest); 16 | } 17 | 18 | constructor(readonly source: Source, readonly linesOfInterest: LineOfInterest[]) {} 19 | 20 | toHighlights() { 21 | const codeLines = this.source.code.split('\n'); 22 | const highlighter = new CodeHighlighter( 23 | codeLines, 24 | Array.from(this.linesOfInterest).sort((a, b) => a - b), 25 | Array.from(new Set(this.linesOfInterest)).sort((a, b) => a - b) 26 | ); 27 | if (!highlighter) return; 28 | const highlights = highlighter.toFormattedString(); 29 | return `\n${this.source.relPath}\n${highlights}`; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/outliner/Outlines.ts: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | import { SourceSet } from '../parser'; 3 | import { DefRef, Tag } from '../tagger'; 4 | import { CodeTagExtractor } from '../tagger/CodeTagExtractor'; 5 | import { Outliner } from './Outliner'; 6 | 7 | export class Outlines { 8 | static async create(sourceSet: SourceSet) { 9 | const extractor = new CodeTagExtractor('', sourceSet.contentPath); 10 | const defs = await Promise.all( 11 | sourceSet.sources.map(async source => { 12 | return DefRef.create(extractor, source); 13 | }) 14 | ); 15 | return new Outlines( 16 | defs.map(defRef => defRef.defs), 17 | sourceSet 18 | ); 19 | } 20 | 21 | constructor(readonly defs: Tag[][], readonly sourceSet: SourceSet) {} 22 | 23 | async toCodeOutlines() { 24 | const codeOutlines = await Promise.all( 25 | _.zip(this.defs, this.sourceSet.sources) 26 | .filter(([tags, _sources]) => { 27 | return tags; 28 | }) 29 | .map(async ([tags, source]) => { 30 | const highlighter = await Outliner.create(tags!, source!.code); 31 | if (!highlighter) return; 32 | return highlighter.toHighlights(); 33 | }) 34 | ); 35 | return _.join(codeOutlines, ''); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/outliner/index.ts: -------------------------------------------------------------------------------- 1 | export { Outlines } from './Outlines'; 2 | -------------------------------------------------------------------------------- /src/parser/AST.ts: -------------------------------------------------------------------------------- 1 | import { Source } from './common'; 2 | import { TreeSitter, Parser } from './TreeSitter'; 3 | 4 | export class AST { 5 | static async createFromCode(source: Source, wasmPath: string, language: string) { 6 | const treeSitter = await TreeSitter.create(wasmPath, language); 7 | const tree = treeSitter.parse(source.code); 8 | return new AST(treeSitter, tree, source.relPath); 9 | } 10 | 11 | constructor( 12 | readonly treeSitter: TreeSitter, 13 | public readonly tree: Parser.Tree, 14 | public readonly relPath: string 15 | ) {} 16 | 17 | captures(queryScm: string): Parser.QueryCapture[] { 18 | const query = this.treeSitter.parser.getLanguage().query(queryScm); 19 | return query.captures(this.tree.rootNode); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/parser/ContentPath.browser.ts: -------------------------------------------------------------------------------- 1 | import { getQueryFileName, getWasmPath } from './lang-utils'; 2 | import { IContentPath } from './common'; 3 | 4 | const qryFiles = require.context('../tag-qry', false, /\.scm$/); 5 | const wasmRoot = 'https://unpkg.com/browse/tree-sitter-wasms@latest/out/'; 6 | 7 | export class BrowserContentPath implements IContentPath { 8 | getQuery(language: string): string { 9 | return qryFiles(`./${getQueryFileName(language)!}`); 10 | } 11 | getWasmURL(language: string): string { 12 | return `${wasmRoot}${getWasmPath(language)}`; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/parser/ContentPath.continue.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs'; 2 | import { getQueryFileName, getWasmPath } from './lang-utils'; 3 | import { IContentPath } from './common'; 4 | 5 | export class ContinueContentPath implements IContentPath { 6 | getQuery(language: string): string { 7 | console.log(__dirname); 8 | console.log(__filename); 9 | const queryFileName = `${__dirname}/tag-qry/${getQueryFileName(language)!}`; 10 | return fs.readFileSync(queryFileName, 'utf8'); 11 | } 12 | 13 | getWasmURL(language: string): string { 14 | return `${__dirname}/tree-sitter-wasms/${getWasmPath(language)}`; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/parser/ContentPath.node.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs'; 2 | import { getQueryFileName, getWasmPath } from './lang-utils'; 3 | import { IContentPath } from './common'; 4 | 5 | export class NodeContentPath implements IContentPath { 6 | getQuery(language: string): string { 7 | const queryFileName = `${__dirname}/../tag-qry/${getQueryFileName(language)!}`; 8 | return fs.readFileSync(queryFileName, 'utf8'); 9 | } 10 | 11 | getWasmURL(language: string): string { 12 | return require.resolve(`tree-sitter-wasms/out/${getWasmPath(language)}`); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/parser/TreeSitter.ts: -------------------------------------------------------------------------------- 1 | import Parser from 'web-tree-sitter'; 2 | 3 | const parserInitPromise = Parser.init(); 4 | 5 | export class TreeSitter { 6 | static async create(wasmPath: string, language: string) { 7 | await parserInitPromise; 8 | const languageWasm = await Parser.Language.load(wasmPath)!; 9 | const parser = new Parser(); 10 | parser.setLanguage(languageWasm); 11 | return new TreeSitter(parser, language); 12 | } 13 | 14 | constructor(readonly parser: Parser, readonly language: any) {} 15 | 16 | parse(code: string): Parser.Tree { 17 | return this.parser.parse(code); 18 | } 19 | } 20 | 21 | export { Parser }; 22 | -------------------------------------------------------------------------------- /src/parser/common.ts: -------------------------------------------------------------------------------- 1 | export type Source = { relPath: string; code: string }; 2 | 3 | export type SourceSet = { contentPath: IContentPath; sources: Source[] }; 4 | 5 | export interface IContentPath { 6 | getQuery(language: string): string; 7 | getWasmURL(language: string): string; 8 | } 9 | -------------------------------------------------------------------------------- /src/parser/index.ts: -------------------------------------------------------------------------------- 1 | export { getLanguage, Language } from './lang-utils'; 2 | export { Source, IContentPath, SourceSet } from './common'; 3 | export { AST } from './AST'; 4 | -------------------------------------------------------------------------------- /src/parser/lang-utils.ts: -------------------------------------------------------------------------------- 1 | export type Language = 2 | | 'C' 3 | | 'C#' 4 | | 'C++' 5 | | 'Elisp' 6 | | 'Elixir' 7 | | 'Elm' 8 | | 'Go' 9 | | 'Java' 10 | | 'JavaScript' 11 | | 'Ocaml' 12 | | 'PHP' 13 | | 'Python' 14 | | 'QL' 15 | | 'Ruby' 16 | | 'Rust' 17 | | 'TypeScript'; 18 | 19 | const extToLang: Record = { 20 | py: 'Python', 21 | js: 'JavaScript', 22 | mjs: 'JavaScript', 23 | go: 'Go', 24 | c: 'C', 25 | cc: 'C++', 26 | cs: 'C#', 27 | cpp: 'C++', 28 | el: 'Elisp', 29 | ex: 'Elixir', 30 | elm: 'Elm', 31 | java: 'Java', 32 | ml: 'Ocaml', 33 | php: 'PHP', 34 | ql: 'QL', 35 | rb: 'Ruby', 36 | rs: 'Rust', 37 | ts: 'TypeScript', 38 | }; 39 | 40 | const lang2QryNameString: Record = { 41 | C: 'c', 42 | 'C#': 'c_sharp', 43 | 'C++': 'cpp', 44 | Elisp: 'elisp', 45 | Elixir: 'elixir', 46 | Elm: 'elm', 47 | Go: 'go', 48 | Java: 'java', 49 | JavaScript: 'javascript', 50 | Ocaml: 'ocaml', 51 | PHP: 'php', 52 | Python: 'python', 53 | QL: 'ql', 54 | Ruby: 'ruby', 55 | Rust: 'rust', 56 | TypeScript: 'typescript', 57 | }; 58 | 59 | export function getLanguage(filename: string) { 60 | const extension = filename.split('.').pop(); 61 | if (!extension || !(extension in extToLang)) return; 62 | return extToLang[extension]; 63 | } 64 | 65 | export function getQueryFileName(lang: string) { 66 | if (!(lang in lang2QryNameString)) return; 67 | return `tree-sitter-${lang2QryNameString[lang as Language]}-tags.scm`; 68 | } 69 | 70 | export function getWasmPath(lang: string) { 71 | if (!(lang in lang2QryNameString)) return; 72 | return `tree-sitter-${lang2QryNameString[lang as Language]}.wasm`; 73 | } 74 | -------------------------------------------------------------------------------- /src/ranker/RankedTags.ts: -------------------------------------------------------------------------------- 1 | import { Tag } from '../tagger'; 2 | 3 | export class RankedTags { 4 | constructor( 5 | readonly definitions: Map>, 6 | readonly rankedFiles: [string, number][], 7 | readonly rankedDefinitions: [string, number][] 8 | ) {} 9 | 10 | without(chatRelPaths: string[]) { 11 | const filteredFiles = this.rankedFiles.filter( 12 | ([relPath, _]) => !chatRelPaths.includes(relPath) 13 | ); 14 | const filteredDefinitions = this.rankedDefinitions.filter(([key, _]) => { 15 | const [relPath, _ident] = key.split(','); 16 | return !chatRelPaths.includes(relPath); 17 | }); 18 | return new RankedTags(this.definitions, filteredFiles, filteredDefinitions); 19 | } 20 | 21 | toTags() { 22 | return this.rankedDefinitions.reduce((acc: Tag[], [key, _rank]: [string, number]) => { 23 | return [...acc, ...Array.from(this.definitions.get(key) as Set)]; 24 | }, []); 25 | } 26 | 27 | toRankedFiles(files: string[]) { 28 | const missingFiles = files.filter( 29 | file => !this.rankedFiles.some(([relPath, _]) => relPath === file) 30 | ); 31 | return [...this.rankedFiles.map(([relPath, _rank]) => relPath), ...missingFiles]; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/ranker/TagRanker.ts: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | import MultiGraph from 'graphology'; 3 | import pagerank from 'graphology-metrics/centrality/pagerank'; 4 | import { AllTags } from '../tagger/AllTags'; 5 | import { RankedTags } from './RankedTags'; 6 | 7 | export class TagRanker { 8 | constructor(readonly tags: AllTags) {} 9 | 10 | pagerank() { 11 | class _Counter extends Map { 12 | constructor(iterable: Iterable = []) { 13 | super(); 14 | for (let item of iterable) { 15 | this.add(item); 16 | } 17 | } 18 | 19 | add(item: any) { 20 | this.set(item, (this.get(item) || 0) + 1); 21 | } 22 | } 23 | 24 | const tags = this.tags; 25 | const G = new MultiGraph(); 26 | tags.identifiers.forEach(ident => { 27 | const definers = tags.defines.get(ident); 28 | const counter = new _Counter(tags.references.get(ident)); 29 | counter.forEach((numRefs, referencer) => { 30 | (definers as Set).forEach(definer => { 31 | G.mergeEdge(referencer, definer, { weight: numRefs, ident: ident }); 32 | }); 33 | }); 34 | }); 35 | try { 36 | pagerank.assign(G); 37 | } catch (e) { 38 | console.log(e); 39 | return; 40 | } 41 | const rankedDefinitionsMap = new Map(); 42 | G.nodes().forEach(referencer => { 43 | const refRank = G.getNodeAttribute(referencer, 'pagerank'); 44 | const totalWeight = G.edges(referencer).reduce( 45 | (total, edge) => total + G.getEdgeAttribute(edge, 'weight'), 46 | 0 47 | ); 48 | G.edges(referencer).map(edge => { 49 | const definer: string = G.target(edge); 50 | const data = G.getEdgeAttributes(edge); 51 | const defRank = ((refRank as number) * data['weight']) / totalWeight; 52 | const key = `${definer},${data['ident']}`; 53 | if (!rankedDefinitionsMap.has(key)) rankedDefinitionsMap.set(key, 0); 54 | rankedDefinitionsMap.set(key, (rankedDefinitionsMap.get(key) as number) + defRank); 55 | }); 56 | }); 57 | const rankedFilesMap = G.nodes().reduce((accumulator: Record, node: string) => { 58 | accumulator[node] = G.getNodeAttribute(node, 'pagerank') as number; 59 | return accumulator; 60 | }, {}); 61 | const rankedDefinitions = Array.from(rankedDefinitionsMap.entries()).sort( 62 | (a, b) => b[1] - a[1] 63 | ); 64 | const rankedFiles = Object.entries(rankedFilesMap).sort((a, b) => b[1] - a[1]); 65 | return new RankedTags(tags.definitions, rankedFiles, rankedDefinitions); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/ranker/index.ts: -------------------------------------------------------------------------------- 1 | import { SourceSet } from '../parser'; 2 | import { createTags } from '../tagger'; 3 | import { TagRanker } from './TagRanker'; 4 | 5 | export async function createRankedTags(sourceSet: SourceSet) { 6 | const tags = await createTags(sourceSet); 7 | if (!tags) return; 8 | const tagRanker = new TagRanker(tags); 9 | return tagRanker.pagerank(); 10 | } 11 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-c-tags.scm: -------------------------------------------------------------------------------- 1 | (struct_specifier name: (type_identifier) @name.definition.class body:(_)) @definition.class 2 | 3 | (declaration type: (union_specifier name: (type_identifier) @name.definition.class)) @definition.class 4 | 5 | (function_declarator declarator: (identifier) @name.definition.function) @definition.function 6 | 7 | (type_definition declarator: (type_identifier) @name.definition.type) @definition.type 8 | 9 | (enum_specifier name: (type_identifier) @name.definition.type) @definition.type 10 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-c_sharp-tags.scm: -------------------------------------------------------------------------------- 1 | (class_declaration 2 | name: (identifier) @name.definition.class 3 | ) @definition.class 4 | 5 | (class_declaration 6 | bases: (base_list (_) @name.reference.class) 7 | ) @reference.class 8 | 9 | (interface_declaration 10 | name: (identifier) @name.definition.interface 11 | ) @definition.interface 12 | 13 | (interface_declaration 14 | bases: (base_list (_) @name.reference.interface) 15 | ) @reference.interface 16 | 17 | (method_declaration 18 | name: (identifier) @name.definition.method 19 | ) @definition.method 20 | 21 | (object_creation_expression 22 | type: (identifier) @name.reference.class 23 | ) @reference.class 24 | 25 | (type_parameter_constraints_clause 26 | target: (identifier) @name.reference.class 27 | ) @reference.class 28 | 29 | (type_constraint 30 | type: (identifier) @name.reference.class 31 | ) @reference.class 32 | 33 | (variable_declaration 34 | type: (identifier) @name.reference.class 35 | ) @reference.class 36 | 37 | (invocation_expression 38 | function: 39 | (member_access_expression 40 | name: (identifier) @name.reference.send 41 | ) 42 | ) @reference.send 43 | 44 | (namespace_declaration 45 | name: (identifier) @name.definition.module 46 | ) @definition.module 47 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-cpp-tags.scm: -------------------------------------------------------------------------------- 1 | (struct_specifier name: (type_identifier) @name.definition.class body:(_)) @definition.class 2 | 3 | (declaration type: (union_specifier name: (type_identifier) @name.definition.class)) @definition.class 4 | 5 | (function_declarator declarator: (identifier) @name.definition.function) @definition.function 6 | 7 | (function_declarator declarator: (field_identifier) @name.definition.function) @definition.function 8 | 9 | (function_declarator declarator: (qualified_identifier scope: (namespace_identifier) @scope name: (identifier) @name.definition.method)) @definition.method 10 | 11 | (type_definition declarator: (type_identifier) @name.definition.type) @definition.type 12 | 13 | (enum_specifier name: (type_identifier) @name.definition.type) @definition.type 14 | 15 | (class_specifier name: (type_identifier) @name.definition.class) @definition.class 16 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-elisp-tags.scm: -------------------------------------------------------------------------------- 1 | ;; defun/defsubst 2 | (function_definition name: (symbol) @name.definition.function) @definition.function 3 | 4 | ;; Treat macros as function definitions for the sake of TAGS. 5 | (macro_definition name: (symbol) @name.definition.function) @definition.function 6 | 7 | ;; Match function calls 8 | (list (symbol) @name.reference.function) @reference.function 9 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-elixir-tags.scm: -------------------------------------------------------------------------------- 1 | ; Definitions 2 | 3 | ; * modules and protocols 4 | (call 5 | target: (identifier) @ignore 6 | (arguments (alias) @name.definition.module) 7 | (#match? @ignore "^(defmodule|defprotocol)$")) @definition.module 8 | 9 | ; * functions/macros 10 | (call 11 | target: (identifier) @ignore 12 | (arguments 13 | [ 14 | ; zero-arity functions with no parentheses 15 | (identifier) @name.definition.function 16 | ; regular function clause 17 | (call target: (identifier) @name.definition.function) 18 | ; function clause with a guard clause 19 | (binary_operator 20 | left: (call target: (identifier) @name.definition.function) 21 | operator: "when") 22 | ]) 23 | (#match? @ignore "^(def|defp|defdelegate|defguard|defguardp|defmacro|defmacrop|defn|defnp)$")) @definition.function 24 | 25 | ; References 26 | 27 | ; ignore calls to kernel/special-forms keywords 28 | (call 29 | target: (identifier) @ignore 30 | (#match? @ignore "^(def|defp|defdelegate|defguard|defguardp|defmacro|defmacrop|defn|defnp|defmodule|defprotocol|defimpl|defstruct|defexception|defoverridable|alias|case|cond|else|for|if|import|quote|raise|receive|require|reraise|super|throw|try|unless|unquote|unquote_splicing|use|with)$")) 31 | 32 | ; ignore module attributes 33 | (unary_operator 34 | operator: "@" 35 | operand: (call 36 | target: (identifier) @ignore)) 37 | 38 | ; * function call 39 | (call 40 | target: [ 41 | ; local 42 | (identifier) @name.reference.call 43 | ; remote 44 | (dot 45 | right: (identifier) @name.reference.call) 46 | ]) @reference.call 47 | 48 | ; * pipe into function call 49 | (binary_operator 50 | operator: "|>" 51 | right: (identifier) @name.reference.call) @reference.call 52 | 53 | ; * modules 54 | (alias) @name.reference.module @reference.module 55 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-elm-tags.scm: -------------------------------------------------------------------------------- 1 | (value_declaration (function_declaration_left (lower_case_identifier) @name.definition.function)) @definition.function 2 | 3 | (function_call_expr (value_expr (value_qid) @name.reference.function)) @reference.function 4 | (exposed_value (lower_case_identifier) @name.reference.function)) @reference.function 5 | (type_annotation ((lower_case_identifier) @name.reference.function) (colon)) @reference.function 6 | 7 | (type_declaration ((upper_case_identifier) @name.definition.type) ) @definition.type 8 | 9 | (type_ref (upper_case_qid (upper_case_identifier) @name.reference.type)) @reference.type 10 | (exposed_type (upper_case_identifier) @name.reference.type)) @reference.type 11 | 12 | (type_declaration (union_variant (upper_case_identifier) @name.definition.union)) @definition.union 13 | 14 | (value_expr (upper_case_qid (upper_case_identifier) @name.reference.union)) @reference.union 15 | 16 | 17 | (module_declaration 18 | (upper_case_qid (upper_case_identifier)) @name.definition.module 19 | ) @definition.module 20 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-go-tags.scm: -------------------------------------------------------------------------------- 1 | ( 2 | (comment)* @doc 3 | . 4 | (function_declaration 5 | name: (identifier) @name.definition.function) @definition.function 6 | (#strip! @doc "^//\\s*") 7 | (#set-adjacent! @doc @definition.function) 8 | ) 9 | 10 | ( 11 | (comment)* @doc 12 | . 13 | (method_declaration 14 | name: (field_identifier) @name.definition.method) @definition.method 15 | (#strip! @doc "^//\\s*") 16 | (#set-adjacent! @doc @definition.method) 17 | ) 18 | 19 | (call_expression 20 | function: [ 21 | (identifier) @name.reference.call 22 | (parenthesized_expression (identifier) @name.reference.call) 23 | (selector_expression field: (field_identifier) @name.reference.call) 24 | (parenthesized_expression (selector_expression field: (field_identifier) @name.reference.call)) 25 | ]) @reference.call 26 | 27 | (type_spec 28 | name: (type_identifier) @name.definition.type) @definition.type 29 | 30 | (type_identifier) @name.reference.type @reference.type 31 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-java-tags.scm: -------------------------------------------------------------------------------- 1 | (class_declaration 2 | name: (identifier) @name.definition.class) @definition.class 3 | 4 | (method_declaration 5 | name: (identifier) @name.definition.method) @definition.method 6 | 7 | (method_invocation 8 | name: (identifier) @name.reference.call 9 | arguments: (argument_list) @reference.call) 10 | 11 | (interface_declaration 12 | name: (identifier) @name.definition.interface) @definition.interface 13 | 14 | (type_list 15 | (type_identifier) @name.reference.implementation) @reference.implementation 16 | 17 | (object_creation_expression 18 | type: (type_identifier) @name.reference.class) @reference.class 19 | 20 | (superclass (type_identifier) @name.reference.class) @reference.class 21 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-javascript-tags.scm: -------------------------------------------------------------------------------- 1 | ( 2 | (comment)* @doc 3 | . 4 | (method_definition 5 | name: (property_identifier) @name.definition.method) @definition.method 6 | (#not-eq? @name.definition.method "constructor") 7 | (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") 8 | (#select-adjacent! @doc @definition.method) 9 | ) 10 | 11 | ( 12 | (comment)* @doc 13 | . 14 | [ 15 | (class 16 | name: (_) @name.definition.class) 17 | (class_declaration 18 | name: (_) @name.definition.class) 19 | ] @definition.class 20 | (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") 21 | (#select-adjacent! @doc @definition.class) 22 | ) 23 | 24 | ( 25 | (comment)* @doc 26 | . 27 | [ 28 | (function 29 | name: (identifier) @name.definition.function) 30 | (function_declaration 31 | name: (identifier) @name.definition.function) 32 | (generator_function 33 | name: (identifier) @name.definition.function) 34 | (generator_function_declaration 35 | name: (identifier) @name.definition.function) 36 | ] @definition.function 37 | (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") 38 | (#select-adjacent! @doc @definition.function) 39 | ) 40 | 41 | ( 42 | (comment)* @doc 43 | . 44 | (lexical_declaration 45 | (variable_declarator 46 | name: (identifier) @name.definition.function 47 | value: [(arrow_function) (function)]) @definition.function) 48 | (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") 49 | (#select-adjacent! @doc @definition.function) 50 | ) 51 | 52 | ( 53 | (comment)* @doc 54 | . 55 | (variable_declaration 56 | (variable_declarator 57 | name: (identifier) @name.definition.function 58 | value: [(arrow_function) (function)]) @definition.function) 59 | (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") 60 | (#select-adjacent! @doc @definition.function) 61 | ) 62 | 63 | (assignment_expression 64 | left: [ 65 | (identifier) @name.definition.function 66 | (member_expression 67 | property: (property_identifier) @name.definition.function) 68 | ] 69 | right: [(arrow_function) (function)] 70 | ) @definition.function 71 | 72 | (pair 73 | key: (property_identifier) @name.definition.function 74 | value: [(arrow_function) (function)]) @definition.function 75 | 76 | ( 77 | (call_expression 78 | function: (identifier) @name.reference.call) @reference.call 79 | (#not-match? @name.reference.call "^(require)$") 80 | ) 81 | 82 | (call_expression 83 | function: (member_expression 84 | property: (property_identifier) @name.reference.call) 85 | arguments: (_) @reference.call) 86 | 87 | (new_expression 88 | constructor: (_) @name.reference.class) @reference.class 89 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-ocaml-tags.scm: -------------------------------------------------------------------------------- 1 | ; Modules 2 | ;-------- 3 | 4 | ( 5 | (comment)? @doc . 6 | (module_definition (module_binding (module_name) @name.definition.module) @definition.module) 7 | (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") 8 | ) 9 | 10 | (module_path (module_name) @name.reference.module) @reference.module 11 | 12 | ; Modules types 13 | ;-------------- 14 | 15 | ( 16 | (comment)? @doc . 17 | (module_type_definition (module_type_name) @name.definition.interface) @definition.interface 18 | (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") 19 | ) 20 | 21 | (module_type_path (module_type_name) @name.reference.implementation) @reference.implementation 22 | 23 | ; Functions 24 | ;---------- 25 | 26 | ( 27 | (comment)? @doc . 28 | (value_definition 29 | [ 30 | (let_binding 31 | pattern: (value_name) @name.definition.function 32 | (parameter)) 33 | (let_binding 34 | pattern: (value_name) @name.definition.function 35 | body: [(fun_expression) (function_expression)]) 36 | ] @definition.function 37 | ) 38 | (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") 39 | ) 40 | 41 | ( 42 | (comment)? @doc . 43 | (external (value_name) @name.definition.function) @definition.function 44 | (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") 45 | ) 46 | 47 | (application_expression 48 | function: (value_path (value_name) @name.reference.call)) @reference.call 49 | 50 | (infix_expression 51 | left: (value_path (value_name) @name.reference.call) 52 | (infix_operator) @reference.call 53 | (#eq? @reference.call "@@")) 54 | 55 | (infix_expression 56 | (infix_operator) @reference.call 57 | right: (value_path (value_name) @name.reference.call) 58 | (#eq? @reference.call "|>")) 59 | 60 | ; Operator 61 | ;--------- 62 | 63 | ( 64 | (comment)? @doc . 65 | (value_definition 66 | (let_binding 67 | pattern: (parenthesized_operator [ 68 | (prefix_operator) 69 | (infix_operator) 70 | (hash_operator) 71 | (indexing_operator) 72 | (let_operator) 73 | (and_operator) 74 | (match_operator) 75 | ] @name.definition.function)) @definition.function) 76 | (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") 77 | ) 78 | 79 | [ 80 | (prefix_operator) 81 | (sign_operator) 82 | (infix_operator) 83 | (hash_operator) 84 | (indexing_operator) 85 | (let_operator) 86 | (and_operator) 87 | (match_operator) 88 | ] @name.reference.call @reference.call 89 | 90 | ; Classes 91 | ;-------- 92 | 93 | ( 94 | (comment)? @doc . 95 | [ 96 | (class_definition (class_binding (class_name) @name.definition.class) @definition.class) 97 | (class_type_definition (class_type_binding (class_type_name) @name.definition.class) @definition.class) 98 | ] 99 | (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") 100 | ) 101 | 102 | [ 103 | (class_path (class_name) @name.reference.class) 104 | (class_type_path (class_type_name) @name.reference.class) 105 | ] @reference.class 106 | 107 | ; Methods 108 | ;-------- 109 | 110 | ( 111 | (comment)? @doc . 112 | (method_definition (method_name) @name.definition.method) @definition.method 113 | (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") 114 | ) 115 | 116 | (method_invocation (method_name) @name.reference.call) @reference.call 117 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-php-tags.scm: -------------------------------------------------------------------------------- 1 | (class_declaration 2 | name: (name) @name.definition.class) @definition.class 3 | 4 | (function_definition 5 | name: (name) @name.definition.function) @definition.function 6 | 7 | (method_declaration 8 | name: (name) @name.definition.function) @definition.function 9 | 10 | (object_creation_expression 11 | [ 12 | (qualified_name (name) @name.reference.class) 13 | (variable_name (name) @name.reference.class) 14 | ]) @reference.class 15 | 16 | (function_call_expression 17 | function: [ 18 | (qualified_name (name) @name.reference.call) 19 | (variable_name (name)) @name.reference.call 20 | ]) @reference.call 21 | 22 | (scoped_call_expression 23 | name: (name) @name.reference.call) @reference.call 24 | 25 | (member_call_expression 26 | name: (name) @name.reference.call) @reference.call 27 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-python-tags.scm: -------------------------------------------------------------------------------- 1 | (class_definition 2 | name: (identifier) @name.definition.class) @definition.class 3 | 4 | (function_definition 5 | name: (identifier) @name.definition.function) @definition.function 6 | 7 | (call 8 | function: [ 9 | (identifier) @name.reference.call 10 | (attribute 11 | attribute: (identifier) @name.reference.call) 12 | ]) @reference.call 13 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-ql-tags.scm: -------------------------------------------------------------------------------- 1 | (classlessPredicate 2 | name: (predicateName) @name.definition.function) @definition.function 3 | 4 | (memberPredicate 5 | name: (predicateName) @name.definition.method) @definition.method 6 | 7 | (aritylessPredicateExpr 8 | name: (literalId) @name.reference.call) @reference.call 9 | 10 | (module 11 | name: (moduleName) @name.definition.module) @definition.module 12 | 13 | (dataclass 14 | name: (className) @name.definition.class) @definition.class 15 | 16 | (datatype 17 | name: (className) @name.definition.class) @definition.class 18 | 19 | (datatypeBranch 20 | name: (className) @name.definition.class) @definition.class 21 | 22 | (qualifiedRhs 23 | name: (predicateName) @name.reference.call) @reference.call 24 | 25 | (typeExpr 26 | name: (className) @name.reference.type) @reference.type 27 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-ruby-tags.scm: -------------------------------------------------------------------------------- 1 | ; Method definitions 2 | 3 | ( 4 | (comment)* @doc 5 | . 6 | [ 7 | (method 8 | name: (_) @name.definition.method) @definition.method 9 | (singleton_method 10 | name: (_) @name.definition.method) @definition.method 11 | ] 12 | (#strip! @doc "^#\\s*") 13 | (#select-adjacent! @doc @definition.method) 14 | ) 15 | 16 | (alias 17 | name: (_) @name.definition.method) @definition.method 18 | 19 | (setter 20 | (identifier) @ignore) 21 | 22 | ; Class definitions 23 | 24 | ( 25 | (comment)* @doc 26 | . 27 | [ 28 | (class 29 | name: [ 30 | (constant) @name.definition.class 31 | (scope_resolution 32 | name: (_) @name.definition.class) 33 | ]) @definition.class 34 | (singleton_class 35 | value: [ 36 | (constant) @name.definition.class 37 | (scope_resolution 38 | name: (_) @name.definition.class) 39 | ]) @definition.class 40 | ] 41 | (#strip! @doc "^#\\s*") 42 | (#select-adjacent! @doc @definition.class) 43 | ) 44 | 45 | ; Module definitions 46 | 47 | ( 48 | (module 49 | name: [ 50 | (constant) @name.definition.module 51 | (scope_resolution 52 | name: (_) @name.definition.module) 53 | ]) @definition.module 54 | ) 55 | 56 | ; Calls 57 | 58 | (call method: (identifier) @name.reference.call) @reference.call 59 | 60 | ( 61 | [(identifier) (constant)] @name.reference.call @reference.call 62 | (#is-not? local) 63 | (#not-match? @name.reference.call "^(lambda|load|require|require_relative|__FILE__|__LINE__)$") 64 | ) 65 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-rust-tags.scm: -------------------------------------------------------------------------------- 1 | ; ADT definitions 2 | 3 | (struct_item 4 | name: (type_identifier) @name.definition.class) @definition.class 5 | 6 | (enum_item 7 | name: (type_identifier) @name.definition.class) @definition.class 8 | 9 | (union_item 10 | name: (type_identifier) @name.definition.class) @definition.class 11 | 12 | ; type aliases 13 | 14 | (type_item 15 | name: (type_identifier) @name.definition.class) @definition.class 16 | 17 | ; method definitions 18 | 19 | (declaration_list 20 | (function_item 21 | name: (identifier) @name.definition.method)) @definition.method 22 | 23 | ; function definitions 24 | 25 | (function_item 26 | name: (identifier) @name.definition.function) @definition.function 27 | 28 | ; trait definitions 29 | (trait_item 30 | name: (type_identifier) @name.definition.interface) @definition.interface 31 | 32 | ; module definitions 33 | (mod_item 34 | name: (identifier) @name.definition.module) @definition.module 35 | 36 | ; macro definitions 37 | 38 | (macro_definition 39 | name: (identifier) @name.definition.macro) @definition.macro 40 | 41 | ; references 42 | 43 | (call_expression 44 | function: (identifier) @name.reference.call) @reference.call 45 | 46 | (call_expression 47 | function: (field_expression 48 | field: (field_identifier) @name.reference.call)) @reference.call 49 | 50 | (macro_invocation 51 | macro: (identifier) @name.reference.call) @reference.call 52 | 53 | ; implementations 54 | 55 | (impl_item 56 | trait: (type_identifier) @name.reference.implementation) @reference.implementation 57 | 58 | (impl_item 59 | type: (type_identifier) @name.reference.implementation 60 | !trait) @reference.implementation 61 | -------------------------------------------------------------------------------- /src/tag-qry/tree-sitter-typescript-tags.scm: -------------------------------------------------------------------------------- 1 | (function_signature 2 | name: (identifier) @name.definition.function) @definition.function 3 | 4 | (method_signature 5 | name: (property_identifier) @name.definition.method) @definition.method 6 | 7 | (abstract_method_signature 8 | name: (property_identifier) @name.definition.method) @definition.method 9 | 10 | (abstract_class_declaration 11 | name: (type_identifier) @name.definition.class) @definition.class 12 | 13 | (module 14 | name: (identifier) @name.definition.module) @definition.module 15 | 16 | (interface_declaration 17 | name: (type_identifier) @name.definition.interface) @definition.interface 18 | 19 | (type_annotation 20 | (type_identifier) @name.reference.type) @reference.type 21 | 22 | (new_expression 23 | constructor: (identifier) @name.reference.class) @reference.class 24 | -------------------------------------------------------------------------------- /src/tagger/AllTags.ts: -------------------------------------------------------------------------------- 1 | import { Tag } from './common'; 2 | 3 | export class AllTags { 4 | constructor( 5 | readonly workspacePath: string, 6 | readonly relPaths: string[], 7 | readonly defines: Map>, 8 | readonly definitions: Map>, 9 | readonly references: Map, 10 | readonly identifiers: string[] 11 | ) {} 12 | } 13 | -------------------------------------------------------------------------------- /src/tagger/CachedFileTagExtractor.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs'; 2 | import * as path from 'path'; 3 | import { Source } from '../parser'; 4 | import { Tag, ITagExtractor } from './common'; 5 | import { CodeTagExtractor } from './CodeTagExtractor'; 6 | import { NodeContentPath } from '../parser/ContentPath.node'; 7 | 8 | export class CachedFileTagExtractor implements ITagExtractor { 9 | static readonly CACHE_FILE_NAME: string = 'tags.cache.json'; 10 | 11 | static create(workspacePath: string): CachedFileTagExtractor { 12 | const cacheFileName = path.join(workspacePath, CachedFileTagExtractor.CACHE_FILE_NAME); 13 | const cache = fs.existsSync(cacheFileName) 14 | ? JSON.parse(fs.readFileSync(cacheFileName, 'utf8')) 15 | : {}; 16 | const extractor = new CodeTagExtractor(workspacePath, new NodeContentPath()); 17 | return new CachedFileTagExtractor(extractor, cache); 18 | } 19 | 20 | private static getMtime(absPath: string): number | undefined { 21 | try { 22 | return fs.statSync(absPath).mtimeMs; 23 | } catch (e) { 24 | return; 25 | } 26 | } 27 | 28 | constructor( 29 | readonly extractor: CodeTagExtractor, 30 | readonly cache: { [key: string]: { mtime: number; data: Tag[] } } 31 | ) {} 32 | 33 | get workspacePath() { 34 | return this.extractor.workspacePath; 35 | } 36 | 37 | getAbsPath(relPath: string): string { 38 | return path.join(this.workspacePath, relPath); 39 | } 40 | 41 | async getTags(relPath: string): Promise { 42 | const absPath = this.getAbsPath(relPath); 43 | const fileMtime = CachedFileTagExtractor.getMtime(absPath); 44 | if (!fileMtime) return []; 45 | const value = this.cache[absPath]; 46 | if (value && value.mtime === fileMtime) { 47 | return value.data; 48 | } 49 | const code = fs.readFileSync(absPath, 'utf8'); 50 | if (!code) return []; 51 | return this.extractor.extractTags({ relPath: relPath, code: code }); 52 | } 53 | 54 | async extractTags(source: Source): Promise { 55 | return this.extractor.extractTags(source); 56 | } 57 | 58 | writeCache() { 59 | const cacheFileName = path.join(this.workspacePath, CachedFileTagExtractor.CACHE_FILE_NAME); 60 | fs.writeFileSync(cacheFileName, JSON.stringify(this.cache), 'utf8'); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/tagger/CodeTagExtractor.ts: -------------------------------------------------------------------------------- 1 | import { IContentPath, Source, getLanguage, AST } from '../parser'; 2 | import { ITagExtractor } from './common'; 3 | import { Tagger } from './Tagger'; 4 | import { TagQuery } from './TagQuery'; 5 | 6 | export class CodeTagExtractor implements ITagExtractor { 7 | constructor(public readonly workspacePath: string, readonly contentPath: IContentPath) {} 8 | 9 | async extractTags(source: Source) { 10 | const language = getLanguage(source.relPath); 11 | if (!language) return []; 12 | const wasmPath = this.contentPath.getWasmURL(language); 13 | const ast = await AST.createFromCode(source, wasmPath, language); 14 | const tagQuery = new TagQuery(this.contentPath); 15 | const tagger = Tagger.create(ast, tagQuery.getQuery(language)); 16 | return tagger.read(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/tagger/DefRef.ts: -------------------------------------------------------------------------------- 1 | import { Source } from '../parser'; 2 | import { Tag, ITagExtractor } from './common'; 3 | 4 | export class DefRef { 5 | static async createEach(extractor: ITagExtractor, sources: Source[]) { 6 | return await Promise.all( 7 | sources.map(async source => { 8 | return DefRef.create(extractor, source); 9 | }) 10 | ); 11 | } 12 | 13 | static async create(extractor: ITagExtractor, source: Source) { 14 | const tags = await extractor.extractTags(source); 15 | const defs = tags.filter(tag => tag.kind === 'def'); 16 | const refs = tags.filter(tag => tag.kind === 'ref'); 17 | return new DefRef(source.relPath, tags, defs, refs); 18 | } 19 | 20 | constructor( 21 | readonly relPath: string, 22 | readonly all: Tag[], 23 | readonly defs: Tag[], 24 | readonly refs: Tag[] 25 | ) {} 26 | } 27 | -------------------------------------------------------------------------------- /src/tagger/DefRefs.node.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs'; 2 | import * as path from 'path'; 3 | import _ from 'lodash'; 4 | import { Source } from '../parser'; 5 | import { ITagExtractor } from './common'; 6 | import { DefRefs } from './DefRefs'; 7 | 8 | export async function createDefRefsFromFiles(tagGetter: ITagExtractor, absPaths: string[]) { 9 | const sources = absPaths.map( 10 | absPath => 11 | ({ 12 | relPath: path.relative(tagGetter.workspacePath, absPath), 13 | code: fs.readFileSync(absPath, 'utf8'), 14 | } as Source) 15 | ); 16 | return DefRefs.create(tagGetter, sources); 17 | } 18 | -------------------------------------------------------------------------------- /src/tagger/DefRefs.ts: -------------------------------------------------------------------------------- 1 | import _ from 'lodash'; 2 | import { Source } from '../parser'; 3 | import { Tag, ITagExtractor } from './common'; 4 | import { AllTags } from './AllTags'; 5 | import { DefRef } from './DefRef'; 6 | 7 | export class DefRefs { 8 | static async create(tagGetter: ITagExtractor, sources: Source[]) { 9 | const defRefs = await DefRef.createEach(tagGetter, sources); 10 | const nonEmpty = defRefs.filter(defRef => defRef.defs.length != 0 || defRef.refs.length != 0); 11 | if (nonEmpty.length == 0) return; 12 | return new DefRefs(tagGetter.workspacePath, nonEmpty); 13 | } 14 | 15 | constructor(readonly workspacePath: string, readonly defRefs: DefRef[]) {} 16 | 17 | static _add(map: Map>, key: K, value: V): void { 18 | if (!map.has(key)) map.set(key, new Set()); 19 | map.get(key)?.add(value); 20 | } 21 | 22 | static _push(map: Map, key: K, value: V): void { 23 | if (!map.has(key)) map.set(key, []); 24 | map.get(key)?.push(value); 25 | } 26 | 27 | createTags() { 28 | const defines = new Map>(); 29 | this.defRefs.forEach(defRef => { 30 | (defRef.defs as Tag[]).forEach(def => { 31 | DefRefs._add(defines, def.text, defRef.relPath); 32 | }); 33 | }); 34 | const definitions = new Map>(); 35 | this.defRefs.forEach(defRef => { 36 | (defRef.defs as Tag[]).forEach(tag => { 37 | DefRefs._add(definitions, `${defRef.relPath},${tag.text}`, tag); 38 | }); 39 | }); 40 | const references = new Map(); 41 | this.defRefs.forEach(defRef => { 42 | (defRef.refs as Tag[]).forEach(tag => { 43 | DefRefs._push(references, tag.text, defRef.relPath); 44 | }); 45 | }); 46 | if (references.size === 0) { 47 | defines.forEach((value, key) => { 48 | references.set(key, Array.from(value)); 49 | }); 50 | } 51 | const relPaths = this.defRefs.map(defRef => { 52 | return defRef.relPath; 53 | }); 54 | if (defines.size === 0 || definitions.size === 0 || references.size === 0) return; 55 | const identifiers = Array.from(defines.keys()).filter(key => references.has(key)); 56 | return new AllTags(this.workspacePath, relPaths, defines, definitions, references, identifiers); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/tagger/TagQuery.ts: -------------------------------------------------------------------------------- 1 | import { IContentPath, Language } from '../parser'; 2 | 3 | export class TagQuery { 4 | constructor(readonly contentPath: IContentPath) {} 5 | getQuery(language: Language) { 6 | if (language === 'TypeScript') { 7 | return this.contentPath.getQuery('JavaScript') + this.contentPath.getQuery('TypeScript'); 8 | } else { 9 | return this.contentPath.getQuery(language); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/tagger/Tagger.ts: -------------------------------------------------------------------------------- 1 | import { AST } from '../parser'; 2 | import { Tag } from './common'; 3 | 4 | export class Tagger { 5 | static create(ast: AST, queryScm: string) { 6 | return new Tagger(ast, queryScm); 7 | } 8 | 9 | static _getKind(tag: string) { 10 | if (tag.startsWith('name.definition.')) { 11 | return 'def'; 12 | } else if (tag.startsWith('name.reference.')) { 13 | return 'ref'; 14 | } else { 15 | return; 16 | } 17 | } 18 | 19 | constructor(readonly ast: AST, readonly queryScm: string) {} 20 | 21 | read(): Tag[] { 22 | return this.ast 23 | .captures(this.queryScm) 24 | .map(({ node, name }: { node: any; name: string }) => { 25 | const kind = Tagger._getKind(name); 26 | return kind 27 | ? ({ 28 | relPath: this.ast.relPath, 29 | text: node.text, 30 | kind: kind, 31 | start: { 32 | ln: node.startPosition.row, 33 | col: node.startPosition.column, 34 | }, 35 | end: { 36 | ln: node.endPosition.row, 37 | col: node.endPosition.column, 38 | }, 39 | } as Tag) 40 | : undefined; 41 | }) 42 | .filter((tag: Tag | undefined): tag is Tag => tag !== undefined); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/tagger/common.ts: -------------------------------------------------------------------------------- 1 | import { Source } from '../parser'; 2 | 3 | export type Tag = { 4 | relPath: string; 5 | text: string; 6 | kind: string; 7 | start: { 8 | ln: number; 9 | col: number; 10 | }; 11 | end: { 12 | ln: number; 13 | col: number; 14 | }; 15 | }; 16 | 17 | export interface ITagExtractor { 18 | workspacePath: string; 19 | extractTags(source: Source): Promise; 20 | } 21 | -------------------------------------------------------------------------------- /src/tagger/index.ts: -------------------------------------------------------------------------------- 1 | export { Tag } from './common'; 2 | 3 | import { SourceSet, Source, AST, IContentPath } from '../parser'; 4 | import { getLanguage } from '../parser/lang-utils'; 5 | import { CodeTagExtractor } from './CodeTagExtractor'; 6 | import { DefRef } from './DefRef'; 7 | import { DefRefs } from './DefRefs'; 8 | 9 | export async function createAST(source: Source, contentPath: IContentPath) { 10 | const language = getLanguage(source.relPath)!; 11 | if (!language) return; 12 | const wasmPath = contentPath.getWasmURL(language); 13 | return AST.createFromCode(source, wasmPath, language); 14 | } 15 | 16 | export async function createDefRefs(sourceSet: SourceSet) { 17 | const extractor = new CodeTagExtractor('', sourceSet.contentPath); 18 | return await DefRefs.create(extractor, sourceSet.sources); 19 | } 20 | 21 | export async function createTags(sourceSet: SourceSet) { 22 | const defRefs = await createDefRefs(sourceSet); 23 | if (!defRefs) return; 24 | return defRefs.createTags(); 25 | } 26 | 27 | export { DefRef }; 28 | -------------------------------------------------------------------------------- /src/webpack.d.ts: -------------------------------------------------------------------------------- 1 | // webpack.d.ts 2 | declare module '*.scm' { 3 | const context: __WebpackModuleApi.RequireContext; 4 | export = context; 5 | } 6 | 7 | declare namespace __WebpackModuleApi { 8 | interface RequireContext { 9 | keys(): string[]; 10 | (id: string): any; 11 | (id: string): T; 12 | resolve(id: string): string; 13 | id: string; 14 | } 15 | } 16 | 17 | interface NodeRequire { 18 | context( 19 | directory: string, 20 | useSubdirectories: boolean, 21 | regExp: RegExp 22 | ): __WebpackModuleApi.RequireContext; 23 | } 24 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es6", 5 | "types": ["node", "jest"], 6 | "strict": true, 7 | "declaration": true, 8 | "sourceMap": true, 9 | "esModuleInterop": true, 10 | "outDir": "dist", 11 | "rootDir": "src" 12 | }, 13 | "include": ["src/**/*.ts"], 14 | "exclude": ["node_modules"] 15 | } 16 | -------------------------------------------------------------------------------- /webpack.config.ts: -------------------------------------------------------------------------------- 1 | import * as path from 'path'; 2 | import { Configuration, node } from 'webpack'; 3 | 4 | const config: Configuration = { 5 | mode: 'production', 6 | entry: { 7 | 'index.browser': './src/index.browser.ts', 8 | }, 9 | module: { 10 | rules: [ 11 | { 12 | test: /\.tsx?$/, 13 | use: 'ts-loader', 14 | exclude: /node_modules/, 15 | }, 16 | { 17 | test: /\.scm$/, 18 | use: 'raw-loader', 19 | }, 20 | ], 21 | }, 22 | resolve: { 23 | fallback: { 24 | fs: false, 25 | path: false, 26 | }, 27 | extensions: ['.tsx', '.ts', '.js'], 28 | }, 29 | output: { 30 | filename: '[name].js', 31 | path: path.resolve(__dirname, 'dist'), 32 | libraryTarget: 'umd', 33 | globalObject: 'this', 34 | }, 35 | target: ['web', 'es5'], 36 | }; 37 | 38 | export default config; 39 | --------------------------------------------------------------------------------