Skip to content

Commit 30b891d

Browse files
committed
Add prettier
1 parent 630df82 commit 30b891d

13 files changed

+173
-125
lines changed

.prettierignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
src/tolkfiftlib.js

README.md

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,13 @@
33
**Tolk** is a next-generation language for smart contracts in TON.
44
It replaces FunC with modern syntax, strong types, and built-in serialization — while generating even more efficient assembler code.
55

6-
**tolk-js** is a WASM wrapper for Tolk compiler.
7-
[Blueprint](https://github.com/ton-org/blueprint) uses tolk-js to compile `.tolk` files,
6+
**tolk-js** is a WASM wrapper for Tolk compiler.
7+
[Blueprint](https://github.com/ton-org/blueprint) uses tolk-js to compile `.tolk` files,
88
so if you develop contracts with blueprint, you don't have to install tolk-js directly.
99
However, you can use tolk-js without blueprint, it has a simple and straightforward API.
1010

1111
tolk-js works both in Node.js and browser (does not depend on filesystem).
1212

13-
1413
## Installation
1514

1615
```
@@ -19,10 +18,9 @@ yarn add @ton/tolk-js
1918
npm install @ton/tolk-js
2019
```
2120

22-
2321
## CLI mode
2422

25-
Its purpose is to launch a Tolk compiler from command-line, without compiling ton repo from sources,
23+
Its purpose is to launch a Tolk compiler from command-line, without compiling ton repo from sources,
2624
without installing apt/homebrew packages, etc. Just run
2725

2826
```
@@ -33,26 +31,25 @@ Output JSON will contain `fiftCode`, `codeBoc64`, `codeHashHex`, and other field
3331

3432
There are some flags like `--cwd`, `--output-fift`, and others (run `npx @ton/tolk-js --help`).
3533

36-
3734
## Usage example
3835

3936
```js
40-
import {runTolkCompiler, getTolkCompilerVersion} from "@ton/tolk-js"
37+
import {runTolkCompiler, getTolkCompilerVersion} from '@ton/tolk-js'
4138

4239
async function compileMainTolk() {
4340
// for example, file `main.tolk` is saved nearby
4441
// fsReadCallback (below) is called for both main.tolk and all its imports
4542
let result = await runTolkCompiler({
4643
entrypointFileName: 'main.tolk',
47-
fsReadCallback: path => fs.readFileSync(__dirname + '/' + path, 'utf-8')
44+
fsReadCallback: path => fs.readFileSync(__dirname + '/' + path, 'utf-8'),
4845
})
4946
if (result.status === 'error') {
5047
throw result.message
5148
}
5249

5350
console.log(result.fiftCode)
5451
// using result.codeBoc64, you can construct a cell
55-
let codeCell = Cell.fromBoc(Buffer.from(result.codeBoc64, "base64"))[0]
52+
let codeCell = Cell.fromBoc(Buffer.from(result.codeBoc64, 'base64'))[0]
5653
// result has several (probably useful) fields, look up TolkResultSuccess
5754
}
5855

@@ -62,8 +59,9 @@ async function showTolkVersion() {
6259
}
6360
```
6461

65-
The only point to pay attention to is `fsReadCallback`. It's called for every `.tolk` file, input or imported, and you should synchronously return file contents.
62+
The only point to pay attention to is `fsReadCallback`. It's called for every `.tolk` file, input or imported, and you should synchronously return file contents.
6663
tolk-js does not access filesystem itself, it just provides a flexible callback, so you can make it easily work if you have file contents in memory, for example:
64+
6765
```js
6866
let sources = {
6967
'main.tolk': 'import "utils/math.tolk"',
@@ -77,18 +75,18 @@ runTolkCompiler({
7775
```
7876

7977
The function `runTolkCompiler()` accepts the following properties (look up `TolkCompilerConfig`):
80-
* `entrypointFileName` — obvious
81-
* `fsReadCallback` — explained above
82-
* `optimizationLevel` (default 2) — controls Tolk compiler stack optimizer
83-
* `withStackComments` (default false) — Fift output will contain stack comments, if you wish to debug its output
84-
* `withSrcLineComments` (default false) — Fift output will contain line comments from original .tolk files
85-
* `experimentalOptions` (default '') — you can pass experimental compiler options here
8678

79+
- `entrypointFileName` — obvious
80+
- `fsReadCallback` — explained above
81+
- `optimizationLevel` (default 2) — controls Tolk compiler stack optimizer
82+
- `withStackComments` (default false) — Fift output will contain stack comments, if you wish to debug its output
83+
- `withSrcLineComments` (default false) — Fift output will contain line comments from original .tolk files
84+
- `experimentalOptions` (default '') — you can pass experimental compiler options here
8785

8886
## Embedded stdlib functions
8987

90-
Tolk standard functions (`beginCell`, `assertEnd`, and lots of others) are available out of the box *(if you worked with FunC earlier, you had to download stdlib.fc and store in your project; in Tolk, you don't need any additional files)*.
88+
Tolk standard functions (`beginCell`, `assertEnd`, and lots of others) are available out of the box _(if you worked with FunC earlier, you had to download stdlib.fc and store in your project; in Tolk, you don't need any additional files)_.
9189

9290
It works, because all stdlib files are embedded into JS, placed near wasm. If you `import "@stdlib/tvm-dicts"` for example, tolk-js will handle it, `fsReadCallback` won't be called.
9391

94-
Note, that folder `tolk-stdlib/` and files within it exist only for IDE purposes. For example, if you use blueprint or tolk-js directly, JetBrains and VS Code plugins locate this folder and auto-complete stdlib functions.
92+
Note, that folder `tolk-stdlib/` and files within it exist only for IDE purposes. For example, if you use blueprint or tolk-js directly, JetBrains and VS Code plugins locate this folder and auto-complete stdlib functions.

jest.config.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/** @type {import('ts-jest').JestConfigWithTsJest} **/
22
module.exports = {
3-
testEnvironment: "node",
3+
testEnvironment: 'node',
44
transform: {
5-
"^.+.tsx?$": ["ts-jest",{}],
5+
'^.+.tsx?$': ['ts-jest', {}],
66
},
7-
};
7+
}

package.json

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@
1313
"stdlib:pack": "node scripts/pack-stdlib-to-object.js",
1414
"wasm:dist": "cp src/tolkfiftlib.js dist && cp src/tolkfiftlib.wasm.js dist",
1515
"stdlib:dist": "cp -r src/tolk-stdlib dist && cp src/stdlib.tolk.js dist",
16-
"test": "yarn wasm:pack && yarn stdlib:pack && yarn jest"
16+
"test": "yarn wasm:pack && yarn stdlib:pack && yarn jest",
17+
"fmt": "prettier --write -l --cache .",
18+
"fmt:check": "prettier --check --cache ."
1719
},
1820
"author": "TON Blockchain",
1921
"license": "MIT",
@@ -27,9 +29,31 @@
2729
"@types/jest": "^29.5.12",
2830
"jest": "^29.7.0",
2931
"ts-jest": "^29.2.4",
30-
"typescript": "^5.5.4"
32+
"typescript": "^5.5.4",
33+
"prettier": "^3.6.2"
3134
},
3235
"dependencies": {
3336
"arg": "^5.0.2"
37+
},
38+
"prettier": {
39+
"arrowParens": "avoid",
40+
"bracketSpacing": false,
41+
"printWidth": 100,
42+
"semi": false,
43+
"tabWidth": 2,
44+
"trailingComma": "all",
45+
"useTabs": false,
46+
"singleQuote": true,
47+
"overrides": [
48+
{
49+
"files": [
50+
"*.yaml",
51+
"*.yml"
52+
],
53+
"options": {
54+
"tabWidth": 2
55+
}
56+
}
57+
]
3458
}
3559
}

scripts/pack-stdlib-to-object.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,18 @@ let out = `// stdlib files are stored as strings in order to make it work on web
44
module.exports = {\n\n`
55

66
let fileNames = [
7-
...fs.readdirSync('./src/tolk-stdlib').filter(s => s.endsWith('.tolk')).sort(),
7+
...fs
8+
.readdirSync('./src/tolk-stdlib')
9+
.filter(s => s.endsWith('.tolk'))
10+
.sort(),
811
]
912

1013
for (let fileName of fileNames) {
1114
const contents = fs.readFileSync('./src/tolk-stdlib/' + fileName, 'utf-8')
1215
out += `'@stdlib/${fileName}':\`${contents.replace(/`/g, '\\`')}\`,\n\n`
1316
}
1417

15-
out += "};\n"
18+
out += '};\n'
1619
fs.writeFileSync('./src/stdlib.tolk.js', out)
1720

1821
// note, that Asm.fif and similar are embedded into wasm binary,

src/cli.ts

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ Options:
4747
}
4848

4949
if (args._.length !== 1) {
50-
throw 'entrypointFileName wasn\'t specified. Run with -h to see help.'
50+
throw "entrypointFileName wasn't specified. Run with -h to see help."
5151
}
5252

5353
console.log(`Compiling using Tolk v${version}`)
@@ -64,14 +64,21 @@ Options:
6464
}
6565

6666
if (args['--output-json']) {
67-
fs.writeFileSync(args['--output-json'], JSON.stringify({
68-
artifactVersion: 1,
69-
tolkVersion: version,
70-
fiftCode: result.fiftCode,
71-
codeBoc64: result.codeBoc64,
72-
codeHashHex: result.codeHashHex,
73-
sourcesSnapshot: result.sourcesSnapshot,
74-
}, null, 2))
67+
fs.writeFileSync(
68+
args['--output-json'],
69+
JSON.stringify(
70+
{
71+
artifactVersion: 1,
72+
tolkVersion: version,
73+
fiftCode: result.fiftCode,
74+
codeBoc64: result.codeBoc64,
75+
codeHashHex: result.codeHashHex,
76+
sourcesSnapshot: result.sourcesSnapshot,
77+
},
78+
null,
79+
2,
80+
),
81+
)
7582
}
7683

7784
if (args['--output-fift']) {

src/index.ts

Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
// @ts-ignore
2-
import wasmModule from "./tolkfiftlib.js"
2+
import wasmModule from './tolkfiftlib.js'
33
// @ts-ignore
4-
import wasmBase64 from "./tolkfiftlib.wasm.js"
4+
import wasmBase64 from './tolkfiftlib.wasm.js'
55
// @ts-ignore
6-
import stdlibContents from "./stdlib.tolk.js"
7-
import {realpath} from "./path-utils"
6+
import stdlibContents from './stdlib.tolk.js'
7+
import {realpath} from './path-utils'
88

99
let wasmBinary: Uint8Array | undefined = undefined
1010

@@ -22,16 +22,16 @@ export type TolkCompilerConfig = {
2222
}
2323

2424
export type TolkResultSuccess = {
25-
status: "ok"
25+
status: 'ok'
2626
fiftCode: string
2727
codeBoc64: string
2828
codeHashHex: string
2929
stderr: string
30-
sourcesSnapshot: { filename: string, contents: string }[]
30+
sourcesSnapshot: {filename: string; contents: string}[]
3131
}
3232

3333
export type TolkResultError = {
34-
status: "error"
34+
status: 'error'
3535
message: string
3636
}
3737

@@ -54,10 +54,12 @@ function copyFromCString(mod: WasmModule, inPtr: any): string {
5454

5555
async function instantiateWasmModule() {
5656
if (wasmBinary === undefined) {
57-
if (typeof Buffer !== 'undefined') { // node.js
57+
if (typeof Buffer !== 'undefined') {
58+
// node.js
5859
wasmBinary = new Uint8Array(Buffer.from(wasmBase64, 'base64'))
59-
} else if (typeof window !== 'undefined') { // browser
60-
const binaryString = atob(wasmBase64) // window.atob() is fast and safe for valid base64 strings
60+
} else if (typeof window !== 'undefined') {
61+
// browser
62+
const binaryString = atob(wasmBase64) // window.atob() is fast and safe for valid base64 strings
6163
wasmBinary = new Uint8Array(binaryString.length)
6264
for (let i = 0; i < binaryString.length; i++) {
6365
wasmBinary[i] = binaryString.charCodeAt(i)
@@ -77,33 +79,41 @@ export async function getTolkCompilerVersion(): Promise<string> {
7779
return result.tolkVersion
7880
}
7981

80-
export async function runTolkCompiler(compilerConfig: TolkCompilerConfig): Promise<TolkResultSuccess | TolkResultError> {
82+
export async function runTolkCompiler(
83+
compilerConfig: TolkCompilerConfig,
84+
): Promise<TolkResultSuccess | TolkResultError> {
8185
const mod = await instantiateWasmModule()
8286
const allocatedPointers = []
8387
const sourcesSnapshot: TolkResultSuccess['sourcesSnapshot'] = []
8488

8589
// see tolk-wasm.cpp: typedef void (*WasmFsReadCallback)(int, char const*, char**, char**)
86-
const callbackPtr = mod.addFunction(function (kind: number, dataPtr: any, destContents: any, destError: any) {
87-
switch (kind) { // enum ReadCallback::Kind in C++
88-
case 0: // realpath
89-
let relativeFilename = copyFromCString(mod, dataPtr) // from `import` statement, relative to cur file
90+
const callbackPtr = mod.addFunction(function (
91+
kind: number,
92+
dataPtr: any,
93+
destContents: any,
94+
destError: any,
95+
) {
96+
// enum ReadCallback::Kind in C++
97+
switch (kind) {
98+
case 0: // realpath
99+
let relativeFilename = copyFromCString(mod, dataPtr) // from `import` statement, relative to cur file
90100
if (!relativeFilename.endsWith('.tolk')) {
91101
relativeFilename += '.tolk'
92102
}
93103
allocatedPointers.push(copyToCStringPtr(mod, realpath(relativeFilename), destContents))
94104
break
95-
case 1: // read file
105+
case 1: // read file
96106
try {
97107
const filename = copyFromCString(mod, dataPtr) // already normalized (as returned above)
98108
if (filename.startsWith('@stdlib/')) {
99109
if (filename in stdlibContents) {
100110
allocatedPointers.push(copyToCStringPtr(mod, stdlibContents[filename], destContents))
101111
} else {
102-
allocatedPointers.push(copyToCStringPtr(mod, filename + " not found", destError))
112+
allocatedPointers.push(copyToCStringPtr(mod, filename + ' not found', destError))
103113
}
104114
} else {
105115
const contents = compilerConfig.fsReadCallback(filename)
106-
sourcesSnapshot.push({ filename, contents })
116+
sourcesSnapshot.push({filename, contents})
107117
allocatedPointers.push(copyToCStringPtr(mod, contents, destContents))
108118
}
109119
} catch (err: any) {
@@ -116,7 +126,8 @@ export async function runTolkCompiler(compilerConfig: TolkCompilerConfig): Promi
116126
}
117127
}, 'viiii')
118128

119-
const configStr = JSON.stringify({ // undefined fields won't be present, defaults will be used, see tolk-wasm.cpp
129+
// undefined fields won't be present, defaults will be used, see tolk-wasm.cpp
130+
const configStr = JSON.stringify({
120131
entrypointFileName: compilerConfig.entrypointFileName,
121132
optimizationLevel: compilerConfig.optimizationLevel,
122133
withStackComments: compilerConfig.withStackComments,

src/path-utils.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,8 @@ export function realpath(p: string): string {
8787
let isAbsolute = p.charCodeAt(0) === SLASH
8888
let path = posixNormalize(p, !isAbsolute)
8989

90-
if (isAbsolute) { // posixNormalize() drops leading slash
90+
if (isAbsolute) {
91+
// posixNormalize() drops leading slash
9192
return '/' + path
9293
}
9394
return path.length === 0 ? '.' : path

tests/codegen-checks.spec.ts

Lines changed: 23 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,38 @@
1-
import {runTolkCompiler, getTolkCompilerVersion, TolkResultSuccess, TolkResultError} from "../src";
2-
import fs from "fs";
1+
import {runTolkCompiler, getTolkCompilerVersion, TolkResultSuccess, TolkResultError} from '../src'
2+
import fs from 'fs'
33

44
const EXPECT_TO_CONTAIN = [
5-
`
5+
`
66
check1() PROC:<{
77
NEWC
88
ENDC
99
CTOS
1010
HASHSU
1111
}>
12-
`
12+
`,
1313
]
1414

15-
const EXPECT_NOT_TO_CONTAIN = [
16-
'HASHBU',
17-
]
15+
const EXPECT_NOT_TO_CONTAIN = ['HASHBU']
1816

1917
describe('codegen-checks', () => {
20-
let outFiftCode = ''
18+
let outFiftCode = ''
19+
20+
beforeAll(async () => {
21+
let result = (await runTolkCompiler({
22+
entrypointFileName: 'codegen-checks.tolk',
23+
fsReadCallback: path => fs.readFileSync(`./tests/contracts/${path}`, 'utf-8'),
24+
})) as TolkResultSuccess
2125

22-
beforeAll(async () => {
23-
let result = await runTolkCompiler({
24-
entrypointFileName: "codegen-checks.tolk",
25-
fsReadCallback: path => fs.readFileSync(`./tests/contracts/${path}`, 'utf-8')
26-
}) as TolkResultSuccess
26+
expect(result.status).toEqual('ok')
27+
outFiftCode = result.fiftCode
28+
})
2729

28-
expect(result.status).toEqual('ok')
29-
outFiftCode = result.fiftCode
30-
})
31-
32-
it('check contains', () => {
33-
for (let subFift of EXPECT_TO_CONTAIN) {
34-
expect(outFiftCode).toContain(subFift.trim())
35-
}
36-
for (let subFift of EXPECT_NOT_TO_CONTAIN) {
37-
expect(outFiftCode).not.toContain(subFift)
38-
}
39-
})
30+
it('check contains', () => {
31+
for (let subFift of EXPECT_TO_CONTAIN) {
32+
expect(outFiftCode).toContain(subFift.trim())
33+
}
34+
for (let subFift of EXPECT_NOT_TO_CONTAIN) {
35+
expect(outFiftCode).not.toContain(subFift)
36+
}
37+
})
4038
})

0 commit comments

Comments
 (0)