├── .gitignore ├── assets └── header.png ├── tsconfig.json ├── package.json ├── src ├── semantic │ ├── typing │ │ ├── types.ts │ │ └── index.ts │ └── analysis.ts ├── lexer │ ├── token.ts │ └── index.ts ├── parser │ ├── ast.ts │ └── index.ts └── bindings │ ├── ffi.ts │ └── index.ts ├── TODO.md ├── syntax_proposal.yt ├── docs ├── ROADMAP.md └── SYNTAX.md ├── index.ts ├── CONTRIBUTING.md ├── tests ├── typing │ └── index.test.ts └── bindings │ └── index.test.ts ├── README.md ├── bun.lock └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | objects 3 | out -------------------------------------------------------------------------------- /assets/header.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/element39/yttria/HEAD/assets/header.png -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext", 4 | "module": "ESNext", 5 | "moduleResolution": "Node", 6 | "strict": true, 7 | "esModuleInterop": true, 8 | } 9 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "devDependencies": { 3 | "@types/bun": "^1.2.19" 4 | }, 5 | "dependencies": { 6 | "cmake-js": "^7.3.1" 7 | }, 8 | "trustedDependencies": [ 9 | "bun-llvm" 10 | ], 11 | "overrides": { 12 | "cmake-js": "7.3.1" 13 | } 14 | } -------------------------------------------------------------------------------- /src/semantic/typing/types.ts: -------------------------------------------------------------------------------- 1 | export type TypeKind = 2 | | "int" 3 | | "float" 4 | | "bool" 5 | | "string" 6 | 7 | export type Type = { 8 | kind: TypeKind 9 | } 10 | 11 | export type IntType = Type & { 12 | kind: "int" 13 | } 14 | 15 | export type FloatType = Type & { 16 | kind: "float" 17 | } 18 | 19 | export type BoolType = Type & { 20 | kind: "bool" 21 | } 22 | 23 | export type StringType = Type & { 24 | kind: "string" 25 | value: string 26 | } 27 | 28 | export const sameType = (a?: Type, b?: Type): boolean => { 29 | if (!a || !b) return false; 30 | 31 | if (a.kind !== b.kind) return false; 32 | return true; 33 | } 34 | 35 | export const similarType = (a?: Type, b?: Type): boolean => { 36 | if (!a || !b) return false; 37 | 38 | const groups: TypeKind[][] = [ 39 | ["int", "float"], 40 | ]; 41 | 42 | for (const group of groups) { 43 | if (group.includes(a.kind) && group.includes(b.kind)) { 44 | return true; 45 | } 46 | } 47 | 48 | return sameType(a, b); 49 | } 50 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | # todo 2 | 3 | ## lexer 4 | - [x] number literals 5 | - [x] string literals 6 | - [x] boolean literals 7 | - [x] null literals 8 | - [x] identifiers 9 | - [x] keywords 10 | - [x] operators 11 | - [x] delimiters 12 | - [x] comments 13 | - [ ] error handling (unknown tokens) 14 | 15 | ## parser 16 | - [x] number literals 17 | - [x] string literals 18 | - [x] boolean literals 19 | - [x] null literals 20 | - [x] identifiers 21 | - [x] functions 22 | - [x] function calls 23 | - [x] blocks 24 | - [x] return expressions 25 | - [x] if statements 26 | - [x] else statements 27 | - [x] binary expressions 28 | - [x] unary expressions 29 | - [x] variables 30 | - [x] comments 31 | - [x] switch statements 32 | - [x] while statements 33 | - [x] member access (dot operator) 34 | - [ ] error handling (syntax errors) 35 | 36 | ## typechecker 37 | - [x] variables 38 | - [x] infer type from usage 39 | - [x] annotation validation 40 | - [x] functions 41 | - [x] infer return type from usage 42 | - [x] type consistency 43 | - [ ] parameter type validation 44 | - [x] function call type validation 45 | - [x] if statements 46 | - [x] expressions 47 | - [x] binary expressions 48 | - [x] unary expressions 49 | - [x] literals 50 | - [x] identifiers 51 | - [ ] member access 52 | 53 | ## code generator (llvm-bindings) 54 | - [x] functions 55 | - [x] returns 56 | - [x] number literals 57 | - [x] if statements 58 | - [x] switch statements 59 | - [x] while statements 60 | - [x] variables 61 | - [x] binary expressions 62 | - [x] unary expressions 63 | - [ ] string comparison (for switch/case) 64 | - [ ] error handling (invalid IR) 65 | - [ ] advanced features (structs, arrays, etc.) -------------------------------------------------------------------------------- /src/lexer/token.ts: -------------------------------------------------------------------------------- 1 | export type Token = { 2 | type: TokenType 3 | literal: string 4 | } 5 | 6 | export type TokenType = 7 | | "EOF" 8 | | "EOL" 9 | | "Unknown" 10 | 11 | | "Comment" 12 | 13 | | "Identifier" 14 | | "Keyword" 15 | 16 | | "Operator" 17 | | "Delimiter" 18 | 19 | | "Null" 20 | | "Number" 21 | | "String" 22 | | "Boolean" 23 | 24 | export const Keywords = [ 25 | "fn", 26 | "return", 27 | 28 | "switch", 29 | "default", 30 | 31 | "if", 32 | "else", 33 | 34 | "while", 35 | "for", 36 | "break", 37 | "continue", 38 | 39 | "use", 40 | "as", 41 | "let", 42 | "const", 43 | ] as const 44 | 45 | export type Keyword = (typeof Keywords)[number] 46 | 47 | export const Modifiers = [ 48 | "pub", 49 | "extern", 50 | "foreign", 51 | ] as const 52 | 53 | export type Modifier = (typeof Modifiers)[number] // i didnt even know you could do this 54 | 55 | export const MultiCharDelimiters = [ 56 | ":=" 57 | ] 58 | 59 | export const SingleCharDelimiters = [ 60 | "(", 61 | ")", 62 | "{", 63 | "}", 64 | ",", 65 | ";", 66 | ":", 67 | "." 68 | ] 69 | 70 | export const SingleCharOperators = [ 71 | "<", 72 | ">", 73 | "!", 74 | "=", 75 | "+", 76 | "-", 77 | "*", 78 | "/", 79 | "&", 80 | "|" 81 | ] 82 | 83 | export const MultiCharOperators = [ 84 | "==", 85 | "!=", 86 | "<=", 87 | ">=", 88 | "->", 89 | "=>", 90 | "&&", 91 | "||", 92 | "++", 93 | "--", 94 | "+=", 95 | "-=", 96 | "*=", 97 | "/=" 98 | ] -------------------------------------------------------------------------------- /syntax_proposal.yt: -------------------------------------------------------------------------------- 1 | // syntax_proposal.yt 2 | 3 | [| 4 | yttria 5 | a blazingly fast*, universal* and easy-to-use* programming language 6 | for anything you can imagine* 7 | * = not true (yet) 8 | 9 | this file is a complete (albeit meaningless) program 10 | that demonstrates the syntax of yttria 11 | it is not meant to be run, but rather to be read 12 | it is a work in progress, so expect changes in the future 13 | |] 14 | 15 | use std/io; 16 | 17 | fn main() -> void { 18 | const a := 1 19 | const b: int = 2 20 | let c := 3 21 | let d: float = 4.5 22 | 23 | io.println(`sum: {a + b}`) 24 | 25 | try io.write("file.txt", "Hello, World!") 26 | catch (e) io.println(`Error writing to file: {e}`) 27 | finally io.println("Attempted to write to file.") 28 | 29 | io.println("File written successfully.") 30 | 31 | const numbers: int[] = [1, 2, 3, 4, 5] 32 | for (const num in numbers) { 33 | io.println(`Number: {num}`) 34 | } 35 | 36 | if (a < b) { 37 | io.println("a is less than b") 38 | } else if (a > b) { 39 | io.println("a is greater than b") 40 | } else { 41 | io.println("a is equal to b") 42 | } 43 | 44 | switch (c) { 45 | case 1: 46 | io.println("c is 1") 47 | case 2: 48 | io.println("c is 2") 49 | default: 50 | io.println("c is something else") 51 | } 52 | 53 | for (let i := 0 -> 5) { 54 | io.println(i) // 0, 1, 2, 3, 4 55 | } 56 | 57 | for (let i := 0 => 5) { 58 | io.println(i) // 0, 1, 2, 3, 4, 5 59 | } 60 | } 61 | 62 | fn fib(n: int) -> int { 63 | if (n <= 1) { 64 | return n 65 | } 66 | 67 | return fib(n - 1) + fib(n - 2) 68 | } -------------------------------------------------------------------------------- /docs/ROADMAP.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 5 | --- 6 | ## roadmap 7 | 8 | > [!NOTE] 9 | > this roadmap is subject to change and might be innacurate/outdated at any time, 10 | > please refer to the [status report](#status-report) for the most up-to-date information 11 | 12 | 13 | 14 | ### language core 15 | current version: `v0.0.3.alpha-1` 16 | ``` 17 | item xx% progress bar time until complete (from last task) 18 | 19 | lexer 100% █████████████ practically complete 20 | parser 100% █████████████ practically complete 21 | typechecker 85% ██████████▓░░ complete soon 22 | codegen 45% ███████▓░░░░░ 2-3 weeks 23 | ``` 24 | 25 | ### std 26 | ``` 27 | item xx% progress bar time until complete (from last task) 28 | 29 | std/io 10% █░░░░░░░░░░░░ 2 weeks 30 | std/fs 0% ░░░░░░░░░░░░░ no eta 31 | std/net 0% ░░░░░░░░░░░░░ no eta 32 | std/math 0% ░░░░░░░░░░░░░ no eta 33 | ``` 34 | 35 | ### tools 36 | ``` 37 | item xx% progress bar time until complete (from last task) 38 | 39 | cli 0% ░░░░░░░░░░░░░ no eta 40 | language server 0% ░░░░░░░░░░░░░ no eta 41 | extensions 0% ░░░░░░░░░░░░░ no eta 42 | ``` 43 | 44 | ## status report 45 | > last updated: 28/7/2025 (dd/mm/yyyy) 46 | 47 | yttria is still in early development; lexer and parser are finished!!! typechecker (and now inferrer) have been overhauled, codegen still supports core features buandt advanced features are still in progress. basic stdlib available but unusable for now 48 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | import { rmSync } from "fs" 2 | import { Lexer } from "./src/lexer" 3 | import { Parser } from "./src/parser" 4 | import { SemanticAnalyzer } from "./src/semantic/analysis" 5 | import { TypeChecker } from "./src/semantic/typing" 6 | rmSync("./out", { recursive: true, force: true }) 7 | 8 | // error driven development right here 9 | // const program = ` 10 | // use std/io 11 | 12 | // pub fn main() { 13 | // io.println("hi") 14 | // } 15 | // `.trim() 16 | 17 | // const program = ` 18 | // fn main() -> int { 19 | // let x := 2 20 | 21 | // switch (x) { 22 | // 0 -> { 23 | // return 22 24 | // } 25 | // 1 -> { 26 | // return 12 27 | // } 28 | // 2 -> { 29 | // return 3 30 | // } 31 | // default -> { 32 | // return 7 33 | // } 34 | // } 35 | 36 | // return 1 37 | // } 38 | // `.trim() 39 | 40 | const program = ` 41 | fn main() { 42 | let x := true 43 | let y := 3 + x 44 | } 45 | `.trim() 46 | 47 | const start = performance.now() 48 | 49 | const l = new Lexer(program) 50 | const t = l.lex() 51 | const lexerTime = performance.now() 52 | await Bun.write("out/tok.json", JSON.stringify(t, null, 2)) 53 | 54 | console.log(`lexed ${t.length} tokens in ${(lexerTime - start).toFixed(3)}ms`) 55 | 56 | const p = new Parser(t) 57 | const ast = p.parse() 58 | await Bun.write("out/ast.json", JSON.stringify(ast, null, 2)) 59 | const astTime = performance.now() 60 | 61 | console.log(`parsed ${t.length} tokens in ${(astTime - lexerTime).toFixed(3)}ms, generated ${ast.body.length} root node(s)`) 62 | 63 | const sa = new SemanticAnalyzer(ast) 64 | const analyzed = sa.analyze() 65 | 66 | const tc = new TypeChecker(ast) 67 | tc.check() 68 | 69 | await Bun.write("out/semantic.json", JSON.stringify(analyzed, null, 2)) 70 | const semanticTime = performance.now() 71 | 72 | console.log(`semantic analysis done in ${(semanticTime - astTime).toFixed(3)}ms`) 73 | 74 | console.log(`total time: ${(semanticTime - start).toFixed(3)}ms`) -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 5 | --- 6 | 7 | # overview 8 | 9 | hey! thanks for thinking about contributing to yttria! 10 | all contributions are welcome, whether it’s code, docs, tests, or ideas. 11 | 12 | ## how to contribute 13 | 14 | - install bun & llvm-14.0.6 15 | - `powershell -c "irm bun.sh/install.ps1 | iex"` (windows) 16 | - `curl -fsSL https://bun.sh/install | bash` (macOS/Linux) 17 | - `scoop install llvm@14.0.6` (windows) 18 | - make sure llvm is in your PATH 19 | - make sure llvm has LLVM-C.dll / libLLVM-C.so in its binaries 20 | - fork the repo and create a new branch for your changes 21 | - make your changes (keep code clean & readable) 22 | - run tests and make sure everything passes 23 | - open a pull request with a clear but small description of your changes 24 | - be respectful and constructive in discussions 25 | 26 | ## setup 27 | ```sh 28 | git clone https://github.com/grngxd/yttria 29 | cd yttria 30 | 31 | # install bun (https://bun.sh) 32 | bun i 33 | 34 | # install llvm (14.0.x) e.g. 14.0.6 35 | bun run --watch . 36 | ``` 37 | 38 | ## style guide 39 | 40 | - PascalCase for constants & types, camelCase for variables & functions 41 | - use tabs for indentation (4 spaces) (not a requirement, we can uses biome or something) 42 | - keep code concise, and easy to read (noticing a theme?) 43 | - prefer type inference where possible (in both yt and ts) 44 | - write meaningful commit messages (im soooo guilty of not doing this before v0.0.1) 45 | 46 | ## issues & suggestions 47 | 48 | - open an issue for bugs, feature requests, or questions 49 | - include as much detail as possible (steps to reproduce, code samples, etc.) 50 | - check for existing issues before opening a new one 51 | - please dont be mad if your issue is closed, it may be a duplicate or not relevant anymore 52 | 53 | ## roadmap 54 | 55 | see [docs/ROADMAP.md](docs/ROADMAP.md) and [TODO.md](TODO.md) for current progress and priorities, try to make your own judgement on current progress though, as these are slightly outdated most of the time, some features may be cut at any time too. 56 | 57 | --- 58 | 59 | happy hacking! -------------------------------------------------------------------------------- /src/semantic/analysis.ts: -------------------------------------------------------------------------------- 1 | import { BinaryExpression, Expression, ExpressionType, FunctionDeclaration, Identifier, ProgramExpression, VariableDeclaration } from "../parser/ast"; 2 | 3 | type Symbol = 4 | | { type: "variable"; name: Identifier, value: Expression } 5 | | { type: "function"; name: Identifier, body: Expression[] } 6 | 7 | export class SemanticAnalyzer { 8 | private symbols: Map = new Map() 9 | private ast: ProgramExpression 10 | 11 | private table: { [key in ExpressionType]?: (e: Expression) => Symbol | undefined } = { 12 | "FunctionDeclaration": (e) => this.visitFunctionDeclaration(e as FunctionDeclaration), 13 | "VariableDeclaration": (e) => this.visitVariableDeclaration(e as VariableDeclaration), 14 | } 15 | 16 | constructor(ast: ProgramExpression) { 17 | this.ast = ast 18 | } 19 | 20 | analyze() { 21 | for (const expr of this.ast.body) { 22 | this.table[expr.type]?.(expr) 23 | } 24 | 25 | return this.ast 26 | } 27 | 28 | private visitVariableDeclaration(v: VariableDeclaration): Symbol | undefined { 29 | const name = (v.name as Identifier).value 30 | const symbol: Symbol = { type: "variable", name: v.name as Identifier, value: v.value } 31 | 32 | if (this.symbols.has(name)) { 33 | throw new Error(`variable ${name} is already declared`) 34 | } else { 35 | this.symbols.set(name, symbol) 36 | } 37 | 38 | this.visitExpression(v.value) 39 | 40 | return symbol 41 | } 42 | 43 | private visitFunctionDeclaration(f: FunctionDeclaration): Symbol | undefined { 44 | const name = (f.name as Identifier).value 45 | const symbol: Symbol = { type: "function", name: f.name as Identifier, body: f.body } 46 | 47 | if (this.symbols.has(name)) { 48 | throw new Error(`function ${name} is already declared`) 49 | } 50 | 51 | this.symbols.set(name, symbol) 52 | for (const expr of f.body) { 53 | this.visitExpression(expr) 54 | } 55 | 56 | return symbol 57 | } 58 | 59 | private visitExpression(e: Expression): Symbol | undefined { 60 | switch (e.type) { 61 | case "BinaryExpression": { 62 | this.visitExpression((e as BinaryExpression).left) 63 | this.visitExpression((e as BinaryExpression).right) 64 | return undefined 65 | } 66 | 67 | case "Identifier": { 68 | const name = (e as Identifier).value 69 | if (!this.symbols.has(name)) { 70 | throw new Error(`symbol "${name}" is not defined`) 71 | } 72 | return undefined 73 | } 74 | } 75 | 76 | return this.table[e.type]?.(e) 77 | } 78 | } -------------------------------------------------------------------------------- /tests/typing/index.test.ts: -------------------------------------------------------------------------------- 1 | import { expect, it } from "bun:test"; 2 | import { Lexer } from "../../src/lexer"; 3 | import { Parser } from "../../src/parser"; 4 | import { FunctionDeclaration, VariableDeclaration } from "../../src/parser/ast"; 5 | import { TypeInferrer } from "../../src/typing/inference"; 6 | import { CheckerType } from "../../src/typing/types"; 7 | import { TypeChecker } from "../../src/typing/checker"; 8 | 9 | it("constrained variables", () => { 10 | const mod = ` 11 | let a := 5 12 | let x := a * 2 13 | let y := x + a 14 | `.trim(); 15 | 16 | const tokens = new Lexer(mod).lex(); 17 | const ast = new Parser(tokens).parse(); 18 | const inf = new TypeInferrer(ast); 19 | const inferred = inf.infer(); 20 | 21 | expect((inferred.body[0] as VariableDeclaration).resolvedType!.type).toBe("CheckerType"); 22 | expect(((inferred.body[0] as VariableDeclaration).resolvedType as CheckerType).value).toBe("int"); 23 | 24 | expect((inferred.body[1] as VariableDeclaration).resolvedType!.type).toBe("CheckerType"); 25 | expect(((inferred.body[1] as VariableDeclaration).resolvedType as CheckerType).value).toBe("int"); 26 | 27 | expect((inferred.body[2] as VariableDeclaration).resolvedType!.type).toBe("CheckerType"); 28 | expect(((inferred.body[2] as VariableDeclaration).resolvedType as CheckerType).value).toBe("int"); 29 | 30 | // console.log(JSON.stringify(inferred.body, null, 2)); 31 | const chk = new TypeChecker(inferred); 32 | const errors = chk.check(); 33 | 34 | expect(errors.length).toBe(0); 35 | }); 36 | 37 | it("bool", () => { 38 | const mod = ` 39 | let a := false 40 | let b: bool = a 41 | `.trim(); 42 | 43 | const tokens = new Lexer(mod).lex(); 44 | const ast = new Parser(tokens).parse(); 45 | const inf = new TypeInferrer(ast); 46 | const inferred = inf.infer(); 47 | 48 | expect((inferred.body[0] as VariableDeclaration).resolvedType!.type).toBe("CheckerType"); 49 | expect(((inferred.body[0] as VariableDeclaration).resolvedType as CheckerType).value).toBe("bool"); 50 | 51 | const chk = new TypeChecker(inferred); 52 | const errors = chk.check(); 53 | 54 | expect(errors.length).toBe(0); 55 | }) 56 | 57 | it("type mismatch", () => { 58 | const mod = ` 59 | let a: string = 5 + 1 60 | let b: bool = a 61 | let c: int = b 62 | `.trim(); 63 | 64 | const tokens = new Lexer(mod).lex(); 65 | const ast = new Parser(tokens).parse(); 66 | const inf = new TypeInferrer(ast); 67 | const inferred = inf.infer(); 68 | 69 | expect((inferred.body[0] as VariableDeclaration).resolvedType!.type).toBe("CheckerType"); 70 | expect(((inferred.body[0] as VariableDeclaration).resolvedType as CheckerType).value).toBe("int"); 71 | 72 | const chk = new TypeChecker(inferred); 73 | const errors = chk.check(); 74 | 75 | //console.log(inferred.body); 76 | console.log(errors) 77 | expect(errors.length).toBe(4); 78 | }) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 5 | --- 6 | 7 | > ` a blazingly fast, statically-typed expressive language for building anything from scripts to systems. ` 8 | 9 | --- 10 | 11 | > [!CAUTION] 12 | > ### yttria is still in early development and is **EXTREMELY** experimental. expect breaking changes and limited documentation, some stuff may not even exist yet. 13 | 14 |
15 | 16 |
17 | 18 | ```rust 19 | // fib.yt 20 | fn fib(n: int) -> int { 21 | if (n <= 1) { 22 | return n 23 | } 24 | 25 | return fib(n - 1) + fib(n - 2) 26 | } 27 | ``` 28 | 29 |
30 | 31 |
32 | 33 | ## key goals 34 | 35 | **high performance**: designed for speed, with performance rivaling Rust & C 36 | **expressiveness**: write concise, clean & clear code for everything from web development to systems programming 37 | **safety & ergonomics**: statically-typed with encouraged type inference & robust error handling 38 | **write once, run anywhere**: build reliable software for any platform (or none at all) with a friendly std library 39 | 40 |
41 | 42 |
43 | 44 | ## why yttria? 45 | 46 | yittria ([/ˈjɪtʃ.ri.ə/](https://ipa-reader.com/?text=%2F%CB%88j%C9%AAt%CA%83.ri.%C9%99%2F), pronounced `yi-tch-ria`) is a **fast, expressive language** that lets you build anything from scripts to systems. 47 | It combines the **performance of C** with the **expressiveness of Typescript**, making it ideal for both beginners and experienced developers. 48 | Whether you're building web apps, games, or low-level systems, yttria has you covered. 49 | 50 | ## syntax guide & language roadmap 51 | 52 | the yttria syntax is designed to be **familiar and intuitive**, especially for those with experience in languages like Go/C, Typescript or Rust. view it [here](./docs/SYNTAX.md). the current progress with the yttria language is documented in the [todo](./TODO.md) and also in the [language roadmap](./docs/ROADMAP.md) 53 | 54 | ## getting started 55 | to get started with yttria, you can use the cli tool. 56 | 57 | ```bash 58 | # install the yttria cli tool 59 | ... 60 | # create a new yttria project 61 | yt init 62 | # run your yttria program 63 | yt run . 64 | # build your yttria program 65 | yt build . 66 | ``` 67 | 68 | ## features 69 | yttria includes a wide range of features to help you build robust applications: 70 | - **statically typed** with type inference 71 | - **powerful pattern matching** for concise data handling 72 | - **macros** for metaprogramming and code generation 73 | - **async/await** for easy concurrency 74 | - **first-class functions** and **closures** (functions inside functions) for functional programming 75 | - **extensive standard library** for common tasks 76 | - **robust error handling** with `try/catch` and `Result` types 77 | - **cross-platform support** for building applications on any platform 78 | - and much more! 79 | 80 | ## community 81 | you can find us on: 82 | - [github](https://github.com/grngxd/yttria) 83 | - [twitter](https://twitter.com/grngxd) -------------------------------------------------------------------------------- /src/semantic/typing/index.ts: -------------------------------------------------------------------------------- 1 | import { BinaryExpression, Expression, ExpressionType, FunctionDeclaration, Identifier, NumberLiteral, ProgramExpression, VariableDeclaration } from "../../parser/ast" 2 | import { similarType, Type } from "./types" 3 | 4 | export class TypeEnvironment { 5 | private types: Map = new Map() 6 | private parent?: TypeEnvironment 7 | 8 | constructor(parent?: TypeEnvironment) { 9 | this.parent = parent 10 | 11 | if (!parent) { 12 | this.types.set("int", { kind: "int" }) 13 | this.types.set("float", { kind: "float" }) 14 | this.types.set("bool", { kind: "bool" }) 15 | this.types.set("string", { kind: "string" }) 16 | } 17 | } 18 | 19 | define(name: string, type: Type) { 20 | if (this.types.has(name)) { 21 | throw new Error(`type ${name} already defined`) 22 | } 23 | this.types.set(name, type) 24 | } 25 | 26 | get(name: string): Type | undefined { 27 | return this.types.get(name) ?? this.parent?.get(name) 28 | } 29 | 30 | createChild(): TypeEnvironment { 31 | return new TypeEnvironment(this) 32 | } 33 | 34 | restoreParent(): TypeEnvironment { 35 | if (!this.parent) throw new Error("no parent environment to restore to"); 36 | return this.parent 37 | } 38 | } 39 | 40 | export class TypeChecker { 41 | private env: TypeEnvironment 42 | private ast: ProgramExpression 43 | 44 | private table: { [key in ExpressionType]?: (expr: Expression) => Type | undefined } = { 45 | "FunctionDeclaration": (expr) => this.visitFunctionDeclaration(expr as FunctionDeclaration), 46 | 47 | "Identifier": (expr) => this.visitIdentifier(expr as Identifier), 48 | 49 | "BinaryExpression": (expr) => this.visitBinaryExpression(expr as BinaryExpression), 50 | "VariableDeclaration": (expr) => this.visitVariableDeclaration(expr as VariableDeclaration), 51 | 52 | "NumberLiteral": (expr) => { return Number.isInteger((expr as NumberLiteral).value) ? { kind: "int" } : { kind: "float" } }, 53 | "BooleanLiteral": (expr) => { return { kind: "bool" } }, 54 | } 55 | 56 | constructor(ast: ProgramExpression, env?: TypeEnvironment) { 57 | this.ast = ast 58 | this.env = env ?? new TypeEnvironment() 59 | } 60 | 61 | check() { 62 | for (const expr of this.ast.body) { 63 | this.checkExpression(expr) 64 | } 65 | 66 | return this.ast 67 | } 68 | 69 | private checkExpression(expr: Expression): Type | undefined { 70 | const fn = this.table[expr.type] 71 | if (!fn) throw new Error(`no type rule for ${expr.type}`) 72 | return fn(expr) 73 | } 74 | 75 | private visitFunctionDeclaration(f: FunctionDeclaration) { 76 | this.env = this.env.createChild(); 77 | 78 | for (const expr of f.body) { 79 | this.checkExpression(expr) 80 | } 81 | 82 | const restored = this.env.restoreParent(); 83 | return undefined; 84 | } 85 | 86 | private visitIdentifier(id: Identifier): Type { 87 | const t = this.env.get(id.value) 88 | if (!t) throw new Error(`undefined symbol: ${id.value}`) 89 | return t 90 | } 91 | 92 | private visitBinaryExpression(b: BinaryExpression): Type { 93 | const leftType = this.checkExpression(b.left) 94 | const rightType = this.checkExpression(b.right) 95 | 96 | if (!leftType) { 97 | throw new Error("Left side of binary expression has undefined type") 98 | } 99 | if (!rightType) { 100 | throw new Error("Right side of binary expression has undefined type") 101 | } 102 | 103 | if (!similarType(leftType, rightType)) { 104 | throw new Error( 105 | `type mismatch in binary expression: ${leftType.kind} vs ${rightType.kind}` 106 | ) 107 | } 108 | 109 | return leftType 110 | } 111 | 112 | private visitVariableDeclaration(v: VariableDeclaration): Type | undefined { 113 | const name = v.name.value 114 | const type = this.checkExpression(v.value) 115 | if (!type) throw new Error(`undefined type for variable: ${name}`) 116 | this.env.define(name, type) 117 | return type 118 | } 119 | } -------------------------------------------------------------------------------- /src/parser/ast.ts: -------------------------------------------------------------------------------- 1 | import { Modifier } from "../lexer/token" 2 | //import { CheckerPlaceholder, CheckerType } from "../typing/types" 3 | 4 | export type Expression = { 5 | type: ExpressionType 6 | } 7 | 8 | export type ExpressionType = 9 | | "Program" 10 | 11 | | "Identifier" 12 | | "MemberAccess" 13 | | "ImportExpression" 14 | 15 | | "FunctionDeclaration" 16 | | "FunctionParam" 17 | | "FunctionCall" 18 | | "ReturnExpression" 19 | 20 | | "IfExpression" 21 | | "ElseExpression" 22 | 23 | | "WhileExpression" 24 | 25 | | "SwitchExpression" 26 | | "CaseExpression" 27 | 28 | | "BinaryExpression" // n > 1 29 | | "PreUnaryExpression" // -n 30 | | "PostUnaryExpression" // x++ 31 | 32 | | "VariableDeclaration" 33 | 34 | | "NumberLiteral" 35 | | "StringLiteral" 36 | | "BooleanLiteral" 37 | | "NullLiteral" 38 | 39 | | "CommentExpression" 40 | 41 | export type ProgramExpression = Expression & { 42 | type: "Program" 43 | body: Expression[] 44 | } 45 | 46 | export type Identifier = Expression & { 47 | type: "Identifier" 48 | value: string 49 | } 50 | 51 | // foo.bar.baz or foo.bar() etc 52 | export type MemberAccess = Expression & { 53 | type: "MemberAccess" 54 | object: Expression 55 | property: Expression 56 | } 57 | 58 | export type ImportExpression = Expression & { 59 | type: "ImportExpression" 60 | path: string // e.g std/io 61 | alias?: string // use std/io as aliased_name 62 | } 63 | 64 | export type FunctionDeclaration = Expression & { 65 | type: "FunctionDeclaration" 66 | name: Identifier 67 | params: FunctionParam[] 68 | returnType?: Identifier 69 | // resolvedReturnType?: CheckerType | CheckerPlaceholder 70 | body: Expression[] 71 | modifiers: Modifier[] 72 | } 73 | 74 | export type FunctionCall = Expression & { 75 | type: "FunctionCall" 76 | callee: Identifier// | MemberAccess 77 | // inferredCallee?: CheckerType | CheckerPlaceholder 78 | args: Expression[] 79 | } 80 | 81 | export type FunctionParam = { 82 | type: "FunctionParam" 83 | name: Identifier 84 | paramType: Identifier 85 | } 86 | 87 | export type IfExpression = Expression & { 88 | type: "IfExpression" 89 | condition: Expression 90 | // inferredCondition?: CheckerType | CheckerPlaceholder 91 | body: Expression[] 92 | alternate?: IfExpression | ElseExpression 93 | } 94 | 95 | export type ElseExpression = Expression & { 96 | type: "ElseExpression" 97 | body: Expression[] 98 | } 99 | 100 | export type WhileExpression = Expression & { 101 | type: "WhileExpression" 102 | condition: Expression 103 | // inferredCondition?: CheckerType | CheckerPlaceholder 104 | body: Expression[] 105 | } 106 | 107 | export type SwitchExpression = Expression & { 108 | type: "SwitchExpression" 109 | value: Expression 110 | // inferredValue?: CheckerType | CheckerPlaceholder 111 | cases: CaseExpression[] 112 | } 113 | 114 | export type CaseExpression = Expression & { 115 | type: "CaseExpression" 116 | value: Expression | "default" 117 | // inferredValue?: CheckerType | CheckerPlaceholder 118 | body: Expression[] 119 | } 120 | 121 | export type ReturnExpression = Expression & { 122 | type: "ReturnExpression" 123 | value: Expression 124 | } 125 | 126 | export type VariableDeclaration = Expression & { 127 | type: "VariableDeclaration" 128 | name: Identifier 129 | value: Expression 130 | typeAnnotation?: Identifier 131 | // resolvedType?: CheckerType | CheckerPlaceholder 132 | mutable: boolean 133 | } 134 | 135 | export type NumberLiteral = Expression & { 136 | type: "NumberLiteral" 137 | value: number 138 | } 139 | 140 | export type StringLiteral = Expression & { 141 | type: "StringLiteral" 142 | value: string 143 | } 144 | 145 | export type BooleanLiteral = Expression & { 146 | type: "BooleanLiteral" 147 | value: boolean 148 | } 149 | 150 | export type NullLiteral = Expression & { 151 | type: "NullLiteral" 152 | value: null 153 | } 154 | 155 | export type BinaryExpression = Expression & { 156 | type: "BinaryExpression" 157 | left: Expression 158 | operator: string 159 | right: Expression 160 | } 161 | 162 | export type BaseUnaryExpression = Expression & { 163 | operator: string 164 | operand: Expression 165 | } 166 | 167 | export type PreUnaryExpression = BaseUnaryExpression & { 168 | type: "PreUnaryExpression" 169 | } 170 | 171 | export type PostUnaryExpression = BaseUnaryExpression & { 172 | type: "PostUnaryExpression" 173 | } 174 | 175 | export type UnaryExpression = PreUnaryExpression | PostUnaryExpression 176 | 177 | export type CommentExpression = Expression & { 178 | type: "CommentExpression" 179 | value: string 180 | } -------------------------------------------------------------------------------- /src/bindings/ffi.ts: -------------------------------------------------------------------------------- 1 | import { dlopen } from "bun:ffi"; 2 | import { platform } from "os"; 3 | 4 | const location = platform() === "win32" ? "LLVM-C.dll" : "libLLVM-C.so"; 5 | 6 | const lib = dlopen(location, { 7 | LLVMConstStringInContext: { args: ["ptr", "cstring", "uint32_t", "bool"], returns: "ptr" }, 8 | LLVMArrayType: { args: ["ptr", "uint32_t"], returns: "ptr" }, 9 | LLVMAddGlobal: { args: ["ptr", "ptr", "cstring"], returns: "ptr" }, 10 | LLVMSetInitializer: { args: ["ptr", "ptr"], returns: "void" }, 11 | LLVMSetGlobalConstant: { args: ["ptr", "bool"], returns: "void" }, 12 | LLVMBuildCall2: { args: ["ptr", "ptr", "ptr", "ptr", "uint32_t", "cstring"], returns: "ptr" }, 13 | LLVMGetNamedFunction: { args: ["ptr", "cstring"], returns: "ptr" }, 14 | LLVMBuildICmp: { args: ["ptr", "int32_t", "ptr", "ptr", "cstring"], returns: "ptr" }, 15 | LLVMGetInsertBlock: { args: ["ptr"], returns: "ptr" }, 16 | 17 | // context & module 18 | LLVMContextCreate: { args: [], returns: "ptr" }, 19 | LLVMModuleCreateWithNameInContext: { args: ["cstring", "ptr"], returns: "ptr" }, 20 | LLVMCreateBuilderInContext: { args: ["ptr"], returns: "ptr" }, 21 | 22 | // types 23 | LLVMInt1TypeInContext: { args: ["ptr"], returns: "ptr" }, 24 | 25 | LLVMInt8TypeInContext: { args: ["ptr"], returns: "ptr" }, 26 | LLVMInt16TypeInContext: { args: ["ptr"], returns: "ptr" }, 27 | LLVMInt32TypeInContext: { args: ["ptr"], returns: "ptr" }, 28 | LLVMInt64TypeInContext: { args: ["ptr"], returns: "ptr" }, 29 | 30 | LLVMFloatTypeInContext: { args: ["ptr"], returns: "ptr" }, 31 | LLVMDoubleTypeInContext: { args: ["ptr"], returns: "ptr" }, 32 | 33 | LLVMVoidTypeInContext: { args: ["ptr"], returns: "ptr" }, 34 | LLVMPointerType: { args: ["ptr", "uint32_t"], returns: "ptr" }, 35 | 36 | // functions & blocks 37 | LLVMFunctionType: { args: ["ptr", "ptr", "uint32_t", "bool"], returns: "ptr" }, 38 | LLVMAddFunction: { args: ["ptr", "cstring", "ptr"], returns: "ptr" }, 39 | LLVMAppendBasicBlockInContext: { args: ["ptr", "ptr", "cstring"], returns: "ptr" }, 40 | LLVMDeleteBasicBlock: { args: ["ptr"], returns: "void" }, 41 | LLVMGetParam: { args: ["ptr", "uint32_t"], returns: "ptr" }, 42 | LLVMSetLinkage: { args: ["ptr", "int32_t"], returns: "void" }, 43 | 44 | // ir building 45 | LLVMPositionBuilderAtEnd: { args: ["ptr", "ptr"], returns: "void" }, 46 | LLVMBuildAdd: { args: ["ptr", "ptr", "ptr", "cstring"], returns: "ptr" }, 47 | LLVMBuildFAdd: { args: ["ptr", "ptr", "ptr", "cstring"], returns: "ptr" }, 48 | LLVMBuildSub: { args: ["ptr", "ptr", "ptr", "cstring"], returns: "ptr" }, 49 | LLVMBuildFSub: { args: ["ptr", "ptr", "ptr", "cstring"], returns: "ptr" }, 50 | LLVMBuildMul: { args: ["ptr", "ptr", "ptr", "cstring"], returns: "ptr" }, 51 | LLVMBuildFMul: { args: ["ptr", "ptr", "ptr", "cstring"], returns: "ptr" }, 52 | LLVMBuildSDiv: { args: ["ptr", "ptr", "ptr", "cstring"], returns: "ptr" }, 53 | LLVMBuildUDiv: { args: ["ptr", "ptr", "ptr", "cstring"], returns: "ptr" }, 54 | LLVMBuildFDiv: { args: ["ptr", "ptr", "ptr", "cstring"], returns: "ptr" }, 55 | LLVMBuildRet: { args: ["ptr", "ptr"], returns: "ptr" }, 56 | LLVMBuildBr: { args: ["ptr", "ptr"], returns: "ptr" }, 57 | LLVMBuildCondBr: { args: ["ptr", "ptr", "ptr", "ptr"], returns: "ptr" }, 58 | 59 | // memory 60 | LLVMBuildAlloca: { args: ["ptr", "ptr", "cstring"], returns: "ptr" }, 61 | LLVMBuildStore: { args: ["ptr", "ptr", "ptr"], returns: "ptr" }, 62 | LLVMBuildLoad: { args: ["ptr", "ptr", "cstring"], returns: "ptr" }, 63 | 64 | // constants 65 | LLVMConstInt: { args: ["ptr", "uint64_t", "bool"], returns: "ptr" }, 66 | LLVMConstReal: { args: ["ptr", "double"], returns: "ptr" }, 67 | 68 | // utils 69 | LLVMPrintModuleToString: { args: ["ptr"], returns: "cstring" }, 70 | LLVMVerifyFunction: { args: ["ptr", "uint32_t"], returns: "int" }, 71 | LLVMVerifyModule: { args: ["ptr", "uint32_t", "ptr"], returns: "int" }, 72 | LLVMBuildBitCast: { args: ["ptr", "ptr", "ptr", "cstring"], returns: "ptr" }, 73 | 74 | // introspection 75 | LLVMGetIntTypeWidth: { args: ["ptr"], returns: "uint32_t" }, 76 | LLVMTypeOf: { args: ["ptr"], returns: "ptr" }, 77 | LLVMGetTypeKind: { args: ["ptr"], returns: "uint32_t" } 78 | }); 79 | 80 | export const { 81 | LLVMContextCreate, 82 | LLVMModuleCreateWithNameInContext, 83 | LLVMCreateBuilderInContext, 84 | 85 | LLVMInt1TypeInContext, 86 | LLVMInt8TypeInContext, 87 | LLVMInt16TypeInContext, 88 | LLVMInt32TypeInContext, 89 | LLVMInt64TypeInContext, 90 | LLVMFloatTypeInContext, 91 | LLVMDoubleTypeInContext, 92 | LLVMVoidTypeInContext, 93 | LLVMPointerType, 94 | 95 | LLVMFunctionType, 96 | LLVMAddFunction, 97 | LLVMAppendBasicBlockInContext, 98 | LLVMGetParam, 99 | LLVMDeleteBasicBlock, 100 | LLVMBuildRet, 101 | LLVMSetLinkage, 102 | 103 | LLVMBuildAdd, 104 | LLVMBuildFAdd, 105 | LLVMBuildSub, 106 | LLVMBuildFSub, 107 | LLVMBuildMul, 108 | LLVMBuildFMul, 109 | LLVMBuildSDiv, 110 | LLVMBuildUDiv, 111 | LLVMBuildFDiv, 112 | 113 | LLVMBuildBr, 114 | LLVMBuildCondBr, 115 | 116 | LLVMPositionBuilderAtEnd, 117 | LLVMPrintModuleToString, 118 | LLVMVerifyFunction, 119 | LLVMVerifyModule, 120 | LLVMTypeOf, 121 | LLVMConstInt, 122 | LLVMConstReal, 123 | LLVMGetIntTypeWidth, 124 | LLVMBuildAlloca, 125 | LLVMBuildStore, 126 | LLVMBuildLoad, 127 | LLVMGetNamedFunction, 128 | LLVMBuildCall2, 129 | LLVMBuildICmp, 130 | LLVMGetInsertBlock, 131 | LLVMConstStringInContext, 132 | LLVMArrayType, 133 | LLVMAddGlobal, 134 | LLVMSetInitializer, 135 | LLVMSetGlobalConstant, 136 | LLVMBuildBitCast, 137 | LLVMGetTypeKind 138 | } = lib.symbols; -------------------------------------------------------------------------------- /src/lexer/index.ts: -------------------------------------------------------------------------------- 1 | import { Keywords, Modifiers, MultiCharDelimiters, MultiCharOperators, SingleCharDelimiters, SingleCharOperators, Token } from "./token" 2 | 3 | export class Lexer { 4 | tokens: Token[] = [] 5 | src: string 6 | pos: number = 0 7 | 8 | constructor(src: string) { 9 | this.src = src 10 | } 11 | 12 | public lex(): Token[] { 13 | this.pos = 0 14 | while (this.pos < this.src.length) { 15 | this.skipWhitespace() 16 | const char = this.advance() 17 | 18 | // if (char === "\n") { 19 | // this.tokens.push({ 20 | // type: "EOL", 21 | // literal: char 22 | // }) 23 | // continue 24 | // } 25 | 26 | // comments 27 | // // ... 28 | if (char == "/" && this.peek() == "/") { 29 | let literal = "" 30 | this.advance() 31 | while (this.pos < this.src.length && this.src[this.pos] !== "\n") { 32 | literal += this.advance() 33 | } 34 | this.tokens.push({ 35 | type: "Comment", 36 | literal 37 | }) 38 | continue 39 | } 40 | 41 | // # ... 42 | if (char == "#") { 43 | let literal = "" 44 | while (this.pos < this.src.length && this.src[this.pos] !== "\n") { 45 | literal += this.advance() 46 | } 47 | this.tokens.push({ 48 | type: "Comment", 49 | literal: literal.trim() 50 | }) 51 | continue 52 | } 53 | 54 | // /* ... */ 55 | if (char === "/" && this.peek() === "*") { 56 | let literal = "" 57 | this.advance() 58 | 59 | while (this.pos < this.src.length && !(this.peek() === "*" && this.peek(1) === "/")) { 60 | literal += this.advance() 61 | } 62 | 63 | if (this.peek() === "*" && this.peek(1) === "/") { 64 | this.advance() 65 | this.advance() 66 | } 67 | 68 | this.tokens.push({ 69 | type: "Comment", 70 | literal: literal.trim() 71 | }) 72 | continue 73 | } 74 | 75 | // [| ... |] 76 | if (char === "[" && this.peek() === "|") { 77 | let literal = "" 78 | this.advance() 79 | 80 | while (this.pos < this.src.length && !(this.peek() === "|" && this.peek(1) === "]")) { 81 | literal += this.advance() 82 | } 83 | 84 | if (this.peek() === "|" && this.peek(1) === "]") { 85 | this.advance() 86 | this.advance() 87 | } 88 | 89 | this.tokens.push({ 90 | type: "Comment", 91 | literal: literal.trim() 92 | }) 93 | continue 94 | } 95 | 96 | // numbers 97 | if (char >= "0" && char <= "9") { 98 | let literal = char 99 | let isDecimal = false 100 | 101 | while (this.pos < this.src.length && (/\d/.test(this.src[this.pos]) || (!isDecimal && this.src[this.pos] === "."))) { 102 | if (this.src[this.pos] === ".") { 103 | isDecimal = true 104 | } 105 | literal += this.advance() 106 | } 107 | 108 | this.tokens.push({ 109 | type: "Number", 110 | literal 111 | }) 112 | 113 | continue 114 | } 115 | 116 | const two = char + this.peek() 117 | 118 | // multi-char delimiters 119 | if (MultiCharDelimiters.includes(two)) { 120 | this.tokens.push({ 121 | type: "Delimiter", 122 | literal: two 123 | }) 124 | this.advance() 125 | continue 126 | } 127 | 128 | 129 | // delimiters 130 | if (SingleCharDelimiters.includes(char)) { 131 | this.tokens.push({ 132 | type: "Delimiter", 133 | literal: char 134 | }) 135 | continue 136 | } 137 | 138 | // multi-char operators 139 | if (MultiCharOperators.includes(two)) { 140 | this.tokens.push({ 141 | type: "Operator", 142 | literal: two 143 | }) 144 | this.advance() 145 | continue 146 | } 147 | 148 | // single-char operators 149 | if (SingleCharOperators.includes(char)) { 150 | this.tokens.push({ 151 | type: "Operator", 152 | literal: char 153 | }) 154 | continue 155 | } 156 | 157 | // strings 158 | if (char === '"') { 159 | let literal = "" 160 | while (this.pos < this.src.length && this.src[this.pos] !== '"') { 161 | literal += this.advance() 162 | } 163 | 164 | if (this.peek() === '"') { 165 | this.advance() 166 | } 167 | 168 | this.tokens.push({ 169 | type: "String", 170 | literal 171 | }) 172 | continue 173 | } 174 | 175 | if (char === "'") { 176 | let literal = "" 177 | while (this.pos < this.src.length && this.src[this.pos] !== "'") { 178 | literal += this.advance() 179 | } 180 | 181 | if (this.peek() === "'") { 182 | this.advance() 183 | } 184 | 185 | this.tokens.push({ 186 | type: "String", 187 | literal 188 | }) 189 | continue 190 | } 191 | 192 | // identifiers / keywords 193 | if ( 194 | (char >= "a" && char <= "z") || 195 | (char >= "A" && char <= "Z") || 196 | char === "_" 197 | ) { 198 | let literal = char 199 | 200 | while (this.pos < this.src.length && /[a-zA-Z0-9_]/.test(this.src[this.pos])) { 201 | literal += this.advance() 202 | } 203 | 204 | if (literal === "true" || literal === "false") { 205 | this.tokens.push({ 206 | type: "Boolean", 207 | literal 208 | }) 209 | continue 210 | } 211 | 212 | if (literal === "null") { 213 | this.tokens.push({ 214 | type: "Null", 215 | literal 216 | }) 217 | continue 218 | } 219 | 220 | this.tokens.push({ 221 | // @ts-expect-error 222 | type: ((Keywords.includes(literal) || Modifiers.includes(literal)) ? "Keyword" : "Identifier"), 223 | literal 224 | }) 225 | 226 | continue 227 | } 228 | } 229 | 230 | this.tokens.push({ 231 | type: "EOF", 232 | literal: "" 233 | }) 234 | 235 | return this.tokens 236 | } 237 | 238 | private advance(): string { 239 | if (this.pos >= this.src.length) return "" 240 | const char = this.src[this.pos] 241 | this.pos++ 242 | return char 243 | } 244 | 245 | private peek(n = 0): string { 246 | if (this.pos >= this.src.length) return "" 247 | return this.src[this.pos + n] 248 | } 249 | 250 | private skipWhitespace(): void { 251 | while ( 252 | this.pos < this.src.length && 253 | (this.src[this.pos] === " " || this.src[this.pos] === "\t" || this.src[this.pos] === "\r") 254 | ) { 255 | this.pos++ 256 | } 257 | } 258 | } -------------------------------------------------------------------------------- /tests/bindings/index.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it } from 'bun:test'; 2 | import LLVM, { Context, IRBuilder, Module, Type, Value } from '../../src/bindings/index'; 3 | 4 | describe('llvm-bun', () => { 5 | it('bitcasts between pointer types', () => { 6 | const ctx = new Context(); 7 | const mod = new Module('test', ctx); 8 | const fnType = new LLVM.FunctionType([], Type.void(ctx)); 9 | const fn = mod.createFunction('main', fnType); 10 | const entry = fn.addBlock('entry'); 11 | const builder = new IRBuilder(ctx); 12 | builder.insertInto(entry); 13 | const i8 = Type.int8(ctx); 14 | const ptrType = Type.pointer(i8); 15 | const ptr = builder.alloca(i8, 'ptr'); 16 | // Bitcast to another pointer type (e.g., i32*) 17 | const i32 = Type.int32(ctx); 18 | const ptrI32 = Type.pointer(i32); 19 | const casted = builder.bitcast(ptr, ptrI32, 'casted'); 20 | expect(casted.handle).toBeTruthy(); 21 | expect(casted.getType().isPointer()).toBe(true); 22 | builder.ret(); 23 | const ir = mod.toString(); 24 | expect(ir).toMatch(/bitcast/); 25 | }); 26 | 27 | it('createFunction sets linkage option', () => { 28 | const ctx = new Context(); 29 | const mod = new Module('test', ctx); 30 | const fnType = new LLVM.FunctionType([], Type.void(ctx)); 31 | // Internal linkage 32 | const fn = mod.createFunction('internal_func', fnType, { linkage: LLVM.Linkage.Internal }); 33 | expect(fn.handle).toBeTruthy(); 34 | const ir = mod.toString(); 35 | expect(ir).toMatch(/internal/); 36 | }); 37 | it('adds a global string constant', () => { 38 | const ctx = new Context(); 39 | const mod = new Module('test', ctx); 40 | const strVal = mod.addGlobalString('hello world'); 41 | const t = strVal.getType(); 42 | expect(t.isPointer()).toBe(true); 43 | const ir = mod.toString(); 44 | expect(ir).toMatch(/hello world/); 45 | expect(ir).toMatch(/constant/); 46 | }); 47 | it('creates a context and module', () => { 48 | const ctx = new Context() 49 | const mod = new Module('test', ctx) 50 | expect(ctx.handle).toBeTruthy() 51 | expect(mod.handle).toBeTruthy() 52 | expect(mod.getContext()).toBe(ctx) 53 | }) 54 | 55 | it('creates integer and float types', () => { 56 | const ctx = new Context() 57 | const i32 = Type.int32(ctx) 58 | const f64 = Type.double(ctx) 59 | expect(i32.isInt()).toBe(true) 60 | expect(i32.isInt(32)).toBe(true) 61 | expect(i32.getBitWidth()).toBe(32) 62 | expect(f64.isDouble()).toBe(true) 63 | expect(f64.isFloat()).toBe(false) 64 | }) 65 | 66 | it('creates pointer types', () => { 67 | const ctx = new Context() 68 | const i8 = Type.int8(ctx) 69 | const ptr = Type.pointer(i8) 70 | expect(ptr.isPointer()).toBe(true) 71 | }) 72 | 73 | it('creates function and basic block', () => { 74 | const ctx = new Context() 75 | const mod = new Module('test', ctx) 76 | const fnType = new LLVM.FunctionType([Type.int32(ctx), Type.int32(ctx)], Type.int32(ctx)) 77 | const fn = mod.createFunction('add', fnType) 78 | const block = fn.addBlock('entry') 79 | expect(fn.handle).toBeTruthy() 80 | expect(block.handle).toBeTruthy() 81 | }) 82 | 83 | it('builds simple ir with irbuilder', () => { 84 | const ctx = new Context() 85 | const mod = new Module('test', ctx) 86 | const fnType = new LLVM.FunctionType([Type.int32(ctx), Type.int32(ctx)], Type.int32(ctx)) 87 | const fn = mod.createFunction('add', fnType) 88 | const entry = fn.addBlock('entry') 89 | const builder = new IRBuilder(ctx) 90 | builder.insertInto(entry) 91 | const args = fn.getArgs() 92 | const sum = builder.add(args[0], args[1]) 93 | builder.ret(sum) 94 | const ir = mod.toString() 95 | expect(ir).toMatch(/define i32 @add/) 96 | expect(ir).toMatch(/add i32/) 97 | }) 98 | it('creates and inspects constants', () => { 99 | const ctx = new Context() 100 | const i32 = Type.int32(ctx) 101 | const v = Value.constInt(i32, 42) 102 | expect(v.handle).toBeTruthy() 103 | const t = v.getType() 104 | expect(t.isInt(32)).toBe(true) 105 | }) 106 | it('alloca, store, load', () => { 107 | const ctx = new Context() 108 | const mod = new Module('test', ctx) 109 | const fnType = new LLVM.FunctionType([], Type.void(ctx)) 110 | const fn = mod.createFunction('main', fnType) 111 | const entry = fn.addBlock('entry') 112 | const builder = new IRBuilder(ctx) 113 | builder.insertInto(entry) 114 | const i32 = Type.int32(ctx) 115 | const ptr = builder.alloca(i32, 'x') 116 | const val = Value.constInt(i32, 123) 117 | builder.store(val, ptr) 118 | const loaded = builder.load(ptr) 119 | expect(loaded.handle).toBeTruthy() 120 | }) 121 | it('builds integer and float arithmetic', () => { 122 | const ctx = new Context() 123 | const mod = new Module('arith', ctx) 124 | const fnType = new LLVM.FunctionType([Type.int32(ctx), Type.int32(ctx), Type.double(ctx), Type.double(ctx)], Type.void(ctx)) 125 | const fn = mod.createFunction('arith', fnType) 126 | const entry = fn.addBlock('entry') 127 | const builder = new IRBuilder(ctx) 128 | builder.insertInto(entry) 129 | const [a, b, x, y] = fn.getArgs() 130 | 131 | const add = builder.add(a, b) 132 | const sub = builder.sub(a, b) 133 | const mul = builder.mul(a, b) 134 | const sdiv = builder.sdiv(a, b) 135 | const udiv = builder.udiv(a, b) 136 | 137 | const fadd = builder.fadd(x, y) 138 | const fsub = builder.fsub(x, y) 139 | const fmul = builder.fmul(x, y) 140 | const fdiv = builder.fdiv(x, y) 141 | 142 | expect(add.handle).toBeTruthy() 143 | expect(sub.handle).toBeTruthy() 144 | expect(mul.handle).toBeTruthy() 145 | expect(sdiv.handle).toBeTruthy() 146 | expect(udiv.handle).toBeTruthy() 147 | expect(fadd.handle).toBeTruthy() 148 | expect(fsub.handle).toBeTruthy() 149 | expect(fmul.handle).toBeTruthy() 150 | expect(fdiv.handle).toBeTruthy() 151 | 152 | builder.ret() 153 | const ir = mod.toString() 154 | expect(ir).toMatch(/add i32/) 155 | expect(ir).toMatch(/sub i32/) 156 | expect(ir).toMatch(/mul i32/) 157 | expect(ir).toMatch(/sdiv i32/) 158 | expect(ir).toMatch(/udiv i32/) 159 | expect(ir).toMatch(/fadd double/) 160 | expect(ir).toMatch(/fsub double/) 161 | expect(ir).toMatch(/fmul double/) 162 | expect(ir).toMatch(/fdiv double/) 163 | }) 164 | it('gets a function by name', () => { 165 | const ctx = new Context(); 166 | const mod = new Module('test', ctx); 167 | const fnType = new LLVM.FunctionType([Type.int32(ctx)], Type.int32(ctx)); 168 | const fn = mod.createFunction('myfunc', fnType); 169 | const found = mod.getFunction('myfunc'); 170 | expect(found).toBeTruthy(); 171 | expect(found?.handle).toBe(fn.handle); 172 | const notFound = mod.getFunction('does_not_exist'); 173 | expect(notFound).toBeUndefined(); 174 | }); 175 | it('calls a function with builder.call', () => { 176 | const ctx = new Context(); 177 | const mod = new Module('test', ctx); 178 | 179 | const fnType = new LLVM.FunctionType([Type.int32(ctx), Type.int32(ctx)], Type.int32(ctx)); 180 | const foo = mod.createFunction('foo', fnType); 181 | const fooEntry = foo.addBlock('entry'); 182 | const builder = new IRBuilder(ctx); 183 | builder.insertInto(fooEntry); 184 | const [x, y] = foo.getArgs(); 185 | const sum = builder.add(x, y); 186 | builder.ret(sum); 187 | 188 | const barType = new LLVM.FunctionType([Type.int32(ctx), Type.int32(ctx)], Type.int32(ctx)); 189 | const bar = mod.createFunction('bar', barType); 190 | const barEntry = bar.addBlock('entry'); 191 | builder.insertInto(barEntry); 192 | const [a, b] = bar.getArgs(); 193 | 194 | const callResult = builder.call(foo, [a, b], 'calltmp'); 195 | builder.ret(callResult); 196 | 197 | const ir = mod.toString(); 198 | expect(ir).toMatch(/call i32 @foo/); 199 | expect(ir).toMatch(/define i32 @bar/); 200 | expect(ir).toMatch(/define i32 @foo/); 201 | }); 202 | it('getFunction returns the same Func instance and preserves type', () => { 203 | const ctx = new Context(); 204 | const mod = new Module('test', ctx); 205 | const fnType = new LLVM.FunctionType([Type.int32(ctx), Type.int32(ctx)], Type.int32(ctx)); 206 | const fn = mod.createFunction('sum', fnType); 207 | const found = mod.getFunction('sum'); 208 | expect(found).toBe(fn); 209 | expect(found?.type).toBe(fnType); 210 | }); 211 | it('builds integer comparisons with icmp', () => { 212 | const ctx = new Context(); 213 | const mod = new Module('test', ctx); 214 | const fnType = new LLVM.FunctionType([Type.int32(ctx), Type.int32(ctx)], Type.int1(ctx)); 215 | const fn = mod.createFunction('cmp', fnType); 216 | const entry = fn.addBlock('entry'); 217 | const builder = new IRBuilder(ctx); 218 | builder.insertInto(entry); 219 | const [a, b] = fn.getArgs(); 220 | const eq = builder.icmpEQ(a, b); 221 | const ne = builder.icmpNE(a, b); 222 | const slt = builder.icmpSLT(a, b); 223 | const sle = builder.icmpSLE(a, b); 224 | const sgt = builder.icmpSGT(a, b); 225 | const sge = builder.icmpSGE(a, b); 226 | // Check handles 227 | expect(eq.handle).toBeTruthy(); 228 | expect(ne.handle).toBeTruthy(); 229 | expect(slt.handle).toBeTruthy(); 230 | expect(sle.handle).toBeTruthy(); 231 | expect(sgt.handle).toBeTruthy(); 232 | expect(sge.handle).toBeTruthy(); 233 | // Return one result to make valid IR 234 | builder.ret(eq); 235 | const ir = mod.toString(); 236 | expect(ir).toMatch(/icmp eq/); 237 | expect(ir).toMatch(/icmp ne/); 238 | expect(ir).toMatch(/icmp slt/); 239 | expect(ir).toMatch(/icmp sle/); 240 | expect(ir).toMatch(/icmp sgt/); 241 | expect(ir).toMatch(/icmp sge/); 242 | }); 243 | it('getInsertBlock returns the correct block and parent func', () => { 244 | const ctx = new Context(); 245 | const mod = new Module('test', ctx); 246 | const fnType = new LLVM.FunctionType([Type.int32(ctx)], Type.int32(ctx)); 247 | const fn = mod.createFunction('main', fnType); 248 | const entry = fn.addBlock('entry'); 249 | const builder = new IRBuilder(ctx); 250 | builder.insertInto(entry); 251 | 252 | const block = builder.getInsertBlock(); 253 | expect(block).toBeTruthy(); 254 | expect(block?.handle).toBe(entry.handle); 255 | expect(block?.parent).toBe(fn); 256 | }); 257 | it('BasicBlock.erase removes the block and sets handle to null', () => { 258 | const ctx = new Context(); 259 | const mod = new Module('test', ctx); 260 | const fnType = new LLVM.FunctionType([], Type.void(ctx)); 261 | const fn = mod.createFunction('main', fnType); 262 | const block = fn.addBlock('entry'); 263 | expect(block.handle).toBeTruthy(); 264 | block.erase(); 265 | expect(block.handle).toBeNull(); 266 | }); 267 | }) 268 | -------------------------------------------------------------------------------- /docs/SYNTAX.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 5 | --- 6 | 7 | > [!NOTE] 8 | > ### advanced features like macros and pattern matching are completely optional in yttria. 9 | > #### You can write powerful and expressive programs without them. they are there if you want extra flexibility or metaprogramming, but you don’t need them to be productive. 10 | 11 | --- 12 | 13 | ## syntax 14 | 15 | yttria's syntax is designed to be expressive, concise, and easy to read. It draws inspiration from languages like Typescript, Go, Rust and Zig, while also introducing unique features to enhance developer experience. 16 | 17 | ### comments 18 | ``` 19 | // single-line comment 20 | # also a single-line comment 21 | 22 | /* comment 23 | that spans multiple lines */ 24 | 25 | [| multi-line comment 26 | that spans multiple lines 27 | (usually used for docs/metadata) |] 28 | ``` 29 | 30 | ### types 31 | yttria is a statically-typed language, meaning types are checked at compile time. Types can be inferred or explicitly declared, it is recommended to let the compiler infer types where possible, unlike languages like C or Rust, yttria does not require explicit type annotations for every variable or function. 32 | 33 | ```ts 34 | // basic types 35 | int // 32-bit signed integer, hard alias to i32 36 | i1 // 1-bit signed integer 37 | i8 // 8-bit signed integer 38 | i16 // 16-bit signed integer 39 | i32 // 32-bit signed integer 40 | i64 // 64-bit signed integer 41 | 42 | float // 64-bit floating point number 43 | 44 | bool // boolean, hard alias to i1 45 | 46 | cstr // utf8 string constant 47 | string // mutable heap string (hard alias to i8[]) 48 | char // single utf8 character 49 | 50 | null // null value (yttria is an expressive language, so null is still a value) 51 | // notice how there is there is no void type, null is used instead for consistency 52 | 53 | // composite types 54 | ... 55 | ``` 56 | 57 | ### type aliases 58 | Type aliases can be used to simplify complex types or to create more meaningful names for existing types. 59 | 60 | ```rs 61 | type UserID = int 62 | type User = { 63 | id: UserID, 64 | name: string, 65 | email: string 66 | } 67 | ``` 68 | 69 | ### variables 70 | yttria supports both mutable and immutable variables. Variables can be declared using `let` for mutable variables or `const` for immutable variables. 71 | 72 | ```ts 73 | let w := 10 // mutable variable with type inference 74 | const x := 20.5 // immutable variable with type inference 75 | 76 | let y: int = 30 // mutable variable with explicit type 77 | const z: float = 40.5 // immutable variable with explicit type 78 | ``` 79 | 80 | 81 | ### template strings 82 | yttria supports template strings for easy string interpolation, similar to JavaScript's template literals. Template strings can span multiple lines and can include expressions within `{}`. 83 | 84 | ```rs 85 | let name := "World" 86 | let greeting := `Hello, {name}!` // Hello, World! 87 | ``` 88 | 89 | ### destructuring 90 | yttria supports destructuring for arrays, objects, and tuples, just like Javascript. 91 | 92 | ```rs 93 | let [x, y, z] := [1, 2, 3] // 1, 2, 3 94 | let {name, age} := {name: "Alice", age: 30} // "Alice", 30 95 | let (a, b) := (10, 20) // 10, 20 96 | ``` 97 | 98 | #### destructuring with defaults 99 | yttria allows destructuring with default values, making it easy to handle missing properties or values. 100 | 101 | ```rs 102 | let {name, age = 18} := {name: "Bob"} // "Bob 18" 103 | let [x, y = 0] := [1, 2] // "1 2" 104 | ``` 105 | #### destructuring with rest 106 | yttria supports destructuring with rest parameters, allowing you to capture remaining values in an array or object. 107 | 108 | ```rs 109 | let [first, ...rest] := [1, 2, 3, 4, 5] // "1 [2, 3, 4, 5]" 110 | let {name, ...details} := {name: "Charlie", age: 25, city: "New York"} // "Charlie {age: 25, city: 'New York'}" 111 | ``` 112 | 113 | ### functions 114 | yttria functions are first-class citizens, meaning they can be passed around like any other value. Functions can be defined using the `fn` keyword, and can have optional return types. the `return` keyword is also optional for single-expression functions, similar to functions with brackets in JavaScript. (`fn () => (...)`) 115 | ```ts 116 | fn add(a: int, b: int) -> int { 117 | return a + b 118 | } 119 | 120 | fn greet(name: string) { 121 | print("Hello, " + name) 122 | } 123 | 124 | fn factorial(n: int) -> int { 125 | if (n <= 1) { 126 | return 1 127 | } 128 | return n * factorial(n - 1) 129 | } 130 | 131 | fn pwr(base: float, exp: int) -> float { 132 | if (exp == 0) { 133 | return 1 134 | } 135 | return base * pwr(base, exp - 1) 136 | } 137 | ``` 138 | 139 | ### control flow 140 | yttria supports standard control flow constructs like `if`, `else`, `for`, and `while`. It also has a unique `switch` statement for pattern matching, like Javascript's `switch` but more powerful, and without the constant `break` statements. yttria's if statements do not support braceless bodies, although you can make them a single line with braces such as `if (x < 10) { io.println("x is less than 10") }` 141 | 142 | ```rs 143 | if (a < b) { 144 | io.println("a is less than b") 145 | } else if (a > b) { 146 | io.println("a is greater than b") 147 | } else { 148 | io.println("a is equal to b") 149 | } 150 | 151 | for (let i := 0 .. 5) { 152 | io.println(i) // 0, 1, 2, 3, 4 (exclusive) 153 | } 154 | 155 | for (let i := 0 ... 5) { 156 | io.println(i) // 0, 1, 2, 3, 4, 5 (inclusive) 157 | } 158 | 159 | while (x < 10) { 160 | x += 1 161 | } 162 | 163 | switch (c) { 164 | 1, 2 -> { 165 | io.println("c is 1 or 2") 166 | } 167 | 3 -> { 168 | io.println("c is 3") 169 | } 170 | default -> { 171 | io.println("c is something else") 172 | } 173 | } 174 | ``` 175 | 176 | ### error handling 177 | yttria uses a unique error handling mechanism similar to JavaScript's `try/catch` but with a more concise syntax. Errors can be caught and handled using the `try`, `catch`, and `finally` keywords. The `catch` block can also be used to handle specific error types, similar to Rust's error handling without the need for `Result` types. 178 | 179 | ```ts 180 | try io.write("file.txt", "Hello, World!") 181 | catch (e) io.println(`Error writing to file: {e}`) 182 | finally io.println("Attempted to write to file.") 183 | 184 | try { 185 | let result = riskyFunction() 186 | } catch (e) { 187 | io.println(`Error: {e}`) 188 | } finally { 189 | io.println("Cleanup code here.") 190 | } 191 | ``` 192 | 193 | ### pattern matching 194 | yttria has powerful pattern matching capabilities, allowing for more expressive and concise code. Pattern matching can be used with enums, structs, and tuples, making it easy to destructure and work with complex data types. 195 | 196 | ```rs 197 | let point := new Point(1.0, 2.0) 198 | 199 | switch (point) { 200 | Point(x, y) as p -> { 201 | io.println(`Point at ({p.x}, {p.y})`) 202 | } 203 | 204 | Point(x, y) as p if (p.x > 0 && p.y > 0) -> { 205 | io.println("Point is in the first quadrant") 206 | } 207 | 208 | default -> { 209 | io.println("Unknown point") 210 | } 211 | } 212 | ``` 213 | 214 | 215 | ### modules 216 | yttria supports modules for organizing code. Modules can be imported using the `use` keyword, and can be aliased for convenience. Similar to Go, odules are folder based, so foo/baz.yt and foo/bar.yt are both part of the module `foo`, unlike JS's `import` syntax which is file-based. 217 | 218 | 219 | ```rs 220 | use std/io; 221 | use std/math as m; 222 | use std/*; // import all items from the std supermodule (not recommended for large modules, this increases filesize by a TON and can cause name clashes 223 | use std/time as .; // import into current module, so you can use `now()` instead of `time.now()` 224 | use std/http as _; // import without using, bypassing the "unused import" warning without commenting it out 225 | ``` 226 | 227 | ### structs 228 | yttria supports structs for defining custom data types. Structs can have methods associated with them, most similar to Go, but more readable & compact. Structs can also have constructors, which are special methods that are called when a new instance of the struct is created, unlike Go. 229 | 230 | ```rs 231 | // point.yt 232 | struct Point { 233 | let x: float 234 | let y: float 235 | 236 | fn constructor(x: float, y: float) { 237 | this.x = x 238 | this.y = y 239 | } 240 | 241 | fn distance(self, other: Point) -> float { 242 | return sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2) 243 | } 244 | } 245 | 246 | // main.yt 247 | use point as poi; 248 | const p := new poi.Point(1.0, 2.0) 249 | ``` 250 | 251 | ### js-style objects 252 | yttria supports objects (also known as maps, dictionaries or hash tables etc), which are collections of key-value pairs. Maps can be created using curly braces (`{}`) and can have keys of any type, but values must be of the same type. They are extremely similar to JS objects. 253 | 254 | ```rs 255 | let user := { 256 | id: 1, 257 | name: "Alice", 258 | age: 30 259 | } 260 | ``` 261 | 262 | ### enums 263 | yttria supports enums for defining a set of named values. Enums can have associated data, and can be used in pattern matching. 264 | 265 | ```rs 266 | enum Color { 267 | Red, 268 | Green, 269 | Blue, 270 | Custom(r: int, g: int, b: int) // enum with associated data 271 | } 272 | 273 | fn printColor(color: Color) { 274 | switch (color) { 275 | Color.Red -> { 276 | io.println("Red") 277 | } 278 | 279 | Color.Green -> { 280 | io.println("Green") 281 | } 282 | 283 | Color.Blue -> { 284 | io.println("Blue") 285 | } 286 | 287 | Color.Custom(r, g, b) -> { 288 | io.println(`Custom color: {r}, {g}, {b}`) 289 | } 290 | 291 | default -> { io.println("Unknown color") } 292 | } 293 | } 294 | ``` 295 | 296 | ### generics 297 | yttria supports generics for defining functions and types that can work with any type. Generics are defined using angle brackets (`<` and `>`), similar to TypeScript. Generics can also be used to make chainable functions, allowing for more flexible and reusable code, unlike Go's generics which are more limited in scope. 298 | 299 | ```rs 300 | fn printList(list: List) { 301 | for (let item in list) { 302 | io.println(item) 303 | } 304 | } 305 | 306 | fn map(list: List, fn: (T) -> U) -> List { 307 | let result := List() 308 | for (let item in list) { 309 | result.append(fn(item)) 310 | } 311 | return result 312 | } 313 | 314 | fn main() { 315 | let numbers := [1, 2, 3, 4, 5] 316 | let strings := map(numbers, (n) => `Number: {n}`) 317 | printList(strings) // "Number: 1", "Number: 2", etc. 318 | printList(numbers) // 1, 2, 3, 4, 5 319 | } 320 | ``` 321 | 322 | ### asynchronous/concurrent programming 323 | yttria has first-class support, allowing for easy parallel execution of code. Asynchronous programming is achieved using the `async` and `await` keywords, similar to JavaScript. yttria also supports channels for communication between concurrent tasks. yttria's `async` keyword can also be called as a block in sync functions, similar to Go's goroutines or Javascript's IIFEs. 324 | 325 | ```rs 326 | use std/http; 327 | use std/io; 328 | 329 | async fn fetchData(url: string) -> string { 330 | let response := await http.get(url) 331 | return response.body 332 | } 333 | 334 | async fn main() { 335 | let data := await fetchData("https://api.example.com/data") 336 | io.println(data) 337 | 338 | let result := await async { 339 | // some async code 340 | return "result" 341 | } 342 | 343 | io.println(result) 344 | } 345 | ``` 346 | 347 | ### macros 348 | macros are just like functions, but they are expanded at compile time, allowing for more powerful code generation and metaprogramming capabilities. Macros can be used to create reusable code snippets, similar to Rust's macros. 349 | 350 | ```rs 351 | macro fn greeting() { 352 | if (os == "windows") { 353 | return "Hello" 354 | } else if (os == "linux") { 355 | return "hi" 356 | } else { 357 | return "hey" 358 | } 359 | } 360 | 361 | fn main() { 362 | io.println(greeting!()) // This expands to io.println("Hello") or io.println("hi") at compile time! 363 | } 364 | ``` 365 | 366 | #### advanced macros 367 | yttria's macros can even swap out entire blocks of code using the `macro` keyword, allowing for more complex code generation and metaprogramming. macros can also be used to create custom syntax, similar to Rust's procedural macros. macro blocks are just like macro functions bu are called automatically 368 | 369 | ```rs 370 | fn main() { 371 | let arch = "" 372 | 373 | macro { 374 | if sys.arch == "x86_64" { 375 | arch = "x86_64" 376 | } else if sys.arch == "arm64" { 377 | arch = "arm64" 378 | } else { 379 | arch = "unknown" 380 | } 381 | } 382 | 383 | io.println(`Running on {arch} architecture`) // This expands to the appropriate code block at compile time! 384 | /* eg: 385 | Running on x86_64 architecture 386 | */ 387 | } 388 | ``` 389 | 390 | ### inline assembly 391 | yttria supports inline assembly for low-level programming, allowing developers to write performance-critical code directly in assembly language. Inline assembly can be used within functions, and is useful for tasks like system calls or hardware manipulation. 392 | 393 | ```rs 394 | fn add(a: int, b: int) -> int { 395 | let result: int 396 | asm(` 397 | mov eax, {a} 398 | add eax, {b} 399 | mov {result}, eax 400 | `) // use template strings for inline assembly 401 | return result 402 | } 403 | ``` 404 | 405 | ### tuples 406 | yttria supports tuples, which are fixed-size collections of elements that can be of different types. Tuples are useful for grouping related values together. Unlike arrays, tuples have a fixed size and can contain elements of different types, however unlike Python, tuples in yttria can have any size. They are also immutable, the `let` keyword has no effect on its mutability. 407 | ```rs 408 | let point: (float, float) = (1.0, 2.0) // tuple with two float elements 409 | let person := ("Steve", 30, "Engineer") // tuple with three elements of different types 410 | let (name, age, profession) := person // destructuring a tuple 411 | ``` 412 | 413 | ### arrays 414 | yttria supports arrays, which are ordered collections of elements of the same type. Arrays can be created using square brackets (`[]`) and can be mutable or immutable. 415 | 416 | ```rs 417 | let numbers := [1, 2, 3, 4, 5] 418 | const names: string[] = ["Alice", "Bob", "Charlie"] 419 | let mixed: (string | int | float)[] = [1, "Hello", 3.14] 420 | ``` 421 | 422 | ### iterators 423 | yttria supports iterators, which allow you to iterate over collections like arrays, maps, and sets. Iterators can be created using the `for` keyword and can be used with any iterable collection. 424 | 425 | ```rs 426 | let numbers := [1, 2, 3, 4, 5] 427 | for (let number in numbers) { 428 | io.println(number) // 1, 2, 3, 4, 5 429 | } 430 | ``` 431 | 432 | ### ffi 433 | yttria supports Foreign Function Interface (FFI), which allows you to leverage existing libraries written in other languages like C or Rust. This is useful for performance-critical code or when you want to use existing libraries without rewriting them in yttria. Here is an example with raylib 434 | 435 | ```rs 436 | // raylib_bindings.yt 437 | use ffi/raylib; // raylib.dll / libraylib.so (depending on your OS) in root directory 438 | 439 | struct Color { 440 | let r: u8 441 | let g: u8 442 | let b: u8 443 | let a: u8 444 | } 445 | 446 | foreign fn InitWindow(width: int, height: int, title: string) -> null 447 | foreign fn WindowShouldClose() -> bool 448 | foreign fn CloseWindow() -> null 449 | foreign fn BeginDrawing() -> null 450 | foreign fn EndDrawing() -> null 451 | foreign fn ClearBackground(color: Color) -> null 452 | foreign fn DrawText(text: string, posX: int, posY: int, fontSize: int, color: Color) -> null 453 | 454 | // main.yt 455 | use path/to/raylib_bindings as r 456 | 457 | fn main() { 458 | r.InitWindow(800, 600, "Hello Raylib") 459 | 460 | while (!r.WindowShouldClose()) { 461 | r.BeginDrawing() 462 | r.ClearBackground(r.Color { r: 0, g: 0, b: 0, a: 255 }) 463 | r.DrawText("Hello, Raylib!", 10, 10, 20, r.Color { r: 255, g: 255, b: 255, a: 255 }) 464 | r.EndDrawing() 465 | } 466 | 467 | r.CloseWindow() 468 | } 469 | ``` 470 | 471 | ### link-time libraries 472 | yttria supports external functions, which are functions that are provided at link-time, unlike FFI, which natively links to libraries at compile time. External functions can be used to call functions from other yttria modules or from external libraries. 473 | 474 | ```rs 475 | extern fn printf(fmt: string, ...) -> int // from C standard library 476 | extern fn writeln(msg: string) -> null // from D standard library 477 | ``` -------------------------------------------------------------------------------- /bun.lock: -------------------------------------------------------------------------------- 1 | { 2 | "lockfileVersion": 1, 3 | "workspaces": { 4 | "": { 5 | "dependencies": { 6 | "cmake-js": "^7.3.1", 7 | }, 8 | "devDependencies": { 9 | "@types/bun": "^1.2.19", 10 | }, 11 | }, 12 | }, 13 | "overrides": { 14 | "cmake-js": "7.3.1", 15 | }, 16 | "packages": { 17 | "@types/bun": ["@types/bun@1.2.19", "", { "dependencies": { "bun-types": "1.2.19" } }, "sha512-d9ZCmrH3CJ2uYKXQIUuZ/pUnTqIvLDS0SK7pFmbx8ma+ziH/FRMoAq5bYpRG7y+w1gl+HgyNZbtqgMq4W4e2Lg=="], 18 | 19 | "@types/node": ["@types/node@24.1.0", "", { "dependencies": { "undici-types": "~7.8.0" } }, "sha512-ut5FthK5moxFKH2T1CUOC6ctR67rQRvvHdFLCD2Ql6KXmMuCrjsSsRI9UsLCm9M18BMwClv4pn327UvB7eeO1w=="], 20 | 21 | "@types/react": ["@types/react@19.1.8", "", { "dependencies": { "csstype": "^3.0.2" } }, "sha512-AwAfQ2Wa5bCx9WP8nZL2uMZWod7J7/JSplxbTmBQ5ms6QpqNYm672H0Vu9ZVKVngQ+ii4R/byguVEUZQyeg44g=="], 22 | 23 | "ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], 24 | 25 | "ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], 26 | 27 | "aproba": ["aproba@2.1.0", "", {}, "sha512-tLIEcj5GuR2RSTnxNKdkK0dJ/GrC7P38sUkiDmDuHfsHmbagTFAxDVIBltoklXEVIQ/f14IL8IMJ5pn9Hez1Ew=="], 28 | 29 | "are-we-there-yet": ["are-we-there-yet@3.0.1", "", { "dependencies": { "delegates": "^1.0.0", "readable-stream": "^3.6.0" } }, "sha512-QZW4EDmGwlYur0Yyf/b2uGucHQMa8aFUP7eu9ddR73vvhFyt4V0Vl3QHPcTNJ8l6qYOBdxgXdnBXQrHilfRQBg=="], 30 | 31 | "asynckit": ["asynckit@0.4.0", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="], 32 | 33 | "axios": ["axios@1.11.0", "", { "dependencies": { "follow-redirects": "^1.15.6", "form-data": "^4.0.4", "proxy-from-env": "^1.1.0" } }, "sha512-1Lx3WLFQWm3ooKDYZD1eXmoGO9fxYQjrycfHFC8P0sCfQVXyROp0p9PFWBehewBOdCwHc+f/b8I0fMto5eSfwA=="], 34 | 35 | "bun-types": ["bun-types@1.2.19", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-uAOTaZSPuYsWIXRpj7o56Let0g/wjihKCkeRqUBhlLVM/Bt+Fj9xTo+LhC1OV1XDaGkz4hNC80et5xgy+9KTHQ=="], 36 | 37 | "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], 38 | 39 | "chownr": ["chownr@2.0.0", "", {}, "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ=="], 40 | 41 | "cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="], 42 | 43 | "cmake-js": ["cmake-js@7.3.1", "", { "dependencies": { "axios": "^1.6.5", "debug": "^4", "fs-extra": "^11.2.0", "memory-stream": "^1.0.0", "node-api-headers": "^1.1.0", "npmlog": "^6.0.2", "rc": "^1.2.7", "semver": "^7.5.4", "tar": "^6.2.0", "url-join": "^4.0.1", "which": "^2.0.2", "yargs": "^17.7.2" }, "bin": { "cmake-js": "bin/cmake-js" } }, "sha512-aJtHDrTFl8qovjSSqXT9aC2jdGfmP8JQsPtjdLAXFfH1BF4/ImZ27Jx0R61TFg8Apc3pl6e2yBKMveAeRXx2Rw=="], 44 | 45 | "color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], 46 | 47 | "color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], 48 | 49 | "color-support": ["color-support@1.1.3", "", { "bin": { "color-support": "bin.js" } }, "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg=="], 50 | 51 | "combined-stream": ["combined-stream@1.0.8", "", { "dependencies": { "delayed-stream": "~1.0.0" } }, "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg=="], 52 | 53 | "console-control-strings": ["console-control-strings@1.1.0", "", {}, "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ=="], 54 | 55 | "csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="], 56 | 57 | "debug": ["debug@4.4.1", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ=="], 58 | 59 | "deep-extend": ["deep-extend@0.6.0", "", {}, "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA=="], 60 | 61 | "delayed-stream": ["delayed-stream@1.0.0", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="], 62 | 63 | "delegates": ["delegates@1.0.0", "", {}, "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ=="], 64 | 65 | "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], 66 | 67 | "emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], 68 | 69 | "es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="], 70 | 71 | "es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="], 72 | 73 | "es-object-atoms": ["es-object-atoms@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="], 74 | 75 | "es-set-tostringtag": ["es-set-tostringtag@2.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA=="], 76 | 77 | "escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="], 78 | 79 | "follow-redirects": ["follow-redirects@1.15.9", "", {}, "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ=="], 80 | 81 | "form-data": ["form-data@4.0.4", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow=="], 82 | 83 | "fs-extra": ["fs-extra@11.3.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-Z4XaCL6dUDHfP/jT25jJKMmtxvuwbkrD1vNSMFlo9lNLY2c5FHYSQgHPRZUjAB26TpDEoW9HCOgplrdbaPV/ew=="], 84 | 85 | "fs-minipass": ["fs-minipass@2.1.0", "", { "dependencies": { "minipass": "^3.0.0" } }, "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg=="], 86 | 87 | "function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="], 88 | 89 | "gauge": ["gauge@4.0.4", "", { "dependencies": { "aproba": "^1.0.3 || ^2.0.0", "color-support": "^1.1.3", "console-control-strings": "^1.1.0", "has-unicode": "^2.0.1", "signal-exit": "^3.0.7", "string-width": "^4.2.3", "strip-ansi": "^6.0.1", "wide-align": "^1.1.5" } }, "sha512-f9m+BEN5jkg6a0fZjleidjN51VE1X+mPFQ2DJ0uv1V39oCLCbsGe6yjbBnp7eK7z/+GAon99a3nHuqbuuthyPg=="], 90 | 91 | "get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="], 92 | 93 | "get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="], 94 | 95 | "get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="], 96 | 97 | "gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="], 98 | 99 | "graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="], 100 | 101 | "has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="], 102 | 103 | "has-tostringtag": ["has-tostringtag@1.0.2", "", { "dependencies": { "has-symbols": "^1.0.3" } }, "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw=="], 104 | 105 | "has-unicode": ["has-unicode@2.0.1", "", {}, "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ=="], 106 | 107 | "hasown": ["hasown@2.0.2", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="], 108 | 109 | "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], 110 | 111 | "ini": ["ini@1.3.8", "", {}, "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew=="], 112 | 113 | "is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="], 114 | 115 | "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], 116 | 117 | "jsonfile": ["jsonfile@6.1.0", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ=="], 118 | 119 | "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], 120 | 121 | "memory-stream": ["memory-stream@1.0.0", "", { "dependencies": { "readable-stream": "^3.4.0" } }, "sha512-Wm13VcsPIMdG96dzILfij09PvuS3APtcKNh7M28FsCA/w6+1mjR7hhPmfFNoilX9xU7wTdhsH5lJAm6XNzdtww=="], 122 | 123 | "mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], 124 | 125 | "mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], 126 | 127 | "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], 128 | 129 | "minipass": ["minipass@5.0.0", "", {}, "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ=="], 130 | 131 | "minizlib": ["minizlib@2.1.2", "", { "dependencies": { "minipass": "^3.0.0", "yallist": "^4.0.0" } }, "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg=="], 132 | 133 | "mkdirp": ["mkdirp@1.0.4", "", { "bin": { "mkdirp": "bin/cmd.js" } }, "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw=="], 134 | 135 | "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], 136 | 137 | "node-api-headers": ["node-api-headers@1.5.0", "", {}, "sha512-Yi/FgnN8IU/Cd6KeLxyHkylBUvDTsSScT0Tna2zTrz8klmc8qF2ppj6Q1LHsmOueJWhigQwR4cO2p0XBGW5IaQ=="], 138 | 139 | "npmlog": ["npmlog@6.0.2", "", { "dependencies": { "are-we-there-yet": "^3.0.0", "console-control-strings": "^1.1.0", "gauge": "^4.0.3", "set-blocking": "^2.0.0" } }, "sha512-/vBvz5Jfr9dT/aFWd0FIRf+T/Q2WBsLENygUaFUqstqsycmZAP/t5BvFJTK0viFmSUxiUKTUplWy5vt+rvKIxg=="], 140 | 141 | "proxy-from-env": ["proxy-from-env@1.1.0", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="], 142 | 143 | "rc": ["rc@1.2.8", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="], 144 | 145 | "readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], 146 | 147 | "require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="], 148 | 149 | "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], 150 | 151 | "semver": ["semver@7.7.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA=="], 152 | 153 | "set-blocking": ["set-blocking@2.0.0", "", {}, "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="], 154 | 155 | "signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="], 156 | 157 | "string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], 158 | 159 | "string_decoder": ["string_decoder@1.3.0", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="], 160 | 161 | "strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], 162 | 163 | "strip-json-comments": ["strip-json-comments@2.0.1", "", {}, "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ=="], 164 | 165 | "tar": ["tar@6.2.1", "", { "dependencies": { "chownr": "^2.0.0", "fs-minipass": "^2.0.0", "minipass": "^5.0.0", "minizlib": "^2.1.1", "mkdirp": "^1.0.3", "yallist": "^4.0.0" } }, "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A=="], 166 | 167 | "undici-types": ["undici-types@7.8.0", "", {}, "sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw=="], 168 | 169 | "universalify": ["universalify@2.0.1", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="], 170 | 171 | "url-join": ["url-join@4.0.1", "", {}, "sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA=="], 172 | 173 | "util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], 174 | 175 | "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], 176 | 177 | "wide-align": ["wide-align@1.1.5", "", { "dependencies": { "string-width": "^1.0.2 || 2 || 3 || 4" } }, "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg=="], 178 | 179 | "wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="], 180 | 181 | "y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="], 182 | 183 | "yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], 184 | 185 | "yargs": ["yargs@17.7.2", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="], 186 | 187 | "yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="], 188 | 189 | "fs-minipass/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], 190 | 191 | "minizlib/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /src/parser/index.ts: -------------------------------------------------------------------------------- 1 | import { Keyword, Modifier, Modifiers, Token, TokenType } from "../lexer/token" 2 | import { BinaryExpression, BooleanLiteral, CaseExpression, CommentExpression, ElseExpression, Expression, FunctionCall, FunctionDeclaration, FunctionParam, Identifier, IfExpression, ImportExpression, MemberAccess, NullLiteral, NumberLiteral, PostUnaryExpression, PreUnaryExpression, ProgramExpression, ReturnExpression, StringLiteral, SwitchExpression, VariableDeclaration, WhileExpression } from "./ast" 3 | export class Parser { 4 | tokens: Token[] 5 | program: ProgramExpression = { 6 | type: "Program", 7 | body: [] 8 | } 9 | pos: number = 0 10 | 11 | table: { [key in TokenType]?: (t: Token) => Expression | null } = { 12 | Number: this.visitNumberLiteral.bind(this), 13 | String: this.visitStringLiteral.bind(this), 14 | Boolean: this.visitBooleanLiteral.bind(this), 15 | Null: this.visitNullLiteral.bind(this), 16 | 17 | Comment: this.visitComment.bind(this), 18 | Identifier: this.visitIdentifier.bind(this), 19 | Keyword: this.visitKeyword.bind(this), 20 | } 21 | 22 | precedence: { [op: string]: number } = { 23 | "==": 1, 24 | "!=": 1, 25 | "<": 2, 26 | ">": 2, 27 | "<=": 2, 28 | ">=": 2, 29 | "+": 3, 30 | "-": 3, 31 | "*": 4, 32 | "/": 4, 33 | } 34 | 35 | modifiers: Modifier[] = [] 36 | 37 | constructor(tokens: Token[]) { 38 | this.tokens = tokens 39 | } 40 | 41 | public parse(): ProgramExpression { 42 | this.pos = 0 43 | while (this.pos < this.tokens.length) { 44 | const t = this.peek() 45 | if (t.type === "EOF") { 46 | break 47 | } 48 | // WTF 49 | if ((Modifiers as unknown as string[]).includes(t.literal)) { 50 | this.modifiers.push(t.literal as Modifier) 51 | this.advance() 52 | continue 53 | } 54 | 55 | const expr = this.parseExpression() 56 | this.modifiers = [] 57 | 58 | if (expr) { 59 | this.program.body.push(expr) 60 | } 61 | } 62 | 63 | return this.program 64 | } 65 | 66 | private parseExpression(precedence = 0, tok?: Token): Expression | null { 67 | let left = this.parsePrimary(tok) 68 | if (!left) return null; 69 | 70 | while (true) { 71 | if (this.peek().type === "Operator" && 72 | (this.peek().literal === "++" || this.peek().literal === "--")) { 73 | const op = this.peek(); 74 | this.advance(); 75 | left = { 76 | type: "PostUnaryExpression", 77 | operator: op.literal, 78 | operand: left 79 | } as PostUnaryExpression; 80 | } 81 | 82 | else if (this.peek().literal === ".") { 83 | this.advance(); 84 | if (this.peek().type !== "Identifier") { 85 | throw new Error("expected identifier after '.'"); 86 | } 87 | const property = { 88 | type: "Identifier", 89 | value: this.peek().literal 90 | } as Identifier; 91 | this.advance(); 92 | 93 | left = { 94 | type: "MemberAccess", 95 | object: left, 96 | property 97 | } as MemberAccess; 98 | } 99 | 100 | else if (this.peek().literal === "(") { 101 | this.advance(); 102 | const args: Expression[] = []; 103 | 104 | if (this.peek().literal !== ")") { 105 | while (this.peek().literal !== ")" && this.peek().type !== "EOF") { 106 | const arg = this.parseExpression(); 107 | if (!arg) throw new Error("expected expression in function call"); 108 | args.push(arg); 109 | 110 | if (this.peek().literal === ",") { 111 | this.advance(); 112 | } 113 | } 114 | } 115 | 116 | if (this.peek().literal !== ")") { 117 | throw new Error("expected ')' to close function call"); 118 | } 119 | this.advance(); 120 | 121 | left = { 122 | type: "FunctionCall", 123 | callee: left, 124 | args 125 | } as FunctionCall; 126 | } 127 | 128 | else if (this.peek().type === "Operator" && this.getPrecedence(this.peek()) > precedence) { 129 | const op = this.peek(); 130 | this.advance(); 131 | const right = this.parseExpression(this.getPrecedence(op)); 132 | if (!right) return null; 133 | 134 | left = { 135 | type: "BinaryExpression", 136 | left, 137 | operator: op.literal, 138 | right 139 | } as BinaryExpression; 140 | } 141 | else { 142 | break; 143 | } 144 | } 145 | 146 | return left 147 | } 148 | 149 | private parsePrimary(tok?: Token): Expression | null { 150 | const t = tok || this.peek() 151 | 152 | // (x + y) / z 153 | if (t.literal === "(") { 154 | this.advance() 155 | const expr = this.parseExpression() 156 | if (this.peek().literal !== ")") { 157 | throw new Error("expected ')' after expression") 158 | } 159 | this.advance() 160 | return expr 161 | } 162 | 163 | // -x !y 164 | if (t.type === "Operator" && (t.literal === "-" || t.literal === "!")) { 165 | this.advance() 166 | const operand = this.parseExpression(100) 167 | if (!operand) throw new Error("expected expression after unary operator") 168 | return { 169 | type: "PreUnaryExpression", 170 | operator: t.literal, 171 | operand 172 | } as PreUnaryExpression 173 | } 174 | 175 | if (t.type in this.table) { 176 | const tok = this.peek() 177 | this.advance() 178 | return this.table[tok.type]!(tok) 179 | } 180 | 181 | return null 182 | } 183 | 184 | private visitNumberLiteral(t: Token): NumberLiteral { 185 | return { 186 | type: "NumberLiteral", 187 | value: parseFloat(t.literal) 188 | } 189 | } 190 | 191 | private visitStringLiteral(t: Token): StringLiteral { 192 | return { 193 | type: "StringLiteral", 194 | value: t.literal 195 | } 196 | } 197 | 198 | private visitBooleanLiteral(t: Token): BooleanLiteral { 199 | return { 200 | type: "BooleanLiteral", 201 | value: t.literal === "true" 202 | } 203 | } 204 | 205 | private visitNullLiteral(t: Token): NullLiteral { 206 | return { 207 | type: "NullLiteral", 208 | value: null 209 | } 210 | } 211 | 212 | private visitIdentifier(t: Token): Identifier { 213 | return { 214 | type: "Identifier", 215 | value: t.literal 216 | }; 217 | } 218 | 219 | private visitKeyword(t: Token): Expression | null { 220 | // turned switch into table :hooray: 221 | const table: { [key in Keyword]?: () => Expression | null } = { 222 | "fn": this.parseFunctionDeclaration.bind(this), 223 | "if": this.parseIfExpression.bind(this), 224 | "while": this.parseWhileExpression.bind(this), 225 | "return": this.parseReturnExpression.bind(this), 226 | "let": () => this.parseVariableDeclaration.bind(this)(true), 227 | "const": () => this.parseVariableDeclaration.bind(this)(false), 228 | "switch": this.parseSwitchExpression.bind(this), 229 | "use": this.parseImportExpression.bind(this), 230 | } 231 | 232 | if (t.literal in table) { 233 | return table[t.literal as Keyword]!() 234 | } 235 | 236 | return null 237 | } 238 | 239 | private parseVariableDeclaration(mutable: boolean): VariableDeclaration { 240 | const name: Identifier = { 241 | type: "Identifier", 242 | value: this.peek().literal 243 | } 244 | 245 | this.advance() 246 | 247 | if (this.peek().literal !== ":") { 248 | // no type annotation 249 | // var x := 5 250 | if (this.peek().literal !== ":=") { 251 | throw new Error("expected ':=' after variable name") 252 | } 253 | 254 | this.advance() 255 | const value = this.parseExpression() 256 | if (!value) { 257 | throw new Error("expected value after ':='") 258 | } 259 | 260 | return { 261 | type: "VariableDeclaration", 262 | name, 263 | value, 264 | mutable 265 | } 266 | } 267 | this.advance() 268 | 269 | const typeAnnotation: Identifier = { 270 | type: "Identifier", 271 | value: this.peek().literal 272 | } 273 | 274 | this.advance() 275 | if (this.peek().literal !== "=") { 276 | throw new Error("expected '=' after type annotation") 277 | } 278 | 279 | this.advance() 280 | const value = this.parseExpression() 281 | if (!value) { 282 | throw new Error("expected value after '='") 283 | } 284 | 285 | return { 286 | type: "VariableDeclaration", 287 | name, 288 | value, 289 | typeAnnotation, 290 | mutable 291 | } 292 | } 293 | 294 | private visitComment(t: Token): CommentExpression { 295 | return { 296 | type: "CommentExpression", 297 | value: t.literal 298 | } 299 | } 300 | 301 | private parseFunctionDeclaration(): FunctionDeclaration { 302 | const modifiers = this.modifiers 303 | const name: Identifier = { 304 | type: "Identifier", 305 | value: this.peek().literal 306 | } 307 | 308 | this.advance() 309 | 310 | if (this.peek().literal !== "(") { 311 | throw new Error("expected '(' after function name") 312 | } 313 | 314 | const params: FunctionParam[] = [] 315 | 316 | if (this.peek(1).literal !== ")") { 317 | while (this.peek().literal !== ")" && this.peek().type !== "EOF") { 318 | const name: Identifier = { 319 | type: "Identifier", 320 | value: this.advance().literal 321 | } 322 | 323 | this.advance() 324 | 325 | if (this.peek().literal !== ":") { 326 | throw new Error("expected ':' after parameter name") 327 | } 328 | 329 | const type: Identifier = { 330 | type: "Identifier", 331 | value: this.advance().literal 332 | } 333 | 334 | params.push({ 335 | type: "FunctionParam", 336 | name, 337 | paramType: type 338 | }) 339 | 340 | if (this.peek().literal === ",") { 341 | this.advance() 342 | } 343 | 344 | this.advance() 345 | } 346 | } else { 347 | this.advance() 348 | } 349 | 350 | this.advance() 351 | 352 | if (this.peek().literal === "->") { 353 | const returnType: Identifier = { 354 | type: "Identifier", 355 | value: this.advance().literal 356 | } 357 | 358 | this.advance() 359 | 360 | let body: Expression[] = [] 361 | if (!modifiers.includes("extern")) body = this.parseBlock() 362 | 363 | return { 364 | type: "FunctionDeclaration", 365 | name, 366 | params, 367 | body, 368 | returnType, 369 | modifiers 370 | } 371 | } 372 | 373 | const body: Expression[] = this.parseBlock() 374 | 375 | return { 376 | type: "FunctionDeclaration", 377 | name, 378 | params, 379 | body, 380 | modifiers 381 | } 382 | } 383 | 384 | private parseBlock(): Expression[] { 385 | const body: Expression[] = [] 386 | if (this.peek().literal !== "{") { 387 | throw new Error(`expected "{" to start function body, got "${this.peek().literal}"`) 388 | } 389 | 390 | this.advance() 391 | 392 | while (this.peek().literal !== "}" && this.peek().type !== "EOF") { 393 | const expr = this.parseExpression() 394 | if (expr) { 395 | body.push(expr) 396 | } 397 | } 398 | 399 | this.advance() 400 | 401 | return body 402 | } 403 | 404 | private parseReturnExpression(): ReturnExpression { 405 | return { 406 | type: "ReturnExpression", 407 | value: this.parseExpression(0, this.peek()) || { 408 | type: "NullLiteral", 409 | value: null 410 | } as NullLiteral 411 | } 412 | } 413 | 414 | private parseIfExpression(): IfExpression { 415 | const condition = this.parseExpression(0, this.advance()) 416 | if (!condition) { 417 | throw new Error("expected condition after 'if'") 418 | } 419 | this.advance() 420 | const body = this.parseBlock() 421 | let alternate: IfExpression | ElseExpression | undefined; 422 | 423 | if (this.peek().literal === "else") { 424 | this.advance() 425 | if (this.peek().literal === "if") { 426 | this.advance() 427 | alternate = this.parseIfExpression() 428 | } else { 429 | alternate = this.parseElseExpression() 430 | } 431 | } 432 | 433 | return { 434 | type: "IfExpression", 435 | condition, 436 | body, 437 | alternate 438 | } 439 | } 440 | 441 | private parseElseExpression(): ElseExpression { 442 | const body = this.parseBlock() 443 | return { 444 | type: "ElseExpression", 445 | body 446 | } 447 | } 448 | 449 | private parseWhileExpression(): WhileExpression { 450 | const condition = this.parseExpression(0, this.advance()) 451 | if (!condition) { 452 | throw new Error("expected condition after 'while'") 453 | } 454 | this.advance() 455 | const body = this.parseBlock() 456 | return { 457 | type: "WhileExpression", 458 | condition, 459 | body 460 | } 461 | } 462 | 463 | private parseSwitchExpression(): SwitchExpression { 464 | const value = this.parseExpression(0, this.advance()) 465 | if (!value) { 466 | throw new Error("expected value after 'switch'") 467 | } 468 | 469 | if (this.advance().literal !== "{") { 470 | throw new Error("expected '{' after switch value") 471 | } 472 | this.advance() 473 | 474 | if (this.peek().literal === "}") { 475 | this.advance() 476 | return { 477 | type: "SwitchExpression", 478 | value, 479 | cases: [] 480 | } 481 | } 482 | 483 | const cases: CaseExpression[] = [] 484 | 485 | while (this.peek().literal !== "}" && this.peek().type !== "EOF") { 486 | let value: Expression | "default" = (() => { 487 | if (this.peek().literal === "default") { 488 | this.advance() 489 | return "default" 490 | } 491 | const val = this.parseExpression(0) 492 | if (!val) { 493 | throw new Error("expected case value") 494 | } 495 | return val 496 | })() 497 | 498 | if (this.peek().literal !== "->") { 499 | throw new Error(`expected '->' after case value, got "${this.peek().literal}"`) 500 | } 501 | this.advance() 502 | 503 | const body: Expression[] = this.parseBlock() 504 | cases.push({ 505 | type: "CaseExpression", 506 | value, 507 | body 508 | }) 509 | } 510 | 511 | this.advance() 512 | 513 | return { 514 | type: "SwitchExpression", 515 | value, 516 | cases 517 | } 518 | } 519 | 520 | private parseImportExpression(): ImportExpression { 521 | let path = (() => { 522 | const parts: string[] = [] 523 | while (this.peek().type === "Identifier" || this.peek().literal === "/") { 524 | parts.push(this.peek().literal) 525 | this.advance() 526 | } 527 | return parts.join("") 528 | })() 529 | 530 | if (this.peek().literal !== "as") { 531 | return { 532 | type: "ImportExpression", 533 | path 534 | } 535 | } 536 | 537 | this.advance() 538 | 539 | if (this.peek().type !== "Identifier") { 540 | throw new Error(`expected identifier after "as", got "${this.peek().literal}"`) 541 | } 542 | 543 | const alias = this.peek().literal 544 | this.advance() 545 | return { 546 | type: "ImportExpression", 547 | path, 548 | alias 549 | } 550 | } 551 | 552 | private advance(n = 1): Token { 553 | this.pos += n 554 | return this.tokens[this.pos] || { type: "EOF", literal: "" } 555 | } 556 | 557 | private peek(n = 0): Token { 558 | return this.tokens[this.pos + n] || { type: "EOF", literal: "" } 559 | } 560 | 561 | private getPrecedence(token: Token): number { 562 | return this.precedence[token.literal] || 0 563 | } 564 | 565 | private peekPrecedence(n = 1): number { 566 | return this.getPrecedence(this.peek()) || 0 567 | } 568 | } -------------------------------------------------------------------------------- /src/bindings/index.ts: -------------------------------------------------------------------------------- 1 | import { 2 | LLVMAddFunction, 3 | LLVMAddGlobal, 4 | LLVMAppendBasicBlockInContext, 5 | LLVMArrayType, 6 | LLVMBuildAdd, 7 | LLVMBuildAlloca, 8 | LLVMBuildBitCast, 9 | LLVMBuildBr, 10 | LLVMBuildCall2, 11 | LLVMBuildCondBr, 12 | LLVMBuildFAdd, 13 | LLVMBuildFDiv, 14 | LLVMBuildFMul, 15 | LLVMBuildFSub, 16 | LLVMBuildICmp, 17 | LLVMBuildLoad, 18 | LLVMBuildMul, 19 | LLVMBuildRet, 20 | LLVMBuildSDiv, 21 | LLVMBuildStore, 22 | LLVMBuildSub, 23 | LLVMBuildUDiv, 24 | LLVMConstInt, 25 | LLVMConstReal, 26 | LLVMConstStringInContext, 27 | LLVMContextCreate, 28 | LLVMCreateBuilderInContext, 29 | LLVMDeleteBasicBlock, 30 | LLVMDoubleTypeInContext, 31 | LLVMFloatTypeInContext, 32 | LLVMFunctionType, 33 | LLVMGetInsertBlock, 34 | LLVMGetIntTypeWidth, 35 | LLVMGetParam, 36 | LLVMGetTypeKind, 37 | LLVMInt16TypeInContext, 38 | LLVMInt1TypeInContext, 39 | LLVMInt32TypeInContext, 40 | LLVMInt64TypeInContext, 41 | LLVMInt8TypeInContext, 42 | LLVMModuleCreateWithNameInContext, 43 | LLVMPointerType, 44 | LLVMPositionBuilderAtEnd, 45 | LLVMPrintModuleToString, 46 | LLVMSetGlobalConstant, 47 | LLVMSetInitializer, 48 | LLVMSetLinkage, 49 | LLVMTypeOf, 50 | LLVMVerifyFunction, 51 | LLVMVerifyModule, 52 | LLVMVoidTypeInContext 53 | } from "./ffi"; 54 | 55 | type Pointer = any; 56 | 57 | export enum Linkage { 58 | External = 0, 59 | Internal = 1, 60 | } 61 | 62 | 63 | /** 64 | * context for llvm objects 65 | */ 66 | export class Context { 67 | private ptr: Pointer; 68 | constructor() { 69 | this.ptr = LLVMContextCreate(); 70 | } 71 | /** 72 | * get the raw pointer 73 | */ 74 | get handle() { return this.ptr; } 75 | } 76 | 77 | /** 78 | module holds functions and global data 79 | */ 80 | export class Module { 81 | private ptr: Pointer; 82 | private context: Context; 83 | private _funcs: Map = new Map(); 84 | private _strCounter = 0; 85 | 86 | /** 87 | * Add a global string constant to the module. 88 | * @param value The string value. 89 | * @param name Optional symbol name. If not provided, autogenerated. 90 | * @returns A Value pointing to the start of the string. 91 | */ 92 | addGlobalString(value: string, name?: string): Value { 93 | if (!name) { 94 | name = `.str.${this._strCounter++}`; 95 | } 96 | const ctx = this.getContext(); 97 | const i8 = Type.int8(ctx); 98 | const strBytes = Buffer.from(value + "\0"); 99 | const strConst = LLVMConstStringInContext(ctx.handle, strBytes, strBytes.length, 1); 100 | const arrType = LLVMArrayType(i8.handle, strBytes.length); 101 | const global = LLVMAddGlobal(this.ptr, arrType, Buffer.from(name + "\0")); 102 | LLVMSetInitializer(global, strConst); 103 | LLVMSetGlobalConstant(global, true); 104 | return new Value(global, Type.pointer(i8)); 105 | } 106 | 107 | /** 108 | create a new module 109 | @param name name of the module 110 | @param context llvm context 111 | */ 112 | constructor(name: string, context: Context) { 113 | this.context = context; 114 | this.ptr = LLVMModuleCreateWithNameInContext(Buffer.from(name + "\0"), context.handle); 115 | } 116 | 117 | /** 118 | add a function to the module 119 | @param name function name 120 | @param fnType function type 121 | @param opts options 122 | @returns the function object 123 | */ 124 | createFunction(name: string, fnType: FunctionType, opts?: { linkage?: Linkage }): Func { 125 | const fnPtr = LLVMAddFunction(this.ptr, Buffer.from(name + "\0"), fnType.handle); 126 | if (!fnPtr) throw new Error(`failed to add function ${name} with type ${fnType.handle}`); 127 | 128 | LLVMSetLinkage(fnPtr, opts?.linkage || Linkage.External); 129 | 130 | const func = new Func(fnPtr, this, fnType); 131 | (func as any)._paramCount = fnType.params.length; 132 | this._funcs.set(name, func); 133 | return func; 134 | } 135 | 136 | /** 137 | check if the module is valid 138 | */ 139 | verify(): void { 140 | if (LLVMVerifyModule(this.ptr, 0, null)) throw new Error("Module verification failed"); 141 | } 142 | 143 | /** 144 | get the ir as a string 145 | */ 146 | toString(): string { 147 | const cstr = LLVMPrintModuleToString(this.ptr); 148 | return cstr.toString(); 149 | } 150 | 151 | /** 152 | get the raw pointer 153 | */ 154 | get handle() { return this.ptr; } 155 | 156 | /** 157 | get the context 158 | */ 159 | getContext() { return this.context; } 160 | 161 | /** 162 | get a function by name 163 | @param name function name 164 | @returns the function object or undefined if not found 165 | */ 166 | getFunction(name: string): Func | undefined { 167 | return this._funcs.get(name); 168 | } 169 | } 170 | 171 | /** 172 | describes a function type 173 | */ 174 | export class FunctionType { 175 | private ptr: Pointer; 176 | public params: Type[]; 177 | public readonly returnType: Type; 178 | 179 | /** 180 | create a function type 181 | @param params parameter types 182 | @param ret return type 183 | @param isVarArg is variadic 184 | */ 185 | constructor(params: Type[], ret: Type, isVarArg = false) { 186 | this.params = params; 187 | this.returnType = ret; 188 | const buf = params.length ? Buffer.allocUnsafe(params.length * 8) : Buffer.alloc(0); 189 | for (let i = 0; i < params.length; ++i) { 190 | const p = params[i]; 191 | if (!p) throw new Error(`parameter at index ${i} is undefined`); 192 | buf.writeBigUInt64LE(BigInt(p.handle), i * 8); 193 | } 194 | this.ptr = LLVMFunctionType(ret.handle, buf, params.length, isVarArg); 195 | } 196 | 197 | /** 198 | get the raw pointer 199 | */ 200 | get handle() { return this.ptr; } 201 | } 202 | 203 | /** 204 | represents a function in the module 205 | */ 206 | export class Func { 207 | private ptr: Pointer; 208 | private module: Module; 209 | public type?: FunctionType; 210 | public readonly paramCount: number; 211 | 212 | /** 213 | create a function object 214 | @param ptr pointer to the function 215 | @param module parent module 216 | */ 217 | constructor(ptr: Pointer, module: Module, type?: FunctionType) { 218 | this.ptr = ptr; 219 | this.module = module; 220 | this.type = type; 221 | this.paramCount = type ? type.params.length : 0; 222 | } 223 | 224 | /** 225 | add a basic block to the function 226 | @param name block name 227 | @returns the basic block 228 | */ 229 | addBlock(name: string): BasicBlock { 230 | return new BasicBlock(LLVMAppendBasicBlockInContext(this.module.getContext().handle, this.ptr, Buffer.from(name + "\0")), this); 231 | } 232 | 233 | /** 234 | get a function argument by index 235 | @param idx argument index 236 | @returns the value 237 | */ 238 | getArg(idx: number): Value { 239 | return new Value(LLVMGetParam(this.ptr, idx)); 240 | } 241 | 242 | /** 243 | get all function arguments as an array 244 | @returns array of values 245 | */ 246 | getArgs(): Value[] { 247 | return Array.from({ length: this.paramCount }, (_, i) => this.getArg(i)); 248 | } 249 | 250 | /** 251 | check if the function is valid 252 | */ 253 | verify(): void { 254 | if (LLVMVerifyFunction(this.ptr, 0)) throw new Error("Function verification failed"); 255 | } 256 | 257 | /** 258 | get the raw pointer 259 | */ 260 | get handle() { return this.ptr; } 261 | } 262 | 263 | /** 264 | represents a basic block in a function 265 | */ 266 | export class BasicBlock { 267 | private ptr: Pointer; 268 | public readonly parent: Func | undefined; 269 | 270 | /** 271 | create a basic block object 272 | @param ptr pointer to the block 273 | @param parent parent function 274 | */ 275 | constructor(ptr: Pointer, parent?: Func) { 276 | this.ptr = ptr; 277 | this.parent = parent; 278 | } 279 | 280 | /** 281 | get the raw pointer 282 | */ 283 | get handle() { return this.ptr; } 284 | 285 | /** 286 | * Erase this block from its parent function 287 | */ 288 | erase(): void { 289 | if (!this.parent) return; 290 | LLVMDeleteBasicBlock(this.ptr); 291 | this.ptr = null; 292 | } 293 | } 294 | 295 | export enum ICmpPredicate { 296 | EQ = 32, 297 | NE = 33, 298 | UGT = 34, 299 | UGE = 35, 300 | ULT = 36, 301 | ULE = 37, 302 | SGT = 38, 303 | SGE = 39, 304 | SLT = 40, 305 | SLE = 41 306 | } 307 | 308 | export class IRBuilder { 309 | private _context: Context; 310 | /** 311 | * Bitcast a value to another type (pointer or int of same width) 312 | * @param value The value to cast 313 | * @param destType The destination type 314 | * @param name Optional name for the result 315 | * @returns The casted value 316 | */ 317 | bitcast(value: Value, destType: Type, name = "bitcasttmp"): Value { 318 | const ptr = LLVMBuildBitCast(this.ptr, value.handle, destType.handle, Buffer.from(name + "\0")); 319 | return new Value(ptr, destType); 320 | } 321 | private _currentFunc?: Func; 322 | 323 | /** 324 | * Set the current function context for this builder 325 | * @param func The function being built 326 | */ 327 | setCurrentFunc(func: Func) { 328 | this._currentFunc = func; 329 | } 330 | 331 | /** 332 | * Set where new instructions will be added in the given block 333 | * and track the parent function for getInsertBlock() 334 | * @param bb the block to insert into 335 | */ 336 | insertInto(bb: BasicBlock): void { 337 | LLVMPositionBuilderAtEnd(this.ptr, bb.handle); 338 | this._currentFunc = bb.parent; 339 | } 340 | 341 | /** 342 | integer comparison equal (==) 343 | */ 344 | icmpEQ(left: Value, right: Value, name = "icmp_eq"): Value { 345 | const valPtr = LLVMBuildICmp(this.ptr, ICmpPredicate.EQ, left.handle, right.handle, Buffer.from(name + "\0")); 346 | return new Value(valPtr, Type.int1(this._context)); 347 | } 348 | /** 349 | * Get the current insertion block 350 | * @returns the BasicBlock currently being inserted into, or undefined if not set 351 | */ 352 | getInsertBlock(): BasicBlock | undefined { 353 | if (typeof LLVMGetInsertBlock !== 'function') throw new Error('LLVMGetInsertBlock FFI not available'); 354 | const blockPtr = LLVMGetInsertBlock(this.ptr); 355 | if (!blockPtr) return undefined; 356 | return new BasicBlock(blockPtr, this._currentFunc); 357 | } 358 | /** 359 | integer comparison not equal (!=) 360 | */ 361 | icmpNE(left: Value, right: Value, name = "icmp_ne"): Value { 362 | const valPtr = LLVMBuildICmp(this.ptr, ICmpPredicate.NE, left.handle, right.handle, Buffer.from(name + "\0")); 363 | return new Value(valPtr, Type.int1(this._context)); 364 | } 365 | /** 366 | integer comparison signed less than (<) 367 | */ 368 | icmpSLT(left: Value, right: Value, name = "icmp_slt"): Value { 369 | const valPtr = LLVMBuildICmp(this.ptr, ICmpPredicate.SLT, left.handle, right.handle, Buffer.from(name + "\0")); 370 | return new Value(valPtr, Type.int1(this._context)); 371 | } 372 | /** 373 | integer comparison signed less or equal (<=) 374 | */ 375 | icmpSLE(left: Value, right: Value, name = "icmp_sle"): Value { 376 | const valPtr = LLVMBuildICmp(this.ptr, ICmpPredicate.SLE, left.handle, right.handle, Buffer.from(name + "\0")); 377 | return new Value(valPtr, Type.int1(this._context)); 378 | } 379 | /** 380 | integer comparison signed greater than (>) 381 | */ 382 | icmpSGT(left: Value, right: Value, name = "icmp_sgt"): Value { 383 | const valPtr = LLVMBuildICmp(this.ptr, ICmpPredicate.SGT, left.handle, right.handle, Buffer.from(name + "\0")); 384 | return new Value(valPtr, Type.int1(this._context)); 385 | } 386 | /** 387 | integer comparison signed greater or equal (>=) 388 | */ 389 | icmpSGE(left: Value, right: Value, name = "icmp_sge"): Value { 390 | const valPtr = LLVMBuildICmp(this.ptr, ICmpPredicate.SGE, left.handle, right.handle, Buffer.from(name + "\0")); 391 | return new Value(valPtr, Type.int1(this._context)); 392 | } 393 | 394 | /** 395 | call a function with arguments 396 | @param fn the function to call 397 | @param args array of argument values 398 | @param name optional result name 399 | @returns the result value 400 | */ 401 | call(fn: Func, args: Value[], name = "calltmp"): Value { 402 | const argPtrs = args.length ? Buffer.allocUnsafe(args.length * 8) : Buffer.alloc(0); 403 | for (let i = 0; i < args.length; ++i) { 404 | argPtrs.writeBigUInt64LE(BigInt(args[i].handle), i * 8); 405 | } 406 | if (!fn.type) throw new Error("Func.type is required for IRBuilder.call"); 407 | const fnType = fn.type.handle; 408 | const valPtr = LLVMBuildCall2(this.ptr, fnType, fn.handle, argPtrs, args.length, Buffer.from(name + "\0")); 409 | return new Value(valPtr, fn.type.returnType); 410 | } 411 | private ptr: Pointer; 412 | 413 | constructor(context: Context) { 414 | this.ptr = LLVMCreateBuilderInContext(context.handle); 415 | this._context = context; 416 | } 417 | 418 | 419 | /** 420 | allocate memory on the stack 421 | @param type the type to allocate 422 | @param name variable name 423 | @returns a pointer to the allocated memory 424 | */ 425 | alloca(type: Type, name = "alloca"): Value { 426 | return new Value(LLVMBuildAlloca(this.ptr, type.handle, Buffer.from(name + "\0"))); 427 | } 428 | 429 | /** 430 | store a value in memory 431 | @param value the value to store 432 | @param ptr the pointer to store to 433 | */ 434 | store(value: Value, ptr: Value): void { 435 | LLVMBuildStore(this.ptr, value.handle, ptr.handle); 436 | } 437 | 438 | /** 439 | load a value from memory 440 | @param ptr the pointer to load from 441 | @param name variable name 442 | @returns the loaded value 443 | */ 444 | load(ptr: Value, name = "load"): Value { 445 | return new Value(LLVMBuildLoad(this.ptr, ptr.handle, Buffer.from(name + "\0"))); 446 | } 447 | 448 | /** 449 | add two values 450 | @param a first value 451 | @param b second value 452 | @returns the result value 453 | */ 454 | add(a: Value, b: Value): Value { 455 | return new Value(LLVMBuildAdd(this.ptr, a.handle, b.handle, Buffer.from("addtmp\0")), a.getType()); 456 | } 457 | 458 | /** 459 | add two floating point values 460 | @param a first value 461 | @param b second value 462 | @returns the result value 463 | */ 464 | fadd(a: Value, b: Value): Value { 465 | return new Value(LLVMBuildFAdd(this.ptr, a.handle, b.handle, Buffer.from("faddtmp\0")), a.getType()); 466 | } 467 | 468 | /** 469 | subtract two floating point values 470 | @param a first value 471 | @param b second value 472 | @returns the result value 473 | */ 474 | fsub(a: Value, b: Value): Value { 475 | return new Value(LLVMBuildFSub(this.ptr, a.handle, b.handle, Buffer.from("fsubtmp\0")), a.getType()); 476 | } 477 | 478 | /** 479 | multiply two floating point values 480 | @param a first value 481 | @param b second value 482 | @returns the result value 483 | */ 484 | fmul(a: Value, b: Value): Value { 485 | return new Value(LLVMBuildFMul(this.ptr, a.handle, b.handle, Buffer.from("fmultmp\0")), a.getType()); 486 | } 487 | 488 | /** 489 | subtract two values 490 | @param a first value 491 | @param b second value 492 | @returns the result value 493 | */ 494 | sub(a: Value, b: Value): Value { 495 | return new Value(LLVMBuildSub(this.ptr, a.handle, b.handle, Buffer.from("subtmp\0")), a.getType()); 496 | } 497 | 498 | /** 499 | multiply two values 500 | @param a first value 501 | @param b second value 502 | @returns the result value 503 | */ 504 | mul(a: Value, b: Value): Value { 505 | return new Value(LLVMBuildMul(this.ptr, a.handle, b.handle, Buffer.from("multmp\0")), a.getType()); 506 | } 507 | 508 | /** 509 | signed integer division 510 | @param a numerator 511 | @param b denominator 512 | @returns the result value 513 | */ 514 | sdiv(a: Value, b: Value): Value { 515 | return new Value(LLVMBuildSDiv(this.ptr, a.handle, b.handle, Buffer.from("sdivtmp\0")), a.getType()); 516 | } 517 | 518 | /** 519 | unsigned integer division 520 | @param a numerator 521 | @param b denominator 522 | @returns the result value 523 | */ 524 | udiv(a: Value, b: Value): Value { 525 | return new Value(LLVMBuildUDiv(this.ptr, a.handle, b.handle, Buffer.from("udivtmp\0")), a.getType()); 526 | } 527 | 528 | /** 529 | floating point division 530 | @param a numerator 531 | @param b denominator 532 | @returns the result value 533 | */ 534 | fdiv(a: Value, b: Value): Value { 535 | return new Value(LLVMBuildFDiv(this.ptr, a.handle, b.handle, Buffer.from("fdivtmp\0")), a.getType()); 536 | } 537 | 538 | /** 539 | unconditional branch to a basic block 540 | @param dest destination block 541 | */ 542 | br(dest: BasicBlock): void { 543 | LLVMBuildBr(this.ptr, dest.handle); 544 | } 545 | 546 | /** 547 | conditional branch 548 | @param cond condition value 549 | @param thenBlock block if true 550 | @param elseBlock block if false 551 | */ 552 | condBr(cond: Value, thenBlock: BasicBlock, elseBlock: BasicBlock): void { 553 | LLVMBuildCondBr(this.ptr, cond.handle, thenBlock.handle, elseBlock.handle); 554 | } 555 | 556 | /** 557 | return from the function (with or without a value) 558 | @param val the value to return (optional) 559 | */ 560 | ret(val?: Value): void { 561 | LLVMBuildRet(this.ptr, val ? val.handle : null); 562 | } 563 | } 564 | 565 | /** 566 | represents a type in llvm 567 | */ 568 | export class Type { 569 | private ptr: Pointer; 570 | private kind: string; 571 | private bitWidth?: number; 572 | private elementType?: Type; 573 | 574 | private constructor(ptr: Pointer, kind: string, bitWidth?: number, elementType?: Type) { 575 | this.ptr = ptr; 576 | this.kind = kind; 577 | if (bitWidth !== undefined) this.bitWidth = bitWidth; 578 | if (elementType) this.elementType = elementType; 579 | } 580 | 581 | /** 582 | create a Type from a raw pointer (internal use) 583 | tries to infer kind/bitWidth for int/float/double/pointer/void 584 | */ static fromRaw(ptr: Pointer): Type { 585 | const typeKind = LLVMGetTypeKind(ptr); 586 | 587 | enum LLVMTypeKind { 588 | Void = 0, 589 | Half = 1, 590 | Float = 2, 591 | Double = 3, 592 | X86_FP80 = 4, 593 | FP128 = 5, 594 | PPC_FP128 = 6, 595 | Label = 7, 596 | Integer = 8, 597 | Function = 9, 598 | Struct = 10, 599 | Array = 11, 600 | Pointer = 12, 601 | Vector = 13, 602 | Metadata = 14, 603 | X86_MMX = 15, 604 | Token = 16, 605 | ScalableVector = 17, 606 | BFloat = 18, 607 | X86_AMX = 19, 608 | TargetExt = 20 609 | } 610 | 611 | switch (typeKind) { 612 | case LLVMTypeKind.Void: 613 | return new Type(ptr, "void"); 614 | case LLVMTypeKind.Float: 615 | return new Type(ptr, "float"); 616 | case LLVMTypeKind.Double: 617 | return new Type(ptr, "double"); 618 | case LLVMTypeKind.Pointer: 619 | return new Type(ptr, "pointer"); 620 | case LLVMTypeKind.Integer: 621 | const width = LLVMGetIntTypeWidth(ptr); 622 | if (typeof width === 'number' && width > 0) { 623 | return new Type(ptr, `int${width}`, width); 624 | } 625 | return new Type(ptr, "int"); 626 | default: 627 | return new Type(ptr, "unknown"); 628 | } 629 | } 630 | 631 | /** 632 | get i1 type 633 | */ 634 | static int1(context: Context): Type { 635 | return new Type(LLVMInt1TypeInContext(context.handle), "int1", 1); 636 | } 637 | 638 | /** 639 | get i8 type 640 | */ 641 | static int8(context: Context): Type { 642 | return new Type(LLVMInt8TypeInContext(context.handle), "int8", 8); 643 | } 644 | 645 | /** 646 | get i16 type 647 | */ 648 | static int16(context: Context): Type { 649 | return new Type(LLVMInt16TypeInContext(context.handle), "int16", 16); 650 | } 651 | 652 | /** 653 | get i32 type 654 | */ 655 | static int32(context: Context): Type { 656 | return new Type(LLVMInt32TypeInContext(context.handle), "int32", 32); 657 | } 658 | 659 | /** 660 | get i64 type 661 | */ 662 | static int64(context: Context): Type { 663 | return new Type(LLVMInt64TypeInContext(context.handle), "int64", 64); 664 | } 665 | /** 666 | get the bit width for integer types (returns undefined for non-integer types) 667 | */ 668 | getBitWidth(): number | undefined { 669 | return this.bitWidth; 670 | } 671 | 672 | /** 673 | get float type 674 | */ 675 | static float(context: Context): Type { 676 | return new Type(LLVMFloatTypeInContext(context.handle), "float"); 677 | } 678 | 679 | /** 680 | get double type 681 | */ 682 | static double(context: Context): Type { 683 | return new Type(LLVMDoubleTypeInContext(context.handle), "double"); 684 | } 685 | 686 | /** 687 | get void type 688 | */ 689 | static void(context: Context): Type { 690 | return new Type(LLVMVoidTypeInContext(context.handle), "void"); 691 | } 692 | 693 | /** 694 | get pointer type 695 | @param elementType type to point to 696 | @param addressSpace address space 697 | */ 698 | static pointer(elementType: Type, addressSpace = 0): Type { 699 | return new Type(LLVMPointerType(elementType.handle, addressSpace), "pointer", undefined, elementType); 700 | } 701 | 702 | /** 703 | get the raw pointer 704 | */ 705 | get handle() { return this.ptr; } 706 | 707 | getElementType(): Type | undefined { 708 | return this.elementType; 709 | } 710 | 711 | /** 712 | check if this is an integer type, optionally with a specific bit width 713 | @param width optional bit width to check 714 | */ 715 | isInt(width?: number): boolean { 716 | if (!this.kind.startsWith("int")) return false; 717 | if (width !== undefined) return this.bitWidth === width; 718 | return true; 719 | } 720 | 721 | /** 722 | check if this is a float type 723 | */ 724 | isFloat(): boolean { 725 | return this.kind === "float"; 726 | } 727 | 728 | /** 729 | check if this is a double type 730 | */ 731 | isDouble(): boolean { 732 | return this.kind === "double"; 733 | } 734 | 735 | /** 736 | check if this is a pointer type 737 | */ 738 | isPointer(): boolean { 739 | return this.kind === "pointer"; 740 | } 741 | 742 | /** 743 | check if this is a void type 744 | */ 745 | isVoid(): boolean { 746 | return this.kind === "void"; 747 | } 748 | } 749 | 750 | /** 751 | represents a value in llvm 752 | */ 753 | export class Value { 754 | private ptr: Pointer; 755 | private _type?: Type; 756 | 757 | /** 758 | create a value object 759 | @param ptr pointer to the value 760 | */ 761 | constructor(ptr: Pointer, type?: Type) { 762 | this.ptr = ptr; 763 | this._type = type; 764 | } 765 | 766 | /** 767 | create an integer constant 768 | @param type the integer type 769 | @param value the value 770 | @param isSignedOverride whether to treat the value as signed (optional), llvm-bun tries to infer 771 | */ 772 | static constInt(type: Type, value: number | bigint, isSignedOverride?: boolean): Value { 773 | let isSigned = true; 774 | const typeName = type.constructor.name.toLowerCase(); 775 | if (typeName.includes('uint')) isSigned = false; 776 | if (isSignedOverride !== undefined) isSigned = isSignedOverride; 777 | const ptr = LLVMConstInt(type.handle, BigInt(value), isSigned); 778 | return new Value(ptr, type); 779 | } 780 | 781 | /** 782 | create a floating point constant 783 | @param type the float type 784 | @param value the value 785 | */ 786 | static constFloat(type: Type, value: number): Value { 787 | const ptr = LLVMConstReal(type.handle, value); 788 | return new Value(ptr, type); 789 | } 790 | 791 | /** 792 | get the type of this value 793 | */ 794 | getType(): Type { 795 | if (this._type) return this._type; 796 | return Type.fromRaw(LLVMTypeOf(this.ptr)); 797 | } 798 | 799 | /** 800 | get the raw pointer 801 | */ 802 | get handle() { return this.ptr; } 803 | } 804 | 805 | const LLVM = { 806 | Context, 807 | Module, 808 | FunctionType, 809 | Func, 810 | BasicBlock, 811 | IRBuilder, 812 | Type, 813 | Linkage 814 | }; 815 | 816 | export default LLVM; 817 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . --------------------------------------------------------------------------------