-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Tolk Language: next-generation FunC #1345
Conversation
The Tolk Language will be positioned as "next-generation FunC". It's literally a fork of a FunC compiler, introducing familiar syntax similar to TypeScript, but leaving all low-level optimizations untouched. Note, that FunC sources are partially stored in the parser/ folder (shared with TL/B). In Tolk, nothing is shared. Everything from parser/ is copied into tolk/ folder.
All changes from PR "FunC v0.5.0": #1026 Instead of developing FunC, we decided to fork it. BTW, the first Tolk release will be v0.6, a metaphor of FunC v0.5 that missed a chance to occur.
As it turned out, PSTRING() created a buffer of 128K. If asm_code exceeded this buffer, it was truncated. I've just dropped PSTRING() from there in favor of std::string.
A new lexer is noticeably faster and memory efficient (although splitting a file to tokens is negligible in a whole pipeline). But the purpose of rewriting lexer was not just to speed up, but to allow writing code without spaces: `2+2` is now 4, not a valid identifier as earlier. The variety of symbols allowed in identifier has greatly reduced and is now similar to other languages. SrcLocation became 8 bytes on stack everywhere. Command-line flags were also reworked: - the input for Tolk compiler is only a single file now, it's parsed, and parsing continues while new #include are resolved - flags like -A -P and so on are no more needed, actually
Several related changes: - stdlib.tolk is embedded into a distribution (deb package or tolk-js), the user won't have to download it and store as a project file; it's an important step to maintain correct language versioning - stdlib.tolk is auto-included, that's why all its functions are available out of the box - strict includes: you can't use symbol `f` from another file unless you've #include'd this file - drop all C++ global variables holding compilation state, merge them into a single struct CompilerState located at compiler-state.h; for instance, stdlib filename is also there
Now, the whole .tolk file can be loaded as AST tree and then converted to Expr/Op. This gives a great ability to implement AST transformations. In the future, more and more code analysis will be moved out of legacy to AST-level.
Since I've implemented AST, now I can drop forward declarations. Instead, I traverse AST of all files and register global symbols (functions, constants, global vars) as a separate step, in advance. That's why, while converting AST to Expr/Op, all available symbols are already registered. This greatly simplifies "intermediate state" of yet unknown functions and checking them afterward. Redeclaration of local variables (inside the same scope) is now also prohibited.
Lots of changes, actually. Most noticeable are: - traditional //comments - #include -> import - a rule "import what you use" - ~ found -> !found (for -1/0) - null() -> null - is_null?(v) -> v == null - throw is a keyword - catch with swapped arguments - throw_if, throw_unless -> assert - do until -> do while - elseif -> else if - drop ifnot, elseifnot - drop rarely used operators A testing framework also appears here. All tests existed earlier, but due to significant syntax changes, their history is useless.
- split stdlib.tolk into multiple files (tolk-stdlib/ folder) (the "core" common.tolk is auto-imported, the rest are needed to be explicitly imported like "@stdlib/tvm-dicts.tolk") - all functions were renamed to long and clear names - new naming is camelCase
This is a very big change. If FunC has `.methods()` and `~methods()`, Tolk has only dot, one and only way to call a `.method()`. A method may mutate an object, or may not. It's a behavioral and semantic difference from FunC. - `cs.loadInt(32)` modifies a slice and returns an integer - `b.storeInt(x, 32)` modifies a builder - `b = b.storeInt()` also works, since it not only modifies, but returns - chained methods also work, they return `self` - everything works exactly as expected, similar to JS - no runtime overhead, exactly same Fift instructions - custom methods are created with ease - tilda `~` does not exist in Tolk at all
Instead on 'ton_crypto', Tolk now depends on 'ton_crypto_core'. The only purpose of ton_crypto (in FunC also, btw) is address parsing: "EQCRDM9...", "0:52b3..." and so on. Such parsing has been implemented manually exactly the same way.
Unary logical NOT was already implemented earlier. Logical AND OR are expressed via conditional expression: * a && b -> a ? (b != 0) : 0 * a || b -> a ? 1 : (b != 0) They work as expected in any expressions. For instance, having `cond && f()`, f is called only if cond is true. For primitive cases, like `a > 0 && b > 0`, Fift code is not optimal, it could potentially be without IFs. These are moments of future optimizations. For now, it's more than enough.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Solana
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Solaaana
Tolk is a new language for writing smart contracts in TON. Think of Tolk as the "next‑generation FunC". Tolk compiler is literally a fork of FunC compiler, introducing familiar syntax similar to TypeScript, but leaving all low-level optimizations untouched.
Motivation behind Tolk
FunC is awesome. It is really low-level and encourages a programmer to think about compiler internals. It gives full control over TVM assembler, allowing a programmer to make his contract as effective as possible. If you get used to it, you love it.
But there is a problem. FunC is "functional C", and it's for ninja. If you are keen on Lisp and Haskell, you'll be happy. But if you are a JavaScript / Go / Kotlin developer, its syntax is peculiar for you, leading to occasional mistakes. A struggle with syntax may decrease your motivation for digging into TON.
Imagine, what if there was a language, also smart, also low-level, but not functional and not like C? Leaving all beauty and complexity inside, what if it would be more similar to popular languages at first glance?
That's what Tolk is about.
Meaning of the name "Tolk"
"Tolk" is a very beautiful word.
In English, it's consonant with talk. Because, generally, what do we need a language for? We need it to talk to computers.
In all slavic languages, the root tolk and the phrase "to have tolk" means "to make sense"; "to have deep internals".
But actually, TOLK is an abbreviation.
You know, that TON is The Open Network.
By analogy, TOLK is The Open Language K.
What is K, will you ask? Probably, "kot" — the nick of Nikolay Durov? Or Kolya? Kitten? Kernel? Kit? Knowledge?
The right answer — none of this. This letter does not mean anything. It's open.
The Open Letter K
History of Tolk origin
In June 2024, I created a pull request FunC v0.5.0. Besides this PR, I've written a roadmap — what can be enhanced in FunC, syntactically and semantically.
All in all, instead of merging v0.5.0 and continuing developing FunC, we decided to fork it. To leave FunC untouched, as it is. As it always was. And to develop a new language, driven by a fresh and new name.
For several months, I have worked on Tolk privately. I have implemented a giant list of changes. And it's not only about the syntax. For instance, Tolk has an internal AST representation, completely missed in FunC.
On TON Gateway, on 1-2 November in Dubai, I had a speech presenting Tolk to the public, and we released it the same day. The video is available on YouTube.
The first version of the Tolk Language is v0.6, a metaphor of FunC v0.5 that missed a chance to occur.
Tolk vs FunC: in short
Tolk is much more similar to TypeScript and Kotlin than to C and Lisp. But it still gives you full control over TVM assembler, since it has a FunC kernel inside.
fun
, get methods viaget
, variables viavar
(andval
for immutable), putting types on the right; parameter types are mandatory; return type can be omitted (auto inferred), as well as for locals; specifiersinline
and others are@
attributesimpure
, it's by default, compiler won't drop user function callsrecv_internal
andrecv_external
, butonInternalMessage
andonExternalMessage
2+2
is 4, not an identifier; identifiers are alpha-numeric; use namingconst OP_INCREASE
instead ofconst op::increase
&&
, OR||
, NOT!
are supported;; comment
→// comment
{- comment -}
→/* comment */
#include
→import
, with a strict rule "import what you use"~ found
→!found
(for true/false only, obviously) (true is -1, like in FunC)v = null()
→v = null
null?(v)
→v == null
, same forbuilder_null?
and others~ null?(v)
→c != null
throw(excNo)
→throw excNo
catch(_, _)
→catch
catch(_, excNo)
→catch(excNo)
throw_unless(excNo, cond)
→assert(cond, excNo)
throw_if(excNo, cond)
→assert(!cond, excNo)
return ()
→return
do ... until (cond)
→do ... while (!cond)
elseif
→else if
ifnot (cond)
→if (!cond)
verboseclear names, camelCase style; it's now embedded, not downloaded from GitHub; it's split into several files; common functions available always, more specific available withimport "@stdlib/tvm-dicts"
, IDE will suggest you~
tilda methods;cs.loadInt(32)
modifies a slice and returns an integer;b.storeInt(x, 32)
modifies a builder;b = b.storeInt()
also works, since it not only modifies, but returns; chained methods work identically to JS, they returnself
; everything works exactly as expected, similar to JS; no runtime overhead, exactly same Fift instructions; custom methods are created with ease; tilda~
does not exist in Tolk at allTooling around:
Tolk vs FunC: in detail
A very huge list below. Will anyone have enough patience to read it up to the end?..
✅ Traditional comments :)
;; comment
// comment
{- multiline comment -}
/* multiline comment */
✅
2+2
is 4, not an identifier. Identifiers can only be alpha-numericIn FunC, almost any character can be a part of identifier. For example,
2+2
(without a space) is an identifier. You can even declare a variable with such a name.In Tolk, spaces are not mandatory.
2+2
is 4, as expected.3+~x
is3 + (~ x)
, and so on.return 2+2; ;; undefined function `2+2`
return 2+2; // 4
More precisely, an identifier can start from
[a-zA-Z$_]
and be continued with[a-zA-Z0-9$_]
. Note, that?
,:
, and others are not valid symbols,found?
andop::increase
are not valid identifiers.You can use backticks to surround an identifier, and then it can contain any symbols (similar to Kotlin and some other langs). Its potential usage is to allow keywords be used as identifiers, in case of code generation by a scheme, for example.
const op::increase = 0x1234;
const OP_INCREASE = 0x1234;
✅ Impure by default, compiler won't drop user function calls
FunC has an
impure
function specifier. When absent, a function is treated as pure. If its result is unused, its call was deleted by the compiler.Though this behavior is documented, it is very unexpected to newcomers. For instance, various functions that don't return anything (throw an exception on mismatch, for example), are silently deleted. This situation is spoilt by the fact that FunC doesn't check and validate function body, allowing impure operations inside pure functions.
In Tolk, all functions are impure by default. You can mark a function pure with annotation, and then impure operations are forbidden in its body (exceptions, globals modification, calling non-pure functions, etc.).
✅ New functions syntax:
fun
keyword,@
attributes, types on the right (like in TypeScript, Kotlin, Python, etc.)cell parse_data(slice cs) { }
fun parse_data(cs: slice): cell { }
(cell, int) load_storage() { }
fun load_storage(): (cell, int) { }
() main() { ... }
fun main() { ... }
Types of variables — also to the right:
slice cs = ...;
var cs: slice = ...;
(cell c, int n) = parse_data(cs);
var (c: cell, n: int) = parse_data(cs);
global int stake_at;
global stake_at: int;
Modifiers
inline
and others — with annotations:global int stake_at;
global stake_at: int;
forall
— this way:forall X -> tuple cons(X head, tuple tail)
fun cons<X>(head: X, tail: tuple): tuple
asm
implementation — like in FunC, but being properly aligned, it looks nicer:There is also a
@deprecated
attribute, not affecting compilation, but for a human and IDE.✅
get
instead ofmethod_id
In FunC,
method_id
(without arguments) actually declared a get method. In Tolk, you use a straightforward syntax:int seqno() method_id { ... }
get seqno(): int { ... }
Both
get methodName()
andget fun methodName()
are acceptable.For
method_id(xxx)
(uncommon in practice, but valid), there is an attribute:✅ It's essential to declare types of parameters (though optional for locals)
There is an
auto
type, sofun f(a: auto)
is valid, though not recommended.If parameter types are mandatory, return type is not (it's often obvious of verbose). If omitted, it means
auto
:For local variables, types are also optional:
✅ Variables are not allowed to be redeclared in the same scope
As a consequence, partial reassignment is not allowed:
Note, that it's not a problem for
loadUint()
and other methods. In FunC, they returned a modified object, so a patternvar (cs, int value) = cs.load_int(32)
was quite common. In Tolk, such methods mutate an object:var value = cs.loadInt(32)
, so redeclaration is unlikely to be needed.✅ Changes in the type system
Type system in the first Tolk release is the same as in FunC, with the following modifications:
void
is effectively an empty tensor (more canonical to be namedunit
, butvoid
is more reliable); btw,return
(without expression) is actuallyreturn ()
, a convenient way to return from void functionsauto
mean "auto infer"; in FunC,_
was used for that purpose; note, that if a function doesn't specify return type, it'sauto
, notvoid
self
, to make chainable methods, described below; actually it's not a type, it can only occur instead of return type of a functioncont
renamed tocontinuation
✅ Another naming for recv_internal / recv_external
All parameter types and their order rename the same, only naming is changed.
fun main
is also available.✅ #include → import. Strict imports
#include "another.fc";
import "another.tolk"
In Tolk, you can not used a symbol from
a.tolk
without importing this file. In other words, "import what you use".All stdlib functions are available out of the box, downloading stdlib and
#include "stdlib.fc"
is not needed. See below about embedded stdlib.There is still a global scope of naming. If
f
is declared in two different files, it's an error. We "import" a whole file, no per-file visibility andexport
keyword is now supported, but probably will be in the future.✅ #pragma → compiler options
In FunC, "experimental" features like
allow-post-modifications
were turned on by a pragma in .fc files (leading to problems when some files contain it, some don't). Indeed, it's not a pragma for a file, it's a compilation option.In Tolk, all pragmas were removed.
allow-post-modification
andcompute-asm-ltr
were merged into Tolk sources (as if they were always on in FunC). Instead of pragmas, there is now an ability to pass experimental options.As for now, there is one experimental option introduced —
remove-unused-functions
, which doesn't include unused symbols to Fift output.#pragma version xxx
was replaced bytolk xxx
(no >=, just a strict version). It's good practice to annotate compiler version you are using. If it doesn't match, Tolk will show a warning.✅ Late symbols resolving. AST representation
In FunC (like in С) you can not access a function declared below:
To avoid an error, a programmer should create a forward declaration at first. The reason is that symbols resolving is performed right at the time of parsing.
Tolk compiler separates these two steps. At first it does parsing, and then it does symbol resolving. Hence, a snippet above would not be erroneous.
Sounds simple, but internally, it's a very huge job. To make this available, I've introduced an intermediate AST representation, completely missed in FunC. That's an essential point of future modifications and performing semantic code analisys.
✅
null
keywordCreating null values and checking variables on null looks very pretty now.
a = null()
a = null
if (null?(a))
if (a == null)
if (~ null?(b))
if (b != null)
if (~ cell_null?(c))
if (c != null)
Note, that it does NOT mean that Tolk language has nullability. No, you can still assign
null
to an integer variable — like in FunC, just syntactically pleasant. A true nullability will be available someday, after hard work on the type system.✅
throw
andassert
keywordsTolk greatly simplifies working with exceptions.
If FunC has
throw()
,throw_if()
,throw_arg_if()
, and the same for unless, Tolk has only two primitives:throw
andassert
.throw(excNo)
throw excNo
throw_arg(arg, excNo)
throw (excNo, arg)
throw_unless(excNo, condition)
assert(condition, excNo)
throw_if(excNo, condition)
assert(!condition, excNo)
Note, that
!condition
is possible since logical NOT is available, see below.There is a long (verbose) syntax of
assert(condition, excNo)
:Also, Tolk swaps
catch
arguments: it'scatch (excNo, arg)
, both optional (since arg is most likely empty).try { } catch (_, _) { }
try { } catch { }
try { } catch (_, excNo) { }
try { } catch(excNo) { }
try { } catch (arg, excNo) { }
try { } catch(excNo, arg) { }
✅
do ... until
→do ... while
do { ... } until (~ condition);
do { ... } while (condition);
do { ... } until (condition);
do { ... } while (!condition);
Note, that
!condition
is possible since logical NOT is available, see below.✅ Operator precedence became identical to C++ / JavaScript
In FunC, such code
if (slices_equal() & status == 1)
is parsed asif( (slices_equal()&status) == 1 )
. This is a reason of various errors in real-world contracts.In Tolk,
&
has lower priority, identical to C++ and JavaScript.Moreover, Tolk fires errors on potentially wrong operators usage to completely eliminate such errors:
will lead to a compilation error (similar to gcc/clang):
Hence, the code should be rewritten:
I've also added a diagnostic for a common mistake in bitshift operators:
a << 8 + 1
is equivalent toa << 9
, probably unexpected.Operators
~% ^% /% ~/= ^/= ~%= ^%= ~>>= ^>>=
no longer exist.✅ Immutable variables, declared via
val
Like in Kotlin:
var
for mutable,val
for immutable, optionally followed by a type. FunC has no analogue ofval
.Parameters of a function are mutable, but since they are copied by value, called arguments aren't changed. Exactly like in FunC, just to clarify.
In Tolk, a function can declare
mutate
parameters. It's a generalization of FunC~
tilda functions, read below.✅ Deprecated command-line options removed
Command-line flags
-A
,-P
, and others, were removed. Default behavioris more than enough. Use
-v
to print version and exit. Use-h
for all available command-line flags.Only one input file can be passed, others should be
import
'ed.✅ stdlib functions renamed to
verboseclear names, camelCase styleAll naming in standard library was reconsidered. Now, functions are named using longer, but clear names.
A former "stdlib.fc" was split into multiple files: common.tolk, tvm-dicts.tolk, and others.
✅ stdlib is now embedded, not downloaded from GitHub
Download stdlib.fc from GitHub
Save into your project
#include "stdlib.fc";
Use standard functions
In Tolk, stdlib a part of distribution. Standard library is inseparable, since keeping a triple "language, compiler, stdlib" together is the only correct way to maintain release cycle.
It works in such a way. Tolk compiler knows how to locate a standard library. If a user has installed an apt package, stdlib sources were also downloaded and exist on a hard disk, so the compiler locates them by system paths. If a user uses a WASM wrapper, they are provided by tolk-js. And so on.
Standard library is split into multiple files:
common.tolk
(most common functions),gas-payments.tolk
(calculating gas fees),tvm-dicts.tolk
, and others. Functions fromcommon.tolk
are available always (a compiler implicitly imports it). Other files are needed to be explicitly imported:Mind the rule "import what you use", it's applied to
@stdlib/...
files also (with the only exception of "common.tolk").JetBrains IDE plugin automatically discovers stdlib folder and inserts necessary imports as you type.
✅ Logical operators
&& ||
, logical not!
In FunC, there are only bitwise operators
~ & | ^
. Developers making first steps, thinking "okay, no logical, I'll use bitwise in the same manner", often do errors, since operator behavior is completely different:a & b
a && b
0 & X = 0
0 & X = 0
-1 & X = -1
-1 & X = -1
1 & 2 = 0
1 && 2 = -1 (true)
~ found
!found
true (-1) → false (0)
-1 → 0
false (0) → true (-1)
0 → -1
1 → -2
1 → 0 (false)
condition & f()
condition && f()
f()
is called alwaysf()
is called only ifcondition
condition | f()
condition || f()
f()
is called alwaysf()
is called only ifcondition
is falseTolk supports logical operators. They behave exactly as you get used to (right column). For now,
&&
and||
sometimes produce not optimal Fift code, but in the future, Tolk compiler will become smarter in this case. It's negligible, just use them like in other languages.if (~ found?)
if (!found)
ifnot (cell_null?(signatures))
if (signatures != null)
elseifnot (eq_checksum)
else if (!eqChecksum)
Keywords
ifnot
andelseifnot
were removed, since now we have logical not (for optimization, Tolk compiler generatesIFNOTJMP
, btw). Keywordelseif
was replaced by traditionalelse if
.Note, that it does NOT mean that Tolk language has
bool
type. No, comparison operators still return an integer. Abool
type support will be available someday, after hard work on the type system.Remember, that
true
is -1, not 1. Both in FunC and Tolk. It's a TVM representation.✅ No tilda
~
methods,mutate
keyword insteadThis change is so huge that it's described in a separate section:
Tolk
mutate
vs FunC~
tilda functionsTLDR:
~
tilda methodscs.loadInt(32)
modifies a slice and returns an integerb.storeInt(x, 32)
modifies a builderb = b.storeInt()
also works, since it not only modifies, but returnsself
~
does not exist in Tolk at allThis is a drastic change. If FunC has
.methods()
and~methods()
, Tolk has only dot, one and only way to call a.method()
. A method may mutate an object, or may not. Unlike the list "in short", it's a behavioral and semantic difference from FunC.The goal is to have calls identical to JS and other languages:
In order to make this available, Tolk offers a mutability conception, which is a generalization of what a tilda means in FunC.
By default, all arguments are copied by value (identical to FunC)
Same goes for cells, slices, whatever:
It means, that when you call a function, you are sure that original data is not modified.
mutate
keyword and mutating functionsBut if you add
mutate
keyword to a parameter, a passed argument will be mutated. To avoid unexpected mutations, you must specifymutate
when calling it, also:Same for slices and any other types:
It's a generalization. A function may have several mutate parameters:
You may ask — is it just passing by reference? It effectively is, but since "ref" is an overloaded term in TON (cells and slices have refs), a keyword
mutate
was chosen.self
parameter turning a function into a methodWhen a first parameter is named
self
, it emphasizes that a function (still a global one) is a method and should be called via dot.self
, withoutmutate
, is immutable (unlike all other parameters). Think of it like "read-only method".Combining
mutate
andself
, we get mutating methods.mutate self
is a method, called via dot, mutating an objectAs follows:
If you take a look into stdlib, you'll notice, that lots of functions are actually
mutate self
, meaning they are methods, modifying an object. Tuples, dictionaries, and so on. In FunC, they were usually called via tilda.return self
makes a method chainableExactly like
return self
in Python orreturn this
in JavaScript. That's what makes methods likestoreInt()
and others chainable.Pay attention to the return type, it's
self
. Currently, you should specify it. Being left empty, compilation will fail. Probably, in the future it would be correct.mutate self
and asm functionsWhile it's obvious for user-defined functions, one could be interested, how to make an
asm
function with such behavior? To answer this question, we should look under the hood, how mutation works inside the compiler.When a function has
mutate
parameters, it actually implicitly returns them, and they are implicitly assigned to arguments. It's better by example:So, an
asm
function should placeself'
onto a stack before its return value:Note, that to return self, you don't have to do anything special, just specify a return type. Compiler will do the rest.
It's very unlikely you'll have to do such tricks. Most likely, you'll just write wrappers around existing functions:
Do I need
@inline
for simple functions/methods?For now, better do it, yes. In most examples above,
@inline
was omitted for clarity. Currently, without@inline
, it will be a separate TVM continuation with jumps in/out. With@inline
, a function will be generated, but inlined by Fift (likeinline
specifer in FunC).In the future, Tolk will automatically detect simple functions and perform a true inlining by itself, on AST level. Such functions won't be even codegenerated to Fift. The compiler would decide, better than a human, whether to inline, to make a ref, etc. But it will take some time for Tolk to become so smart :) For now, please specify the
@inline
attribute.But
self
is not a method, it's still a function! I feel like I've been cheatedAbsolutely. Like FunC, Tolk has only global functions (as of v0.6). There are no classes / structures with methods. There are no methods
hash()
forslice
andhash()
forcell
. Instead, there are functionssliceHash()
andcellHash()
, which can be called either like functions or by dot (preferred):In the future, after a giant work on the type system, having fully refactored FunC kernel inside, Tolk might have an ability of declaring structures with real methods, generalized enough for covering built-in types. But it will take a long journey to follow.
Tolk vs FunC gas consumption
TLDR: Tolk gas consumption could be a bit higher, because it fixes unexpected arguments shuffling in FunC. It's negligible in practice. In the future, Tolk compiler will become smart enough to reorder arguments targeting less stack manipulations, but still avoiding a shuffling problem.
FunC compiler could unexpectedly shuffle arguments when calling an assembly function:
Sometimes,
f2()
could be called beforef1()
, and it's unexpected. To fix this behavior, one could specify#pragma compute-asm-ltr
, forcing arguments to be always evaluated in ltr-order. This was experimental, and therefore turned off by default.This pragma reorders arguments on a stack, often leading to more stack manipulations than without it. In other words, in fixes unexpected behavior, but increases gas consumption.
Tolk puts arguments onto a stack exactly the same as if this pragma turned on. So, its gas consumption is sometimes higher than in FunC if you didn't use this pragma. Of course, there is no shuffling problem in Tolk.
In the future, Tolk compiler will become smart enough to reorder arguments targeting less stack manipulations, but still avoiding a shuffling problem.
Some technical details
Here I keep a list of points not seen by a user's eye, but related to implementation.
{repo}/tolk
. All tests are in{repo}/tolk-tester
.lexer.cpp
), it's not unified with TL/B. Spaces in .tolk files are not mandatory (2+2
is 4, identifiers are alpha-numeric), lexing works based on Trie. A new lexer is faster than an old one (though lexing part is negligible in all the process, of course).ast.h
for comments.CompilerState G
, the only C++ global variable in Tolk compiler. Seecompiler-state.h
.te_ForAll
(just having new<T>
syntax), but it will be resonsidered some day.Asm.fif
was not modified. Tolk entrypoint isonInternalMessage
(notrecv_internal
), but whereas method_id for recv_internal is generated by Fift, method_id for onInternalMessage is generated by Tolk compiler itself withDECLMETHOD
in fif output.&& ||
are expressed as ternary expressions:a && b
→a ? !!b : 0
,a || b
→a ? -1 : !!b
, later generated asIFJMP
to Fift. For simple cases, codegeneration could avoid jumps, but I had no time for optimizing it. So, logical operators exist and work, but not gas-optimal in simple cases. To be improved in future releases.crypto/smartcont/tolk-stdlib/
folder. It's placed there, becausesmartcont
is copied as-is into apt packages./usr/bin/tolk
), locate stdlib in/usr/share/ton/smartcont
. When it's built from sources (e.g.~/ton/cmake-build-debug/tolk/tolk
), check the~/ton/crypto/smartcont
folder. If a user has non-standard installation, he may passTOLK_STDLIB
env variable. It's standard practice for compilers, though it could be a bit simplified if we used CPack. Seetolk-main.cpp
.tolk-wasm.cpp
. It's similar tofuncfiftlib
, but supports more options. A GitHub repo tolk-js is a npm package with wasm distribution. It also contains stdlib. So, when a user takes tolk-js or blueprint, all stdlib functions are still available out of the box.ton_block
andton_crypto
CMake targets.A framework for testing Tolk compiler
In FunC, there is an
auto-tests
folder with several .fc files, specifying provided input and expected output. For example:There is a
run_tests.py
which traverses each file in a folder, detects such lines from comments, compiles to fif, and executes every testcase, comparing output.It is okay, it works, but... This framework is very-very poor. I am speaking not about the amount of tests, but what exactly we can test using such possibilities.
For example, as a compiler developer, I want to implement functions inlining:
But even without inlining, all tests for input-output will work :) Because what we really want to test, it that
myCell()
is not codegenerated (noDECLPROC
and similar)myCell()
are replaced withNEWC
(notCALLDICT
)None of these cases could be explained in terms of input-output.
I have fully rewritten an internal testing framework and added lots of capabilities to it. Let's look though.
@compilation_should_fail
— checks that compilation fails, and it's expected (this is called "negative tests").@stderr
— checks, when compilation fails, that stderr (compilation error) is expected.Example:
@fif_codegen
— checks that contents of compiled.fif matches the expected pattern.@fif_codegen_avoid
— checks that it does not match the pattern.The pattern is a multiline piece of fift code, optionally with "..." meaning "any lines here". It may contain //stack_comments, they will also be checked.
Example:
@code_hash
— checks that hash of compiled output.fif matches the provided value. It's used to "record" code boc hash and to check that it remains the same on compiler modifications. Being much less flexible than@fif_codegen
, it nevertheless gives a guarantee of bytecode stability.Example:
Of course, different tags can be mixed up in a single file: multiple
@testcase
, multiple@fif_codegen
, etc.Also, I've implemented
tolk-tester.js
, fully in sync withtolk-tester.py
. It means, that now we can test fif codegen, compilation errors and so on for WASM also.Consider
tolk-tester/
folder for an implementation and coverage.Moreover, I've downloaded sources of 300 verified FunC contracts from verifier.ton.org, converted them to Tolk, and written a tool to launch Tolk compiler on a whole database after every commit. That makes me sure that all future changes in the compiler won't break compilation of "flagship" codebase, and when Fift output is changed, I look through to ensure that changes are expected. That codebase lives outside of
ton-blockchain
repository.Tolk roadmap
The first released version of Tolk will be v0.6, emphasizing missing FunC v0.5.
Here are some (yet not all and not ordered in any way) points to be investigated:
Note, that most of the points above are a challenge to implement. At first, FunC kernel must be fully refactored to "interbreed" with abilities it was not designed for.
Also, I see Tolk evolution partially guided by community needs. It would be nice to talk to developers who have created interconnected FunC contracts, to absorb their pain points and discuss how things could be done differently.
What fate awaits FunC?
We decided to leave FunC untouched. Carved in stone, exactly the same as visioned by Dr. Nikolay Durov. If critical bugs are found, they would be fixed, of course. But active development is not planned. All contracts written in FunC will continue working, obviously. And FunC will forever be available for use.
Since Tolk allows doing literally the same as FunC, all newcomers will be onboarded to Tolk.
In 2025, FunC will be officially deprecated to avoid confusion.
Tooling around Tolk Language
Sources of the Tolk compiler are a part of the
ton-blockchain
repo. Besides the compiler, we have:.fc
file to a.tolk
file with a singlenpx
command.