├── .envrc ├── .gitattributes ├── .gitignore ├── .gitmodules ├── .luarc.json ├── .vscode ├── launch.json ├── settings.json └── tasks.json ├── DESIGN.md ├── LICENSE ├── README.md ├── get-ast.tl ├── src ├── abi.lua ├── backends │ ├── gccjit.lua │ └── gccjit │ │ ├── cdef.lua │ │ ├── init.d.tl │ │ └── init.lua ├── codegen │ └── gccjit.lua ├── main.lua └── utilities.lua ├── teal-compiler-dev-1.rockspec ├── test.tl ├── tlconfig.lua └── types ├── ffi.d.tl ├── jit.d.tl ├── jit └── p.d.tl ├── pl.d.tl ├── pl ├── Date.d.tl ├── List.d.tl ├── Map.d.tl ├── app.d.tl ├── array2d.d.tl ├── class.d.tl ├── compat.d.tl ├── comprehension.d.tl ├── config.d.tl ├── data.d.tl ├── dir.d.tl ├── file.d.tl ├── func.d.tl ├── input.d.tl ├── lapp.d.tl ├── lexer.d.tl ├── luabalanced.d.tl ├── operator.d.tl ├── path.d.tl ├── permute.d.tl ├── pretty.d.tl ├── seq.d.tl ├── sip.d.tl ├── strict.d.tl ├── stringio.d.tl ├── stringx.d.tl ├── tablex.d.tl ├── template.d.tl ├── test.d.tl ├── text.d.tl ├── types.d.tl ├── url.d.tl ├── utils.d.tl └── xml.d.tl └── teal └── tl.lua /.envrc: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | export PATH="teal/:lua_modules/bin/:$PATH" 4 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.tl linguist-language=Lua 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /archive/ 3 | /.xmake 4 | /build/ 5 | .cache 6 | t.* 7 | compile_commands.json 8 | /luarocks 9 | /lua 10 | /lua_modules 11 | /.luarocks 12 | 13 | *.S 14 | *.gimple 15 | *.o 16 | *.asm 17 | *.so 18 | ast.lua 19 | 20 | 21 | *.dot 22 | 23 | test 24 | out 25 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "teal"] 2 | path = teal 3 | url = https://github.com/Frityet/tl 4 | branch = next 5 | -------------------------------------------------------------------------------- /.luarc.json: -------------------------------------------------------------------------------- 1 | { 2 | "diagnostics.groupSeverity": { 3 | "ambiguity": "Error", 4 | "await": "Error", 5 | "codestyle": "Error", 6 | "duplicate": "Hint", 7 | "global": "Error", 8 | "luadoc": "Error", 9 | "redefined": "Information", 10 | "strict": "Error", 11 | "strong": "Error", 12 | "type-check": "Error", 13 | "unbalanced": "Error", 14 | "unused": "Hint", 15 | "conventions": "Error" 16 | }, 17 | "diagnostics.disable": [ 18 | "duplicate-doc-alias", 19 | "duplicate-doc-field" 20 | ], 21 | "workspace.library": [ 22 | "types/", 23 | "/Users/frityet/Library/Application Support/Code/User/globalStorage/sumneko.lua/addonManager/addons/penlight/module/library", 24 | "${3rd}/lfs/library", 25 | "/Users/frityet/.vscode/extensions/sumneko.lua-3.7.4-darwin-x64/server/meta/47e10203", 26 | // "/Users/frityet/.vscode/extensions/sumneko.lua-3.7.4-darwin-x64/server/meta/47e10203", 27 | ], 28 | "runtime.path": [ 29 | "src/?.lua", 30 | "src/?/init.lua", 31 | "?.lua", 32 | "?/init.lua" 33 | ], 34 | "workspace.useGitIgnore": false, 35 | "runtime.pathStrict": true, 36 | "runtime.version": "LuaJIT", 37 | "workspace.ignoreDir": [ 38 | ".vscode", 39 | ".luarocks", 40 | "build" 41 | ], 42 | "workspace.checkThirdParty": false 43 | } 44 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "arg": [ 5 | "test.tl", 6 | "-o", "out" 7 | ], 8 | // "runtimeArgs": "-joff -O0 -jp=a", 9 | "name": "launch", 10 | "program": "${workspaceFolder}/src/main.lua", 11 | "request": "launch", 12 | "luaVersion": "luajit", 13 | "luaexe": "${workspaceFolder}/lua", 14 | "path": "${workspaceFolder}/?.lua;${workspaceFolder}/?/init.lua;${workspaceFolder}/src/?.lua;${workspaceFolder}/src/?/init.lua;${workspaceFolder}/lua_modules/share/lua/5.1/?.lua;${workspaceFolder}/lua_modules/share/lua/5.1/?/init.lua;", 15 | "cpath": "${workspaceFolder}/?.so;${workspaceFolder}/lua_modules/lib/lua/5.1/?.so;", 16 | "stopOnEntry": false, 17 | "type": "lua", 18 | "console": "internalConsole", 19 | } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "teal.compilerPath": "teal/tl", 3 | "clangd.fallbackFlags": [ 4 | "-D__uint64_t='typeof(unsigned long long)'", 5 | "-D__uint32_t='typeof(unsigned int)'", 6 | "-D__int32_t='typeof(int)'", 7 | "-D__uint8_t='typeof(unsigned char)'", 8 | "-D__int8_t='typeof(char)'" 9 | ], 10 | } 11 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "Build", 6 | "command": "./luarocks", 7 | "type": "process", 8 | "args": [ 9 | "make" 10 | ], 11 | "presentation": { 12 | "reveal": "always" 13 | }, 14 | "group": "build" 15 | } 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /DESIGN.md: -------------------------------------------------------------------------------- 1 | # Teal compiler language design document 2 | 3 | The language used for the teal compiler is a soft superset of [teal](https://github.com/teal-language/tl) with some additional features and restrictions. Read the [teal documentation](https://github.com/teal-language/tl/tree/master/docs) first. 4 | 5 | ## Key ideas 6 | 7 | - Lua interop: 8 | - You should be able to easily run lua functions from teal and vice versa. 9 | - One of the main motivations for this compiler was to make it easier and faster to write Lua modules 10 | - C interop 11 | - You should be able to easily call C functions from teal and vice versa. 12 | - This adds on to making it easier to write Lua modules, as you can write C functions to be called from Lua. 13 | 14 | ## Modules 15 | 16 | Perhaps the biggest difference is with modules: 17 | 18 | ```lua 19 | local export = {} 20 | 21 | function export.say_hello() 22 | print("Hello, world!") 23 | end 24 | 25 | return export 26 | ``` 27 | 28 | ### Lua interop 29 | 30 | This is an example of a basic module, it is the same as regular teal. You may return either a table or a function. This module can only be accessed from other native teal code. To make it accessible from Lua, you must use the `#lua module` pragma: 31 | 32 | ```lua 33 | --#lua module "hello" 34 | local export = {} 35 | 36 | --This is now implicitly a "lua" function. 37 | --The first argument to the function is the lua_State *. 38 | function export.say_hello() 39 | print("Hello, world!") 40 | end 41 | 42 | --you can also declare a function to not be a lua function within a lua module with 43 | --#lua off 44 | function export.my_function() 45 | print("This is a regular, compiled teal function") 46 | end 47 | --this will not be accessible from Lua but is accessible from other teal code, including teal functions which are accessible from Lua 48 | 49 | return export 50 | ``` 51 | 52 | This module can now be accessed from Lua: 53 | 54 | ```lua 55 | local hello = require("hello") 56 | hello.say_hello() 57 | ``` 58 | 59 | ### C interop 60 | 61 | You can also call C functions from teal: 62 | 63 | ```lua 64 | --#extern c 65 | local function printf(format: c.string, ...: c.varadict): c.int32 end 66 | 67 | local function f() 68 | printf("Hello, world!\n") 69 | end 70 | ``` 71 | 72 | This will call the C function `printf` from the standard library. You can access any symbol that is linked into the executable this way. 73 | 74 | ## Exporting symbols 75 | 76 | Any `global` variables in the top scope (`global` variables in any other scope is prohibited) will be accessable from outside the object file. This is also how to define a `main` function. 77 | 78 | ```lua 79 | 80 | --a symbol `x` will be exported 81 | global x: integer = 5 82 | 83 | global function main(argc: integer, argv: c.ptr): integer 84 | print("Argc: "..tostring(argc)) 85 | 86 | return 0 87 | end 88 | ``` 89 | 90 | ## Type representation 91 | 92 | More primitive types are defined in order to make it easier to interface with C. This table 93 | 94 | | Teal type | C type | Description | Lua equivalent type | 95 | | :------------------ | :--------------------------------- | :-------------------------------------------------------------------------------------------------------- | :------------------ | 96 | | `nil` | `void` | no value | `nil` | 97 | | `byte` | `uint8_t` | 8-bit unsigned integer | `number` | 98 | | `integer8` | `int8_t` | 8-bit signed integer | `number` | 99 | | `integer16` | `int16_t` | 16-bit signed integer | `number` | 100 | | `integer32` | `int32_t` | 32-bit signed integer | `number` | 101 | | `integer64` | `int64_t` | 64-bit signed integer | `number` | 102 | | `float32` | `float` | single-precision floating point number | `number` | 103 | | `float64` | `double` | double-precision floating point number | `number` | 104 | | `float128` | `long double` | quadruple-precision floating point number (available on supporting architectures) | | 105 | | `record T` | `struct T` | Standard product type | `table` | 106 | | `interface T` | `struct T` | Interface (new in teal `next`) | `table` | 107 | | `{T}` | `T[]` | Array | `table` | 108 | | `{T1, T2}` | `struct {T1; T2} []` | Tuple | `table` | 109 | | `enum` | `const char *` | Enum, in teal this is represented as strings, so the same must be done in C. | `string` | 110 | | `T1 \| T2` | `struct {union {T1;T2}; enum tag}` | Sum type, in C this would be a tagged union, where in Lua it would be any value | `any` | 111 | | `any` | `void *` | Any value, can be any type | `lightuserdata` | 112 | | | | | | 113 | | `function(T...): T` | `T(T...)` | Function | `function` | 114 | | `unsigned` | `unsigned T` | Marks an integral type to be unsigned | `number` | 115 | | `value` | | By default, any `record` type is a reference on the heap. `value` forces it to be located on the stack | | 116 | | `integer` | `int64_t` | 64-bit signed integer | `number` | 117 | | `number` | `double` | double-precision floating point number | `number` | 118 | | `boolean` | `bool` | boolean | `boolean` | 119 | | `string` | | Proper string type, not null-terminated | `string` | 120 | | | | | | 121 | | `c.ptr` | `T *` | Pointer to value. This is a raw pointer, so be careful! | `lightuserdata` | 122 | | `c.string` | `const char *` | C string type, must be null terminated | `string` | 123 | | `c.varadict` | `...` | C varadict, only valid in arguments for C funcitons | | 124 | | `c.const` | `const T` | Constant type specifier | | 125 | | | | | | 126 | 127 | ### Records 128 | 129 | The layout of a record is the same as the layout of a C struct. Methods within a record are not fields. In order to add function pointers, use `c.ptr` 130 | 131 | -------------------------------------------------------------------------------- /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 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # teal-compiler 2 | 3 | AOT compiler for the [teal language](https://github.com/teal-language/tl) using the [libgccjit](https://gcc.gnu.org/onlinedocs/jit/index.html) library, and [luajit](https://luajit.org) 4 | -------------------------------------------------------------------------------- /get-ast.tl: -------------------------------------------------------------------------------- 1 | -- Copyright (C) 2024 Amrit Bhogal 2 | -- 3 | -- This file is part of teal-compiler. 4 | -- 5 | -- teal-compiler is free software: you can redistribute it and/or modify 6 | -- it under the terms of the GNU General Public License as published by 7 | -- the Free Software Foundation, either version 3 of the License, or 8 | -- (at your option) any later version. 9 | -- 10 | -- teal-compiler is distributed in the hope that it will be useful, 11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | -- GNU General Public License for more details. 14 | -- 15 | -- You should have received a copy of the GNU General Public License 16 | -- along with teal-compiler. If not, see . 17 | 18 | local tl = require("tl") 19 | local pretty = require("pl.pretty") 20 | 21 | local input_file, output_file = arg[1], arg[2] or "ast.lua" 22 | if not input_file then error("Missing input file as first argument") end 23 | 24 | local f = assert(io.open(input_file, "rb")) 25 | local ast, errors, modules = tl.parse(f:read("*a"), input_file) 26 | f:close() 27 | 28 | if #errors > 0 then 29 | for _, err in ipairs(errors) do 30 | io.stderr:write(string.format("%s:%d:%d: %s\n", input_file, err.y, err.x, err.msg)) 31 | end 32 | os.exit(1) 33 | end 34 | 35 | local f = assert(io.open(output_file, "w+b")) 36 | f:write("return ", pretty.write(ast as table)) 37 | f:close() 38 | -------------------------------------------------------------------------------- /src/abi.lua: -------------------------------------------------------------------------------- 1 | -- Copyright (C) 2024 Amrit Bhogal 2 | -- 3 | -- This file is part of teal-compiler. 4 | -- 5 | -- teal-compiler is free software: you can redistribute it and/or modify 6 | -- it under the terms of the GNU General Public License as published by 7 | -- the Free Software Foundation, either version 3 of the License, or 8 | -- (at your option) any later version. 9 | -- 10 | -- teal-compiler is distributed in the hope that it will be useful, 11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | -- GNU General Public License for more details. 14 | -- 15 | -- You should have received a copy of the GNU General Public License 16 | -- along with teal-compiler. If not, see . 17 | 18 | local export = {} 19 | 20 | export.version = 1 21 | 22 | ---The symbol name to be used for the function, must be a valid C identifier 23 | ---@param fn_name string 24 | ---@param params {name: string, type: tl.TypeName}[]? 25 | function export.function_name(fn_name, params) 26 | local symname = string.format("TEAL_V%d_NAME__%s", export.version, fn_name) 27 | 28 | if params then 29 | symname = symname.."__PARAMS" 30 | for _, param in ipairs(params) do 31 | symname = string.format("%s_NAME_%s_TYPE_%s", symname, param.name, param.type) 32 | end 33 | symname = symname.."__END" 34 | end 35 | 36 | return symname 37 | end 38 | 39 | return export 40 | -------------------------------------------------------------------------------- /src/backends/gccjit.lua: -------------------------------------------------------------------------------- 1 | return require("backends.gccjit.init") 2 | -------------------------------------------------------------------------------- /src/backends/gccjit/init.d.tl: -------------------------------------------------------------------------------- 1 | local ffi = require("ffi") 2 | 3 | local record libgccjit 4 | interface Object end 5 | record Context is Object 6 | enum StringOption 7 | "progname" -- GCC_JIT_STR_OPTION_PROGNAME 8 | "add command line option" -- void gcc_jit_context_add_command_line_option (gcc_jit_context *ctxt, const char *option); 9 | "add driver option" -- void gcc_jit_context_add_driver_option (gcc_jit_context *ctxt, const char *option); 10 | 11 | end 12 | 13 | enum IntegerOption 14 | "optimization level" -- GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL 15 | end 16 | 17 | enum BooleanOption 18 | "debuginfo" -- GCC_JIT_BOOL_OPTION_DEBUGINFO 19 | "dump initial tree" -- GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE 20 | "dump initial gimple" -- GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE 21 | "dump generated code" -- GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE 22 | "dump summary" -- GCC_JIT_BOOL_OPTION_DUMP_SUMMARY 23 | "dump everything" -- GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING 24 | "selfcheck GC" -- GCC_JIT_BOOL_OPTION_SELFCHECK_GC 25 | "keep intermediates" -- GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES 26 | "allow unreachable blocks" -- void gcc_jit_context_set_bool_allow_unreachable_blocks (gcc_jit_context *ctxt, int bool_value); 27 | "print errors to stderr" -- void gcc_jit_context_set_bool_print_errors_to_stderr (gcc_jit_context *ctxt, int enabled); 28 | "use external driver" -- void gcc_jit_context_set_bool_use_external_driver (gcc_jit_context *ctxt, int enabled); 29 | end 30 | 31 | enum CompilationKind 32 | "assembler" -- GCC_JIT_OUTPUT_KIND_ASSEMBLER 33 | "object file" -- GCC_JIT_OUTPUT_KIND_OBJECT_FILE 34 | "dynamic library" -- GCC_JIT_OUTPUT_KIND_DYNAMIC_LIBRARY 35 | "executable" -- GCC_JIT_OUTPUT_KIND_EXECUTABLE 36 | "assembler" -- GCC_JIT_OUTPUT_KIND_ASSEMBLER 37 | "object file" -- GCC_JIT_OUTPUT_KIND_OBJECT_FILE 38 | "dynamic library" -- GCC_JIT_OUTPUT_KIND_DYNAMIC_LIBRARY 39 | "executable" -- GCC_JIT_OUTPUT_KIND_EXECUTABLE 40 | end 41 | 42 | acquire: function(): Context 43 | 44 | set_option: function(self: Context, option: StringOption, value: string) 45 | set_option: function(self: Context, option: IntegerOption, value: integer) 46 | set_option: function(self: Context, option: BooleanOption, value: boolean) 47 | 48 | compile: function(self: Context): Result | nil 49 | compile_to_file: function(self: Context, kind: CompilationKind, filename: string) 50 | 51 | dump_reproducer_to_file: function(self: Context, filename: string) 52 | dump_to_file: function(self: Context, filename: string, update_locations: boolean) 53 | 54 | enable_dump: function(self: Context, name: string): ffi.CData 55 | 56 | get_builtin_function: function(self: Context, name: string): Function 57 | 58 | get_first_error: function(self: Context): string 59 | get_last_error: function(self: Context): string 60 | 61 | get_timer: function(self: Context): Timer 62 | get_type: function(self: Context, name: Type.Name): Type 63 | get_type: function(self: Context, name: Type.IntTypeName, num_bytes: integer, is_signed: boolean): Type 64 | 65 | new_array_access: function(self: Context, array: RValue, index: RValue, loc?: Location): LValue 66 | new_array_constructor: function(self: Context, element_type: Type, fields: {RValue}): RValue 67 | new_array_type: function(self: Context, element_type: Type, num_elements: integer, loc?: Location): Type 68 | new_binary_op: function(self: Context, result: Type, lhs: RValue, op: BinaryOperation, rhs: RValue, loc?: Location) 69 | new_bitcast: function(self: Context, target_type: Type, value: RValue, loc?: Location): RValue 70 | new_bitfield: function(self: Context, type: Type, name: string, width: integer, loc?: Location): Field 71 | new_call: function(self: Context, func: Function, result: Type, args?: {RValue}, loc?: Location): RValue 72 | new_call_through_ptr: function(self: Context, func_ptr: RValue, args?: {RValue}, loc?: Location): RValue 73 | new_case: function(self: Context, min: RValue, max: RValue, body: Block): Case 74 | new_cast: function(self: Context, target_type: Type, value: RValue, loc?: Location): RValue 75 | new_child_context: function(self: Context): Context 76 | new_comparison: function(self: Context, result: Type, lhs: RValue, op: ComparisonOperation, rhs: RValue, loc?: Location): RValue 77 | new_field: function(self: Context, type: Type, name: string, loc?: Location): Field 78 | new_function: function(self: Context, kind: Function.Kind, name: string, return_type: Type, params: {Param}, is_variadic?: boolean, loc?: Location): Function 79 | new_function_ptr_type: function(self: Context, return_type: Type, params: {Type}, is_variadic?: boolean, loc?: Location): Type 80 | new_global: function(self: Context, kind: GlobalKind, type: Type, name: string, loc?: Location): LValue 81 | new_location: function(self: Context, filename: string, line: integer, column: integer): Location 82 | new_opaque_struct_type: function(self: Context, name: string, loc?: Location): Struct 83 | new_param: function(self: Context, type: Type, name: string, loc?: Location): Param 84 | new_rvalue_from_int: function(self: Context, type: Type, value_type: RValue.InitalizerValueType, value: integer | ffi.CData): RValue 85 | new_rvalue_from_vector: function(self: Context, type: Type, values: {RValue}, loc?: Location): RValue 86 | new_string_literal: function(self: Context, value: string): RValue 87 | new_struct_constructor: function(self: Context, type: Type, fields: {Field}, values: {RValue}, loc?: Location): RValue 88 | new_struct_type: function(self: Context, name: string, fields: {Field}, loc?: Location): Struct 89 | new_unary_op: function(self: Context, result: Type, op: UnaryOperation, operand: RValue, loc?: Location): RValue 90 | new_union_constructor: function(self: Context, field: Field, value: RValue, loc?: Location): RValue 91 | new_union_type: function(self: Context, name: string, fields: {Field}, loc?: Location): Struct 92 | null: function(self: Context, type: Type): RValue 93 | zero: function(self: Context, type: Type): RValue 94 | one: function(self: Context, type: Type): RValue 95 | set_timer: function(self: Context, timer: Timer) 96 | end 97 | 98 | record ExtendedAssembly is Object 99 | add_clobber: function(self: ExtendedAssembly, clobber: string) 100 | add_input_operand: function(self: ExtendedAssembly, name: string, constraint: string, value: RValue) 101 | add_output_operand: function(self: ExtendedAssembly, name: string, constraint: string, dest: LValue) 102 | add_top_level_asm: function(self: ExtendedAssembly, asm_string: string) 103 | 104 | set_inline: function(self: ExtendedAssembly, is_inline: boolean) 105 | set_volatile: function(self: ExtendedAssembly, is_volatile: boolean) 106 | end 107 | 108 | record Function is Object 109 | enum Kind 110 | "exported" -- GCC_JIT_FUNCTION_EXPORTED 111 | "internal" -- GCC_JIT_FUNCTION_INTERNAL 112 | "imported" -- GCC_JIT_FUNCTION_IMPORTED 113 | "always inline" -- GCC_JIT_FUNCTION_ALWAYS_INLINE 114 | end 115 | 116 | dump_to_dot: function(self: Function, filename: string) 117 | 118 | get_address: function(self: Function, loc?: Location): RValue 119 | get_param_count: function(self: Function): integer 120 | get_return_type: function(self: Function): Type 121 | 122 | new_block: function(self: Function, name?: string): Block 123 | new_local: function(self: Function, type: Type, name: string, loc?: Location): LValue 124 | end 125 | 126 | record Field is Object end 127 | 128 | record Block is Object 129 | add_assignment: function(self: Block, lhs: LValue, rhs: RValue, loc?: Location) 130 | add_assignment_op: function(self: Block, lhs: LValue, op: BinaryOperation, rhs: RValue, loc?: Location) 131 | add_comment: function(self: Block, comment: string, loc?: Location) 132 | add_eval: function(self: Block, expr: RValue, loc?: Location) 133 | add_extended_asm: function(self: Block, asm: string, loc?: Location): ExtendedAssembly 134 | 135 | end_with_conditional: function(self: Block, condition: RValue, on_true: Block, on_false: Block, loc?: Location) 136 | end_with_extended_asm_goto: function(self: Block, asm: string, goto_blocks: {Block}, fallthrough_block: Block, loc?: Location): ExtendedAssembly 137 | end_with_jump: function(self: Block, target: Block, loc?: Location) 138 | end_with_return: function(self: Block, value: RValue, loc?: Location) 139 | end_with_switch: function(self: Block, value: RValue, on_default: Block, cases: {Case}, loc?: Location) 140 | end_with_void_return: function(self: Block, loc?: Location) 141 | end 142 | record Case is Object end 143 | record Location is Object end 144 | 145 | 146 | interface RValue is Object 147 | enum InitalizerValueType 148 | "int" 149 | "long" 150 | "double" 151 | "pointer" 152 | end 153 | 154 | dereference: function(self: RValue, loc?: Location): LValue 155 | dereference_field: function(self: RValue, field: Field, loc?: Location): LValue 156 | end 157 | interface LValue is Object 158 | enum TLSModel 159 | "none" -- GCC_JIT_TLS_MODEL_NONE 160 | "global dynamic" -- GCC_JIT_TLS_MODEL_GLOBAL_DYNAMIC 161 | "local dynamic" -- GCC_JIT_TLS_MODEL_LOCAL_DYNAMIC 162 | "initial exec" -- GCC_JIT_TLS_MODEL_INITIAL_EXEC 163 | "local exec" -- GCC_JIT_TLS_MODEL_LOCAL_EXEC 164 | end 165 | 166 | access_field: function(self: LValue, field: Field, loc?: Location): LValue 167 | as_rvalue: function(self: LValue): RValue 168 | get_address: function(self: LValue, loc?: Location): RValue 169 | get_alignment: function(self: LValue): integer 170 | set_alignment: function(self: LValue, alignment: integer) 171 | set_intaliser: function(self: LValue, initializer: RValue) 172 | set_link_section: function(self: LValue, section: string) 173 | set_register_name: function(self: LValue, name: string) 174 | set_require_tailcall: function(self: LValue, require_tailcall: boolean) 175 | set_tls_model: function(self: LValue, model: TLSModel) 176 | end 177 | record Param is LValue end 178 | 179 | interface Type is Object 180 | enum Name 181 | "void" -- GCC_JIT_TYPE_VOID 182 | "void *" -- GCC_JIT_TYPE_VOID_PTR 183 | "bool" -- GCC_JIT_TYPE_BOOL 184 | "char" -- GCC_JIT_TYPE_CHAR 185 | "signed char" -- GCC_JIT_TYPE_SIGNED_CHAR 186 | "unsigned char" -- GCC_JIT_TYPE_UNSIGNED_CHAR 187 | "short" -- GCC_JIT_TYPE_SHORT 188 | "unsigned short" -- GCC_JIT_TYPE_UNSIGNED_SHORT 189 | "unsigned int" -- "int" GCC_JIT_TYPE_INT 190 | "long" -- GCC_JIT_TYPE_LONG 191 | "unsigned long" -- GCC_JIT_TYPE_UNSIGNED_LONG 192 | "long long" -- GCC_JIT_TYPE_LONG_LONG 193 | "unsigned long long" -- GCC_JIT_TYPE_UNSIGNED_LONG_LONG 194 | "float" -- GCC_JIT_TYPE_FLOAT 195 | "double" -- GCC_JIT_TYPE_DOUBLE 196 | "long double" -- GCC_JIT_TYPE_LONG_DOUBLE 197 | "const char *" -- GCC_JIT_TYPE_CONST_CHAR_PTR 198 | "size_t" -- GCC_JIT_TYPE_SIZE_T 199 | "FILE *" -- GCC_JIT_TYPE_FILE_PTR 200 | "complex float" -- GCC_JIT_TYPE_COMPLEX_FLOAT 201 | "complex double" -- GCC_JIT_TYPE_COMPLEX_DOUBLE 202 | "complex long double" -- GCC_JIT_TYPE_COMPLEX_LONG_DOUBLE 203 | "uint8_t" -- GCC_JIT_TYPE_UINT8 204 | "uint16_t" -- GCC_JIT_TYPE_UINT16 205 | "uint32_t" -- GCC_JIT_TYPE_UINT32 206 | "uint64_t" -- GCC_JIT_TYPE_UINT64 207 | "uint128_t" -- GCC_JIT_TYPE_UINT128 208 | "int8_t" -- GCC_JIT_TYPE_INT8 209 | "int16_t" -- GCC_JIT_TYPE_INT16 210 | "int32_t" -- GCC_JIT_TYPE_INT32 211 | "int64_t" -- GCC_JIT_TYPE_INT64 212 | "int128_t" -- GCC_JIT_TYPE_INT128 213 | "void" -- GCC_JIT_TYPE_VOID 214 | "void *" -- GCC_JIT_TYPE_VOID_PTR 215 | "bool" -- GCC_JIT_TYPE_BOOL 216 | "char" -- GCC_JIT_TYPE_CHAR 217 | "signed char" -- GCC_JIT_TYPE_SIGNED_CHAR 218 | "unsigned char" -- GCC_JIT_TYPE_UNSIGNED_CHAR 219 | "short" -- GCC_JIT_TYPE_SHORT 220 | "unsigned short" -- GCC_JIT_TYPE_UNSIGNED_SHORT 221 | "unsigned int" -- "int" GCC_JIT_TYPE_INT 222 | "long" -- GCC_JIT_TYPE_LONG 223 | "unsigned long" -- GCC_JIT_TYPE_UNSIGNED_LONG 224 | "long long" -- GCC_JIT_TYPE_LONG_LONG 225 | "unsigned long long" -- GCC_JIT_TYPE_UNSIGNED_LONG_LONG 226 | "float" -- GCC_JIT_TYPE_FLOAT 227 | "double" -- GCC_JIT_TYPE_DOUBLE 228 | "long double" -- GCC_JIT_TYPE_LONG_DOUBLE 229 | "const char *" -- GCC_JIT_TYPE_CONST_CHAR_PTR 230 | "size_t" -- GCC_JIT_TYPE_SIZE_T 231 | "FILE *" -- GCC_JIT_TYPE_FILE_PTR 232 | "complex float" -- GCC_JIT_TYPE_COMPLEX_FLOAT 233 | "complex double" -- GCC_JIT_TYPE_COMPLEX_DOUBLE 234 | "complex long double" -- GCC_JIT_TYPE_COMPLEX_LONG_DOUBLE 235 | "uint8_t" -- GCC_JIT_TYPE_UINT8 236 | "uint16_t" -- GCC_JIT_TYPE_UINT16 237 | "uint32_t" -- GCC_JIT_TYPE_UINT32 238 | "uint64_t" -- GCC_JIT_TYPE_UINT64 239 | "uint128_t" -- GCC_JIT_TYPE_UINT128 240 | "int8_t" -- GCC_JIT_TYPE_INT8 241 | "int16_t" -- GCC_JIT_TYPE_INT16 242 | "int32_t" -- GCC_JIT_TYPE_INT32 243 | "int64_t" -- GCC_JIT_TYPE_INT64 244 | "int128_t" -- GCC_JIT_TYPE_INT128 245 | end 246 | enum IntTypeName 247 | "int" 248 | end 249 | 250 | aligned: function(self: Type, alignment: integer): Type 251 | const: function(self: Type): Type 252 | dyncast_array: function(self: Type): Type 253 | dyncast_function_ptr: function(self: Type): Type 254 | dyncast_vector: function(self: Type): VectorType 255 | get_size: function(self: Type): integer 256 | is_bool: function(self: Type): boolean 257 | is_compatable_with: function(self: Type, other: Type): boolean 258 | is_integral: function(self: Type): boolean 259 | is_pointer: function(self: Type): boolean 260 | is_struct: function(self: Type): boolean 261 | pointer: function(self: Type): Type 262 | unqualified: function(self: Type): Type 263 | vector: function(self: Type, num_elements: integer): VectorType 264 | volatile: function(self: Type): Type 265 | end 266 | record FunctionType is Type 267 | get_param: function(self: FunctionType, index: integer): Type 268 | get_param_count: function(self: FunctionType): integer 269 | get_return_type: function(self: FunctionType): Type 270 | end 271 | record Struct is {Field}, Type 272 | get_field: function(self: Struct, idx: integer): Field 273 | get_field_count: function(self: Struct): integer 274 | set_fields: function(self: Struct, fields: {Field}, loc?: Location) 275 | end 276 | record VectorType is Type end 277 | 278 | record Result is Object 279 | get_code: function(self: Result, symbol: string, type: string | ffi.CType): ffi.CData | nil 280 | get_global: function(self: Result, name: string, type: string | ffi.CType): ffi.CData | nil 281 | end 282 | record Timer is Object end 283 | 284 | enum UnaryOperation 285 | "minus" 286 | "-" -- GCC_JIT_UNARY_OP_MINUS 287 | "bitwise negate" 288 | "~" -- GCC_JIT_UNARY_OP_BITWISE_NEGATE 289 | "logical negate" 290 | "!" -- GCC_JIT_UNARY_OP_LOGICAL_NEGATE 291 | "minus" 292 | "-" -- GCC_JIT_UNARY_OP_MINUS 293 | "bitwise negate" 294 | "~" -- GCC_JIT_UNARY_OP_BITWISE_NEGATE 295 | "logical negate" 296 | "!" -- GCC_JIT_UNARY_OP_LOGICAL_NEGATE 297 | end 298 | 299 | enum BinaryOperation 300 | "plus" 301 | "+" -- GCC_JIT_BINARY_OP_PLUS 302 | "mult" 303 | "*" -- GCC_JIT_BINARY_OP_MULT 304 | "divide" 305 | "/" -- GCC_JIT_BINARY_OP_DIVIDE 306 | "modulo" 307 | "%" -- GCC_JIT_BINARY_OP_MODULO 308 | "bitwise and" 309 | "&" -- GCC_JIT_BINARY_OP_BITWISE_AND 310 | "bitwise or" 311 | "|" -- GCC_JIT_BINARY_OP_BITWISE_OR 312 | "bitwise xor" 313 | "^" -- GCC_JIT_BINARY_OP_BITWISE_XOR 314 | "left shift" 315 | "<<" -- GCC_JIT_BINARY_OP_LEFT_SHIFT 316 | "right shift" 317 | ">>" -- GCC_JIT_BINARY_OP_RIGHT_SHIFT 318 | "logical and" 319 | "&&" -- GCC_JIT_BINARY_OP_LOGICAL_AND 320 | "logical or" 321 | "||" -- GCC_JIT_BINARY_OP_LOGICAL_OR 322 | "plus" 323 | "+" -- GCC_JIT_BINARY_OP_PLUS 324 | "mult" 325 | "*" -- GCC_JIT_BINARY_OP_MULT 326 | "divide" 327 | "/" -- GCC_JIT_BINARY_OP_DIVIDE 328 | "modulo" 329 | "%" -- GCC_JIT_BINARY_OP_MODULO 330 | "bitwise and" 331 | "&" -- GCC_JIT_BINARY_OP_BITWISE_AND 332 | "bitwise or" 333 | "|" -- GCC_JIT_BINARY_OP_BITWISE_OR 334 | "bitwise xor" 335 | "^" -- GCC_JIT_BINARY_OP_BITWISE_XOR 336 | "left shift" 337 | "<<" -- GCC_JIT_BINARY_OP_LEFT_SHIFT 338 | "right shift" 339 | ">>" -- GCC_JIT_BINARY_OP_RIGHT_SHIFT 340 | "logical and" 341 | "&&" -- GCC_JIT_BINARY_OP_LOGICAL_AND 342 | "logical or" 343 | "||" -- GCC_JIT_BINARY_OP_LOGICAL_OR 344 | end 345 | 346 | enum ComparisonOperation 347 | "eq" 348 | "==" -- GCC_JIT_COMPARISON_EQ 349 | "ne" 350 | "!=" -- GCC_JIT_COMPARISON_NE 351 | "lt" 352 | "<" -- GCC_JIT_COMPARISON_LT 353 | "le" 354 | "<=" -- GCC_JIT_COMPARISON_LE 355 | "gt" 356 | ">" -- GCC_JIT_COMPARISON_GT 357 | "ge" 358 | ">=" -- GCC_JIT_COMPARISON_GE 359 | "eq" 360 | "==" -- GCC_JIT_COMPARISON_EQ 361 | "ne" 362 | "!=" -- GCC_JIT_COMPARISON_NE 363 | "lt" 364 | "<" -- GCC_JIT_COMPARISON_LT 365 | "le" 366 | "<=" -- GCC_JIT_COMPARISON_LE 367 | "gt" 368 | ">" -- GCC_JIT_COMPARISON_GT 369 | "ge" 370 | ">=" -- GCC_JIT_COMPARISON_GE 371 | end 372 | 373 | enum GlobalKind 374 | "exported" -- GCC_JIT_GLOBAL_EXPORTED 375 | "internal" -- GCC_JIT_GLOBAL_INTERNAL 376 | "imported" -- GCC_JIT_GLOBAL_IMPORTED 377 | end 378 | end 379 | 380 | return libgccjit 381 | -------------------------------------------------------------------------------- /src/backends/gccjit/init.lua: -------------------------------------------------------------------------------- 1 | -- Copyright (C) 2024 Amrit Bhogal 2 | -- 3 | -- This file is part of teal-compiler. 4 | -- 5 | -- teal-compiler is free software: you can redistribute it and/or modify 6 | -- it under the terms of the GNU General Public License as published by 7 | -- the Free Software Foundation, either version 3 of the License, or 8 | -- (at your option) any later version. 9 | -- 10 | -- teal-compiler is distributed in the hope that it will be useful, 11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | -- GNU General Public License for more details. 14 | -- 15 | -- You should have received a copy of the GNU General Public License 16 | -- along with teal-compiler. If not, see . 17 | 18 | local ffi = require("ffi") 19 | local libgccjit = require("backends.gccjit.cdef") 20 | 21 | ffi.cdef [[ 22 | void free(void *ptr); 23 | ]] 24 | 25 | ---@param x string 26 | ---@return (function | integer)? 27 | local function sym(x) 28 | local ok, res = pcall(function(x) return libgccjit[x] end, x) 29 | if ok then return res end 30 | end 31 | 32 | ---@class gccjit 33 | local export = {} 34 | 35 | ---@param obj gccjit.Object* 36 | ---@return string? 37 | function export.debug_string(obj) 38 | local to_obj = obj.as_object 39 | return to_obj and ffi.string(libgccjit.gcc_jit_object_get_debug_string(to_obj(obj))) or nil 40 | end 41 | 42 | ---@class gccjit.Object* : ffi.cdata* 43 | ---@field as_object nil | fun(self: self): gccjit.Object* 44 | 45 | --#region Context 46 | ---@class gccjit.Context* : gccjit.Object* 47 | local Context = {} 48 | Context.__index = Context 49 | 50 | ---@return gccjit.Context* 51 | function Context.acquire() 52 | return ffi.gc(libgccjit.gcc_jit_context_acquire(), libgccjit.gcc_jit_context_release) --[[@as gccjit.Context*]] 53 | end 54 | 55 | ---@alias gccjit.Options.String 56 | ---| "progname" GCC_JIT_STR_OPTION_PROGNAME 57 | ---Extras: 58 | ---| "add command line option" void gcc_jit_context_add_command_line_option (gcc_jit_context *ctxt, const char *option); 59 | ---| "add driver option" void gcc_jit_context_add_driver_option (gcc_jit_context *ctxt, const char *option); 60 | 61 | ---@alias gccjit.Options.Integer 62 | ---| "optimization level" GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL 63 | 64 | ---@alias gccjit.Options.Boolean 65 | ---| "debuginfo" GCC_JIT_BOOL_OPTION_DEBUGINFO 66 | ---| "dump initial tree" GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE 67 | ---| "dump initial gimple" GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE 68 | ---| "dump generated code" GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE 69 | ---| "dump summary" GCC_JIT_BOOL_OPTION_DUMP_SUMMARY 70 | ---| "dump everything" GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING 71 | ---| "selfcheck GC" GCC_JIT_BOOL_OPTION_SELFCHECK_GC 72 | ---| "keep intermediates" GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES 73 | ---Extras: 74 | ---| "allow unreachable blocks" void gcc_jit_context_set_bool_allow_unreachable_blocks (gcc_jit_context *ctxt, int bool_value); 75 | ---| "print errors to stderr" void gcc_jit_context_set_bool_print_errors_to_stderr (gcc_jit_context *ctxt, int enabled); 76 | ---| "use external driver" void gcc_jit_context_set_bool_use_external_driver (gcc_jit_context *ctxt, int enabled); 77 | 78 | --overload fun(self: gccjit.Context*, option: gccjit.Options.Boolean, value: boolean) 79 | --overload fun(self: gccjit.Context*, option: gccjit.Options.Integer, value: integer) 80 | --overload fun(self: gccjit.Context*, option: gccjit.Options.String, value: string) 81 | ---@param option gccjit.Options.Boolean | gccjit.Options.Integer | gccjit.Options.String 82 | ---@param value boolean | integer | string 83 | function Context:set_option(option, value) 84 | option = option:gsub(" ", "_"):upper() 85 | if type(value) == "boolean" then 86 | local s = sym("GCC_JIT_BOOL_OPTION_"..option) 87 | if not s then 88 | s = sym["gcc_jit_context_set_bool_"..option:lower()] 89 | if not s then error("Unknown option: "..option) end 90 | s(self, value) 91 | else 92 | libgccjit.gcc_jit_context_set_bool_option(self, s, value) 93 | end 94 | elseif type(value) == "number" then 95 | local s = sym("GCC_JIT_INT_OPTION_"..option) 96 | if not s then 97 | s = sym["gcc_jit_context_"..option:lower()] 98 | if not s then error("Unknown option: "..option) end 99 | s(self, value) 100 | else 101 | libgccjit.gcc_jit_context_set_int_option(self, s, value) 102 | end 103 | elseif type(value) == "string" then 104 | local s = sym("GCC_JIT_STR_OPTION_"..option) 105 | if not s then 106 | s = sym["gcc_jit_context_"..option:lower()] 107 | if not s then error("Unknown option: "..option) end 108 | s(self, value) 109 | else 110 | libgccjit.gcc_jit_context_set_str_option(self, s, value) 111 | end 112 | else error("Unknown option type: "..type(value)) end 113 | end 114 | 115 | ---@return gccjit.Context* 116 | function Context:new_child_context() 117 | return libgccjit.gcc_jit_context_new_child_context(self) --[[@as gccjit.Context*]] 118 | end 119 | 120 | ---@param path string 121 | function Context:dump_reproducer_to_file(path) 122 | libgccjit.gcc_jit_context_dump_reproducer_to_file(self, path) 123 | end 124 | 125 | ---@param dumpname string 126 | ---@return ffi.cdata* `char *` 127 | function Context:enable_dump(dumpname) 128 | local ret = ffi.new("char*[1]") 129 | libgccjit.gcc_jit_context_enable_dump(self, dumpname, ret) 130 | return ffi.gc(ret[1], ffi.C.free) 131 | end 132 | 133 | ---@param func gccjit.Function* 134 | ---@param args gccjit.RValue*[]? 135 | ---@param location gccjit.Location*? 136 | ---@return gccjit.RValue* 137 | function Context:new_call(func, args, location) 138 | local numargs = args and #args or 0 139 | local cargs = ffi.new("gcc_jit_rvalue*[?]", numargs) 140 | for i = 1, numargs do 141 | --[[ @cast args gccjit.RValue*[] ]] 142 | cargs[i-1] = args[i] 143 | end 144 | return libgccjit.gcc_jit_context_new_call(self, location, func, numargs, cargs) --[[@as gccjit.RValue*]] 145 | end 146 | 147 | ---@param fn_ptr gccjit.RValue* 148 | ---@param args gccjit.RValue*[]? 149 | ---@param location gccjit.Location*? 150 | ---@return gccjit.RValue* 151 | function Context:new_call_through_ptr(fn_ptr, args, location) 152 | local numargs = args and #args or 0 153 | local cargs = ffi.new("gcc_jit_rvalue*[?]", numargs) 154 | for i = 1, numargs do 155 | cargs[i-1] = (args)[i] 156 | end 157 | return libgccjit.gcc_jit_context_new_call_through_ptr(self, location, fn_ptr, numargs, cargs) --[[@as gccjit.RValue*]] 158 | end 159 | 160 | ---@param type gccjit.Type* 161 | ---@param value gccjit.RValue* 162 | ---@param location gccjit.Location*? 163 | ---@return gccjit.RValue* 164 | function Context:new_cast(type, value, location) 165 | return libgccjit.gcc_jit_context_new_cast(self, location, value, type) --[[@as gccjit.RValue*]] 166 | end 167 | 168 | ---@param type gccjit.Type* 169 | ---@param value gccjit.RValue* 170 | ---@param location gccjit.Location*? 171 | ---@return gccjit.RValue* 172 | function Context:new_bitcast(type, value, location) 173 | return libgccjit.gcc_jit_context_new_bitcast(self, location, type, value) --[[@as gccjit.RValue*]] 174 | end 175 | 176 | ---@alias gccjit.Type*.Type 177 | ---| "void" GCC_JIT_TYPE_VOID 178 | ---| "void *" GCC_JIT_TYPE_VOID_PTR 179 | ---| "bool" GCC_JIT_TYPE_BOOL 180 | ---| "char" GCC_JIT_TYPE_CHAR 181 | ---| "signed char" GCC_JIT_TYPE_SIGNED_CHAR 182 | ---| "unsigned char" GCC_JIT_TYPE_UNSIGNED_CHAR 183 | ---| "short" GCC_JIT_TYPE_SHORT 184 | ---| "unsigned short" GCC_JIT_TYPE_UNSIGNED_SHORT 185 | --- "int" GCC_JIT_TYPE_INT, specialised in the func def, purposefully not as an alias 186 | ---| "unsigned int" GCC_JIT_TYPE_UNSIGNED_INT 187 | ---| "long" GCC_JIT_TYPE_LONG 188 | ---| "unsigned long" GCC_JIT_TYPE_UNSIGNED_LONG 189 | ---| "long long" GCC_JIT_TYPE_LONG_LONG 190 | ---| "unsigned long long" GCC_JIT_TYPE_UNSIGNED_LONG_LONG 191 | ---| "float" GCC_JIT_TYPE_FLOAT 192 | ---| "double" GCC_JIT_TYPE_DOUBLE 193 | ---| "long double" GCC_JIT_TYPE_LONG_DOUBLE 194 | ---| "const char *" GCC_JIT_TYPE_CONST_CHAR_PTR 195 | ---| "size_t" GCC_JIT_TYPE_SIZE_T 196 | ---| "FILE *" GCC_JIT_TYPE_FILE_PTR 197 | ---| "complex float" GCC_JIT_TYPE_COMPLEX_FLOAT 198 | ---| "complex double" GCC_JIT_TYPE_COMPLEX_DOUBLE 199 | ---| "complex long double" GCC_JIT_TYPE_COMPLEX_LONG_DOUBLE 200 | ---| "uint8_t" GCC_JIT_TYPE_UINT8 201 | ---| "uint16_t" GCC_JIT_TYPE_UINT16 202 | ---| "uint32_t" GCC_JIT_TYPE_UINT32 203 | ---| "uint64_t" GCC_JIT_TYPE_UINT64 204 | ---| "uint128_t" GCC_JIT_TYPE_UINT128 205 | ---| "int8_t" GCC_JIT_TYPE_INT8 206 | ---| "int16_t" GCC_JIT_TYPE_INT16 207 | ---| "int32_t" GCC_JIT_TYPE_INT32 208 | ---| "int64_t" GCC_JIT_TYPE_INT64 209 | ---| "int128_t" GCC_JIT_TYPE_INT128 210 | 211 | ---@overload fun(self: gccjit.Context*, tname: "int", num_bytes: integer, is_signed: boolean): gccjit.Type* 212 | ---@param tname gccjit.Type*.Type 213 | ---@return gccjit.Type* 214 | function Context:get_type(tname, num_bytes, is_signed) 215 | if tname == "int" then 216 | return libgccjit.gcc_jit_context_get_int_type(self, num_bytes, is_signed) 217 | end 218 | tname = tname:gsub(" ", "_"):gsub("*", "PTR"):upper() 219 | return libgccjit.gcc_jit_context_get_type(self, libgccjit["GCC_JIT_TYPE_"..tname]) --[[@as gccjit.Type*]] 220 | end 221 | 222 | ---@param path string 223 | ---@param update_locations boolean 224 | function Context:dump_to_file(path, update_locations) 225 | libgccjit.gcc_jit_context_dump_to_file(self, path, update_locations) 226 | end 227 | 228 | ---@return string 229 | function Context:get_first_error() 230 | return ffi.string(libgccjit.gcc_jit_context_get_first_error(self)) 231 | end 232 | 233 | ---@return string 234 | function Context:get_last_error() 235 | return ffi.string(libgccjit.gcc_jit_context_get_last_error(self)) 236 | end 237 | 238 | function Context:as_object() 239 | return self 240 | end 241 | 242 | function Context:__tostring() 243 | return assert(export.debug_string(self), "Failed to get debug string") 244 | end 245 | 246 | --#endregion 247 | 248 | ---@class gccjit.Field* : gccjit.Object* 249 | local Field = {} 250 | Field.__index = Field 251 | 252 | ---@param element_type gccjit.Type* 253 | ---@param num_elements integer 254 | ---@param location gccjit.Location*? 255 | ---@return gccjit.Type* 256 | function Context:new_array_type(element_type, num_elements, location) 257 | return libgccjit.gcc_jit_context_new_array_type(self, location, element_type, num_elements) --[[@as gccjit.Type*]] 258 | end 259 | 260 | ---@param type gccjit.Type* 261 | ---@param name string 262 | ---@param location gccjit.Location*? 263 | ---@return gccjit.Field* 264 | function Context:new_field(type, name, location) 265 | return libgccjit.gcc_jit_context_new_field(self, location, type, name) --[[@as gccjit.Field*]] 266 | end 267 | 268 | ---@param type gccjit.Type* 269 | ---@param name string 270 | ---@param width integer 271 | ---@param location gccjit.Location*? 272 | ---@return gccjit.Field* 273 | function Context:new_bitfield(type, name, width, location) 274 | return libgccjit.gcc_jit_context_new_bitfield(self, location, type, name, width) --[[@as gccjit.Field*]] 275 | end 276 | 277 | function Field:as_object() 278 | return libgccjit.gcc_jit_field_as_object(self) 279 | end 280 | 281 | function Field:__tostring() 282 | return export.debug_string(self) 283 | end 284 | 285 | ---@class gccjit.Struct* : gccjit.Type* 286 | ---@field [integer] gccjit.Field* 287 | local Struct = {} 288 | Struct.__index = function (self, n) 289 | if type(n) == "number" then 290 | return libgccjit.gcc_jit_struct_get_field(self, n) --[[@as gccjit.Field*]] 291 | end 292 | end 293 | 294 | ---@param name string 295 | ---@param fields gccjit.Field*[] 296 | ---@param location gccjit.Location*? 297 | ---@return gccjit.Struct* 298 | function Context:new_struct_type(name, fields, location) 299 | local num_fields = #fields 300 | local cfields = ffi.new("gcc_jit_field*[?]", num_fields) 301 | for i = 1, num_fields do 302 | cfields[i-1] = (fields)[i] 303 | end 304 | return libgccjit.gcc_jit_context_new_struct_type(self, location, name, num_fields, cfields) --[[@as gccjit.Struct*]] 305 | end 306 | 307 | ---@param name string 308 | ---@param location gccjit.Location*? 309 | ---@return gccjit.Struct* 310 | function Context:new_opaque_struct_type(name, location) 311 | return libgccjit.gcc_jit_context_new_opaque_struct(self, location, name) --[[@as gccjit.Struct*]] 312 | end 313 | 314 | ---@param fields gccjit.Field*[] 315 | ---@param location gccjit.Location*? 316 | function Struct:set_fields(fields, location) 317 | local num_fields = #fields 318 | local cfields = ffi.new("gcc_jit_field*[?]", num_fields) 319 | for i = 1, num_fields do 320 | cfields[i-1] = (fields)[i] 321 | end 322 | libgccjit.gcc_jit_struct_set_fields(self, location, num_fields, cfields) 323 | end 324 | 325 | ---@param idx integer 326 | ---@return gccjit.Field* 327 | function Struct:get_field(idx) 328 | return libgccjit.gcc_jit_struct_get_field(self, idx) --[[@as gccjit.Field*]] 329 | end 330 | 331 | ---@return integer 332 | function Struct:get_field_count() 333 | return libgccjit.gcc_jit_struct_get_field_count(self) 334 | end 335 | Struct.__len = Struct.get_field_count 336 | 337 | function Struct:as_type() 338 | return libgccjit.gcc_jit_struct_as_type(self) 339 | end 340 | 341 | ---@param type gccjit.Type* 342 | ---@param fields gccjit.Field*[] 343 | ---@param values gccjit.RValue*[] 344 | ---@param loc gccjit.Location*? 345 | ---@return gccjit.RValue* 346 | function Context:new_struct_constructor(type, fields, values, loc) 347 | --fields and values must have the exact same length 348 | local num_fields = #fields 349 | assert(num_fields == #values, "fields and values must have the same length") 350 | local cfields = ffi.new("gcc_jit_field*[?]", num_fields) 351 | local cvalues = ffi.new("gcc_jit_rvalue*[?]", num_fields) 352 | for i = 1, num_fields do 353 | cfields[i-1] = fields[i] 354 | cvalues[i-1] = values[i] 355 | end 356 | 357 | return libgccjit.gcc_jit_context_new_struct_constructor(self, loc, type, num_fields, cfields, cvalues) --[[@as gccjit.RValue*]] 358 | end 359 | 360 | ---@param type gccjit.Type* 361 | ---@param field gccjit.Field* 362 | ---@param value gccjit.RValue* 363 | ---@param loc gccjit.Location*? 364 | ---@return gccjit.RValue* 365 | function Context:new_union_constructor(type, field, value, loc) 366 | return libgccjit.gcc_jit_context_new_union_constructor(self, loc, type, field, value) --[[@as gccjit.RValue*]] 367 | end 368 | 369 | ---@param type gccjit.Type* 370 | ---@param fields gccjit.RValue*[] 371 | ---@param loc gccjit.Location*? 372 | ---@return gccjit.RValue* 373 | function Context:new_array_constructor(type, fields, loc) 374 | local num_fields = #fields 375 | local cfields = ffi.new("gcc_jit_rvalue*[?]", num_fields) 376 | for i = 1, num_fields do 377 | cfields[i-1] = (fields)[i] 378 | end 379 | return libgccjit.gcc_jit_context_new_array_constructor(self, loc, type, num_fields, cfields) --[[@as gccjit.RValue*]] 380 | end 381 | 382 | ---@param ptr gccjit.RValue* 383 | ---@param index gccjit.RValue* 384 | ---@param loc gccjit.Location*? 385 | ---@return gccjit.LValue* 386 | function Context:new_array_access(ptr, index, loc) 387 | return libgccjit.gcc_jit_context_new_array_access(self, loc, ptr, index) --[[@as gccjit.LValue*]] 388 | end 389 | 390 | function Struct:as_object() 391 | return libgccjit.gcc_jit_struct_as_object(self) 392 | end 393 | 394 | function Struct:__tostring() 395 | return export.debug_string(self) 396 | end 397 | 398 | ---@class gccjit.Type* : gccjit.Object* 399 | local Type = {} 400 | Type.__index = Type 401 | 402 | ---@param name string 403 | ---@param fields gccjit.Field*[] 404 | ---@param location gccjit.Location*? 405 | ---@return gccjit.Type* 406 | function Context:new_union_type(name, fields, location) 407 | local num_fields = #fields 408 | local cfields = ffi.new("gcc_jit_field*[?]", num_fields) 409 | for i = 1, num_fields do 410 | cfields[i-1] = (fields)[i] 411 | end 412 | return libgccjit.gcc_jit_context_new_union_type(self, location, name, num_fields, cfields) --[[@as gccjit.Type*]] 413 | end 414 | 415 | ---@param return_type gccjit.Type* 416 | ---@param param_types gccjit.Type*[] 417 | ---@param is_variadic boolean 418 | ---@param location gccjit.Location*? 419 | ---@return gccjit.Type* 420 | function Context:new_function_ptr_type(return_type, param_types, is_variadic, location) 421 | local num_params = #param_types 422 | local cparams = ffi.new("gcc_jit_type*[?]", num_params) 423 | for i = 1, num_params do 424 | cparams[i-1] = (param_types)[i] 425 | end 426 | return libgccjit.gcc_jit_context_new_function_ptr_type(self, location, return_type, num_params, cparams, not not is_variadic) --[[@as gccjit.Type*]] 427 | end 428 | 429 | ---@return gccjit.Type* 430 | function Type:pointer() 431 | return libgccjit.gcc_jit_type_get_pointer(self) --[[@as gccjit.Type*]] 432 | end 433 | 434 | ---@return gccjit.Type* 435 | function Type:const() 436 | return libgccjit.gcc_jit_type_get_const(self) --[[@as gccjit.Type*]] 437 | end 438 | 439 | ---@return gccjit.Type* 440 | function Type:volatile() 441 | return libgccjit.gcc_jit_type_get_volatile(self) --[[@as gccjit.Type*]] 442 | end 443 | 444 | ---@return integer 445 | function Type:get_size() 446 | return libgccjit.gcc_jit_type_get_size(self) 447 | end 448 | 449 | ---@param t2 gccjit.Type* 450 | ---@return boolean 451 | function Type:is_compatable_with(t2) 452 | return libgccjit.gcc_jit_type_is_compatible(self, t2) ~= 0 453 | end 454 | Type.__eq = Type.is_compatable_with 455 | 456 | ---@param bytes integer 457 | ---@return gccjit.Type* 458 | function Type:aligned(bytes) 459 | return libgccjit.gcc_jit_type_get_aligned(self, bytes) --[[@as gccjit.Type*]] 460 | end 461 | 462 | ---@param n integer 463 | ---@return gccjit.Type* 464 | function Type:vector(n) 465 | return libgccjit.gcc_jit_type_get_vector(self, n) --[[@as gccjit.Type*]] 466 | end 467 | 468 | ---@return gccjit.Type* 469 | function Type:unqualified() 470 | return libgccjit.gcc_jit_type_unqualified(self) --[[@as gccjit.Type*]] 471 | end 472 | 473 | ---@return gccjit.Type*? 474 | function Type:dyncast_array() 475 | return libgccjit.gcc_jit_type_dyncast_array(self) --[[@as gccjit.Type*]] 476 | end 477 | 478 | ---@return boolean 479 | function Type:is_bool() 480 | return libgccjit.gcc_jit_type_is_boolean(self) ~= 0 481 | end 482 | 483 | ---@return boolean 484 | function Type:is_integral() 485 | return libgccjit.gcc_jit_type_is_integral(self) ~= 0 486 | end 487 | 488 | ---@return boolean 489 | function Type:is_pointer() 490 | return libgccjit.gcc_jit_type_is_pointer(self) ~= 0 491 | end 492 | 493 | ---@return boolean 494 | function Type:is_struct() 495 | return libgccjit.gcc_jit_type_is_struct(self) ~= 0 496 | end 497 | 498 | function Type:as_type() 499 | return self 500 | end 501 | 502 | function Type:as_object() 503 | return libgccjit.gcc_jit_type_as_object(self) 504 | end 505 | 506 | function Type:__tostring() 507 | return export.debug_string(self) 508 | end 509 | 510 | ---@class gccjit.VectorType* : gccjit.Type* 511 | local VectorType = {} 512 | VectorType.__index = VectorType 513 | 514 | ---@return gccjit.VectorType*? 515 | function Type:dyncast_vector() 516 | return libgccjit.gcc_jit_type_dyncast_vector(self) --[[@as gccjit.VectorType*]] 517 | end 518 | 519 | ---@return integer 520 | function VectorType:get_num_units() 521 | return libgccjit.gcc_jit_vector_type_get_num_units(self) 522 | end 523 | 524 | ---@return gccjit.Type* 525 | function VectorType:get_element_type() 526 | return libgccjit.gcc_jit_vector_type_get_element_type(self) --[[@as gccjit.Type*]] 527 | end 528 | 529 | ---@class gccjit.FunctionType* : gccjit.Type* 530 | local FunctionType = {} 531 | FunctionType.__index = FunctionType 532 | 533 | ---@return gccjit.FunctionType*? 534 | function Type:dyncast_function_ptr() 535 | return libgccjit.gcc_jit_type_dyncast_function_ptr(self) --[[@as gccjit.FunctionType*]] 536 | end 537 | 538 | ---@return gccjit.Type* 539 | function FunctionType:get_return_type() 540 | return libgccjit.gcc_jit_function_type_get_return_type(self) --[[@as gccjit.Type*]] 541 | end 542 | 543 | ---@return integer 544 | function FunctionType:get_param_count() 545 | return libgccjit.gcc_jit_function_type_get_param_count(self) 546 | end 547 | 548 | ---@param idx integer 549 | ---@return gccjit.Type* 550 | function FunctionType:get_param(idx) 551 | return libgccjit.gcc_jit_function_type_get_param(self, idx) --[[@as gccjit.Type*]] 552 | end 553 | 554 | ---@param vec_t gccjit.Type* 555 | ---@param elems gccjit.RValue*[] 556 | ---@param loc gccjit.Location*? 557 | function Context:new_rvalue_from_vector(vec_t, elems, loc) 558 | local num_elems = #elems 559 | local celems = ffi.new("gcc_jit_rvalue*[?]", num_elems) 560 | for i = 1, num_elems do 561 | celems[i-1] = (elems)[i] 562 | end 563 | return libgccjit.gcc_jit_context_new_rvalue_from_vector(self, loc, vec_t, num_elems, celems) --[[@as gccjit.RValue*]] 564 | end 565 | 566 | ---@class gccjit.Location* : gccjit.Object* 567 | local Location = {} 568 | Location.__index = Location 569 | 570 | ---@param filename string 571 | ---@param line integer 572 | ---@param column integer 573 | ---@return gccjit.Location* 574 | function Context:new_location(filename, line, column) 575 | return libgccjit.gcc_jit_context_new_location(self, filename, line, column) --[[@as gccjit.Location*]] 576 | end 577 | 578 | function Location:as_object() 579 | return libgccjit.gcc_jit_location_as_object(self) 580 | end 581 | 582 | function Location:__tostring() 583 | return export.debug_string(self) 584 | end 585 | 586 | ---@class gccjit.RValue* : gccjit.Object* 587 | local RValue = {} 588 | RValue.__index = RValue 589 | 590 | ---@param field gccjit.Field* 591 | ---@param location gccjit.Location*? 592 | ---@return gccjit.RValue* 593 | function RValue:access_field(field, location) 594 | return libgccjit.gcc_jit_rvalue_access_field(self, location, field) 595 | end 596 | 597 | ---@return gccjit.Type* 598 | function RValue:get_type() 599 | return libgccjit.gcc_jit_rvalue_get_type(self) 600 | end 601 | 602 | ---@param field gccjit.Field* 603 | ---@param location gccjit.Location*? 604 | ---@return gccjit.LValue* 605 | function RValue:dereference_field(field, location) 606 | return libgccjit.gcc_jit_rvalue_dereference_field(self, location, field) 607 | end 608 | 609 | ---@param location gccjit.Location*? 610 | ---@return gccjit.LValue* 611 | function RValue:dereference(location) 612 | return libgccjit.gcc_jit_rvalue_dereference(self, location) 613 | end 614 | 615 | ---@param cond boolean 616 | function RValue:set_require_tailcall(cond) 617 | libgccjit.gcc_jit_rvalue_set_bool_require_tailcall(self, cond) 618 | end 619 | 620 | ---@param str string 621 | ---@return gccjit.RValue* 622 | function Context:new_string_literal(str) 623 | return libgccjit.gcc_jit_context_new_string_literal(self, str) 624 | end 625 | 626 | ---@param kind gccjit.GlobalKind 627 | ---@param name string 628 | ---@param type gccjit.Type* 629 | ---@param location gccjit.Location*? 630 | ---@return gccjit.LValue* 631 | function Context:new_global(kind, type, name, location) 632 | return libgccjit.gcc_jit_context_new_global(self, location, libgccjit["GCC_JIT_GLOBAL_"..kind:gsub(" ", "_"):upper()], type, name) 633 | end 634 | 635 | function RValue:as_object() 636 | return libgccjit.gcc_jit_rvalue_as_object(self) 637 | end 638 | 639 | function RValue:__tostring() 640 | return export.debug_string(self) 641 | end 642 | 643 | ---Utility func 644 | function RValue:as_rvalue() 645 | return self 646 | end 647 | 648 | ---@class gccjit.Param* : gccjit.LValue* 649 | local Param = {} 650 | Param.__index = Param 651 | 652 | ---@return gccjit.RValue* 653 | function Param:as_rvalue() 654 | return libgccjit.gcc_jit_param_as_rvalue(self) --[[@as gccjit.RValue*]] 655 | end 656 | 657 | ---@param type gccjit.Type* 658 | ---@param value_type "int" | "long" | "double" | "pointer" 659 | ---@param value integer | ffi.cdata* 660 | function Context:new_rvalue(type, value_type, value) 661 | if value_type == "int" then 662 | return libgccjit.gcc_jit_context_new_rvalue_from_int(self, type, value) --[[@as gccjit.RValue*]] 663 | elseif value_type == "long" then 664 | return libgccjit.gcc_jit_context_new_rvalue_from_long(self, type, value) --[[@as gccjit.RValue*]] 665 | elseif value_type == "double" then 666 | return libgccjit.gcc_jit_context_new_rvalue_from_double(self, type, value) --[[@as gccjit.RValue*]] 667 | elseif value_type == "pointer" then 668 | return libgccjit.gcc_jit_context_new_rvalue_from_pointer(self, type, value) --[[@as gccjit.RValue*]] 669 | else error("Unknown value type: "..value_type) end 670 | end 671 | 672 | ---@param type gccjit.Type* 673 | ---@return gccjit.RValue* 674 | function Context:zero(type) 675 | return libgccjit.gcc_jit_context_zero(self, type) --[[@as gccjit.RValue*]] 676 | end 677 | 678 | ---@param type gccjit.Type* 679 | ---@return gccjit.RValue* 680 | function Context:one(type) 681 | return libgccjit.gcc_jit_context_one(self, type) --[[@as gccjit.RValue*]] 682 | end 683 | 684 | ---@param type gccjit.Type* 685 | function Context:null(type) 686 | return libgccjit.gcc_jit_context_null(self, type) --[[@as gccjit.RValue*]] 687 | end 688 | 689 | 690 | ---@alias gccjit.UnaryOperation 691 | ---| "minus" 692 | ---| "-" GCC_JIT_UNARY_OP_MINUS 693 | ---| "bitwise negate" 694 | ---| "~" GCC_JIT_UNARY_OP_BITWISE_NEGATE 695 | ---| "logical negate" 696 | ---| "!" GCC_JIT_UNARY_OP_LOGICAL_NEGATE 697 | 698 | ---@param op gccjit.UnaryOperation 699 | ---@param result_type gccjit.Type* 700 | ---@param value gccjit.RValue* 701 | ---@param location gccjit.Location*? 702 | ---@return gccjit.RValue* 703 | function Context:new_unary_op(op, result_type, value, location) 704 | op = op :gsub("-", "minus") 705 | :gsub("~", "bitwise negate") 706 | :gsub("!", "logical negate") 707 | :gsub(" ", "_"):upper() 708 | return libgccjit.gcc_jit_context_new_unary_op(self, location, libgccjit["GCC_JIT_UNARY_OP_"], result_type, value) --[[@as gccjit.RValue*]] 709 | end 710 | 711 | ---@alias gccjit.Comparison 712 | ---| "eq" 713 | ---| "==" GCC_JIT_COMPARISON_EQ 714 | ---| "ne" 715 | ---| "!=" GCC_JIT_COMPARISON_NE 716 | ---| "lt" 717 | ---| "<" GCC_JIT_COMPARISON_LT 718 | ---| "le" 719 | ---| "<=" GCC_JIT_COMPARISON_LE 720 | ---| "gt" 721 | ---| ">" GCC_JIT_COMPARISON_GT 722 | ---| "ge" 723 | ---| ">=" GCC_JIT_COMPARISON_GE 724 | 725 | ---@param op gccjit.Comparison 726 | ---@param lhs gccjit.RValue* 727 | ---@param rhs gccjit.RValue* 728 | ---@param location gccjit.Location*? 729 | ---@return gccjit.RValue* 730 | function Context:new_comparison(op, lhs, rhs, location) 731 | op = op :gsub("==", "eq") 732 | :gsub("!=", "ne") 733 | :gsub("<=", "le") 734 | :gsub(">=", "ge") 735 | :gsub("<", "lt") 736 | :gsub(">", "gt") 737 | :gsub(" ", "_"):upper() 738 | return libgccjit.gcc_jit_context_new_comparison(self, location, libgccjit["GCC_JIT_COMPARISON_"..op], lhs, rhs) --[[@as gccjit.RValue*]] 739 | end 740 | 741 | ---@alias gccjit.BinaryOperation 742 | ---| "plus" 743 | ---| "+" GCC_JIT_BINARY_OP_PLUS 744 | ---| "mult" 745 | ---| "*" GCC_JIT_BINARY_OP_MULT 746 | ---| "divide" 747 | ---| "/" GCC_JIT_BINARY_OP_DIVIDE 748 | ---| "modulo" 749 | ---| "%" GCC_JIT_BINARY_OP_MODULO 750 | ---| "bitwise and" 751 | ---| "&" GCC_JIT_BINARY_OP_BITWISE_AND 752 | ---| "bitwise or" 753 | ---| "|" GCC_JIT_BINARY_OP_BITWISE_OR 754 | ---| "bitwise xor" 755 | ---| "^" GCC_JIT_BINARY_OP_BITWISE_XOR 756 | ---| "left shift" 757 | ---| "<<" GCC_JIT_BINARY_OP_LEFT_SHIFT 758 | ---| "right shift" 759 | ---| ">>" GCC_JIT_BINARY_OP_RIGHT_SHIFT 760 | ---| "logical and" 761 | ---| "&&" GCC_JIT_BINARY_OP_LOGICAL_AND 762 | ---| "logical or" 763 | ---| "||" GCC_JIT_BINARY_OP_LOGICAL_OR 764 | 765 | ---@param op gccjit.BinaryOperation 766 | ---@param result_type gccjit.Type* 767 | ---@param lhs gccjit.RValue* 768 | ---@param rhs gccjit.RValue* 769 | ---@param location gccjit.Location*? 770 | ---@return gccjit.RValue* 771 | function Context:new_binary_op(result_type, lhs, op, rhs, location) 772 | op = op :gsub("%+", "plus") 773 | :gsub("%-", "minus") 774 | :gsub("%*", "mult") 775 | :gsub("%/", "divide") 776 | :gsub("%%", "modulo") 777 | :gsub("%&", "bitwise and") 778 | :gsub("%|", "bitwise or") 779 | :gsub("%^", "bitwise xor") 780 | :gsub("<<", "left shift") 781 | :gsub(">>", "right shift") 782 | :gsub("%&%&", "logical and") 783 | :gsub("%|%|", "logical or") 784 | :gsub(" ", "_"):upper() 785 | return libgccjit.gcc_jit_context_new_binary_op(self, location, libgccjit["GCC_JIT_BINARY_OP_"..op], result_type, lhs, rhs) --[[@as gccjit.RValue*]] 786 | end 787 | 788 | ---@param name string 789 | ---@param type gccjit.Type* 790 | ---@param location gccjit.Location*? 791 | ---@return gccjit.Param* 792 | function Context:new_param(type, name, location) 793 | return libgccjit.gcc_jit_context_new_param(self, location, type, name) --[[@as gccjit.Param*]] 794 | end 795 | 796 | function Param:as_object() 797 | return libgccjit.gcc_jit_param_as_object(self) 798 | end 799 | 800 | function Param:__tostring() 801 | return export.debug_string(self) 802 | end 803 | 804 | ---@class gccjit.Function* : gccjit.Object* 805 | local Function = {} 806 | Function.__index = Function 807 | 808 | ---@alias gccjit.Function*.Kind 809 | ---| "exported" GCC_JIT_FUNCTION_EXPORTED 810 | ---| "internal" GCC_JIT_FUNCTION_INTERNAL 811 | ---| "imported" GCC_JIT_FUNCTION_IMPORTED 812 | ---| "always inline" GCC_JIT_FUNCTION_ALWAYS_INLINE 813 | 814 | ---@alias gccjit.TLSModel 815 | ---| "none" GCC_JIT_TLS_MODEL_NONE 816 | ---| "global dynamic" GCC_JIT_TLS_MODEL_GLOBAL_DYNAMIC 817 | ---| "local dynamic" GCC_JIT_TLS_MODEL_LOCAL_DYNAMIC 818 | ---| "initial exec" GCC_JIT_TLS_MODEL_INITIAL_EXEC 819 | ---| "local exec" GCC_JIT_TLS_MODEL_LOCAL_EXEC 820 | 821 | ---@param kind gccjit.Function*.Kind 822 | ---@param name string 823 | ---@param return_type gccjit.Type* 824 | ---@param params gccjit.Param*[]? 825 | ---@param is_variadic boolean? 826 | ---@param location gccjit.Location*? 827 | ---@return gccjit.Function* 828 | function Context:new_function(kind, name, return_type, params, is_variadic, location) 829 | local num_params = params and #params or 0 830 | local cparams = ffi.new("gcc_jit_param*[?]", num_params) 831 | for i = 1, num_params do 832 | cparams[i-1] = (params)[i] 833 | end 834 | return libgccjit.gcc_jit_context_new_function(self, location, libgccjit["GCC_JIT_FUNCTION_"..kind:upper()], return_type, name, num_params, cparams, not not is_variadic) --[[@as gccjit.Function*]] 835 | end 836 | 837 | ---@param name string 838 | ---@return gccjit.Function* 839 | function Context:get_builtin_function(name) 840 | return libgccjit.gcc_jit_context_get_builtin_function(self, name) --[[@as gccjit.Function*]] 841 | end 842 | 843 | ---@param path string 844 | function Function:dump_to_dot(path) 845 | libgccjit.gcc_jit_function_dump_to_dot(self, path) 846 | end 847 | 848 | ---@param loc gccjit.Location*? 849 | ---@return gccjit.RValue* 850 | function Function:get_address(loc) 851 | return libgccjit.gcc_jit_function_get_address(self, loc) --[[@as gccjit.RValue*]] 852 | end 853 | 854 | ---@return gccjit.Type* 855 | function Function:get_return_type() 856 | return libgccjit.gcc_jit_function_get_return_type(self) --[[@as gccjit.Type*]] 857 | end 858 | 859 | ---@return integer 860 | function Function:get_param_count() 861 | return libgccjit.gcc_jit_function_get_param_count(self) 862 | end 863 | 864 | function Function:as_object() 865 | return libgccjit.gcc_jit_function_as_object(self) 866 | end 867 | 868 | function Function:__tostring() 869 | return export.debug_string(self) 870 | end 871 | 872 | ---@class gccjit.Block* : gccjit.Object* 873 | local Block = {} 874 | Block.__index = Block 875 | 876 | ---@param name string? 877 | ---@return gccjit.Block* 878 | function Function:new_block(name) 879 | return libgccjit.gcc_jit_function_new_block(self, name) --[[@as gccjit.Block*]] 880 | end 881 | 882 | ---@alias gccjit.GlobalKind 883 | ---| "exported" GCC_JIT_GLOBAL_EXPORTED 884 | ---| "internal" GCC_JIT_GLOBAL_INTERNAL 885 | ---| "imported" GCC_JIT_GLOBAL_IMPORTED 886 | 887 | ---@param rvalue gccjit.RValue* 888 | ---@param location gccjit.Location*? 889 | function Block:add_eval(rvalue, location) 890 | libgccjit.gcc_jit_block_add_eval(self, location, rvalue) 891 | end 892 | 893 | ---@param to gccjit.LValue* 894 | ---@param from gccjit.RValue* 895 | ---@param location gccjit.Location*? 896 | function Block:add_assignment(to, from, location) 897 | libgccjit.gcc_jit_block_add_assignment(self, location, to, from) 898 | end 899 | 900 | ---@param to gccjit.LValue* 901 | ---@param op gccjit.BinaryOperation 902 | ---@param from gccjit.RValue* 903 | ---@param location gccjit.Location*? 904 | function Block:add_assignment_op(to, op, from, location) 905 | op = op :gsub("%+", "plus") 906 | :gsub("%-", "minus") 907 | :gsub("%*", "mult") 908 | :gsub("%/", "divide") 909 | :gsub("%%", "modulo") 910 | :gsub("%&", "bitwise and") 911 | :gsub("%|", "bitwise or") 912 | :gsub("%^", "bitwise xor") 913 | :gsub("<<", "left shift") 914 | :gsub(">>", "right shift") 915 | :gsub("%&%&", "logical and") 916 | :gsub("%|%|", "logical or") 917 | :gsub(" ", "_"):upper() 918 | 919 | libgccjit.gcc_jit_block_add_assignment_op(self, location, to, libgccjit["GCC_JIT_BINARY_OP_"..op], from) 920 | end 921 | 922 | ---@param text string 923 | ---@param location gccjit.Location*? 924 | function Block:add_comment(text, location) 925 | libgccjit.gcc_jit_block_add_comment(self, location, text) 926 | end 927 | 928 | ---@param cond gccjit.RValue* 929 | ---@param on_true gccjit.Block* 930 | ---@param on_false gccjit.Block* 931 | ---@param location gccjit.Location*? 932 | function Block:end_with_conditional(cond, on_true, on_false, location) 933 | libgccjit.gcc_jit_block_end_with_conditional(self, location, cond, on_true, on_false) 934 | end 935 | 936 | ---@param target gccjit.Block* 937 | ---@param location gccjit.Location*? 938 | function Block:end_with_jump(target, location) 939 | return libgccjit.gcc_jit_block_end_with_jump(self, location, target) 940 | end 941 | 942 | ---@param value gccjit.RValue* 943 | ---@param location gccjit.Location*? 944 | function Block:end_with_return(value, location) 945 | return libgccjit.gcc_jit_block_end_with_return(self, location, value) 946 | end 947 | 948 | ---@param location gccjit.Location*? 949 | function Block:end_with_void_return(location) 950 | return libgccjit.gcc_jit_block_end_with_void_return(self, location) 951 | end 952 | 953 | ---@param expr gccjit.RValue* 954 | ---@param on_default gccjit.Block* 955 | ---@param cases gccjit.Case*[] 956 | function Block:end_with_switch(expr, on_default, cases, loc) 957 | local num_cases = #cases 958 | local ccases = ffi.new("gcc_jit_case*[?]", num_cases) 959 | for i = 1, num_cases do 960 | ccases[i-1] = cases[i] 961 | end 962 | return libgccjit.gcc_jit_block_end_with_switch(self, loc, expr, on_default, num_cases, ccases) 963 | end 964 | 965 | function Block:as_object() 966 | return libgccjit.gcc_jit_block_as_object(self) 967 | end 968 | 969 | function Block:__tostring() 970 | return export.debug_string(self) 971 | end 972 | 973 | ---@class gccjit.ExtendedAssembly* : gccjit.Object* 974 | local ExtendedAssembly = {} 975 | ExtendedAssembly.__index = ExtendedAssembly 976 | 977 | ---@param asm_templ string 978 | ---@param location gccjit.Location*? 979 | ---@return gccjit.ExtendedAssembly* 980 | function Block:add_extended_asm(asm_templ, location) 981 | return libgccjit.gcc_jit_block_add_extended_asm(self, location, asm_templ) --[[@as gccjit.ExtendedAssembly*]] 982 | end 983 | 984 | ---@param asm_templ string 985 | ---@param goto_blocks gccjit.Block*[] 986 | ---@param fallthrough_block gccjit.Block* 987 | ---@param location gccjit.Location*? 988 | ---@return gccjit.ExtendedAssembly* 989 | function Block:end_with_extended_asm_goto(asm_templ, goto_blocks, fallthrough_block, location) 990 | local num_goto_blocks = #goto_blocks 991 | local cgoto_blocks = ffi.new("gcc_jit_block*[?]", num_goto_blocks) 992 | for i = 1, num_goto_blocks do 993 | cgoto_blocks[i-1] = (goto_blocks)[i] 994 | end 995 | return libgccjit.gcc_jit_block_end_with_extended_asm_goto(self, location, asm_templ, num_goto_blocks, cgoto_blocks, fallthrough_block) --[[@as gccjit.ExtendedAssembly*]] 996 | end 997 | 998 | ---@param x boolean 999 | function ExtendedAssembly:set_volatile(x) 1000 | return libgccjit.gcc_jit_extended_asm_set_volatile(self, x) 1001 | end 1002 | 1003 | ---@param x boolean 1004 | function ExtendedAssembly:set_inline(x) 1005 | return libgccjit.gcc_jit_extended_asm_set_inline(self, x) 1006 | end 1007 | 1008 | ---@param asmname string 1009 | ---@param constraint string 1010 | ---@param dest gccjit.LValue* 1011 | function ExtendedAssembly:add_output_operand(asmname, constraint, dest) 1012 | return libgccjit.gcc_jit_extended_asm_add_output_operand(self, asmname, constraint, dest) 1013 | end 1014 | 1015 | ---@param asmname string 1016 | ---@param constraint string 1017 | ---@param src gccjit.RValue* 1018 | function ExtendedAssembly:add_input_operand(asmname, constraint, src) 1019 | return libgccjit.gcc_jit_extended_asm_add_input_operand(self, asmname, constraint, src) 1020 | end 1021 | 1022 | ---@param target string 1023 | function ExtendedAssembly:add_clobber(target) 1024 | return libgccjit.gcc_jit_extended_asm_add_clobber(self, target) 1025 | end 1026 | 1027 | ---@param asmname string 1028 | ---@param loc gccjit.Location*? 1029 | function ExtendedAssembly:add_top_level_asm(asmname, loc) 1030 | return libgccjit.gcc_jit_extended_asm_add_top_level_asm(self, loc, asmname) 1031 | end 1032 | 1033 | function ExtendedAssembly:as_object() 1034 | return libgccjit.gcc_jit_extended_asm_as_object(self) 1035 | end 1036 | 1037 | function ExtendedAssembly:__tostring() 1038 | return export.debug_string(self) 1039 | end 1040 | 1041 | ---@class gccjit.Case* : gccjit.Object* 1042 | local Case = {} 1043 | Case.__index = Case 1044 | 1045 | ---@param min gccjit.RValue* 1046 | ---@param max gccjit.RValue* 1047 | ---@param dest gccjit.Block* 1048 | function Context:new_case(min, max, dest) 1049 | return libgccjit.gcc_jit_context_new_case(self, min, max, dest) --[[@as gccjit.Case*]] 1050 | end 1051 | 1052 | function Case:as_object() 1053 | return libgccjit.gcc_jit_case_as_object(self) 1054 | end 1055 | 1056 | function Case:__tostring() 1057 | return export.debug_string(self) 1058 | end 1059 | 1060 | ---@class gccjit.LValue* : gccjit.RValue* 1061 | local LValue = {} 1062 | LValue.__index = LValue 1063 | 1064 | ---@param type gccjit.Type* 1065 | ---@param name string 1066 | ---@param location gccjit.Location*? 1067 | ---@return gccjit.LValue* 1068 | function Function:new_local(type, name, location) 1069 | return libgccjit.gcc_jit_function_new_local(self, location, type, name) --[[@as gccjit.LValue*]] 1070 | end 1071 | 1072 | 1073 | ---@param bytes integer 1074 | function LValue:set_alignment(bytes) 1075 | return libgccjit.gcc_jit_lvalue_set_alignment(self, bytes) 1076 | end 1077 | 1078 | ---@return integer 1079 | function LValue:get_alignment() 1080 | return libgccjit.gcc_jit_lvalue_get_alignment(self) 1081 | end 1082 | 1083 | ---@param field gccjit.Field* 1084 | ---@param location gccjit.Location*? 1085 | ---@return gccjit.LValue* 1086 | function LValue:access_field(field, location) 1087 | return libgccjit.gcc_jit_lvalue_access_field(self, location, field) --[[@as gccjit.LValue*]] 1088 | end 1089 | 1090 | ---@param location gccjit.Location*? 1091 | ---@return gccjit.RValue* 1092 | function LValue:get_address(location) 1093 | return libgccjit.gcc_jit_lvalue_get_address(self, location) --[[@as gccjit.RValue*]] 1094 | end 1095 | 1096 | ---@param tls_model gccjit.TLSModel 1097 | function LValue:set_tls_model(tls_model) 1098 | return libgccjit.gcc_jit_lvalue_set_tls_model(self, libgccjit["GCC_JIT_TLS_MODEL_"..tls_model:gsub(" ", "_"):upper()]) 1099 | end 1100 | 1101 | ---@param section string 1102 | function LValue:set_link_section(section) 1103 | return libgccjit.gcc_jit_lvalue_set_link_section(self, section) 1104 | end 1105 | 1106 | ---@param name string 1107 | function LValue:set_register_name(name) 1108 | return libgccjit.gcc_jit_lvalue_set_register_name(self, name) 1109 | end 1110 | 1111 | ---@return gccjit.RValue* 1112 | function LValue:as_rvalue() 1113 | return libgccjit.gcc_jit_lvalue_as_rvalue(self) --[[@as gccjit.RValue*]] 1114 | end 1115 | 1116 | function LValue:as_object() 1117 | return libgccjit.gcc_jit_lvalue_as_object(self) 1118 | end 1119 | 1120 | function LValue:__tostring() 1121 | return export.debug_string(self) 1122 | end 1123 | 1124 | ---@class gccjit.Result* : gccjit.Object* 1125 | local Result = {} 1126 | Result.__index = Result 1127 | 1128 | ---@return gccjit.Result*? 1129 | function Context:compile() 1130 | return ffi.gc(libgccjit.gcc_jit_context_compile(self), libgccjit.gcc_jit_result_release) --[[@as gccjit.Result*]] 1131 | end 1132 | 1133 | ---@alias gccjit.OutputKind 1134 | ---| "assembler" GCC_JIT_OUTPUT_KIND_ASSEMBLER 1135 | ---| "object file" GCC_JIT_OUTPUT_KIND_OBJECT_FILE 1136 | ---| "dynamic library" GCC_JIT_OUTPUT_KIND_DYNAMIC_LIBRARY 1137 | ---| "executable" GCC_JIT_OUTPUT_KIND_EXECUTABLE 1138 | 1139 | ---@param kind gccjit.OutputKind 1140 | ---@param to string 1141 | function Context:compile_to_file(kind, to) 1142 | libgccjit.gcc_jit_context_compile_to_file(self, libgccjit["GCC_JIT_OUTPUT_KIND_"..kind:gsub(" ", "_"):upper()], to) 1143 | end 1144 | 1145 | 1146 | ---@param symbol string 1147 | ---@param type string | ffi.ctype* 1148 | ---@return ffi.cdata*? 1149 | function Result:get_code(symbol, type) 1150 | local code = libgccjit.gcc_jit_result_get_code(self, symbol) 1151 | if code == nil then return nil end 1152 | local ct = ffi.typeof(type --[[@as ffi.ctype*]]) 1153 | return ffi.cast(ct, code) 1154 | end 1155 | 1156 | ---@param symbol string 1157 | ---@param type string 1158 | ---@return ffi.cdata*? 1159 | function Result:get_global(symbol, type) 1160 | local global = libgccjit.gcc_jit_result_get_global(self, symbol) 1161 | if global == nil then return nil end 1162 | local ct = ffi.typeof(type --[[@as ffi.ctype*]]) 1163 | return ffi.cast(ct, global) 1164 | end 1165 | 1166 | ---@class gccjit.Timer* : ffi.cdata* 1167 | local Timer = {} 1168 | Timer.__index = Timer 1169 | 1170 | ---@return gccjit.Timer* 1171 | function Timer.new() 1172 | return ffi.gc(libgccjit.gcc_jit_timer_new(), libgccjit.gcc_jit_timer_release) --[[@as gccjit.Timer*]] 1173 | end 1174 | 1175 | ---@param timer gccjit.Timer* 1176 | function Context:set_timer(timer) 1177 | libgccjit.gcc_jit_context_set_timer(self, timer) 1178 | end 1179 | 1180 | ---@return gccjit.Timer* 1181 | function Context:get_timer() 1182 | return libgccjit.gcc_jit_context_get_timer(self) --[[@as gccjit.Timer*]] 1183 | end 1184 | 1185 | ---@param name string 1186 | function Timer:push(name) 1187 | libgccjit.gcc_jit_timer_push(self, name) 1188 | end 1189 | 1190 | ---@param name string 1191 | function Timer:pop(name) 1192 | libgccjit.gcc_jit_timer_pop(self, name) 1193 | end 1194 | 1195 | export.Type = ffi.metatype("gcc_jit_type", Type) --[[@as gccjit.Type*]] 1196 | export.Context = ffi.metatype("gcc_jit_context", Context) --[[@as gccjit.Context*]] 1197 | export.Field = ffi.metatype("gcc_jit_field", Field) --[[@as gccjit.Field*]] 1198 | export.Struct = ffi.metatype("gcc_jit_struct", Struct) --[[@as gccjit.Struct*]] 1199 | export.Location = ffi.metatype("gcc_jit_location", Location) --[[@as gccjit.Location*]] 1200 | export.RValue = ffi.metatype("gcc_jit_rvalue", RValue) --[[@as gccjit.RValue*]] 1201 | export.Param = ffi.metatype("gcc_jit_param", Param) --[[@as gccjit.Param*]] 1202 | export.Function = ffi.metatype("gcc_jit_function", Function) --[[@as gccjit.Function*]] 1203 | export.Block = ffi.metatype("gcc_jit_block", Block) --[[@as gccjit.Block*]] 1204 | export.Case = ffi.metatype("gcc_jit_case", Case) --[[@as gccjit.Case*]] 1205 | export.LValue = ffi.metatype("gcc_jit_lvalue", LValue) --[[@as gccjit.LValue*]] 1206 | export.Result = ffi.metatype("gcc_jit_result", Result) --[[@as gccjit.Result*]] 1207 | export.Timer = ffi.metatype("gcc_jit_timer", Timer) --[[@as gccjit.Timer*]] 1208 | export.ExtendedAssembly = ffi.metatype("gcc_jit_extended_asm", ExtendedAssembly) --[[@as gccjit.ExtendedAssembly*]] 1209 | export.VectorType = ffi.metatype("gcc_jit_vector_type", VectorType) --[[@as gccjit.VectorType*]] 1210 | export.FunctionType = ffi.metatype("gcc_jit_function_type", FunctionType) --[[@as gccjit.FunctionType*]] 1211 | export.libgccjit = libgccjit 1212 | return export 1213 | -------------------------------------------------------------------------------- /src/codegen/gccjit.lua: -------------------------------------------------------------------------------- 1 | -- Copyright (C) 2024 Amrit Bhogal 2 | -- 3 | -- This file is part of teal-compiler. 4 | -- 5 | -- teal-compiler is free software: you can redistribute it and/or modify 6 | -- it under the terms of the GNU General Public License as published by 7 | -- the Free Software Foundation, either version 3 of the License, or 8 | -- (at your option) any later version. 9 | -- 10 | -- teal-compiler is distributed in the hope that it will be useful, 11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | -- GNU General Public License for more details. 14 | -- 15 | -- You should have received a copy of the GNU General Public License 16 | -- along with teal-compiler. If not, see . 17 | 18 | local gccjit = require("backends.gccjit") 19 | local ffi = require("ffi") 20 | 21 | local utilities = require("utilities") 22 | local pretty = require("pl.pretty") 23 | 24 | local ctx = gccjit.Context.acquire() 25 | 26 | local l_type = type 27 | 28 | ---@param x any 29 | ---@return type | string 30 | local function type(x) 31 | local l_t = l_type(x) 32 | if l_t == "cdata" then 33 | return tostring(ffi.typeof(x)) 34 | else 35 | return l_t 36 | end 37 | end 38 | 39 | ---@param node tl.Where | tl.Node 40 | ---@return gccjit.Location*? 41 | local function loc(node) 42 | return ctx:new_location(node.f, node.y, node.x) 43 | end 44 | 45 | ---Turn stuff like \\n into \n 46 | ---@param str string 47 | function string.unescape(str) 48 | return (str:gsub("\\(.)", function (c) 49 | return ({ 50 | ["n"] = "\n", 51 | ["t"] = "\t", 52 | ["r"] = "\r", 53 | ["\\"] = "\\" 54 | })[c] or c 55 | end)) 56 | end 57 | 58 | local is_comparison = { 59 | ["=="] = true, 60 | ["~="] = true, 61 | ["<"] = true, 62 | [">"] = true, 63 | ["<="] = true, 64 | [">="] = true 65 | } 66 | 67 | ---@alias PrimitiveType '"integer"' | '"boolean"' | '"number"' | '"String"' | '"nil_t"' 68 | ---@alias PrimitiveTypes.C '"int8_t"' | '"int16_t"' | '"int32_t"' | '"int64_t"' | '"uint8_t"' | '"uint16_t"' | '"uint32_t"' | '"uint64_t"' | '"const char *"' | '"cvaradict"' 69 | 70 | local RAW_TYPES = { 71 | c = { 72 | int8_t = ctx:get_type("int8_t"), 73 | int16_t = ctx:get_type("int16_t"), 74 | int32_t = ctx:get_type("int32_t"), 75 | int64_t = ctx:get_type("int64_t"), 76 | 77 | uint8_t = ctx:get_type("uint8_t"), 78 | uint16_t = ctx:get_type("uint16_t"), 79 | uint32_t = ctx:get_type("uint32_t"), 80 | uint64_t = ctx:get_type("uint64_t"), 81 | 82 | float = ctx:get_type("float"), 83 | double = ctx:get_type("double"), 84 | 85 | string = ctx:get_type("const char *"), 86 | varadict = ctx:new_opaque_struct_type("cvaradict"), 87 | void = ctx:get_type("void"), 88 | bool = ctx:get_type("bool") 89 | }, 90 | } 91 | 92 | RAW_TYPES.integer = RAW_TYPES.c.int64_t 93 | RAW_TYPES.boolean = RAW_TYPES.c.bool 94 | RAW_TYPES.number = RAW_TYPES.c.double 95 | RAW_TYPES.nil_t = RAW_TYPES.c.void 96 | 97 | RAW_TYPES.String = ctx:new_struct_type("String", { 98 | ctx:new_field(RAW_TYPES.c.uint64_t, "length"), 99 | ctx:new_field(RAW_TYPES.c.int8_t:pointer(), "data") 100 | }) 101 | 102 | ---@alias Type.Type 103 | ---| '"function"' 104 | ---| '"tuple"' 105 | ---| '"tuple field"' 106 | ---| '"primitive"' 107 | ---| '"c"' 108 | 109 | ---@class Type 110 | ---@field id integer 111 | ---@field raw gccjit.Type* 112 | ---@field type Type.Type 113 | ---@field name string 114 | 115 | ---@class Type.Function.Parameter 116 | ---@field name string? 117 | ---@field type Type 118 | 119 | ---@class Type.Function : Type 120 | ---@field args Type.Function.Parameter[] 121 | ---@field return_types Type[] 122 | ---@field is_varadict boolean 123 | ---@field type "function" 124 | 125 | ---@class Type.Tuple : Type 126 | ---@field elements Type.Tuple.Field[] 127 | ---@field type "tuple" 128 | 129 | ---@class Type.Tuple.Field : Type 130 | ---@field raw gccjit.Field* 131 | ---@field backing_type Type 132 | ---@field type "tuple field" 133 | 134 | ---@param ty Type.Function.Parameter[] 135 | ---@return gccjit.Type*[] 136 | local function get_rawargtypes(ty) 137 | local rawargs = {} 138 | for _, arg in ipairs(ty) do 139 | rawargs[#rawargs+1] = arg.type.raw 140 | end 141 | return rawargs 142 | end 143 | 144 | ---@type { [string] : Type, [integer] : Type } 145 | local type_cache = setmetatable({}, { 146 | __index = function (self, k) 147 | if type(k) == "number" then 148 | for _, v in pairs(self) do 149 | if v.id == k then return v end 150 | end 151 | end 152 | end 153 | }) 154 | 155 | ---@type { [integer] : Type.Tuple } 156 | local tuple_type_cache = {} 157 | 158 | ---@type { [integer] : Type.Function } 159 | local function_type_cache = {} 160 | 161 | ---@param type tl.Type 162 | ---@return Type 163 | local function conv_teal_type(type) 164 | local function ret_prim(name) 165 | -- if type_cache[name] then return function() return type_cache[name] end end 166 | 167 | -- local dat = { 168 | -- id = type.typeid, 169 | -- raw = RAW_TYPES[name], 170 | -- type = "primitive", 171 | -- name = name 172 | -- } 173 | -- type_cache[name] = dat 174 | -- pretty(dat) 175 | 176 | -- return function() return dat end 177 | return function () 178 | if type_cache[name] then return type_cache[name] end 179 | 180 | local dat = { 181 | id = type.typeid, 182 | raw = RAW_TYPES[name], 183 | type = "primitive", 184 | name = name 185 | } 186 | type_cache[name] = dat 187 | return dat 188 | end 189 | end 190 | return utilities.switch(type.typename) { 191 | ["integer"] = ret_prim "integer", 192 | ["boolean"] = ret_prim "boolean", 193 | ["number"] = ret_prim "number", 194 | ["string"] = ret_prim "String", 195 | ["nil"] = ret_prim "nil_t", 196 | ["tuple"] = function () 197 | --[[@cast type tl.TupleType]] 198 | if #type.tuple == 0 then return type_cache.nil_t 199 | elseif #type.tuple == 1 then return conv_teal_type(type.tuple[1]) end 200 | if tuple_type_cache[type.typeid] then return tuple_type_cache[type.typeid] end 201 | 202 | local tuplename = "tuple-"..type.typeid 203 | 204 | ---@type Type.Tuple 205 | local tuple = { 206 | id = type.typeid, 207 | type = "tuple", 208 | elements = {}, 209 | } 210 | 211 | for _, tl_type in ipairs(type.tuple) do 212 | local t = conv_teal_type(tl_type) 213 | local n = "tuple-element_"..#tuple.elements.."_"..tl_type.typeid 214 | tuple.elements[#tuple.elements+1] = { 215 | id = tl_type.typeid, 216 | raw = ctx:new_field(t.raw, n), 217 | type = "tuple field", 218 | backing_type = t, 219 | name = n 220 | } 221 | end 222 | local friendly_name = "tuple"..type.typeid.." { " 223 | for i, field in ipairs(tuple.elements) do 224 | friendly_name = friendly_name..field.backing_type.name..(i == #tuple.elements and "" or ", ") 225 | end 226 | friendly_name = friendly_name.." }" 227 | tuple.name = friendly_name 228 | 229 | ---@type gccjit.Field*[] 230 | local tup_fields = {} 231 | for i, field in ipairs(tuple.elements) do 232 | tup_fields[i] = field.raw 233 | end 234 | 235 | tuple.raw = ctx:new_struct_type(tuplename, tup_fields, loc(type)) 236 | tuple_type_cache[tuplename] = tuple 237 | return tuple 238 | end, 239 | ["nominal"] = function () 240 | --[[@cast type tl.NominalType]] 241 | local names = assert(type.names) 242 | if names[1] == "c" then 243 | return utilities.switch(names[2]) { 244 | pointer = function () 245 | local pt = conv_teal_type(type.typevals[1]) 246 | 247 | return { 248 | id = type.typeid, 249 | raw = pt.raw:pointer(), 250 | type = "c", 251 | name = pt.name..'*' 252 | } 253 | end, 254 | const = function () 255 | local ct = conv_teal_type(type.typevals[1]) 256 | 257 | return { 258 | id = type.typeid, 259 | raw = ct.raw:const(), 260 | type = "c", 261 | name = "const "..ct.name 262 | } 263 | end, 264 | default = function(x) 265 | return RAW_TYPES.c[x] and { 266 | id = type.typeid, 267 | raw = RAW_TYPES.c[x], 268 | type = "c", 269 | name = x 270 | } or error(string.format("Unsupported C type: %s", x)) 271 | end 272 | } 273 | else 274 | --search through the cache 275 | local t = type_cache[type.typeid] 276 | if t then return t end 277 | 278 | error(string.format("Unsupported nominal type \"%s\". Did you declare it?", table.concat(names, '.'))) 279 | end 280 | end, 281 | ["function"] = function () 282 | --[[@cast type tl.FunctionType]] 283 | if function_type_cache[type.typeid] then return function_type_cache[type.typeid] end 284 | 285 | ---@type Type.Function.Parameter[] 286 | local args = {} 287 | for _, arg in ipairs(type.args) do 288 | local a = conv_teal_type(arg) 289 | args[#args+1] = { 290 | name = arg.name, 291 | type = a 292 | } 293 | end 294 | 295 | ---TODO: support multi-ret 296 | local ret = type.rets and conv_teal_type(type.rets.tuple[1]) or type_cache.nil_t 297 | local ftype = ctx:new_function_ptr_type(ret.raw, get_rawargtypes(args), type.args.is_va, loc(type)) 298 | local dat = { 299 | id = type.typeid, 300 | raw = ftype, 301 | type = "function", 302 | args = args, 303 | return_types = {ret}, --TODO: support multi-ret 304 | is_varadict = type.args.is_va, 305 | name = string.format("function (%s): %s", table.concat(args, ", "), ret.name) 306 | } 307 | function_type_cache[type.typeid] = dat 308 | 309 | return dat 310 | end, 311 | ["typealias"] = function () 312 | --[[@cast type tl.TypeAliasType]] 313 | type_cache[type.alias_to.typeid] = conv_teal_type(type.alias_to) 314 | return type_cache[type.typeid] 315 | end, 316 | default = function(x) 317 | error(string.format("Unsupported type: %s", x)) 318 | end 319 | } 320 | end 321 | 322 | ---@class TypeIs 323 | ---@field rvalue fun(x: ffi.cdata*): gccjit.RValue* 324 | ---@field lvalue fun(x: ffi.cdata*): gccjit.LValue* 325 | ---@field type fun(x: ffi.cdata*): gccjit.Type* 326 | 327 | ---@type TypeIs 328 | local type_is = setmetatable({}, { 329 | __index = function (self, tname) 330 | local expected_t = ffi.typeof("gcc_jit_"..tname.." *") 331 | self[tname] = function (x) 332 | assert(x, "Expected a value") 333 | 334 | local t = ffi.typeof(x) 335 | if x.as_rvalue and tname == "rvalue" then 336 | return x:as_rvalue() 337 | end 338 | assert(t == expected_t, string.format("Expected %s, got %s", expected_t, t)) 339 | return x --[[@as any]] 340 | end 341 | return rawget(self, tname) 342 | end 343 | }) 344 | 345 | --cache the results of type_is, this will fill the table 346 | _=type_is.rvalue 347 | _=type_is.lvalue 348 | _=type_is.type 349 | 350 | ---@class FunctionContext 351 | ---@field name string 352 | ---@field is_external boolean 353 | ---@field raw gccjit.Function* 354 | 355 | ---@class FunctionContext.Local : FunctionContext 356 | ---@field is_external false 357 | ---@field block_stack gccjit.Block*[] 358 | ---@field variables { [string] : gccjit.LValue* } 359 | 360 | ---@class FunctionContext.External : FunctionContext 361 | ---@field is_external true 362 | 363 | ---@type { [string] : FunctionContext } 364 | local functions = {} 365 | 366 | ---@alias Visitor.Function fun(node: tl.Node, fctx: FunctionContext.Local): ... 367 | 368 | ---@class Visitor 369 | ---@field [tl.NodeKind] Visitor.Function 370 | local visitor = {} 371 | 372 | ---This needs to be 3 lines so its not inlined properly, making it easier to debug! 373 | ---@type Visitor.Function 374 | local function visit(node, fctx) 375 | -- return (visitor[node.kind] or error(string.format("Unsupported node kind '%s' at %s", node.kind, tostring(loc(node)))))(node) 376 | local vtor = visitor[node.kind] 377 | if not vtor then 378 | error(string.format("Unsupported node kind '%s' at %s", node.kind, tostring(loc(node)))) 379 | end 380 | 381 | --don't TCO so debug looks nicer 382 | return vtor(node, fctx) 383 | end 384 | 385 | --#region Visitor functions 386 | 387 | ---@class VariableDeclaration 388 | ---@field name string 389 | ---@field attribute string 390 | 391 | function visitor.identifier(node) 392 | return { 393 | name = node.tk, 394 | attribute = node.attribute 395 | } 396 | end 397 | 398 | ---@return VariableDeclaration[] 399 | function visitor.variable_list(node, func) 400 | local vars = {} 401 | for i, var in ipairs(node) do 402 | vars[i] = visit(var, func) 403 | end 404 | return vars 405 | end 406 | 407 | ---@param node tl.Node 408 | ---@param fvar VariableDeclaration 409 | ---@return gccjit.Function* 410 | local function extern_func_decl(node, fvar) 411 | local ty = conv_teal_type(node.decltuple) 412 | if ty.type ~= "function" then error("Expected a function type") end 413 | --[[@cast ty Type.Function]] 414 | 415 | ---@type gccjit.Type*[] 416 | local params = {} 417 | for _, arg in ipairs(ty.args) do 418 | params[#params+1] = arg.type.raw 419 | end 420 | 421 | local fn = ctx:new_function("imported", fvar.name, ty.return_types[1].raw, params, ty.is_varadict, loc(node)) 422 | functions[fvar.name] = { 423 | raw = fn, 424 | is_external = true, 425 | name = fvar.name 426 | } 427 | 428 | return fn 429 | end 430 | 431 | ---@alias Scope "'local'" | "'global'" 432 | 433 | ---@param node tl.Node 434 | ---@param fctx FunctionContext.Local 435 | ---@param scope Scope 436 | local function declaration(node, fctx, scope) 437 | ---@type VariableDeclaration 438 | local var = visit(node.vars, fctx)[1] 439 | if var.attribute == "extern" then 440 | return extern_func_decl(node, var) 441 | end 442 | 443 | ---@type (gccjit.RValue* | gccjit.LValue*)[]? 444 | local val = node.exps and visit(node.exps, fctx) or nil 445 | ---@type gccjit.Type*? 446 | local ty = nil 447 | local tynode = conv_teal_type(node.decltuple) 448 | if tynode.id == type_cache.nil_t.id then 449 | if val then 450 | ty = val[1]:as_rvalue():get_type() 451 | end 452 | else 453 | ty = tynode.raw:as_type() 454 | end 455 | if not ty then error("Variable "..var.name.." declared without a type!") end 456 | local lval = fctx.raw:new_local(ty, var.name, loc(node)) 457 | fctx.variables[var.name] = lval 458 | 459 | if val then 460 | fctx.block_stack[#fctx.block_stack]:add_assignment(lval, val[1]:as_rvalue(), loc(node)) 461 | end 462 | 463 | return lval 464 | end 465 | 466 | function visitor.local_declaration(node, fctx) 467 | return declaration(node, fctx, "local") 468 | end 469 | 470 | function visitor.global_declaration(node, fctx) 471 | return declaration(node, fctx, "global") 472 | end 473 | 474 | function visitor.assignment(node, fctx) 475 | local lval = visit(node.vars, fctx) 476 | local rval = visit(node.exps, fctx) 477 | 478 | assert(ffi.typeof(lval[1]) == ffi.typeof("gcc_jit_lvalue *"), "Expected an lvalue") 479 | 480 | fctx.block_stack[#fctx.block_stack]:add_assignment(lval[1], rval[1]:as_rvalue(), loc(node)) 481 | end 482 | 483 | function visitor.paren(node, fctx) 484 | return visit(node.e1, fctx) 485 | end 486 | 487 | ---@return Type.Function.Parameter 488 | function visitor.argument(node) 489 | return { 490 | name = node.tk, 491 | type = conv_teal_type(node.argtype) 492 | } 493 | end 494 | 495 | ---@return Type.Function.Parameter[] 496 | function visitor.argument_list(node, fctx) 497 | local args = {} 498 | for i, arg in ipairs(node) do 499 | args[i] = visit(arg, fctx) 500 | end 501 | return args 502 | end 503 | 504 | ---@param node tl.Node 505 | ---@param fctx FunctionContext 506 | ---@param scope Scope 507 | ---@return gccjit.Function* 508 | local function func(node, fctx, scope) 509 | if fctx then error("Cannot nest functions") end 510 | 511 | ---@type string 512 | local name = visit(node.name, fctx).name 513 | 514 | local ret = conv_teal_type(node.rets) 515 | ---@type Type.Function.Parameter[] 516 | local args = visit(node.args, fctx) 517 | 518 | ---@type { [string] : gccjit.LValue* } 519 | local vars = {} 520 | ---@type gccjit.Param*[] 521 | local params = {} 522 | for i, arg in ipairs(args) do 523 | params[i] = ctx:new_param(arg.type.raw, arg.name, loc(node)) 524 | vars[arg.name] = params[i] 525 | end 526 | 527 | local func = ctx:new_function(scope == "local" and "internal" or "exported", name, ret.raw, params, false, loc(node)) 528 | local root_block = func:new_block("root") 529 | 530 | ---@type FunctionContext.Local 531 | local fctx = { 532 | raw = func, 533 | is_external = false, 534 | block_stack = { root_block }, 535 | variables = vars, 536 | name = name 537 | } 538 | functions[name] = fctx 539 | 540 | visit(node.body, fctx) 541 | 542 | local block = fctx.block_stack[#fctx.block_stack] 543 | if block then 544 | if ret.id == type_cache.nil_t.id then 545 | block:end_with_void_return(loc(node)) 546 | fctx.block_stack[#fctx.block_stack] = nil 547 | else 548 | error("["..tostring(loc(node)).."] Function with non-nil return type must end with a return statement") 549 | end 550 | end 551 | 552 | func:dump_to_dot(name..".dot") 553 | return func 554 | end 555 | 556 | function visitor.local_function(node, fctx) 557 | return func(node, fctx, "local") 558 | end 559 | 560 | function visitor.global_function(node, fctx) 561 | return func(node, fctx, "global") 562 | end 563 | 564 | function visitor.statements(node, fctx) 565 | local statements = {} 566 | for _, stmt in ipairs(node) do 567 | local var, is_func_call = visit(stmt, fctx) 568 | if is_func_call then fctx.block_stack[#fctx.block_stack]:add_eval(var, loc(node)) end 569 | statements[#statements+1] = var 570 | end 571 | return statements 572 | end 573 | 574 | function visitor.expression_list(node, fctx) 575 | local expressions = {} 576 | for _, exp in ipairs(node) do 577 | expressions[#expressions+1] = visit(exp, fctx) 578 | end 579 | return expressions 580 | end 581 | --#region literals 582 | function visitor.variable(node, fctx) 583 | return fctx.variables[node.tk] or functions[node.tk] 584 | end 585 | 586 | function visitor.integer(node) 587 | return ctx:new_rvalue(RAW_TYPES.integer, "long", node.constnum) 588 | end 589 | 590 | function visitor.number(node) 591 | return ctx:new_rvalue(RAW_TYPES.number, "double", node.constnum) 592 | end 593 | 594 | ---for now will just make a literal, in the future switch to String 595 | function visitor.string(node) 596 | return ctx:new_string_literal(node.conststr:unescape()) 597 | end 598 | 599 | --#endregion 600 | 601 | ---@param func gccjit.Function* 602 | ---@param args gccjit.RValue*[] 603 | ---@param loc gccjit.Location*? 604 | ---@param fctx FunctionContext.Local 605 | ---@return gccjit.RValue* 606 | local function function_call(func, args, loc, fctx) 607 | ---@type gccjit.RValue*[] 608 | local rawargs = {} 609 | for i, v in ipairs(args) do 610 | rawargs[i] = v:as_rvalue() 611 | end 612 | 613 | return ctx:new_call(func, rawargs, loc) 614 | end 615 | 616 | --this just gets the type to cast to 617 | function visitor.cast(node) 618 | return conv_teal_type(node.casttype) 619 | end 620 | 621 | ---@param node tl.Node 622 | ---@param fctx FunctionContext.Local 623 | ---@param scope Scope 624 | ---@return Type 625 | local function typedef(node, fctx, scope) 626 | ---@type string 627 | local name = visit(node.var, fctx).name 628 | assert(node.value.kind == "newtype", "Expected a newtype node") 629 | return conv_teal_type(node.value.newtype) 630 | end 631 | 632 | function visitor.local_type(node, fctx) 633 | return typedef(node, fctx, "local") 634 | end 635 | 636 | function visitor.global_type(node, fctx) 637 | return typedef(node, fctx, "global") 638 | end 639 | 640 | local special_operators = {} 641 | 642 | ---@param node tl.Node 643 | ---@param fctx FunctionContext.Local 644 | ---@return gccjit.RValue*, true 645 | function special_operators.funcall(node, fctx) 646 | ---@type FunctionContext.External 647 | local func = visit(node.e1, fctx) 648 | ---@type (gccjit.RValue* | gccjit.Param*)[] 649 | local args = visit(node.e2, fctx) 650 | --the `true` indicates its a function call, so the statement can be added to the block. This is a godawful hack but I dont care 651 | return function_call(func.raw, args, loc(node), fctx), true 652 | end 653 | 654 | ---@param node tl.Node 655 | ---@param fctx FunctionContext.Local 656 | ---@return gccjit.RValue* 657 | function special_operators.as(node, fctx) 658 | local ty = visit(node.e2, fctx) 659 | local val = visit(node.e1, fctx) 660 | return ctx:new_cast(ty.raw, val:as_rvalue(), loc(node)) 661 | end 662 | 663 | ---TODO: When tables are implemented make this also work with tables 664 | ---@param node tl.Node 665 | ---@param fctx FunctionContext.Local 666 | function special_operators.index(node, fctx) 667 | ---@type gccjit.RValue* 668 | local tbl = visit(node.e1, fctx):as_rvalue() 669 | ---@type gccjit.RValue* 670 | local idx = visit(node.e2, fctx):as_rvalue() 671 | 672 | return ctx:new_array_access(tbl, idx, loc(node)) --gccjit should catch any type errors :) 673 | end 674 | 675 | function visitor.op(node, fctx) 676 | local op = assert(node.op.op, "Expected an operator") 677 | 678 | if op:sub(1, 1) == "@" or op == "as" then 679 | local specop = special_operators[op == "as" and "as" or op:sub(2)] 680 | if not specop then 681 | error("Unsupported special operator: "..op) 682 | end 683 | return specop(node, fctx) 684 | elseif is_comparison[op] then 685 | local lhs = visit(node.e1, fctx) 686 | local rhs = visit(node.e2, fctx) 687 | return ctx:new_comparison(op, lhs:as_rvalue(), rhs:as_rvalue(), loc(node)) 688 | else 689 | local lhs = visit(node.e1, fctx) 690 | local rhs = visit(node.e2, fctx) 691 | return ctx:new_binary_op(lhs:as_rvalue():get_type(), lhs:as_rvalue(), op, rhs:as_rvalue(), loc(node)) 692 | end 693 | end 694 | 695 | visitor["if"] = function (node, fctx) 696 | assert(fctx, "Expected a function context") 697 | local if_block_node = assert(node.if_blocks[1], "Expected at least one if block") 698 | ---@type gccjit.RValue* 699 | local cond = visit(if_block_node.exp, fctx):as_rvalue() --just in case its a `LValue*` 700 | local if_block = fctx.raw:new_block("if") 701 | local else_block = fctx.raw:new_block("else") 702 | local end_block = fctx.raw:new_block("end") 703 | 704 | if_block:add_comment("if block for function "..fctx.name, loc(node)) 705 | end_block:add_comment("end block for function "..fctx.name, loc(node)) 706 | 707 | local newidx = #fctx.block_stack+1 708 | fctx.block_stack[newidx] = if_block 709 | visit(if_block_node.body, fctx) --fill the block 710 | 711 | --if the block is still on the stack, then it didn't end, so it can continue to the end block 712 | if fctx.block_stack[newidx] then 713 | if_block:end_with_jump(end_block, loc(node)) 714 | fctx.block_stack[newidx] = nil 715 | end 716 | 717 | if node.if_blocks[2] then 718 | else_block:add_comment("else block for function "..fctx.name, loc(node)) 719 | newidx = #fctx.block_stack+1 720 | fctx.block_stack[newidx] = else_block 721 | visit(node.if_blocks[2].body, fctx) 722 | if fctx.block_stack[newidx] then 723 | else_block:end_with_jump(end_block, loc(node)) 724 | fctx.block_stack[newidx] = nil 725 | end 726 | else 727 | else_block:end_with_jump(end_block, loc(node)) 728 | end 729 | 730 | assert(fctx.block_stack[#fctx.block_stack], "Block has already ended") 731 | fctx.block_stack[#fctx.block_stack]:end_with_conditional(cond, if_block, else_block, loc(node)) 732 | fctx.block_stack[#fctx.block_stack] = nil 733 | fctx.block_stack[#fctx.block_stack+1] = end_block 734 | end 735 | 736 | visitor["return"] = function (node, fctx) 737 | local ret = visit(node.exps[1], fctx) 738 | fctx.block_stack[#fctx.block_stack]:end_with_return(ret:as_rvalue(), loc(node)) 739 | fctx.block_stack[#fctx.block_stack] = nil 740 | end 741 | --#endregion 742 | 743 | return { 744 | compiler_context = ctx, 745 | visitor = visitor, 746 | -- compile = visit --[=[@as fun(node: tl.Node): gccjit.Object*[]]=] 747 | ---@param node tl.Node 748 | ---@return any? 749 | compile = function (node) 750 | ---@diagnostic disable-next-line: param-type-mismatch 751 | return visit(node, nil) 752 | end 753 | } 754 | -------------------------------------------------------------------------------- /src/main.lua: -------------------------------------------------------------------------------- 1 | -- Copyright (C) 2024 Amrit Bhogal 2 | -- 3 | -- This file is part of teal-compiler. 4 | -- 5 | -- teal-compiler is free software: you can redistribute it and/or modify 6 | -- it under the terms of the GNU General Public License as published by 7 | -- the Free Software Foundation, either version 3 of the License, or 8 | -- (at your option) any later version. 9 | -- 10 | -- teal-compiler is distributed in the hope that it will be useful, 11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | -- GNU General Public License for more details. 14 | -- 15 | -- You should have received a copy of the GNU General Public License 16 | -- along with teal-compiler. If not, see . 17 | local gccjit_translator = require("codegen.gccjit") 18 | local utilities = require("utilities") 19 | local teal = require("teal.tl") 20 | 21 | if not arg[1] or arg[1] == "-h" or arg[1] == "--help" then 22 | io.stderr:write(string.format([=[Usage: %s [-O] [-o ] [-g] [--use-gc-for-compile] [--dump-tree]]=], arg[0])) 23 | os.exit(1) 24 | end 25 | 26 | local in_f = arg[1] 27 | -- local opt_level = 0 28 | -- local debug_info = false 29 | -- local use_gc_for_compile = false 30 | -- local opt_level, debug_info, use_gc_for_compile = 0, false, false 31 | local opts = { 32 | opt_level = 0, 33 | debug_info = false, 34 | use_gc_for_compile = false, 35 | ---@type string? 36 | outfile = nil, 37 | dump_tree = false 38 | } 39 | 40 | for i = 2, #arg do 41 | local v = arg[i] 42 | if v:match("-O%d") then 43 | opts.opt_level = assert(tonumber(v:match("-O(%d)")) or tonumber(arg[i + 1])) 44 | end 45 | 46 | if v == "-o" then opts.outfile = arg[i + 1] end 47 | if v == "-g" then opts.debug_info = true end 48 | if v == "--use-gc-for-compile" then opts.use_gc_for_compile = true end 49 | if v == "--dump-tree" then opts.dump_tree = true end 50 | end 51 | 52 | if not opts.use_gc_for_compile then 53 | collectgarbage("stop") 54 | collectgarbage("stop") 55 | end 56 | 57 | if not opts.outfile then opts.outfile = in_f:gsub("%.tl$", ".so") end 58 | 59 | ---@type string 60 | local contents do 61 | local f = assert(io.open(in_f, "r")) 62 | contents = f:read("*a") 63 | assert(f:close()) 64 | end 65 | 66 | local ast, errs, modules = teal.parse(contents, in_f) 67 | if #errs > 0 then 68 | for _, err in ipairs(errs) do 69 | io.stderr:write(string.format("%s:%d:%d: %s\n", in_f, err.y, err.x, err.msg)) 70 | end 71 | os.exit(1) 72 | end 73 | 74 | gccjit_translator.compile(ast) 75 | local ctx = gccjit_translator.compiler_context 76 | ctx:set_option("optimization level", opts.opt_level) 77 | ctx:set_option("debuginfo", opts.debug_info) 78 | ctx:set_option("dump initial tree", opts.dump_tree) 79 | 80 | local out_ext = opts.outfile:match("%.(%w+)$") 81 | ---@type gccjit.OutputKind | "gimple" 82 | local kind = utilities.match(out_ext) { 83 | so = "dynamic library", 84 | S = "assembler", 85 | o = "object file", 86 | gimple = "gimple", 87 | default = "executable" 88 | } 89 | 90 | if kind == "gimple" then 91 | ctx:dump_to_file(opts.outfile, true) 92 | else 93 | ctx:compile_to_file(kind --[[@as gccjit.OutputKind]], opts.outfile) 94 | end 95 | -------------------------------------------------------------------------------- /src/utilities.lua: -------------------------------------------------------------------------------- 1 | -- Copyright (C) 2024 Amrit Bhogal 2 | -- 3 | -- This file is part of teal-compiler. 4 | -- 5 | -- teal-compiler is free software: you can redistribute it and/or modify 6 | -- it under the terms of the GNU General Public License as published by 7 | -- the Free Software Foundation, either version 3 of the License, or 8 | -- (at your option) any later version. 9 | -- 10 | -- teal-compiler is distributed in the hope that it will be useful, 11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | -- GNU General Public License for more details. 14 | -- 15 | -- You should have received a copy of the GNU General Public License 16 | -- along with teal-compiler. If not, see . 17 | 18 | local export = {} 19 | 20 | ---@generic T, TRet 21 | ---@param x T 22 | ---@return fun(match: { default: (fun(x: T): TRet?)?, [T] : fun(goto: fun(x: T): (TRet?)): TRet }): (TRet?) 23 | function export.switch(x) 24 | return function (match) 25 | local m = match[x] 26 | local function go_to(x) return match[x] and match[x](go_to) or error("Could not goto match "..tostring(x)) end 27 | 28 | return m and m(go_to) or (match.default and match.default(x) or nil) 29 | end 30 | end 31 | 32 | ---@generic T, TRet 33 | ---@param x T 34 | ---@return fun(match: { default?: TRet, [T] : TRet }): (TRet?) 35 | function export.match(x) 36 | return function (match) 37 | local m = match[x] 38 | return m or match.default 39 | end 40 | end 41 | 42 | return export 43 | -------------------------------------------------------------------------------- /teal-compiler-dev-1.rockspec: -------------------------------------------------------------------------------- 1 | package = "teal-compiler" 2 | version = "dev-1" 3 | source = { 4 | url = "git+https://github.com/Frityet/teal-compiler.git" 5 | } 6 | description = { 7 | homepage = "https://github.com/Frityet/teal-compiler", 8 | license = "GPLv3" 9 | } 10 | dependencies = { 11 | "lua ~> 5.1", 12 | "penlight", 13 | "argparse", 14 | "tl" 15 | } 16 | build = { 17 | type = "builtin", 18 | install = { 19 | bin = { 20 | ["teal-compiler"] = "src/main.lua" 21 | } 22 | }, 23 | modules = { 24 | ["utilities"] = "src/utilities.lua", 25 | ["abi"] = "src/abi.lua", 26 | ["codegen.gccjit"] = "src/codegen/gccjit.lua", 27 | ["backends.gccjit"] = "src/backends/gccjit/init.lua", 28 | ["backends.gccjit.cdef"] = "src/backends/gccjit/cdef.lua", 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /test.tl: -------------------------------------------------------------------------------- 1 | local type cstring = c.pointer> 2 | local printf: function(s: cstring, ...: c.varadict): c.int32_t 3 | 4 | global function main(argc: c.int32_t, argv: c.pointer): c.int32_t 5 | printf("Argc: %d, argv: %p\n", argc, argv) 6 | printf("progname: %s\n", argv[0]) 7 | 8 | return 0 as c.int32_t 9 | end 10 | -------------------------------------------------------------------------------- /tlconfig.lua: -------------------------------------------------------------------------------- 1 | return { 2 | include_dir = { 3 | "teal/", 4 | "types/", 5 | "src/" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /types/ffi.d.tl: -------------------------------------------------------------------------------- 1 | 2 | local record libffi 3 | type CData = integer | number | string | { string | integer : CData } | nil 4 | type CType = string | CData 5 | type CFunction = function(...: any): CData 6 | type CNamespace = { string : CFunction | CData } 7 | 8 | load: function(string): { string : CFunction | CData } 9 | load: function(string): T 10 | cdef: function(string) 11 | new: function(CType, integer | nil, ...: any): CData 12 | typeof: function(CType, ...: any): CType 13 | cast: function(CType, ...: any): CType 14 | metatype: function(CType, metatable): CType 15 | gc: function(CData, function(CData)): CData 16 | sizeof: function(CType, integer | nil): integer | nil 17 | alignof: function(CType): integer 18 | offsetof: function(CType, string): integer, integer | nil, integer | nil 19 | istype: function(CType, any): boolean 20 | errno: function(integer | nil): integer 21 | string: function(CData, integer | nil): string 22 | copy: function(CData, CData, integer) 23 | copy: function(CData, string) 24 | fill: function(CData, integer, CData) 25 | abi: function(string): boolean 26 | set: function(function) 27 | 28 | C: CNamespace 29 | end 30 | 31 | return libffi 32 | -------------------------------------------------------------------------------- /types/jit.d.tl: -------------------------------------------------------------------------------- 1 | local record jitlib 2 | enum OSName 3 | "Windows" 4 | "Linux" 5 | "OSX" 6 | "BSD" 7 | "POSIX" 8 | "Other" 9 | end 10 | 11 | on: function(function | boolean, boolean | nil) 12 | off: function(function | boolean, boolean | nil) 13 | flush: function(function | boolean, boolean | nil) 14 | 15 | --Status 16 | status: function(): boolean, string... 17 | 18 | os: OSName 19 | end 20 | 21 | global jit: jitlib 22 | 23 | return jitlib 24 | -------------------------------------------------------------------------------- /types/jit/p.d.tl: -------------------------------------------------------------------------------- 1 | local record jitplib 2 | start: function(options: string, out: string) 3 | stop: function() 4 | end 5 | 6 | return jitplib 7 | -------------------------------------------------------------------------------- /types/pl.d.tl: -------------------------------------------------------------------------------- 1 | local record pl 2 | -- This is not divided into multiple files due to circular 3 | -- dependency issues. For now, everything is declared here 4 | -- and just reexported in the right file 5 | 6 | record List 7 | {T} 8 | 9 | new: function({T}): pl.List 10 | metamethod __call: function(pl.List, {T}): pl.List 11 | metamethod __concat: function(pl.List, pl.List): pl.List 12 | 13 | range: function(number, number, number): pl.List 14 | split: function(string, string): pl.List 15 | 16 | len: function(pl.List): number 17 | 18 | append: function(pl.List, T): pl.List 19 | clone: function(pl.List): pl.List 20 | extend: function(pl.List, pl.List): pl.List 21 | insert: function(pl.List, number, T): pl.List 22 | pop: function(pl.List, number): T 23 | put: function(pl.List, T): pl.List 24 | remove: function(pl.List, number): pl.List 25 | remove_value: function(pl.List, T): pl.List 26 | 27 | chop: function(pl.List, number, number): pl.List 28 | slice_assign: function(pl.List, number, number, pl.List): pl.List 29 | splice: function(pl.List, number, pl.List): pl.List 30 | 31 | reverse: function(pl.List): pl.List 32 | sorted: function(pl.List, string | function(T, T): boolean): pl.List 33 | sort: function(pl.List, string | function(T, T): boolean): pl.List 34 | 35 | clear: function(pl.List): pl.List 36 | contains: function(pl.List, T): boolean 37 | count: function(pl.List, T): number 38 | index: function(pl.List, T, number): number 39 | minmax: function(pl.List): number, number 40 | slice: function(pl.List, number, number): pl.List 41 | 42 | concat: function(pl.List, string): string 43 | join: function(pl.List, string): string 44 | 45 | foreach: function(pl.List, string | function(T, ...: any), ...: any) 46 | foreachm: function(pl.List, string, ...: any) 47 | filter: function(pl.List, (string | function(T, U): boolean), U): pl.List 48 | 49 | transform: function(pl.List, (string | function(T, ...: any): T), ...: any): pl.List 50 | 51 | map: function(pl.List, (string | function(T, ...: any): U), ...: any): pl.List 52 | map2: function(pl.List, (string | function(T, U, ...: any): V), pl.List, ...: any): pl.List 53 | mapm: function(pl.List, string, ...: any): pl.List 54 | reduce: function(pl.List, (string | function(T, T): T)): T 55 | 56 | partition: function(List, (function(T, ...: any): K), ...: any): pl.Map > 57 | 58 | iter: function(pl.List): (function(): T) 59 | iterate: function(string | table | function) -- FILE is also considered a table 60 | end 61 | 62 | record Map 63 | metamethod __call: function(any, {K: V}): Map 64 | 65 | -- These two are substitutes for maprecords ({K: V}) 66 | metamethod __index: function(pl.Map, K): V 67 | metamethod __newindex: function(pl.Map, K, V) 68 | 69 | keys: pl.List 70 | values: pl.List 71 | 72 | iter: function(pl.Map): (function(): {K, V}) 73 | items: function(pl.Map): (function(): {K, V}) 74 | 75 | get: function(pl.Map, K): V 76 | set: function(pl.Map, K, V) 77 | setdefault: function(pl.Map, K, V): V 78 | 79 | getvalues: function(pl.Map, {K}): pl.List 80 | update: function(pl.Map, {K: V}) 81 | 82 | len: function(pl.Map): number 83 | end 84 | 85 | record Date 86 | metamethod __call: function(pl.Date, number, boolean): pl.Date 87 | metamethod __call: function(pl.Date, {pl.Date.datefield: number}, boolean): pl.Date 88 | metamethod __call: function(pl.Date, number, number, number, number, number, number) 89 | 90 | metamethod __lt: function(pl.Date, pl.Date): boolean 91 | metamethod __add: function(pl.Date, pl.Date): pl.Date 92 | metamethod __add: function(pl.Date, {pl.Date.datefield: number}): pl.Date 93 | metamethod __sub: function(pl.Date, pl.Date): pl.Date 94 | 95 | enum datefield 96 | 'year' 97 | 'month' 98 | 'day' 99 | 'hour' 100 | 'min' 101 | 'sec' 102 | end 103 | 104 | set: function(pl.Date, number) 105 | tzone: function(pl.Date, number): number 106 | toUTC: function(pl.Date): pl.Date 107 | toLocal: function(pl.Date): pl.Date 108 | 109 | year: function(pl.Date): number 110 | month: function(pl.Date): number 111 | day: function(pl.Date): number 112 | hour: function(pl.Date): number 113 | min: function(pl.Date): number 114 | sec: function(pl.Date): number 115 | yday: function(pl.Date): number 116 | 117 | year: function(pl.Date, number) 118 | month: function(pl.Date, number) 119 | day: function(pl.Date, number) 120 | hour: function(pl.Date, number) 121 | min: function(pl.Date, number) 122 | sec: function(pl.Date, number) 123 | yday: function(pl.Date, number) 124 | 125 | is_weekend: function(pl.Date): boolean 126 | weekday_name: function(pl.Date, boolean): string 127 | month_name: function(pl.Date, boolean): string 128 | 129 | add: function(pl.Date, {pl.Date.datefield: number}) 130 | diff: function(pl.Date, pl.Date): pl.Date 131 | 132 | last_day: function(pl.Date): number 133 | 134 | Interval: function(number): pl.Date 135 | 136 | record Format 137 | metamethod __call: function(string): pl.Date.Format 138 | parse: function(string): pl.Date 139 | tostring: function(pl.Date): string 140 | US_order: function(boolean) 141 | end 142 | end 143 | 144 | -- MultiMap inherits from Map, so this is just a weird case that can't 145 | -- really be easily described in teal for now. Same for OrderedMap and Set. 146 | 147 | -- TODO MultiMap 148 | -- TODO OrderedMap 149 | -- TODO Set 150 | 151 | record app 152 | script_name: function(): string 153 | require_here: function(string): any 154 | appfile: function(string): string 155 | platform: function(): string 156 | lua: function(): string, string 157 | parse_args: function({string}, table, table) 158 | end 159 | 160 | record array2d 161 | record Array2D -- record just for generics 162 | {{T}} 163 | end 164 | 165 | new: function(number, number, T): Array2D 166 | 167 | size: function(pl.array2d.Array2D): number, number 168 | column: function(pl.array2d.Array2D, number): List 169 | flatten: function(pl.array2d.Array2D): List 170 | reshape: function(pl.array2d.Array2D, number, boolean): pl.array2d.Array2D 171 | 172 | swap_rows: function(pl.array2d.Array2D, number, number) 173 | swap_cols: function(pl.array2d.Array2D, number, number) 174 | 175 | reduce_rows: function(function(T, T): T, pl.array2d.Array2D): pl.List 176 | reduce_cols: function(function(T, T): T, pl.array2d.Array2D): pl.List 177 | reduce2: function(function(T, T): T, function(T, T): T, pl.array2d.Array2D): T 178 | 179 | map: function( 180 | (string | function(T, ...: A): R), 181 | pl.array2d.Array2D, ...: A 182 | ): pl.array2d.Array2D 183 | 184 | map2: function( 185 | (string | function({T1}, {T2}, ...: A): {R}), 186 | number, number, 187 | pl.array2d.Array2D, pl.array2d.Array2D, 188 | ...: A 189 | ): pl.array2d.Array2D 190 | map2: function( 191 | (string | function({T1}, {T2}, ...: A): R), 192 | number, number, 193 | pl.array2d.Array2D, {T2}, 194 | ...: A 195 | ): Array2D 196 | map2: function( 197 | (string | function({T1}, {T2}, ...: A): R), 198 | number, number, 199 | {T1}, pl.array2d.Array2D, 200 | ...: A 201 | ): pl.array2d.Array2D 202 | map2: function( 203 | (string | function({T1}, {T2}, ...: A): R), 204 | number, number, 205 | {T1}, {T2}, 206 | ...: A 207 | ): {R} 208 | 209 | product: function( 210 | (string | function(T, U): R), 211 | {T}, {U} 212 | ): pl.array2d.Array2D 213 | 214 | extract_rows: function(pl.array2d.Array2D, {number}): pl.array2d.Array2D 215 | extract_cols: function(pl.array2d.Array2D, {number}): pl.array2d.Array2D 216 | 217 | remove_row: function(pl.array2d.Array2D, number) 218 | remove_col: function(pl.array2d.Array2D, number) 219 | 220 | parse_range: function(string): number, number, number, number 221 | range: function(pl.array2d.Array2D, string): {T} 222 | slice: function(pl.array2d.Array2D, number, number, number, number): {T} 223 | set: function(pl.array2d.Array2D, T, number, number, number, number) 224 | write: function(pl.array2d.Array2D, FILE, string, number, number, number, number) 225 | 226 | forall: function( 227 | pl.array2d.Array2D, 228 | (function({T}, number): any...), 229 | (function(number): any...), 230 | number, number, number, number 231 | ) 232 | move: function( 233 | pl.array2d.Array2D, 234 | number, number, 235 | pl.array2d.Array2D, 236 | number, number, number, number 237 | ) 238 | 239 | iter: function( 240 | pl.array2d.Array2D, boolean, 241 | number, number, number, number 242 | ): (function(): (T | {number, number, T})) 243 | 244 | columns: function(pl.array2d.Array2D): (function(): List) 245 | end 246 | 247 | record class 248 | metamethod __index: function(any, string): Class 249 | metamethod __call: function(any, Class): Class 250 | 251 | record Class 252 | class_of: function(Class, Instance): boolean 253 | cast: function(Class, Instance) 254 | end 255 | 256 | record Instance 257 | -- FIXME this is not ideal, but I can't think of a better solution... 258 | metamethod __index: function(Instance, any): any 259 | 260 | is_a: function(Instance, Class): boolean 261 | end 262 | end 263 | 264 | record compat 265 | lua51: boolean 266 | jit: boolean 267 | jit52: boolean 268 | is_windows: boolean 269 | 270 | dir_separator: string 271 | 272 | execute: function(string): boolean, number 273 | 274 | enum LoadMode 275 | 'b' 276 | 't' 277 | 'bt' 278 | end 279 | load: function(any, string, LoadMode, {string: any}) 280 | 281 | getfenv: function(function): {string: any} 282 | setfenv: function(function, {string: any}) 283 | end 284 | 285 | record comprehension 286 | type generator = (function(): {any}) 287 | type parser = (function(string): generator) 288 | new: function(): parser 289 | end 290 | 291 | record config 292 | enum ReadOpt 293 | 'smart' 294 | 'variabilize' 295 | 'convert_numbers' 296 | 'trim_space' 297 | 'trim_quotes' 298 | 'list_delim' 299 | 'keysep' 300 | end 301 | 302 | enum ReadError 303 | 'not a file-like object' 304 | 'file is nil' 305 | end 306 | 307 | lines: function(FILE | string): function(): string, pl.config.ReadError 308 | read: function(FILE | string, {pl.config.ReadOpt: any}): table, pl.config.ReadError 309 | end 310 | 311 | record data 312 | enum ReadOpt 313 | 'delim' 314 | 'fieldnames' 315 | 'no_convert' 316 | 'convert' 317 | 'numfields' 318 | 'last_field_collect' 319 | 'thousands_dot' 320 | 'csv' 321 | end 322 | 323 | type rowiterator = function(): any... 324 | 325 | record Data 326 | {{any}} 327 | 328 | fieldnames: pl.List 329 | original_fieldnames: {string} 330 | 331 | column_by_name: function(pl.data.Data, string): pl.List 332 | 333 | select: function(pl.data.Data, string): pl.data.rowiterator 334 | select_row: function(pl.data.Data, string): function(): {any} 335 | 336 | copy_select: function(pl.data.Data, string): Data 337 | column_names: function(pl.data.Data): {string} 338 | 339 | write_row: function(pl.data.Data, FILE, {any}) 340 | 341 | write: function(pl.data.Data, FILE) 342 | read: function(FILE | string, {pl.data.ReadOpt: any}): pl.data.Data, string 343 | end 344 | write: function(array2d.Array2D, FILE, {string}, string): boolean, string 345 | 346 | new: function({{any}}, {string}) 347 | 348 | query: function(pl.data.Data, (string | table), {table}, boolean): pl.data.rowiterator, string 349 | filter: function(string, FILE | string, FILE | string, boolean) 350 | end 351 | 352 | record dir 353 | fnmatch: function(string, string): boolean 354 | filter: function({string}, string): pl.List 355 | 356 | copyfile: function(string, string, boolean): boolean 357 | movefile: function(string, string): boolean 358 | makepath: function(string): boolean, string 359 | rmtree: function(string): boolean, string 360 | clonetree: function(string, string, (function(string, string): any)) 361 | 362 | getfiles: function(string, string): pl.List 363 | getdirectories: function(string): pl.List 364 | walk: function(string, boolean, boolean): (function(): string, pl.List, pl.List) 365 | 366 | dirtree: function(string): (function(): string, boolean) 367 | getallfiles: function(string, string): pl.List 368 | end 369 | 370 | record file 371 | -- TODO copy declarations from other functions 372 | -- this whole module is just renaming of other functions 373 | end 374 | 375 | record func 376 | record PHExp end 377 | 378 | _0: pl.func.PHExp 379 | _1: pl.func.PHExp 380 | _2: pl.func.PHExp 381 | _3: pl.func.PHExp 382 | _4: pl.func.PHExp 383 | _5: pl.func.PHExp 384 | 385 | -- FIXME properly define return type of this... thing 386 | import: function(string, {any: function}) 387 | register: function(function, string): function 388 | 389 | tail: function({T}): {T} 390 | 391 | isPE: function(table): boolean 392 | repr: function(pl.func.PHExp): string 393 | instantiate: function(pl.func.PHExp): function 394 | I: function(pl.func.PHExp): function 395 | 396 | -- FIXME this is horrible... 397 | bind1: function((function(T): U), T): (function(): U) 398 | bind1: function((function(T1, T2): U), T1): (function(T2): U) 399 | bind1: function( 400 | (function(T1, T2, T3): U), 401 | T1 402 | ): (function(T2, T3): U) 403 | bind1: function( 404 | (function(T1, T2, T3, T4): U), 405 | T1 406 | ): (function(T2, T3, T4): U) 407 | bind1: function( 408 | (function(T1, T2, T3, T4, T5): U), T1 409 | ): (function(T2, T3, T4, T5): U) 410 | bind1: function( 411 | (function(T1, T2, T3, T4, T5, T6): U), T1 412 | ): (function(T2, T3, T4, T5, T6): U) 413 | 414 | -- FIXME Will these screw up the above definitions? 415 | bind1: function((function(...: T): U), T): (function(...: T): U) 416 | 417 | compose: function( 418 | (function(T): U), 419 | (function(U): V) 420 | ): (function(T): V) 421 | 422 | -- FIXME same as above 423 | compose: function( 424 | (function(...: T): U...), 425 | (function(...: U): V...) 426 | ): (function(...: T): V...) 427 | compose: function( 428 | (function(...: any): any...), 429 | (function(...: any): any...) 430 | ): (function(...: any): any...) 431 | 432 | -- FIXME same as above 433 | bind: function((function(T, ...: any): U), T): (function(...: any): U) 434 | 435 | bind: function((function(T1, T2, ...: any): U), T1, T2): (function(...: any): U) 436 | bind: function((function(T1, T2, ...: any): U), pl.func.PHExp, T2): (function(T1, ...: any): U) 437 | 438 | -- This is literally exponential, I am NOT doing a 4 parameter version 439 | bind: function((function(T1, T2, T3, ...: any): U), T1, T2, T3): (function(...: any): U) 440 | bind: function((function(T1, T2, T3, ...: any): U), pl.func.PHExp, T2, T3): (function(T1, ...: any): U) 441 | bind: function((function(T1, T2, T3, ...: any): U), T1, pl.func.PHExp, T3): (function(T2, ...: any): U) 442 | bind: function((function(T1, T2, T3, ...: any): U), pl.func.PHExp, pl.func.PHExp, T3): (function(T1, T2, ...: any): U) 443 | bind: function((function(T1, T2, T3, ...: any): U), T1, T2, pl.func.PHExp): (function(T3, ...: any): U) 444 | bind: function((function(T1, T2, T3, ...: any): U), pl.func.PHExp, T2, pl.func.PHExp): (function(T1, T3, ...: any): U) 445 | bind: function((function(T1, T2, T3, ...: any): U), T1, pl.func.PHExp, pl.func.PHExp): (function(T2, T3, ...: any): U) 446 | end 447 | 448 | import_into: function(table): (table, table) 449 | 450 | record input 451 | type linegetter = function(...: any): string 452 | type source = string | table 453 | 454 | enum FieldsOpt 455 | 'no_fail' 456 | end 457 | 458 | alltokens: function(pl.input.linegetter, string, function(string): T): (function(): T) 459 | create_getter: function(source): pl.input.linegetter 460 | numbers: function(source): (function(): number) 461 | words: function(source): (function(): string) 462 | 463 | -- {fields, nil} is a hacky substitute for a 1-tuple type 464 | fields: function({number, nil}, string, source, {pl.input.FieldsOpt: any}): (function(): string) 465 | fields: function( 466 | {number, number}, 467 | string, 468 | source, 469 | {pl.input.FieldsOpt: any} 470 | ): (function(): string, string) 471 | fields: function( 472 | {number, number, number}, 473 | string, 474 | source, 475 | {pl.input.FieldsOpt: any} 476 | ): (function(): string, string, string) 477 | fields: function( 478 | {number, number, number, number}, 479 | string, 480 | source, 481 | {pl.input.FieldsOpt: any} 482 | ): (function(): string, string, string, string) 483 | fields: function( 484 | {number} | number, 485 | string, 486 | source, 487 | {pl.input.FieldsOpt: any} 488 | ): (function(): string...) 489 | end 490 | 491 | record lapp 492 | enum argtype 493 | 'string' 494 | 'number' 495 | 'file' 496 | 'file-in' 497 | 'boolean' 498 | end 499 | 500 | show_usage_error: boolean 501 | 502 | quit: function(string, boolean) 503 | open: function(string, string): FILE 504 | error: function(string, boolean) 505 | assert: function(boolean, string) 506 | add_type: function(string, (argtype | function(string): any), function(any)) 507 | process_options_string: function(string, {string}): {string: any} 508 | 509 | metamethod __call: function(pl.lapp, string, {string}): {string: any} 510 | end 511 | 512 | record lexer 513 | type token = {string, string} 514 | type tokenaction = function(string, {string: any}): (string, string) 515 | type tokendesc = {string, pl.lexer.tokenaction} 516 | type tokenstream = function(any): (string, string) 517 | 518 | scan: function( 519 | string | FILE, 520 | {tokendesc, tokenaction}, 521 | {string: boolean}, 522 | {string: any} 523 | ): tokenstream 524 | lua: function( 525 | string | FILE, 526 | {string: boolean}, 527 | {string: any} 528 | ) 529 | cpp: function( 530 | string | FILE, 531 | {string: boolean}, 532 | {string: any} 533 | ) 534 | 535 | insert: function(pl.lexer.tokenstream, string, string) 536 | insert: function(pl.lexer.tokenstream, {pl.lexer.token} | pl.lexer.tokenstream) 537 | 538 | getline: function(pl.lexer.tokenstream): string 539 | getrest: function(pl.lexer.tokenstream): string 540 | lineno: function(pl.lexer.tokenstream): number, number 541 | get_keywords: function(): {string: boolean} 542 | 543 | get_separated_list: function( 544 | pl.lexer.tokenstream, 545 | string, 546 | string 547 | ): {{pl.lexer.token}}, pl.lexer.token 548 | 549 | skipws: function(pl.lexer.tokenstream): pl.lexer.token 550 | expecting: function( 551 | pl.lexer.tokenstream, 552 | string, 553 | boolean 554 | ): pl.lexer.token 555 | end 556 | 557 | record luabalanced 558 | match_string: function(string, number): string, number 559 | match_bracketed: function(string, number): string, number 560 | match_expression: function(string, number): string, number 561 | match_namelist: function(string, number): string, number 562 | match_explist: function(string, number): string, number 563 | 564 | enum snippettype 565 | 'e' 566 | 'c' 567 | 's' 568 | end 569 | match_gsub: function( 570 | string, 571 | (function(pl.luabalanced.snippettype, string): string) 572 | ): string 573 | end 574 | 575 | record operator 576 | enum OpRepr 577 | '+' 578 | '-' 579 | '*' 580 | '/' 581 | '%' 582 | '^' 583 | '..' 584 | '()' 585 | '[]' 586 | '<' 587 | '<=' 588 | '>' 589 | '>=' 590 | '==' 591 | '~=' 592 | '#' 593 | 'and' 594 | 'or' 595 | '{}' 596 | '~' 597 | '' 598 | end 599 | 600 | optable: {pl.operator.OpRepr: function} 601 | 602 | -- TODO properly annotate types as in func 603 | call: function(function, ...: any): any... 604 | index: function(table, any): any 605 | 606 | eq: function(any, any): boolean 607 | neq: function(any, any): boolean 608 | lt: function(any, any): boolean 609 | le: function(any, any): boolean 610 | gt: function(any, any): boolean 611 | ge: function(any, any): boolean 612 | 613 | len: function(string | table): number 614 | 615 | add: function(number, number): number 616 | sub: function(number, number): number 617 | mul: function(number, number): number 618 | div: function(number, number): number 619 | pow: function(number, number): number 620 | mod: function(number, number): number 621 | unm: function(number): number 622 | concat: function(string, string): string 623 | 624 | add: function(any, any): any 625 | sub: function(any, any): any 626 | mul: function(any, any): any 627 | div: function(any, any): any 628 | pow: function(any, any): any 629 | mod: function(any, any): any 630 | unm: function(any): any 631 | concat: function(any, any): any 632 | 633 | lnot: function(any): boolean 634 | land: function(any, any): boolean 635 | lor: function(any, any): boolean 636 | 637 | table: function(...: any): {any} 638 | match: function(string, string): boolean 639 | nop: function(...: any) 640 | end 641 | 642 | record path 643 | is_windows: boolean 644 | sep: string 645 | dirsep: string 646 | 647 | dir: function(string): function(): string 648 | mkdir: function(string): boolean, string 649 | rmdir: function(string): boolean, string 650 | 651 | currentdir: function(): string 652 | chdir: function(string): boolean, string 653 | 654 | getsize: function(string): number 655 | 656 | isdir: function(string): boolean 657 | isfile: function(string): boolean 658 | isabs: function(string): boolean 659 | exists: function(string): boolean 660 | 661 | getatime: function(string): number 662 | getmtime: function(string): number 663 | getctime: function(string): number 664 | 665 | splitpath: function(string): string, string 666 | splitext: function(string): string, string 667 | 668 | abspath: function(string, string): string 669 | dirname: function(string): string 670 | basename: function(string): string 671 | extension: function(string): string 672 | 673 | -- 2 mandatory parts 674 | join: function(string, string, ...: string): string 675 | 676 | normcase: function(string): string 677 | normpath: function(string): string 678 | relpath: function(string, string): string 679 | expanduser: function(string): string 680 | 681 | tmpname: function(): string 682 | common_prefix: function(string, string): string 683 | package_path: function(string): string, string 684 | 685 | -- TODO attrib (is there a way to 686 | -- copy these and functions from lfs.d.tl?) 687 | -- TODO linkattrib 688 | end 689 | 690 | record permute 691 | iter: function({any}): (function(): {any}) 692 | table: function({any}): {{any}} 693 | end 694 | 695 | record pretty 696 | read: function(string): table, string 697 | load: function(string, table, boolean): table, string 698 | write: function(table, ?string, ?boolean): string, string 699 | dump: function(table, string) 700 | debug: function(...: any) 701 | 702 | enum PrettyNumberKind 703 | 'N' 704 | 'M' 705 | 'T' 706 | end 707 | number: function(number, pl.pretty.PrettyNumberKind, number) 708 | end 709 | 710 | record seq 711 | matching: function(string): (function(string): number, number, any...) 712 | list: function({T}): (function(): T) 713 | 714 | -- TODO check if this is an OK overload 715 | keys: function(table): (function(): any) 716 | keys: function({K: any}): (function(): K) 717 | 718 | range: function(number, number): (function(): number) 719 | minmax: function({T} | function(): T): T, T 720 | sum: function({T} | function(): T): T, number 721 | sum: function({T} | function(): T, function(T): U): U, number 722 | 723 | copy: function({T} | function(): T): pl.List 724 | copy2: function((function(T1, T2): R1, R2), T1, T2): {{R1, R2}} 725 | copy_tuples: function(function(): any...): {{any}} 726 | 727 | random: function(number, number, number): (function(): number) 728 | sort: function((function(): T), function(T, T): boolean): (function(): T) 729 | zip: function((function(): T), (function(): U)): (function(): T, U) 730 | printall: function({T} | function(): T, string, number, function(T): string) 731 | 732 | -- The official documentation is wrong, this only returns 1 value 733 | count_map: function({T} | function(): T): pl.Map 734 | 735 | -- TODO 736 | map: function((function(T): U), {T} | function(): T): (function(): U) 737 | map: function((function(T1, T2): U), ({T1} | function(): T1), T2): (function(): U) 738 | map: function((function(T1, T2): U), ({{T1, T2}} | function(): T1, T2)): (function(): U) 739 | 740 | filter: function(({T} | function(): T), (function(T): boolean)): (function(): T) 741 | filter: function(({T} | function(): T), (function(T, U): boolean), U): (function(): T) 742 | 743 | reduce: function((function(R, T): R), ({T} | function(): T), R): R 744 | take: function(({T} | function(): T), number): function(): T 745 | take: function((function(): T, U), number): function(): T, U 746 | 747 | skip: function({T}, number): {T} 748 | skip: function((function(): T), number): {T} 749 | 750 | enum: function(({T} | function(): T)): function(): number, T 751 | enum: function((function(): T, U)): function(): number, T, U 752 | 753 | -- TODO Is this necessary? 754 | mapmethod: function(({table} | function(): table), string): function(): any 755 | mapmethod: function(({table} | function(T): table), string, T): function(): any 756 | mapmethod: function(({table} | function(T, U): table), string, T, U): function(): any 757 | 758 | last: function(({T} | function(): T)): function(): T, T 759 | 760 | foreach: function(({T} | function(): T), (function(T))) 761 | 762 | lines: function(string | FILE, ...: any): function(): any... 763 | end 764 | 765 | record sip 766 | enum PatCompileOpt 767 | 'at_start' 768 | end 769 | type matcher = function(string, table): boolean 770 | 771 | create_pattern: function(string, {pl.sip.PatCompileOpt: boolean}): string, {string}|string, {any} 772 | compile: function(string, {pl.sip.PatCompileOpt: boolean}): matcher, {string}|string 773 | match: function(string, string, table, {PatCompileOpt: boolean}): boolean 774 | match_at_start: function(string, string, table): boolean 775 | end 776 | 777 | record strict 778 | module: function(table): table 779 | module: function(table, table): table 780 | module: function(string, table, table): table 781 | 782 | make_all_strict: function(table) 783 | 784 | closed_module: function(table, string) 785 | end 786 | 787 | record stringio 788 | record WriteBuffer 789 | write: function(pl.stringio.WriteBuffer, {string | number}) 790 | end 791 | record ReadBuffer 792 | read: function(...: string): any... 793 | end 794 | 795 | create: function(): pl.stringio.WriteBuffer 796 | open: function(string): pl.stringio.ReadBuffer 797 | end 798 | 799 | record stringx 800 | isalpha: function(string): boolean 801 | isdigit: function(string): boolean 802 | isalnum: function(string): boolean 803 | isspace: function(string): boolean 804 | islower: function(string): boolean 805 | isupper: function(string): boolean 806 | startswith: function(string): boolean 807 | endswith: function(string): boolean 808 | 809 | join: function(string, {string} | function(): string): string 810 | splitlines: function(string, boolean): pl.List 811 | split: function(string, string, string): pl.List 812 | expandtabs: function(string, number): string 813 | 814 | lfind: function(string, string, number, number): number 815 | rfind: function(string, string, number, number): number 816 | replace: function(string, string, string, number): string 817 | count: function(string, string, boolean): number 818 | 819 | ljust: function(string, number, string): string 820 | rjust: function(string, number, string): string 821 | center: function(string, number, string): string 822 | lstrip: function(string, string): string 823 | rstrip: function(string, string): string 824 | strip: function(string, string): string 825 | 826 | splitv: function(string, string): string, string... 827 | partition: function(string, string): string, string, string 828 | rpartition: function(string, string): string, string, string 829 | at: function(string, number): string 830 | 831 | lines: function(string): function(): string 832 | 833 | title: function(string): string 834 | shorten: function(string, number, boolean): string 835 | quote_string: function(string): string 836 | end 837 | 838 | record tablex 839 | size: function(table): number 840 | 841 | index_by: function(table, {any}): pl.List 842 | index_by: function({T: U}, {T}): pl.List 843 | 844 | -- TODO check if these are OK 845 | transform: function((function(T): U), {any: T}) 846 | transform: function((function(T, A): U), {any: T}, A) 847 | transform: function((function(T): U), {T}) 848 | transform: function((function(T, A): U), {T}, A) 849 | transform: function((function(any, A)), table, A) 850 | 851 | range: function(number, number, number): {number} 852 | reduce: function((function(R, T): R), {T}, R): R 853 | index_map: function({T: U}): {U: T} 854 | 855 | makeset: function({T}): {T: boolean} 856 | union: function({T: any}, {T: any}): {T: any} 857 | intersection: function({T: any}, {T: any}): {T: any} 858 | merge: function({T: any}, {T: any}, boolean): {T: any} 859 | difference: function({T: any}, {T: any}, boolean): {T: any} 860 | 861 | count_map: function({T}, function(T, T): boolean): {T: number} 862 | set: function({T}, T, number, number) 863 | new: function(number, T): {T} 864 | clear: function({T}, number) 865 | 866 | removevalues: function({T}, number, number) 867 | readonly: function(table): table 868 | 869 | update: function(table, table): table 870 | copy: function(table): table 871 | deepcopy: function(table): table 872 | icopy: function({T}, {T}, number, number, number) 873 | 874 | insertvalues: function({T}, {T}) 875 | insertvalues: function({T}, number, {T}) 876 | 877 | compare: function({T}, {T}, function(T, T): boolean): boolean 878 | deepcompare: function(table, table, boolean, number): boolean 879 | compare_no_order: function({T}, {T}, function(T, T): boolean): boolean 880 | 881 | find: function({T}, T, number): number 882 | rfind: function({T}, T, number): number 883 | 884 | type cmpf = function(T, U): boolean 885 | find_if: function({T}, cmpf, U): number, R 886 | 887 | search: function(table, any, {table}): string 888 | 889 | map: function((function(T): R), {K: T}): {K: R} 890 | map: function((function(T, A): R), {K: T}, A): {K: R} 891 | 892 | imap: function((function(T): R), {T}): {R} 893 | imap: function((function(T, A): R), {T}, A): {R} 894 | 895 | map_named_method: function(string, {table}, ...: any): pl.List 896 | 897 | map2: function((function(T, U, A): R), {any: T}, {any: U}, A): {any: R} 898 | imap2: function((function(T, U, A): R), {T}, {U}, A): {R} 899 | mapn: function((function(...: T): R), ...: {T}): {R} 900 | pairmap: function((function(K, V): R)): {R} 901 | 902 | filter: function({T}, (function(T): boolean)): pl.List 903 | filter: function({T}, (function(T, A): boolean), A): pl.List 904 | 905 | foreach: function((function(V, K)), {K: V}) 906 | foreach: function((function(V, K, A)), {K: V}, A) 907 | foreachi: function((function(V, number)), {V}) 908 | foreachi: function((function(V, number, A)), {V}, A) 909 | 910 | sort: function({K: V}, cmpf): function(): K, V 911 | sortv: function({K: V}, cmpf): function(): K, V 912 | 913 | keys: function({any}): pl.List 914 | keys: function({K: any}): pl.List 915 | values: function({any: V}): pl.List 916 | values: function({V}): pl.List 917 | 918 | sub: function({V}, number, number): pl.List 919 | zip: function(...: {T}): {{T}} 920 | zip: function({T1}, {T2}): {{T1, T2}} 921 | zip: function({T1}, {T2}, {T3}): {{T1, T2, T3}} 922 | end 923 | 924 | record template 925 | record CompiledTemplate 926 | render: function(pl.template.CompiledTemplate, table, table, boolean): string 927 | end 928 | 929 | enum CompileOpt 930 | 'chunk_name' 931 | 'escape' 932 | 'inline_escape' 933 | 'inline_brackets' 934 | 'newline' 935 | 'debug' 936 | end 937 | 938 | substitute: function(string, table): string 939 | compile: function(string, {pl.template.CompileOpt: any}): pl.template.CompiledTemplate, string, string 940 | end 941 | 942 | record test 943 | error_handler: function(string, number, string, string, string) 944 | complain: function(any, any, string, number) 945 | assertmatch: function(string, string, number) 946 | assertraise: function(function, string, number) 947 | asserteq: function(any, any, number, number) 948 | asserteq2: function(any, any, any, any, number, number) 949 | tuple: function(...: any): {any} 950 | 951 | timer: function(string, number, function): number 952 | timer: function(string, number, function(A), A): number 953 | end 954 | 955 | record text 956 | format_operator: function 957 | 958 | indent: function(string, number, string): string 959 | dedent: function(string): string 960 | wrap: function(string, number): pl.List 961 | fill: function(string, number): string 962 | 963 | record Template 964 | -- metamethod __call -- TODO 965 | substitute: function(pl.text.Template, {string: any}): string 966 | safe_substitute: function(pl.text.Template, {string: any}): string 967 | indent_substitute: function(pl.text.Template, {string: any}): string 968 | end 969 | end 970 | 971 | record types 972 | type: function(any): string 973 | 974 | is_type: function(any, any): boolean 975 | is_callable: function(any): boolean 976 | is_integer: function(number): boolean 977 | is_empty: function(any, boolean) 978 | is_indexable: function(any): boolean 979 | is_iterable: function(any): boolean 980 | is_writeable: function(any): boolean 981 | 982 | to_bool: function(any, {string}, boolean): boolean 983 | end 984 | 985 | record url 986 | quote: function(string, boolean): string 987 | unquote: function(string): string 988 | end 989 | 990 | record utils 991 | record packedarray 992 | {T} 993 | n: number 994 | end 995 | pack: function(...: T): pl.utils.packedarray 996 | unpack: function({T}, number, number) 997 | printf: function(string, ...: any) 998 | fprintf: function(FILE, string, ...: any) 999 | import: function(string | table, table) 1000 | choose: function(boolean, T, T): T 1001 | 1002 | array_tostring: function({T}, table, function(T, number): string): string 1003 | is_type: function(any, string | metatable): boolean 1004 | 1005 | enum knownpattern 1006 | 'FLOAT' 1007 | 'INTEGER' 1008 | 'IDEN' 1009 | 'FILE' 1010 | end 1011 | patterns: {pl.utils.knownpattern: string} 1012 | 1013 | enum knownmt 1014 | 'List' 1015 | 'Map' 1016 | 'Set' 1017 | 'MultiMap' 1018 | end 1019 | record stdmt_entry 1020 | _name: string 1021 | end 1022 | 1023 | stdmt: {pl.utils.knownmt: pl.utils.stdmt_entry} 1024 | 1025 | function_arg: function(number, function | string, string): function 1026 | assert_arg: function( 1027 | number, 1028 | T, 1029 | string | metatable, 1030 | (function(any): boolean), 1031 | string, 1032 | number 1033 | ): T 1034 | assert_string: function(number, T): T 1035 | 1036 | enum errormode 1037 | 'default' 1038 | 'error' 1039 | 'quit' 1040 | end 1041 | on_error: function(pl.utils.errormode) 1042 | raise: function(string) 1043 | 1044 | readfile: function(string, boolean): string 1045 | writefile: function(string, string, boolean): boolean, string 1046 | readlines: function(string, boolean): {string} 1047 | 1048 | executeex: function(string, boolean): boolean, number, string, string 1049 | quote_arg: function(string | {string}): string 1050 | quit: function(string, ...: any) 1051 | quit: function(number, string, ...: any) 1052 | 1053 | escape: function(string): string 1054 | split: function(string, string, boolean, number): {string} 1055 | splitv: function(string, string): string... 1056 | 1057 | -- T must be callable, but this should be a good enough compromise 1058 | -- to guarantee function signature remains intact after memoization 1059 | memoize: function(T): T 1060 | 1061 | add_function_factory: function(metatable, (function(T): function)) 1062 | string_lambda: function(string): function(...: any): any... 1063 | bind1: function((string | function(T, U, ...: any): R), T): function(U, ...: any): R 1064 | bind2: function((string | function(T, U, ...: any): R), U): function(T, ...: any): R 1065 | end 1066 | 1067 | record xml 1068 | 1069 | end 1070 | end 1071 | 1072 | return pl 1073 | -------------------------------------------------------------------------------- /types/pl/Date.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".Date 2 | -------------------------------------------------------------------------------- /types/pl/List.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".List 2 | -------------------------------------------------------------------------------- /types/pl/Map.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".Map 2 | -------------------------------------------------------------------------------- /types/pl/app.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".app 2 | -------------------------------------------------------------------------------- /types/pl/array2d.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".array2d 2 | -------------------------------------------------------------------------------- /types/pl/class.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".class 2 | -------------------------------------------------------------------------------- /types/pl/compat.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".compat 2 | -------------------------------------------------------------------------------- /types/pl/comprehension.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".comprehension 2 | -------------------------------------------------------------------------------- /types/pl/config.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".config 2 | -------------------------------------------------------------------------------- /types/pl/data.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".data 2 | -------------------------------------------------------------------------------- /types/pl/dir.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".dir 2 | -------------------------------------------------------------------------------- /types/pl/file.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".file 2 | -------------------------------------------------------------------------------- /types/pl/func.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".func 2 | -------------------------------------------------------------------------------- /types/pl/input.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".input 2 | -------------------------------------------------------------------------------- /types/pl/lapp.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".lapp 2 | -------------------------------------------------------------------------------- /types/pl/lexer.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".lexer 2 | -------------------------------------------------------------------------------- /types/pl/luabalanced.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".luabalanced 2 | -------------------------------------------------------------------------------- /types/pl/operator.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".operator 2 | -------------------------------------------------------------------------------- /types/pl/path.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".path 2 | -------------------------------------------------------------------------------- /types/pl/permute.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".permute 2 | -------------------------------------------------------------------------------- /types/pl/pretty.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".pretty 2 | -------------------------------------------------------------------------------- /types/pl/seq.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".seq 2 | -------------------------------------------------------------------------------- /types/pl/sip.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".sip 2 | -------------------------------------------------------------------------------- /types/pl/strict.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".strict 2 | -------------------------------------------------------------------------------- /types/pl/stringio.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".stringio 2 | -------------------------------------------------------------------------------- /types/pl/stringx.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".stringx 2 | -------------------------------------------------------------------------------- /types/pl/tablex.d.tl: -------------------------------------------------------------------------------- 1 | return require("pl").tablex 2 | -------------------------------------------------------------------------------- /types/pl/template.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".template 2 | -------------------------------------------------------------------------------- /types/pl/test.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".test 2 | -------------------------------------------------------------------------------- /types/pl/text.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".text 2 | -------------------------------------------------------------------------------- /types/pl/types.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".types 2 | -------------------------------------------------------------------------------- /types/pl/url.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".url 2 | -------------------------------------------------------------------------------- /types/pl/utils.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".utils 2 | -------------------------------------------------------------------------------- /types/pl/xml.d.tl: -------------------------------------------------------------------------------- 1 | return require "pl".xml 2 | -------------------------------------------------------------------------------- /types/teal/tl.lua: -------------------------------------------------------------------------------- 1 | -- Copyright (C) 2024 Amrit Bhogal 2 | -- 3 | -- This file is part of teal-compiler. 4 | -- 5 | -- teal-compiler is free software: you can redistribute it and/or modify 6 | -- it under the terms of the GNU General Public License as published by 7 | -- the Free Software Foundation, either version 3 of the License, or 8 | -- (at your option) any later version. 9 | -- 10 | -- teal-compiler is distributed in the hope that it will be useful, 11 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | -- GNU General Public License for more details. 14 | -- 15 | -- You should have received a copy of the GNU General Public License 16 | -- along with teal-compiler. If not, see . 17 | 18 | ---@meta 19 | 20 | ---@class tl 21 | local tl = {} 22 | 23 | ---@class tl.Where 24 | ---@field f? string 25 | ---@field y integer 26 | ---@field x integer 27 | 28 | ---@class tl.Errors 29 | ---@field filename? string 30 | ---@field errors? tl.Error[] 31 | ---@field warnings? tl.Error[] 32 | ---@field unknown_dots? { [string] : boolean } 33 | 34 | ---@alias tl.WarningKind 35 | ---| "unknown" 36 | ---| "unused" 37 | ---| "redeclaration" 38 | ---| "branch" 39 | ---| "hint" 40 | ---| "debug" 41 | 42 | ---@alias tl.GenCompat 43 | ---| "off" 44 | ---| "optional" 45 | ---| "required" 46 | 47 | ---@alias tl.GenTarget 48 | ---| "5.1" 49 | ---| "5.3" 50 | ---| "5.4" 51 | 52 | ---@class tl.Error 53 | ---@field y? integer 54 | ---@field x? integer 55 | ---@field msg? string 56 | ---@field filename? string 57 | ---@field tag? tl.WarningKind 58 | 59 | ---@alias tl.TypeName 60 | ---| "typedecl" 61 | ---| "typealias" 62 | ---| "typevar" 63 | ---| "typearg" 64 | ---| "function" 65 | ---| "array" 66 | ---| "map" 67 | ---| "tupletable" 68 | ---| "record" 69 | ---| "interface" 70 | ---| "enum" 71 | ---| "boolean" 72 | ---| "string" 73 | ---| "nil" 74 | ---| "thread" 75 | ---| "number" 76 | ---| "integer" 77 | ---| "union" 78 | ---| "nominal" 79 | ---| "emptytable" 80 | ---| "literal_table_item" 81 | ---| "unresolved_emptytable_value" 82 | ---| "unresolved_typearg" 83 | ---| "unresolvable_typearg" 84 | ---| "circular_require" 85 | ---| "tuple" 86 | ---| "poly" intersection types, currently restricted to polymorphic functions defined inside records 87 | ---| "any" 88 | ---| "unknown" to be used in lax mode only 89 | ---| "invalid" producing a new value of this type (not propagating) must always produce a type error 90 | ---| "none" 91 | ---| "*" 92 | 93 | ---@class tl.Type : tl.Where 94 | ---@field typename? tl.TypeName 95 | ---@field typeid? integer 96 | ---@field inferred_at? tl.Where 97 | ---@field needs_compat? boolean 98 | 99 | ---@class tl.StringType : tl.Type 100 | ---@field typename? "string" 101 | ---@field literal? string 102 | 103 | ---@class tl.NumericType : tl.Type 104 | 105 | ---@class tl.IntegerType : tl.NumericType 106 | ---@field typename? "integer" 107 | 108 | ---@class tl.BooleanType : tl.Type 109 | ---@field typename? "boolean" 110 | 111 | ---@class tl.TypeDeclType : tl.Type 112 | ---@field typename? "typedecl" 113 | ---@field def? tl.Type 114 | ---@field closed? boolean 115 | ---@field typeargs? tl.TypeArgType[] 116 | 117 | ---@class tl.TypeAliasType : tl.Type 118 | ---@field typename? "typealias" 119 | ---@field alias_to? tl.NominalType 120 | ---@field is_nested_alias? boolean 121 | 122 | ---@alias tl.TypeType tl.TypeDeclType | tl.TypeAliasType 123 | 124 | ---@class tl.LiteralTableItemType : tl.Type 125 | ---@field typename? "literal_table_item" 126 | ---@field kname? string 127 | ---@field ktype? tl.Type 128 | ---@field vtype? tl.Type 129 | 130 | ---@class tl.Scope 131 | ---@field vars? { [string] : tl.Variable } 132 | ---@field labels? { [string] : tl.Node } 133 | ---@field pending_labels? { [string] : tl.Node[] } 134 | ---@field pending_nominals? { [string] : tl.NominalType[] } 135 | ---@field pending_global_types? { [string] : boolean } 136 | ---@field narrows? { [string] : boolean } 137 | 138 | ---@class tl.HasTypeArgs : tl.Type 139 | ---@field typeargs? tl.TypeArgType[] 140 | 141 | ---@class tl.HasDeclName 142 | ---@field declname? string 143 | 144 | ---@class tl.NominalType : tl.Type 145 | ---@field typename? "nominal" 146 | ---@field names? string[] 147 | ---@field typevals? tl.Type[] 148 | ---@field found? tl.TypeType 149 | ---@field resolved? tl.Type 150 | 151 | ---@class tl.ArrayLikeType : tl.Type 152 | ---@field elements? tl.Type 153 | ---@field consttypes? tl.Type[] 154 | ---@field inferred_len? integer 155 | 156 | ---@class tl.RecordLikeType : tl.Type, tl.HasTypeArgs, tl.HasDeclName, tl.ArrayLikeType 157 | ---@field interface_list? (tl.ArrayType | tl.NominalType)[] 158 | ---@field interfaces_expanded? boolean 159 | ---@field fields? { [string] : tl.Type } 160 | ---@field field_order? string[] 161 | ---@field meta_fields? { [string] : tl.Type } 162 | ---@field meta_field_order? string[] 163 | ---@field is_userdata? boolean 164 | 165 | ---@class tl.ArrayType : tl.ArrayLikeType 166 | ---@field typename? "array" 167 | 168 | ---@class tl.RecordType : tl.RecordLikeType 169 | ---@field typename? "record" 170 | 171 | ---@class tl.InterfaceType : tl.RecordLikeType 172 | ---@field typename? "interface" 173 | 174 | ---@class tl.InvalidType : tl.Type 175 | ---@field typename? "invalid" 176 | 177 | ---@class tl.UnknownType : tl.Type 178 | ---@field typename? "unknown" 179 | 180 | ---@class tl.TupleType : tl.Type 181 | ---@field typename? "tuple" 182 | ---@field is_va? boolean 183 | ---@field tuple? tl.Type[] 184 | 185 | ---@class tl.TypeArgType : tl.Type 186 | ---@field typename? "typearg" 187 | ---@field typearg? string 188 | ---@field constraint? tl.Type 189 | 190 | ---@class tl.UnresolvedTypeArgType : tl.Type 191 | ---@field typename? "unresolved_typearg" 192 | ---@field typearg? string 193 | ---@field constraint? tl.Type 194 | 195 | ---@class tl.UnresolvableTypeArgType : tl.Type 196 | ---@field typename? "unresolvable_typearg" 197 | ---@field typearg? string 198 | 199 | ---@class tl.TypeVarType : tl.Type 200 | ---@field typename? "typevar" 201 | ---@field typevar? string 202 | ---@field constraint? tl.Type 203 | 204 | ---@class tl.MapType : tl.Type 205 | ---@field typename? "map" 206 | ---@field keys? tl.Type 207 | ---@field values? tl.Type 208 | 209 | ---@class tl.EmptyTableType : tl.Type 210 | ---@field typename? "emptytable" 211 | ---@field declared_at? tl.Node 212 | ---@field assigned_to? string 213 | ---@field keys? tl.Type 214 | 215 | ---@class tl.UnresolvedEmptyTableValueType : tl.Type 216 | ---@field typename? "unresolved_emptytable_value" 217 | ---@field emptytable_type? tl.EmptyTableType 218 | 219 | ---@class tl.FunctionType : tl.Type, tl.HasTypeArgs 220 | ---@field typename? "function" 221 | ---@field is_method? boolean 222 | ---@field min_arity? integer 223 | ---@field args? tl.TupleType 224 | ---@field rets? tl.TupleType 225 | ---@field macroexp? tl.Node 226 | ---@field is_record_function? boolean 227 | 228 | ---@class tl.AggregateType : tl.Type 229 | ---@field types? tl.Type[] 230 | 231 | ---@class tl.UnionType : tl.AggregateType 232 | ---@field typename? "union" 233 | 234 | ---@class tl.TupleTableType : tl.AggregateType 235 | ---@field typename? "tupletable" 236 | 237 | ---@class tl.PolyType : tl.AggregateType 238 | ---@field typename? "poly" 239 | ---@field types? tl.FunctionType[] 240 | 241 | ---@class tl.EnumType : tl.Type, tl.HasDeclName 242 | ---@field typename? "enum" 243 | ---@field enumset? { [string] : boolean } 244 | 245 | ---@class tl.Operator 246 | ---@field y? integer 247 | ---@field x? integer 248 | ---@field arity? integer 249 | ---@field op? string 250 | ---@field prec? integer 251 | 252 | ---@alias tl.NodeKind 253 | ---| "op" 254 | ---| "nil" 255 | ---| "string" 256 | ---| "number" 257 | ---| "integer" 258 | ---| "boolean" 259 | ---| "literal_table" 260 | ---| "literal_table_item" 261 | ---| "function" 262 | ---| "expression_list" 263 | ---| "enum_item" 264 | ---| "if" 265 | ---| "if_block" 266 | ---| "while" 267 | ---| "fornum" 268 | ---| "forin" 269 | ---| "goto" 270 | ---| "label" 271 | ---| "repeat" 272 | ---| "do" 273 | ---| "break" 274 | ---| "return" 275 | ---| "newtype" 276 | ---| "argument" 277 | ---| "type_identifier" 278 | ---| "variable" 279 | ---| "variable_list" 280 | ---| "statements" 281 | ---| "assignment" 282 | ---| "argument_list" 283 | ---| "local_function" 284 | ---| "global_function" 285 | ---| "local_type" 286 | ---| "global_type" 287 | ---| "record_function" 288 | ---| "local_declaration" 289 | ---| "global_declaration" 290 | ---| "identifier" 291 | ---| "cast" 292 | ---| "..." 293 | ---| "paren" 294 | ---| "macroexp" 295 | ---| "local_macroexp" 296 | ---| "interface" 297 | ---| "error_node" 298 | 299 | ---@alias tl.FactType 300 | ---| "is" type-based type judgement (its negation implies the subtracted type) 301 | ---| "==" value-based type judgement (its negation does not imply a subtracted type negated) 302 | ---| "not" negation: type-based judgements subtract, value-based judgements prove nothing 303 | ---| "and" conjunction: type-based judgements intersect, any value-based judgement downgrades all 304 | ---| "or" disjunction: type-based judgements unite, any value-based judgement downgrades all 305 | ---| "truthy" expression that is either truthy or a runtime error 306 | 307 | ---@class tl.Fact 308 | ---@field fact? tl.FactType 309 | ---@field w? tl.Where 310 | ---@field no_infer? boolean 311 | 312 | ---@class tl.TruthyFact : tl.Fact 313 | ---@overload fun(f1: tl.Fact, f2: tl.Fact): tl.TruthyFact 314 | ---@field fact? "truthy" 315 | 316 | ---@class tl.NotFact : tl.Fact 317 | ---@overload fun(f1: tl.Fact, f2: tl.Fact): tl.NotFact 318 | ---@field fact? "not" 319 | ---@field f1? tl.Fact 320 | 321 | ---@class tl.AndFact : tl.Fact 322 | ---@overload fun(f1: tl.Fact, f2: tl.Fact): tl.AndFact 323 | ---@field fact? "and" 324 | ---@field f1? tl.Fact 325 | ---@field f2? tl.Fact 326 | 327 | ---@class tl.OrFact : tl.Fact 328 | ---@overload fun(f1: tl.Fact, f2: tl.Fact): tl.OrFact 329 | ---@field fact? "or" 330 | ---@field f1? tl.Fact 331 | ---@field f2? tl.Fact 332 | 333 | ---@class tl.EqFact : tl.Fact 334 | ---@overload fun(f1: tl.Fact, f2: tl.Fact): tl.EqFact 335 | ---@field fact? "==" 336 | ---@field var? string 337 | ---@field typ? tl.Type 338 | 339 | ---@class tl.IsFact : tl.Fact 340 | ---@overload fun(f1: tl.Fact, f2: tl.Fact): tl.IsFact 341 | ---@field fact? "is" 342 | ---@field var? string 343 | ---@field typ? tl.Type 344 | 345 | ---@alias tl.KeyParsed 346 | ---| "short" 347 | ---| "long" 348 | ---| "implicit" 349 | 350 | ---@alias tl.Attribute string 351 | 352 | ---@alias tl.Narrow 353 | ---| "narrow" 354 | ---| "narrowed_declaration" 355 | ---| "declaration" 356 | 357 | ---@class tl.Variable 358 | ---@field t? tl.Type 359 | ---@field attribute? tl.Attribute 360 | ---@field needs_compat? boolean 361 | ---@field narrowed_from? tl.Type 362 | ---@field is_narrowed? tl.Narrow 363 | ---@field declared_at? tl.Node 364 | ---@field is_func_arg? boolean 365 | ---@field used? boolean 366 | ---@field used_as_type? boolean 367 | ---@field aliasing? tl.Variable 368 | ---@field implemented? { [string] : boolean } 369 | 370 | ---@class tl.Node.ExpectedContext 371 | ---@field kind? tl.NodeKind 372 | ---@field name? string 373 | 374 | ---@class tl.Node : tl.Where 375 | ---@field [integer] tl.Node 376 | ---@field tk? string 377 | ---@field kind tl.NodeKind 378 | ---@field symbol_list_slot? integer 379 | ---@field semicolon? boolean 380 | ---@field hashbang? string 381 | ---@field is_longstring? boolean 382 | ---@field yend? integer 383 | ---@field xend? integer 384 | ---@field known? tl.Fact 385 | ---@field expected? tl.Type 386 | ---@field expected_context? tl.Node.ExpectedContext 387 | ---@field key? tl.Node 388 | ---@field value? tl.Node 389 | ---@field key_parsed? tl.KeyParsed 390 | ---@field typeargs? tl.TypeArgType[] 391 | ---@field min_arity? integer 392 | ---@field args? tl.Node 393 | ---@field rets? tl.TupleType 394 | ---@field body? tl.Node 395 | ---@field implicit_global_function? boolean 396 | ---@field is_predeclared_local_function? boolean 397 | ---@field name? tl.Node 398 | ---@field attribute? tl.Attribute 399 | ---@field fn_owner? tl.Node 400 | ---@field is_method? boolean 401 | ---@field exp? tl.Node 402 | ---@field if_parent? tl.Node 403 | ---@field if_block_n? integer 404 | ---@field if_blocks? tl.Node[] 405 | ---@field block_returns? boolean 406 | ---@field var? tl.Node 407 | ---@field from? tl.Node 408 | ---@field to? tl.Node 409 | ---@field step? tl.Node 410 | ---@field vars? tl.Node 411 | ---@field exps? tl.Node 412 | ---@field newtype? tl.TypeType 413 | ---@field elide_type? boolean 414 | ---@field op? tl.Operator 415 | ---@field e1? tl.Node 416 | ---@field e2? tl.Node 417 | ---@field constnum? number 418 | ---@field conststr? string 419 | ---@field failstore? boolean 420 | ---@field discarded_tuple? boolean 421 | ---@field receiver? tl.Type 422 | ---@field array_len? integer 423 | ---@field is_total? boolean 424 | ---@field missing? string[] 425 | ---@field label? string 426 | ---@field used_label? boolean 427 | ---@field casttype? tl.Type 428 | ---@field is_lvalue? boolean 429 | ---@field macrodef? tl.Node 430 | ---@field expanded? tl.Node 431 | ---@field argtype? tl.Type 432 | ---@field itemtype? tl.Type 433 | ---@field decltuple? tl.TupleType 434 | ---@field opt? boolean 435 | ---@field debug_type? tl.Type 436 | 437 | ---@param contents string 438 | ---@param filename string 439 | ---@return tl.Node ast, tl.Error[] errors, string[] modules 440 | function tl.parse(contents, filename) end 441 | 442 | return tl 443 | --------------------------------------------------------------------------------