thyscript 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/DOKUMEN.md ADDED
@@ -0,0 +1,525 @@
1
+ # 📖 ThyScript v2.0 Language Reference & Documentation
2
+
3
+ Welcome to the official **ThyScript v2.0 Language Specification & Technical Documentation**.
4
+
5
+ ---
6
+
7
+ ## 📑 Table of Contents
8
+
9
+ 1. [Introduction & Architecture](#1-introduction--architecture)
10
+ 2. [Lexical Structure & Types](#2-lexical-structure--types)
11
+ 3. [Complete Keyword Dictionary](#3-complete-keyword-dictionary)
12
+ - [3.1 Variables & Assignment](#31-variables--assignment)
13
+ - [3.2 Control Flow](#32-control-flow)
14
+ - [3.3 Object-Oriented Programming](#33-object-oriented-programming)
15
+ - [3.4 State Mutations & Persistence](#34-state-mutations--persistence)
16
+ - [3.5 Numeric & Fast Math JIT](#35-numeric--fast-math-jit)
17
+ - [3.6 Functions & Asynchronous Programming](#36-functions--asynchronous-programming)
18
+ - [3.7 Module & npm Package Management](#37-module--npm-package-management)
19
+ - [3.8 Web Server, Routing & HTTP](#38-web-server-routing--http)
20
+ - [3.9 External & Inline HTML](#39-external--inline-html)
21
+ - [3.10 Component System](#310-component-system)
22
+ - [3.11 Machine Learning & Neural Networks](#311-machine-learning--neural-networks)
23
+ - [3.12 Physics Simulation Engine](#312-physics-simulation-engine)
24
+ - [3.13 Concurrency & Multi-Processing](#313-concurrency--multi-processing)
25
+ - [3.14 Database Engine](#314-database-engine)
26
+ - [3.15 Error Handling](#315-error-handling)
27
+ 4. [Standard Library (Built-ins)](#4-standard-library-built-ins)
28
+ 5. [ThyScript Control Panel & Remote Execution](#5-thyscript-control-panel--remote-execution)
29
+
30
+ ---
31
+
32
+ ## 1. Introduction & Architecture
33
+
34
+ ThyScript is a compiled, high-performance programming language hosted on top of Node.js and the Google V8 engine.
35
+
36
+ ```
37
+ ┌────────────────────────────────────────────────────────┐
38
+ │ ThyScript Source (.thy) │
39
+ └───────────────────────────┬────────────────────────────┘
40
+ │
41
+ ┌──────▼──────┐
42
+ │ Lexer │
43
+ └──────┬──────┘
44
+ │
45
+ ┌──────▼──────┐
46
+ │ Parser │
47
+ └──────┬──────┘
48
+ │
49
+ ┌──────▼──────┐
50
+ │ Error Guard │
51
+ └──────┬──────┘
52
+ │
53
+ ┌──────▼──────┐
54
+ │ JITCompiler │
55
+ └──────┬──────┘
56
+ │
57
+ ┌───────────────┴───────────────┐
58
+ │ │
59
+ ┌────────▼────────┐ ┌────────▼────────┐
60
+ │ Memory JIT VM │ │ Disk Build │
61
+ │ (Zero Compile) │ │ (.thy.js) │
62
+ └─────────────────┘ └─────────────────┘
63
+ ```
64
+
65
+ ---
66
+
67
+ ## 2. Lexical Structure & Types
68
+
69
+ ### 2.1 Basic Types
70
+ - `Number`: 64-bit IEEE 754 float or 32-bit signed integer.
71
+ - `String`: UTF-8 string enclosed in single (`'...'`) or double (`"..."`) quotes.
72
+ - `Boolean`: `true` or `false`.
73
+ - `Null`: `null` (representing absence of a value).
74
+ - `Array`: Ordered collection `[1, 2, 3]`.
75
+ - `Object`: Key-value map `{ key: "value" }`.
76
+
77
+ ### 2.2 Comments
78
+ ```thy
79
+ // Single-line comment
80
+ /*
81
+ Multi-line comment block
82
+ */
83
+ ```
84
+
85
+ ---
86
+
87
+ ## 3. Complete Keyword Dictionary
88
+
89
+ ### 3.1 Variables & Assignment
90
+
91
+ #### `const table`
92
+ Declares a mutable or immutable variable with scoped block visibility.
93
+ ```thy
94
+ const table maxRetries = 5
95
+ const table username = "Alice"
96
+ ```
97
+
98
+ #### `table`
99
+ Shorthand variable declaration.
100
+ ```thy
101
+ table counter = 0
102
+ ```
103
+
104
+ #### `become`
105
+ Type coercion / casting statement.
106
+ ```thy
107
+ const table strNum = "42"
108
+ const table num = become(strNum to number)
109
+ ```
110
+
111
+ ---
112
+
113
+ ### 3.2 Control Flow
114
+
115
+ #### `if`, `elif`, `else`, `end()`
116
+ Conditional statement blocks terminated by `end()`.
117
+ ```thy
118
+ if(score >= 90):
119
+ print("Grade: A")
120
+ elif(score >= 80):
121
+ print("Grade: B")
122
+ else:
123
+ print("Grade: C")
124
+ end()
125
+ ```
126
+
127
+ #### `while`, `end()`
128
+ Executes code repeatedly while condition evaluates to true.
129
+ ```thy
130
+ const table count = 0
131
+ while(count < 5):
132
+ print("Count: " + count)
133
+ add 1 in count
134
+ end()
135
+ ```
136
+
137
+ #### `for`, `in`, `end()`
138
+ Iterates over an array, string, or range.
139
+ ```thy
140
+ const table fruits = ["Apple", "Banana", "Cherry"]
141
+ for item in fruits:
142
+ print("Fruit: " + item)
143
+ end()
144
+ ```
145
+
146
+ #### `switch`, `case`, `default`, `end()`
147
+ Multi-way branching statement.
148
+ ```thy
149
+ switch(command):
150
+ case "start":
151
+ print("Starting engine...")
152
+ break
153
+ case "stop":
154
+ print("Stopping engine...")
155
+ break
156
+ default:
157
+ print("Unknown command")
158
+ end()
159
+ ```
160
+
161
+ #### `match`, `when`, `end()`
162
+ Pattern matching expression.
163
+ ```thy
164
+ match status:
165
+ when 200: "OK"
166
+ when 404: "Not Found"
167
+ when 500: "Server Error"
168
+ end()
169
+ ```
170
+
171
+ ---
172
+
173
+ ### 3.3 Object-Oriented Programming
174
+
175
+ #### `public class(Name): ... end()`
176
+ Declares a class with public visibility. Methods and properties are bound to instance scope.
177
+ ```thy
178
+ public class(Account):
179
+ const table owner = "Unknown"
180
+ const table balance = 0
181
+
182
+ func deposit(amount):
183
+ add amount in balance
184
+ print(owner + " deposited $" + amount + ". New balance: $" + balance)
185
+ end()
186
+ end()
187
+ ```
188
+
189
+ #### `private`, `protected`
190
+ Access modifier specifiers for class members.
191
+ ```thy
192
+ public class(Vault):
193
+ private secretKey = "top-secret"
194
+ end()
195
+ ```
196
+
197
+ #### `new`
198
+ Instantiates a class.
199
+ ```thy
200
+ const table acc = new Account()
201
+ change(acc.owner to("Dede"))
202
+ acc.deposit(500)
203
+ ```
204
+
205
+ ---
206
+
207
+ ### 3.4 State Mutations & Persistence
208
+
209
+ #### `add <value> in <target>`
210
+ Universal mutation operator:
211
+ - For numbers: Increments target by value (`target += value`).
212
+ - For arrays/lists: Appends value to array (`target.push(value)`).
213
+ ```thy
214
+ // Numeric addition
215
+ const table total = 100
216
+ add 25 in total // total is now 125
217
+
218
+ // Array insertion
219
+ const table list = ["a", "b"]
220
+ add "c" in list // list is now ["a", "b", "c"]
221
+ ```
222
+
223
+ #### `change(<target> to(<value>))`
224
+ Mutates an existing variable or object property.
225
+ ```thy
226
+ const table player = { name: "Bob", level: 1 }
227
+ change(player.level to(2))
228
+ ```
229
+
230
+ #### `save(<variable>)`
231
+ Serializes and persists variable state to a `.thysave` JSON file on disk.
232
+ ```thy
233
+ save(playerState)
234
+ ```
235
+
236
+ #### `free()`
237
+ Hints the V8 Garbage Collector to free references and clean heap memory.
238
+ ```thy
239
+ free(largeDataset)
240
+ ```
241
+
242
+ ---
243
+
244
+ ### 3.5 Numeric & Fast Math JIT
245
+
246
+ #### `calculate(<expr>)`
247
+ Forces high-speed math expression evaluation using typed arrays and V8 TurboFan compilation.
248
+ ```thy
249
+ const table radius = 7
250
+ const table area = calculate(Math.PI * (radius ** 2))
251
+ print("Circle area: " + area)
252
+ ```
253
+
254
+ ---
255
+
256
+ ### 3.6 Functions & Asynchronous Programming
257
+
258
+ #### `func <name>(<params>): ... end()`
259
+ Declares a callable function.
260
+ ```thy
261
+ func multiply(x, y):
262
+ return calculate(x * y)
263
+ end()
264
+ ```
265
+
266
+ #### `async func`, `await`
267
+ Asynchronous routines backed by Node.js Promises.
268
+ ```thy
269
+ async func fetchUserData(id):
270
+ const table response = await fetch("https://api.example.com/user/" + id)
271
+ return await response.json()
272
+ end()
273
+ ```
274
+
275
+ #### Arrow Functions
276
+ Inline lambda functions with implicit return.
277
+ ```thy
278
+ const table numbers = [1, 2, 3, 4]
279
+ const table doubled = numbers.map((n) => n * 2)
280
+ ```
281
+
282
+ ---
283
+
284
+ ### 3.7 Module & npm Package Management
285
+
286
+ #### `import "<npm-package>"`
287
+ Directly imports and binds an npm package.
288
+ ```thy
289
+ import "chalk"
290
+ import "axios"
291
+
292
+ print(chalk.blue("HTTP request ready"))
293
+ ```
294
+
295
+ #### `import "<npm-package>" as <alias>`
296
+ Imports an npm package under a custom variable name.
297
+ ```thy
298
+ import "lodash" as _
299
+ ```
300
+
301
+ #### `import <name> from "<module>"`
302
+ ES-style default import.
303
+ ```thy
304
+ import express from "express"
305
+ ```
306
+
307
+ #### `import { <item> } from "<module>"`
308
+ Named imports from local files or npm packages.
309
+ ```thy
310
+ import { readFileSync, writeFileSync } from "fs"
311
+ ```
312
+
313
+ #### `export`
314
+ Exports functions, classes, or values from the current file.
315
+ ```thy
316
+ export func add(a, b):
317
+ return a + b
318
+ end()
319
+ ```
320
+
321
+ ---
322
+
323
+ ### 3.8 Web Server, Routing & HTTP
324
+
325
+ #### `server(<port>): ... end()`
326
+ Initializes an HTTP/Express web server automatically binding to `0.0.0.0` with CORS, JSON body-parsing, and URL-encoding enabled.
327
+ ```thy
328
+ server(8080):
329
+ print("Server online on port 8080")
330
+ end()
331
+ ```
332
+
333
+ #### `route get`, `route post`, `route put`, `route delete`, `route patch`
334
+ Defines HTTP endpoint route handlers. Inside the block, `req` / `request` and `res` / `response` are pre-injected.
335
+ ```thy
336
+ route get "/api/health":
337
+ res.json({ status: "healthy", timestamp: Date.now() })
338
+ end()
339
+
340
+ route post "/api/submit":
341
+ const table payload = req.body
342
+ res.json({ success: true, received: payload })
343
+ end()
344
+ ```
345
+
346
+ #### `socket on "<event>": ... end()`
347
+ WebSocket event listener for bidirectional real-time communications.
348
+ ```thy
349
+ socket on "chat-message":
350
+ socket.broadcast.emit("chat-message", req.data)
351
+ end()
352
+ ```
353
+
354
+ ---
355
+
356
+ ### 3.9 External & Inline HTML
357
+
358
+ #### `classHtml(<Name>) from "<file.html>"`
359
+ Serves an external HTML file at route `/<Name>`.
360
+ ```thy
361
+ classHtml(Home) from "public/index.html"
362
+ ```
363
+
364
+ #### `res.renderHtml("<path.html>", <context>)`
365
+ Renders an external HTML file with dynamic Mustache-style `{{key}}` parameter substitution.
366
+ ```thy
367
+ route get "/profile":
368
+ res.renderHtml("views/profile.html", {
369
+ username: "Dede",
370
+ role: "Lead Engineer"
371
+ })
372
+ end()
373
+ ```
374
+
375
+ #### `classHtml(<Name>): ... end()`
376
+ Inline HTML component serving directly from ThyScript.
377
+ ```thy
378
+ classHtml(StatusPage):
379
+ <!DOCTYPE html>
380
+ <html>
381
+ <body><h1>ThyScript Live Status</h1></body>
382
+ </html>
383
+ end()
384
+ ```
385
+
386
+ ---
387
+
388
+ ### 3.10 Component System
389
+
390
+ #### `component <Name>(<props>): ... end()`
391
+ Declares a reactive web component with managed state.
392
+ ```thy
393
+ component UserBadge(name, role):
394
+ state active = true
395
+ render:
396
+ print("<div class='badge'>" + name + " (" + role + ")</div>")
397
+ end()
398
+ ```
399
+
400
+ ---
401
+
402
+ ### 3.11 Machine Learning & Neural Networks
403
+
404
+ #### `neural <Name>: ... end()`
405
+ Declares a neural network architecture powered by TensorFlow.js.
406
+ ```thy
407
+ neural Classifier:
408
+ optimizer "adam"
409
+ loss "categoricalCrossentropy"
410
+ layer dense(64, activation: "relu")
411
+ layer dense(10, activation: "softmax")
412
+ end()
413
+ ```
414
+
415
+ ---
416
+
417
+ ### 3.12 Physics Simulation Engine
418
+
419
+ #### `physics <Name>: ... end()`
420
+ Configures a 2D Matter.js physics simulation environment.
421
+ ```thy
422
+ physics SandboxWorld:
423
+ gravity(0, 9.8)
424
+ body box(x: 100, y: 100, w: 50, h: 50, density: 1.0)
425
+ body ground(x: 0, y: 600, w: 800, h: 50, static: true)
426
+ end()
427
+ ```
428
+
429
+ ---
430
+
431
+ ### 3.13 Concurrency & Multi-Processing
432
+
433
+ #### `parallel: ... end()`
434
+ Executes code asynchronously across worker threads utilizing all available CPU cores.
435
+ ```thy
436
+ parallel:
437
+ print("Running in worker thread ID: " + threadId)
438
+ end()
439
+ ```
440
+
441
+ #### `stream <Name>: ... end()`
442
+ Creates high-throughput data processing pipelines.
443
+ ```thy
444
+ stream FilePipeline:
445
+ pipe gzip()
446
+ pipe write("output.tar.gz")
447
+ end()
448
+ ```
449
+
450
+ ---
451
+
452
+ ### 3.14 Database Engine
453
+
454
+ #### `database connect: ... end()`
455
+ Connects to SQL (Postgres, MySQL, SQLite) or NoSQL (MongoDB, Redis) databases.
456
+ ```thy
457
+ database connect:
458
+ driver "sqlite"
459
+ database "./app.db"
460
+ end()
461
+ ```
462
+
463
+ ---
464
+
465
+ ### 3.15 Error Handling
466
+
467
+ #### `try`, `catch(<err>)`, `finally`, `end()`
468
+ Structured exception handling block.
469
+ ```thy
470
+ try:
471
+ const table data = JSON.parse(invalidString)
472
+ catch(err):
473
+ print("Caught error: " + err.message)
474
+ finally:
475
+ print("Cleanup complete")
476
+ end()
477
+ ```
478
+
479
+ #### `throw`
480
+ Raises an exception.
481
+ ```thy
482
+ if(divisor == 0):
483
+ throw "Division by zero is not allowed"
484
+ end()
485
+ ```
486
+
487
+ ---
488
+
489
+ ## 4. Standard Library (Built-ins)
490
+
491
+ All compiled ThyScript files automatically receive the `__thy_stdlib` namespace and top-level helper functions:
492
+
493
+ | Module | Methods |
494
+ |--------|---------|
495
+ | `math` | `abs`, `sqrt`, `pow`, `floor`, `ceil`, `round`, `sin`, `cos`, `tan`, `log`, `min`, `max`, `clamp`, `lerp`, `hypot`, `random` |
496
+ | `str` | `upper`, `lower`, `trim`, `split`, `replace`, `includes`, `startsWith`, `endsWith`, `reverse`, `slice`, `pad` |
497
+ | `arr` | `map`, `filter`, `reduce`, `find`, `sort`, `reverse`, `chunk`, `unique`, `sum`, `avg`, `range` |
498
+ | `file` | `read`, `write`, `append`, `exists`, `mkdir`, `readJSON`, `writeJSON`, `readLines` |
499
+ | `io` | `print`, `printErr`, `write`, `read`, `cwd`, `home` |
500
+ | `security` | `hash`, `hmac`, `random`, `uuid`, `encrypt`, `decrypt`, `base64encode`, `base64decode` |
501
+ | `server` | Native Express + fallback HTTP engine, CORS, WebSocket, SSE |
502
+ | `database` | Unified query builder for MySQL, PostgreSQL, SQLite, MongoDB, Redis |
503
+
504
+ ---
505
+
506
+ ## 5. ThyScript Control Panel & Remote Execution
507
+
508
+ The Control Panel provides a browser-based, zero-compile execution environment:
509
+
510
+ 1. **Start the Panel**:
511
+ ```bash
512
+ thy panel --port 7777
513
+ ```
514
+ 2. **Access Remotely**:
515
+ - Local: `http://localhost:7777`
516
+ - LAN / WiFi: `http://<YOUR_LAN_IP>:7777` (e.g. `http://192.168.1.7:7777`)
517
+ 3. **Features**:
518
+ - Write and test ThyScript code in real-time.
519
+ - Run code on-the-fly in host memory without creating files on disk.
520
+ - Monitor host CPU, RAM, and process heap live.
521
+ - Browse and edit project workspace files.
522
+
523
+ ---
524
+
525
+ *ThyScript Language Specification — Version 2.0.0 — Licensed under MIT.*