├── .gitignore ├── LICENSE ├── README.md ├── package.json ├── src ├── import-cli.ts └── import.ts └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (C) 2022 by Marijn Haverbeke and others 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # import-tree-sitter 2 | 3 | Utility to help convert grammars written for [tree-sitter](https://tree-sitter.github.io/) to Lezer's grammar notation. 4 | 5 | ## Status 6 | 7 | This isn't a polished easy-to-use tool, but might help save time when porting a grammar. 8 | 9 | ## Usage 10 | 11 | ### CLI 12 | 13 | ```sh 14 | npm install -g https://github.com/lezer-parser/import-tree-sitter 15 | lezer-import-tree-sitter src/grammar.json >some_language.grammar 16 | ``` 17 | 18 | ### API 19 | 20 | If you pass the tree-sitter grammar JSON representation (usually in `src/grammar.json`), as a string, to the `buildGrammar` function defined in `src/import.ts`, it'll spit out an equivalent Lezer grammar file. 21 | 22 | ## Limitations 23 | 24 | Because tree-sitter's concepts don't all map to Lezer concepts, you'll only get a working, finished grammar for very trivial grammars. Specifically: 25 | 26 | - Precedences are specified in a more fine-grained way in Lezer, so the tool only emits a comment indicating that a precedence was specified, and leaves it to you to put the proper conflict markers in. 27 | 28 | - Tree-sitter's alias expressions are a bit like inline rules, but make the inner rule's name disappear. That's not something you can do in Lezer, so you'll get additional noise in your tree in some cases if you don't further clean up the grammar. 29 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "lezer-import-tree-sitter", 3 | "type": "module", 4 | "bin": { 5 | "lezer-import-tree-sitter": "dist/import-cli.js" 6 | }, 7 | "scripts": { 8 | "prepare": "tsc", 9 | "watch": "tsc --watch", 10 | "build": "tsc" 11 | }, 12 | "dependencies": { 13 | "regexp-parser-literal": "^1.1.35", 14 | "regexpp2": "^1.3.27" 15 | }, 16 | "devDependencies": { 17 | "@types/node": "^18.11.14", 18 | "typescript": "^4.9.4" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/import-cli.ts: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env node 2 | 3 | import { importGrammar } from "./import.js" 4 | import { readFileSync } from "fs" 5 | 6 | const binName = "lezer-import-tree-sitter" 7 | 8 | function main(args: string[]) { 9 | if (args.length != 2) { 10 | console.error(`usage: ${binName} path/to/grammar.json`) 11 | process.exit(1) 12 | } 13 | const inputFile = args[1] 14 | const content = readFileSync(inputFile, "utf8") 15 | const grammar = importGrammar(content) 16 | console.log(grammar) 17 | } 18 | 19 | main(process.argv.slice(1)) 20 | -------------------------------------------------------------------------------- /src/import.ts: -------------------------------------------------------------------------------- 1 | import {createRegExpParser} from "regexp-parser-literal" 2 | import {AST as RE} from "regexpp2" 3 | 4 | type RepeatExpr = {type: "REPEAT" | "REPEAT1", content: TSExpr} 5 | type SymbolExpr = {type: "SYMBOL", name: string} 6 | type ChoiceExpr = {type: "CHOICE", members: TSExpr[]} 7 | type AliasExpr = {type: "ALIAS", content: TSExpr, named: boolean, value: string} 8 | type SeqExpr = {type: "SEQ", members: TSExpr[]} 9 | type StringExpr = {type: "STRING", value: string} 10 | type PatternExpr = {type: "PATTERN", value: string} 11 | type FieldExpr = {type: "FIELD", name: string, content: TSExpr} 12 | type TokenExpr = {type: "TOKEN" | "IMMEDIATE_TOKEN", content: TSExpr} 13 | type BlankExpr = {type: "BLANK"} 14 | type PrecExpr = {type: "PREC" | "PREC_DYNAMIC" | "PREC_LEFT" | "PREC_RIGHT", value: number, content: TSExpr} 15 | 16 | type TSExpr = RepeatExpr | SymbolExpr | ChoiceExpr | AliasExpr | SeqExpr | StringExpr | PatternExpr | FieldExpr | 17 | TokenExpr | BlankExpr | PrecExpr 18 | 19 | type TSDefinition = { 20 | name: string, 21 | word?: string, 22 | rules: {[name: string]: TSExpr}, 23 | extras?: TSExpr[], 24 | conflicts?: string[][], 25 | externals?: (SymbolExpr | StringExpr)[], 26 | inline?: string[], 27 | supertypes?: string[] 28 | } 29 | 30 | function prec(expr: TSExpr): number { 31 | switch (expr.type) { 32 | case "CHOICE": return isOption(expr) ? 10 : 1 33 | case "SEQ": return 2 34 | case "REPEAT": case "REPEAT1": return 3 35 | case "ALIAS": return expr.named ? 10 : prec(expr.content) 36 | case "FIELD": return prec(expr.content) 37 | default: return 10 38 | } 39 | } 40 | 41 | function isOption(expr: ChoiceExpr): TSExpr | null { 42 | if (expr.members.length != 2) return null 43 | let empty = expr.members.findIndex(e => e.type == "BLANK") 44 | if (empty < 0) return null 45 | return expr.members[empty ? 0 : 1] 46 | } 47 | 48 | function choices(expr: TSExpr): TSExpr[] { 49 | if (expr.type != "CHOICE") return [expr] 50 | return expr.members.reduce((a, b) => a.concat(choices(b)), [] as TSExpr[]) 51 | } 52 | 53 | function isPrec(expr: TSExpr): expr is PrecExpr { 54 | return expr.type == "PREC" || expr.type == "PREC_RIGHT" || expr.type == "PREC_LEFT" || expr.type == "PREC_DYNAMIC" 55 | } 56 | 57 | function takePrec(expr: TSExpr) { 58 | let comment = "" 59 | while (isPrec(expr)) { 60 | let label = expr.type.slice(5).toLowerCase() 61 | comment += (comment ? " " : "") + (label ? label + " " : "") + expr.value 62 | expr = expr.content 63 | } 64 | return {expr, comment: comment ? `/* precedence: ${comment} */ ` : ""} 65 | } 66 | 67 | class Context { 68 | rules: {[name: string]: string} = Object.create(null) 69 | tokens: {[name: string]: string} = Object.create(null) 70 | skip: string = "" 71 | 72 | wordRE: RegExp | null = null 73 | wordRule: string = "" 74 | wordRuleName: string = "" 75 | 76 | constructor(readonly def: TSDefinition) {} 77 | 78 | translateInner(expr: TSExpr, token: boolean, outerPrec: number): string { 79 | let inner = this.translateExpr(expr, token) 80 | return prec(expr) < outerPrec ? "(" + inner + ")" : inner 81 | } 82 | 83 | translateName(name: string) { 84 | if (name[0] != "_") return name[0].toUpperCase() + name.slice(1).replace(/_\w/g, m => m.slice(1).toUpperCase()) 85 | if (name[1].toUpperCase() != name[1]) return name[1] + name.slice(2).replace(/_\w/g, m => m.slice(1).toUpperCase()) 86 | return name 87 | } 88 | 89 | translateExpr(expr: TSExpr, token: boolean): string { 90 | switch (expr.type) { 91 | case "REPEAT": case "REPEAT1": 92 | return this.translateInner(expr.content, token, prec(expr)) + (expr.type == "REPEAT" ? "*" : "+") 93 | case "SYMBOL": 94 | return this.translateName(expr.name) 95 | case "CHOICE": 96 | let opt = isOption(expr) 97 | return opt ? this.translateInner(opt, token, 10) + "?" 98 | : expr.members.map(e => this.translateInner(e, token, prec(expr))).join(" | ") 99 | case "ALIAS": // FIXME this should override/drop the name of the inner expr, somehow 100 | if (token) throw new RangeError("Alias expression in token") 101 | if (expr.named && (expr.content.type == "TOKEN" || expr.content.type == "IMMEDIATE_TOKEN")) 102 | return this.defineToken(expr.value, expr.content.content) 103 | let inner = this.translateExpr(expr.content, token) 104 | return expr.named ? `${this.translateName(expr.value)} { ${inner} }` : inner 105 | case "SEQ": 106 | return expr.members.map(e => this.translateInner(e, token, 2)).join(" ") 107 | case "STRING": 108 | if (!token && this.wordRE?.test(expr.value)) return `${this.wordRuleName}<${JSON.stringify(expr.value)}>` 109 | return JSON.stringify(expr.value) 110 | case "PATTERN": 111 | if (!token) return this.defineToken(null, expr) 112 | return this.translateRegExp(expr.value) 113 | case "FIELD": 114 | return this.translateExpr(expr.content, token) 115 | case "TOKEN": case "IMMEDIATE_TOKEN": 116 | return this.defineToken(null, expr.content) 117 | case "BLANK": 118 | return '""' 119 | case "PREC": case "PREC_LEFT": case "PREC_RIGHT": case "PREC_DYNAMIC": 120 | let {expr: innerExpr, comment} = takePrec(expr) 121 | return `${comment}(${this.translateExpr(innerExpr, token)})` 122 | default: 123 | throw new RangeError("Unexpected expression type: " + (expr as any).type) 124 | } 125 | } 126 | 127 | isTokenish(expr: TSExpr): boolean { 128 | return (expr.type == "STRING" && !this.wordRE?.test(expr.value)) || 129 | expr.type == "PATTERN" || expr.type == "BLANK" || 130 | (expr.type == "SEQ" || expr.type == "CHOICE") && expr.members.every(e => this.isTokenish(e)) || 131 | (expr.type == "REPEAT" || expr.type == "REPEAT1" || isPrec(expr)) && this.isTokenish(expr.content) 132 | } 133 | 134 | translateRule(name: string, content: TSExpr, top: boolean) { 135 | if (!top && content.type == "TOKEN") { 136 | this.defineToken(name, content.content) 137 | } else if (!top && this.isTokenish(content)) { 138 | this.defineToken(name, content) 139 | } else { 140 | let {comment, expr} = takePrec(content) 141 | let result = choices(expr).map(choice => this.translateExpr(choice, false)) 142 | this.rules[(top ? "@top " : "") + this.translateName(name)] = 143 | `${comment}{\n ${result.join(" |\n ")}\n}` 144 | } 145 | } 146 | 147 | translateRegExp(value: string) { 148 | let parsed = createRegExpParser().parsePattern(value) 149 | return this.translateRegExpElements(parsed.elements) 150 | } 151 | 152 | translateRegExpElements(elts: RE.Element[]): string { 153 | let result = "" 154 | for (let i = 0; i < elts.length;) { 155 | if (result) result += " " 156 | let next = elts[i++] 157 | if (next.type == "Character") { 158 | let chars = next.raw 159 | while (i < elts.length && elts[i].type == "Character") chars += elts[i++].raw 160 | result += JSON.stringify(chars) 161 | } else { 162 | result += this.translateRegExpElement(next) 163 | } 164 | } 165 | return result 166 | } 167 | 168 | translateRegExpElement(elt: RE.Element): string { 169 | switch (elt.type) { 170 | case "Disjunction": 171 | return elt.alternatives.map(e => this.translateRegExpElements(e)).join(" | ") 172 | case "Group": case "CapturingGroup": 173 | return "(" + this.translateRegExpElements(elt.elements) + ")" 174 | case "Quantifier": 175 | let inner = this.translateRegExpElement(elt.element), {min, max} = elt 176 | if (min == 0 && max == 1) return inner + "?" 177 | if (min == 0 && max == Infinity) return inner + "*" 178 | if (min == 1 && max == Infinity) return inner + "+" 179 | return (inner + " ").repeat(min) + (max == Infinity ? inner + "*" : (inner + "? ").repeat(max - min)) 180 | case "CharacterClass": 181 | return (elt.negate ? "!" : "$") + "[" + elt.elements.map(r => { 182 | switch (r.type) { 183 | case "CharacterSet": 184 | if ((r as any).negate) throw new Error("No support for negated character set elements") 185 | if (r.kind == "digit") return "0-9" 186 | else if (r.kind == "space") return " \\t\\n\\r" 187 | else if (r.kind == "word") return "a-zA-Z0-9_" 188 | else throw new Error("Unhandled range type: EscapeCharacterSet/property") 189 | case "Character": 190 | return r.raw 191 | case "CharacterClassRange": 192 | return r.min.raw + "-" + r.max.raw 193 | default: 194 | throw new Error("Unhandled range type: " + r.type) 195 | } 196 | }).join("") + "]" 197 | case "CharacterSet": 198 | if (elt.kind == "any") return "![\\n]" 199 | else if (elt.kind == "digit") return `${elt.negate ? "!" : "$"}[0-9]` 200 | else if (elt.kind == "space") return `${elt.negate ? "!" : "$"}[ \\t\\r\\n]` 201 | else if (elt.kind == "word") return `${elt.negate ? "!" : "$"}[a-zA-Z0-9_]` 202 | else throw new Error("Unhandled range type: EscapeCharacterSet/property") 203 | case "Character": 204 | return JSON.stringify(elt.raw) 205 | default: 206 | throw new RangeError("Unhandled regexp element type: " + elt.type) 207 | } 208 | } 209 | 210 | defineToken(name: string | null, content: TSExpr) { 211 | let {comment, expr} = takePrec(content) 212 | if (!comment && name == null && expr.type == "STRING") 213 | return JSON.stringify(expr.value) 214 | let newName = name ? this.translateName(name) : this.generateName("token") 215 | this.tokens[newName] = `${comment}{\n ${this.translateExpr(expr, true)}\n }` 216 | return newName 217 | } 218 | 219 | generateName(prefix: string) { 220 | for (let i = 1;; i++) { 221 | let name = prefix + "_" + i 222 | if (!(name in this.tokens || name in this.rules)) return name 223 | } 224 | } 225 | 226 | build() { 227 | if (this.def.word) { 228 | let expr = this.def.rules[this.def.word], pattern = toRegExp(expr) 229 | this.wordRuleName = this.def.rules["_kw"] ? this.generateName("kw") : "kw" 230 | this.wordRule = `${this.wordRuleName} { @specialize[@name={term}]<${this.translateName(this.def.word)}, term> }\n\n` 231 | this.wordRE = new RegExp("^(" + pattern + ")$") 232 | } 233 | 234 | if (this.def.extras) { 235 | this.skip = this.def.extras.map(e => this.translateExpr(e, false)).join(" | ") 236 | } else { 237 | this.tokens["space_1"] = "{ std.whitespace+ }" 238 | this.skip = "space_1" 239 | } 240 | 241 | let first = true 242 | for (let name in this.def.rules) { 243 | this.translateRule(name, this.def.rules[name], first) 244 | first = false 245 | } 246 | } 247 | 248 | grammar() { 249 | let rules = Object.keys(this.rules) 250 | let ruleStr = rules.map(r => `${r} ${this.rules[r]}\n\n`).join("") 251 | let externalStr = "" 252 | if (this.def.externals && this.def.externals.length) { 253 | const tmp = this.def.externals.filter((s): s is SymbolExpr => s.type == "SYMBOL").map(s => this.translateName(s.name)).join(", ") 254 | externalStr = `@external tokens token from "./tokens" { ${tmp} }\n\n` 255 | } 256 | let tokens = Object.keys(this.tokens) 257 | let tokenStr = `@tokens {\n${tokens.map(t => ` ${t} ${this.tokens[t]}\n`).join("")}}` 258 | let skipStr = `@skip { ${this.skip} }\n\n` 259 | return ruleStr + this.wordRule + skipStr + externalStr + tokenStr 260 | } 261 | } 262 | 263 | function toRegExp(expr: TSExpr): string { 264 | switch (expr.type) { 265 | case "TOKEN": 266 | return toRegExp(expr.content) 267 | case "SEQ": 268 | return expr.members.map(child => toRegExp(child)).join("") 269 | case "CHOICE": 270 | return `(?:${expr.members.map(child => toRegExp(child)).join("|")})` 271 | case "REPEAT": 272 | return `(?:${toRegExp(expr.content)})*` 273 | case "REPEAT1": 274 | return `(?:${toRegExp(expr.content)})+` 275 | case "PATTERN": 276 | return expr.value 277 | case "STRING": 278 | return expr.value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") 279 | default: 280 | throw new Error("not implemented: expr.type = " + expr.type) 281 | } 282 | } 283 | 284 | export function importGrammar(content: string) { 285 | let def = JSON.parse(content) as TSDefinition 286 | let cx = new Context(def) 287 | cx.build() 288 | return cx.grammar() 289 | } 290 | 291 | const test = /^\s*==+\n(.*)\n==+\n\s*([^]+?)\n---+\n\s*([^]+?)(?=\n==+|$)/ 292 | 293 | function translateName(name: string) { 294 | if (name[0] != "_") return name[0].toUpperCase() + name.slice(1).replace(/_\w/g, m => m.slice(1).toUpperCase()) 295 | if (name[1].toUpperCase() != name[1]) return name[1] + name.slice(2).replace(/_\w/g, m => m.slice(1).toUpperCase()) 296 | return name 297 | } 298 | 299 | export function importTest(file: string, renamed: {[name: string]: string} = {}) { 300 | let result: string[] = [], pos = 0 301 | while (pos < file.length) { 302 | let next = test.exec(file.slice(pos)) 303 | if (!next) throw new Error("Failing to find test at " + pos) 304 | let [, name, code, tree] = next 305 | tree = tree 306 | .replace(/\w+: */g, "") 307 | .replace(/\((\w+)(\)| *)/g, (_, n, p) => n + (p == ")" ? "" : "(")) 308 | .replace(/(\w|\))(\s+)(\w)/g, (_, before, space, after) => `${before},${space}${after}`) 309 | .replace(/\w+/g, w => { 310 | return Object.prototype.hasOwnProperty.call(renamed, w) ? renamed[w] : translateName(w) 311 | }) 312 | result.push(`# ${name}\n\n${code}\n==>\n\n${tree}`) 313 | pos += next[0].length 314 | } 315 | return result.join("\n\n") 316 | } 317 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "lib": ["esnext"], 4 | "module": "esnext", 5 | "noFallthroughCasesInSwitch": true, 6 | "noImplicitReturns": true, 7 | "noUnusedLocals": true, 8 | "sourceMap": true, 9 | "strict": true, 10 | "types": ["node"], 11 | "target": "esnext", 12 | "moduleResolution": "node", 13 | "suppressImplicitAnyIndexErrors": true, 14 | "newLine": "lf", 15 | "preserveConstEnums": true, 16 | "outDir": "dist", 17 | "stripInternal": true 18 | }, 19 | "include": ["src/*.ts"] 20 | } 21 | --------------------------------------------------------------------------------