├── README.md ├── syntax.ebnf ├── LICENSE └── tact-design.md /README.md: -------------------------------------------------------------------------------- 1 | # Tact Documentation 2 | 3 | Tact is a programming language for writing multi-actor smart contracts in TON. 4 | 5 | This repository contains various documentation for the [Tact](https://tact-lang.org) language. 6 | 7 | * [📄 Design Documentation](tact-design.md) 8 | * [📄 Tact syntax (EBNF)](syntax.ebnf) 9 | -------------------------------------------------------------------------------- /syntax.ebnf: -------------------------------------------------------------------------------- 1 | letter = ? A-Za-z ?; 2 | digit = ? 0-9 ?; 3 | 4 | (* Common stuff *) 5 | ident = letter, { letter | digit | "_" }; 6 | typed ident = ident, ":", expr; 7 | int = ["-"], digit, {digit}; 8 | 9 | code block = "{", stmts, "}"; 10 | (* Note that generics in Tact is not same as generics in other languages. *) 11 | generics = "(", { typed ident, "," }, ")"; 12 | 13 | (* Expressions *) 14 | fn call = expr, "(", { expr, "," }, ")"; 15 | method call = expr, ".", ident, "(", { expr, "," }, ")"; 16 | field access = expr, ".", ident; 17 | struct constr = expr, "{", { ident, ":", expr, "," }, "}"; 18 | 19 | expr = struct def | struct constr | ident | field access | fn call | method call | fn def | int; 20 | 21 | (* Statements *) 22 | let = "let", ident, "=", expr; 23 | if = "if", "(", expr, ")", "{", stmts "}", [else]; 24 | else = "else", if | code_block; 25 | return = "return", expr; 26 | switch = "switch", "(", expr, ")", "{", { switch branch }, "}"; 27 | switch branch = "case", expr, ident, "=>", code_block; 28 | 29 | non semicolon stmt = if | code block | switch; 30 | semicolon stmt = let | expr | return; 31 | 32 | (* List of statements with possibly trailing semicolon. *) 33 | stmts = (non semicolon stmt, stmt) | 34 | (semicolon stmt, ";", [stmt]) | 35 | (semicolon stmt | non semicolon stmt); 36 | 37 | (* Functions *) 38 | fn sig = "(", { typed ident, "," }, ")", [ "->", expr ]; 39 | fn body = fn sig, "{", stmts, "}"; 40 | fn def = "fn", fn body; 41 | (* Note that "fn foo(x: T)(y: Z) ..." is valid syntax while "fn(x: T)(y: Z) ..." is invalid *) 42 | sugar fn def = "fn", ident, [generics], fn def; 43 | named fn sig = "fn", ident, [generics], fn sig; 44 | 45 | (* Structs *) 46 | struct field = "val", ident, ":" expr, [";"]; 47 | struct body = "{", { struct field }, { sugar fn def | impl intf } , "}"; 48 | struct def = "struct", struct body; 49 | sugar struct def = "struct", ident, [generics], struct body; 50 | 51 | (* Unions *) 52 | union case = "case", expr, [";"]; 53 | union body = "{", { union case }, { sugar fn def } , "}"; 54 | union def = "union", union body; 55 | sugar union def = "union", ident, [generics], union body; 56 | 57 | (* Interfaces *) 58 | intf body = "{", { named intf sig } , "}"; 59 | intf def = "interface", intf body; 60 | sugar intf def = "interface", ident, [generics], union body; 61 | impl intf = "impl", expr, "{", { sugar fn def }, "}"; 62 | 63 | (* Top level *) 64 | top_level_stmt = sugar fn def | sugar struct def | sugar union def | sugar intf def | let; 65 | program = { top_level_stmt }; 66 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /tact-design.md: -------------------------------------------------------------------------------- 1 | # Tact Design 2 | 3 | * [Why Tact?](#why-tact) 4 | * [Syntax overview](#syntax-overview) 5 | * [Type system](#type-system) 6 | * [Built-in types](#built-in-types) 7 | * [Standard types](#standard-types) 8 | * [Structs](#structs) 9 | * [Unions](#unions) 10 | * [Functions](#functions) 11 | * [Interfaces](#interfaces) 12 | * [Type Hiearchy](#type-hierarchy) 13 | * [Generics](#generics) 14 | * [Compile-time execution](#compile-time-execution) 15 | * [Compile-time reflection](#compile-time-reflection) 16 | * [Dependent types](#dependent-types) 17 | * [Higher-order types](#higher-order-types) 18 | * [Generic types](#generic-types) 19 | * [Generic functions](#generic-functions) 20 | * [Annotations](#annotations) 21 | * [Numerical bounds](#numerical-bounds) 22 | * [Representation in TVM](#representation-in-tvm) 23 | * [Memory Representation](#memory-representation) 24 | * [Mutability](#mutability) 25 | * [Serialization](#serialization) 26 | * [Namespaces and visibility](#namespaces-and-visibility) 27 | * [Operators](#operators) 28 | * [Control flow](#control-flow) 29 | * [Actors](#actors) 30 | 31 | 32 | ## Why Tact? 33 | 34 | Blockchains are naturally hard to scale and make tradeoffs between decentralization and expressiveness. 35 | TON offers a different tradeoff: actor-based architecture allows both decentralization and infinite scalability, 36 | but developers have to write complex multi-actor apps with asynchronous communication. 37 | 38 | Fift and FunC provide precise control over execution and require developer to keep in mind important aspects of cross-actor communication. 39 | To unleash the full power of TON architecture we need a higher-level language designed specifically for cross-actor communication. With a rich type system, automatic verification of complex invariants and assurances of correct gas usage across multiple actors in the system. 40 | 41 | ## Tact features 42 | 43 | **Actor-oriented:** Tact is designed specifically for the TON actor model. Strongly typed messages enforce communication contracts between actors. 44 | 45 | **High-level type system with algebraic types and numeric bounds** allows expressing precise invariants that can be checked statically. 46 | Compiler guides developer to put runtime checks where necessary to make the types match across actor and call boundaries. 47 | 48 | Tact offers **automatic serialization into cells** and **partial access to cells** to maximize efficiency while letting the developer focus on the problem at hand. 49 | 50 | **Gas control:** Tact makes cross-contract messages safe with precise gas commitments and compiler checks of the execution costs. 51 | Variable costs either have static bounds or will be checked explicitly in runtime. 52 | 53 | 54 | ## Syntax overview 55 | 56 | TBD: short examples and key points 57 | * variables 58 | * code style 59 | * comments 60 | * semicolons 61 | * types 62 | * generics 63 | * functions 64 | * methods 65 | * actors 66 | 67 | ``` 68 | #tact 1.0 69 | 70 | let CONSTANT = 1; 71 | 72 | fn plus_one(a: Int(8)) -> Int(257) { 73 | return a + 1; 74 | } 75 | 76 | ... 77 | ``` 78 | 79 | ## Type system 80 | 81 | TBD: a quick overview of the main features/aspects. 82 | 83 | * Strict type checking, no automatic casts. 84 | * Generics are supported via compile-time execution, where types are values. 85 | * Algebraic types: sum types (unions) and product types (structs). 86 | * Numeric bounds. 87 | 88 | 89 | ### Built-in types 90 | 91 | TBD: relation between TVM types and Tact types. 92 | 93 | #### Never 94 | 95 | The type that has no possible values. Used for eliminating branches of code and values. 96 | 97 | ``` 98 | let Never = builtin::Never; 99 | ``` 100 | 101 | #### Null 102 | 103 | ``` 104 | let Null = builtin::NULL; 105 | ``` 106 | 107 | #### Integers 108 | 109 | The default integer type is an `Integer` type which is a big integer - i.e. has no constraints about possible range. This type is primarily used by the compile-time functions and by compiler built-in types. All numeric literals have the type `Integer`. 110 | 111 | Type `Int` is a type based on the `Integer` type but has constraints on the possible range of values. To be clear, `Int` is a function that takes a number and returns a type, for example, `Int(257)` is an integer that accepts numbers in the range -2^256..2^256 which corresponds to the `int257` type from FunC or TVM. It is also possible to declare integers with different ranges, for example, `Int(64)` which accepts integers in the range -2^63..2^63, etc. 112 | 113 | Since `Int` is a struct type it cannot be created directly from the literal (can be changed in the future). To create a value of type `Int(257)`, you need to call method `new`, for example, `Int(257).new(10)`. 114 | 115 | Note that types with different ranges of values cannot be used simultaneously - they have different types, i.e. `Integer` ≠ `Int(257)` ≠ `Int(64)`. 116 | 117 | This separation between `Integer` and `Int` was made for the following reasons: 118 | 1. Tact has compile-time functions that may want to operate on a different range of types than `Int257` from TVM. 119 | 2. We want to add custom-ranged integer types. 120 | 121 | #### Cell 122 | 123 | `Cell` is a built-in type. It has no methods currently. `Cell` can be made from `Builder` by a `builder.build()`. 124 | 125 | `Builder` is a built-in type. It has a few methods: 126 | 1. `Builder.new()` method will create an empty builder. It is analog to the `NEWC` instruction. 127 | 2. `builder.store_int(value, bits)` method will add a value of type `Integer` to the builder. It is analog to the `STIQ` instruction. Note that if you want to store value with `Int` type you need to use other methods. 128 | 3. `builder.build()` method will create a `Cell` from the builder. It is analog to the `ENDC` instruction. 129 | 130 | #### Tuples? 131 | 132 | TBD? 133 | 134 | 135 | ### Standard types 136 | 137 | TBD: what do we ship as a standard library: ranges, subranges of integers, Option/Result etc? 138 | 139 | 140 | 141 | ## Structs 142 | 143 | TBD: define structs without introducing generics first. Generics will be dealt in a separate section. 144 | 145 | Structs (aka "product types") allow multiple fields of different types that exists as one entity. Product types have fields and methods — functions that operate with these fields. 146 | 147 | Example of the declaration of the struct: 148 | ``` 149 | let Foo = struct { 150 | // val keyword is required to declare fields 151 | val field1: Type1 152 | val field2: Type2 153 | 154 | // Free method that can be called as Foo.free_methods() 155 | fn free_method() { /* implementation */ } 156 | // Method that can be called only on Foo instance 157 | fn method(self: Self) { /* implementation */ } 158 | }; 159 | ``` 160 | 161 | or using a sugared version: 162 | ``` 163 | struct Foo { 164 | /* fields and methods */ 165 | } 166 | ``` 167 | 168 | It is also possible to generalize structs using compile-time functions. To learn more, see the [Generics section](#generics). 169 | 170 | Usage of the struct types: 171 | ``` 172 | // Type construction 173 | let foo = Foo{field1: value1, field: value2, /* etc */}; 174 | 175 | // Type deconstruction (isn't supported by the compiler, can be changed in the future): 176 | let Foo{field1: binding_name1, field2: binding_name2} = foo; 177 | let Foo{field1: binding_name1, _} = foo; 178 | 179 | // Get acces to the field 180 | let _ = foo.field1; 181 | 182 | // Call free method 183 | let _ = Foo.free_method(); 184 | // Call method 185 | let _ = foo.method(); 186 | ``` 187 | 188 | ### Unions 189 | 190 | Union (aka sum-type) means it is a type that can be one of the multiple possible options. The difference between unions (in Tact) and tagged unions (in Rust, Haskell, Scala) is that any variant in tagged unions must be created using a constructor, while in unions there are no constructors at all. Union is a structural typing type-sum while tagged union is a nominative typing type-sum. 191 | 192 | Union type definition: 193 | ``` 194 | let UnionType = union { 195 | case Type1; 196 | case Type2; 197 | 198 | // Free method that can be called as UnionType.free_methods() 199 | fn free_method() { /* implementation */ } 200 | // Method that can be called only at UnionType instance 201 | fn method(self: Self) { /* implementation */ } 202 | }; 203 | ``` 204 | 205 | or using a sugared version: 206 | 207 | ``` 208 | union UnionType { 209 | /* cases and methods */ 210 | } 211 | ``` 212 | 213 | It is also possible to generalize structs using compile-time functions. To learn more, see the [Generics section](#generics). 214 | 215 | When a union was declared, also were declared cases - its possible variants. Case is a type that is a possible option of a union. There are possible to use a case when the union was expected, but there is no way to use union when concrete type was expected. 216 | 217 | ``` 218 | struct Red{} 219 | struct Green{val field: Type} 220 | enum RG { case Red; case Green; } 221 | 222 | // Create union instance 223 | let x: RG = Red{}; 224 | // Match union instance 225 | switch (x) { 226 | case Red x => { /* x has type Red */ } 227 | case Green {field} => { /* field has type Red */ } 228 | } 229 | ``` 230 | 231 | #### Union subtyping 232 | 233 | ``` 234 | struct Red{} 235 | struct Green{} 236 | enum RG { case Red; case Green; } 237 | 238 | // It is allowed here to pass Red, Green, RG types as argument but return value can have only `RG` type. 239 | fn function(arg: RG) -> RG { arg } 240 | 241 | let x: RG = Green{}; 242 | let test1: RG = function(Red{}); // OK. 243 | let test2: RG = function(x); // OK. 244 | let test3: Red = function(Red{}); // ERR: expected `RG` type, found `Red`. 245 | ``` 246 | 247 | #### Union extending 248 | ``` 249 | struct Red{} 250 | struct Green{} 251 | enum RG { case Red; case Green; } 252 | 253 | // This: 254 | enum RGB { case RG; case Blue; } 255 | // is equivalent with this: 256 | enum RGB { case Red; case Green; case Blue; } 257 | ``` 258 | 259 | #### Why not tagged unions? 260 | 261 | When unions were discussed, all developers suggest that tagged unions have many ergonomic problems: 262 | 1. Hard to create and unpack. 263 | 2. Constructors are not types. 264 | 3. Making one tagged union from another isn't a simple operation. 265 | 266 | ### Functions 267 | 268 | Functions in Tact are like functions in other programming languages. They have a list of typed arguments and a body. When a function is called it returns some value or does something. 269 | 270 | The declaration of the function is as follows: 271 | ``` 272 | let func = fn(arg1: Type1, arg2: Type2, ...) -> Type { 273 | /* body of stmts */ 274 | } 275 | ``` 276 | or using a sugared version: 277 | ``` 278 | fn func(arg1: Type1, arg2: Type2, ...) -> Type { 279 | /* body of stmts */ 280 | } 281 | ``` 282 | 283 | It is also possible to generalize functions using compile-time functions. To learn more, see the [Generics section](#generics). 284 | 285 | It is possible to create anonymous functions, i.e. function without names and use them in place as follows: 286 | ``` 287 | let two = (fn(x: Int) { x + 1 })(1); 288 | ``` 289 | 290 | ### Interfaces 291 | 292 | Interface in Tact is an object that describes which functions other types that implement this interface should contain. When a type decides to implement an interface it must provide an implementation of all functions from the interface definition with concrete signatures. 293 | 294 | Interfaces are a default way to polymorphic computation. For example, 295 | 296 | To define an interface, use the following syntax: 297 | ``` 298 | interface InterfaceName { 299 | fn function_name(arg: Ty) -> ReturnTy 300 | fn second_function(...) -> ... 301 | ... 302 | } 303 | ``` 304 | 305 | When struct or union should implement an interface, the following construction should be used: 306 | ``` 307 | struct Foo { 308 | /* fields and function */ 309 | impl InterfaceName { 310 | /* interface functions implementation */ 311 | } 312 | } 313 | ``` 314 | 315 | Then, functions defined in the `impl` body can be used as functions declared in the struct body, like in the following example: 316 | ``` 317 | interface Test { 318 | fn static_fn() 319 | fn method_fn(self: Self) 320 | } 321 | struct Empty { 322 | impl Test { 323 | fn static_fn() {} 324 | fn method_fn(self: Self) {} 325 | } 326 | } 327 | let _ = Empty.static_fn(); 328 | let _ = Empty{}.method_fn(); 329 | ``` 330 | 331 | #### Use interface to constraint a type 332 | 333 | Primarily goal of the interfaces is to add a possibility to constrain types. When type is constrained - it means that the input type should implement an interface, otherwise type-checker will throw a compile error. 334 | 335 | ``` 336 | fn serialize_pair(A: Serialize, B: Serialize)(arg1: A, arg2: B) -> Builder { 337 | let b = Builder.new(); 338 | let b = arg1.serialize(b); 339 | let b = arg2.serialize(b); 340 | return b; 341 | } 342 | ``` 343 | 344 | In the above example function with 2 generic types were declared. These generic types are constrained over `Serialize` interface, so if this function will be called with types that do not implement `Serialize` interface, compile error will be thrown. 345 | 346 | ``` 347 | let _ = serialize_pair(Int(64), Int(128))(...); // OK: Int type implements `Serialize` 348 | let _ = serialize_pair(Builder, Slice)(...); // ERR: Builder and Slice does not implement `Serialize` 349 | ``` 350 | 351 | More about how constraints work you can find in the [Type Hierarchy section](#type-hierarchy). 352 | 353 | ## Type hierarchy 354 | 355 | With the rigid separation of programs by types and terms, there is no need to introduce type hierarchies. But in Tact types are terms, so it needs to introduce a type hierarchy that allows differentiation between types and types of types (e.g. type `Type`). 356 | 357 | Currently, the type hierarchy in Tact is as follows: 358 | 1. Runtime values have types `Int`, `Builder`, etc. 359 | 2. Values `Int`, `Bool`, etc. have type `Type 0`. 360 | 3. Value `Type N` has type `Type N+1`. 361 | 362 | Hierarchy of integer type: 363 | 364 |
| Value | 367 |Type | 368 |
| 1, 2, 3... | 371 |Integer | 372 |
| Integer | 375 |Type 0 | 376 |
| Type N | 379 |Type N+1 | 380 |