SuperAPI AI Directory

yaklang-syntax

Coding & development

View repository

Updated 10-16 01:48

About this skill

SKILL: Yaklang DSL syntax examples

AI LOAD INSTRUCTION: Yaklang is a DSL designed for security research; its syntax is close to Go but more dynamic. This page provides directly runnable syntax examples and several real "pitfalls" (see Section 5). Both examples examples/syntax-tour.yak / examples/error-handling.yak can be self-tested and passed with yak <file> When writing Yaklang, refer here first rather than guessing the syntax out of thin air.

0. Related routes

1. Variables, types, and collections

a = 10              // int, 整数除法截断: 10/3 == 3
name = "yaklang"    // string
ok = true           // bool
pi = 3.14           // float

nums = [1, 2, 3] // slice (dynamic array) nums = append(nums, 4, 5) // append can add multiple sub = nums[1:3] // slice expression -> [2, 3]

m = {"host": "a.com", "port": 443} // map v = m["port"] // get value exist = "host" in m // in checks whether the key exists delete(m, "port") // delete key


## 2. 控制流

```yak
for i := 0; i < 5; i++ { sum += i }   // 经典三段式 for

for v in [10, 20, 30] { total += v }  // for-in: 单变量 = 元素值 (推荐)

if score >= 90 {
    grade = "A"
} else if score >= 60 {
    grade = "B"
} else {
    grade = "C"
}

3. Functions (core; hot-loading depends entirely on them)

In Yaklang, functions are "values"; it is recommended to assign literals to variables:

add = func(a, b) { return a + b }     // func 字面量
add = fn(a, b) { return a + b }       // fn / def 等价于 func
func named(a, b) { return a + b }     // 命名函数

twice = (x) => { return x * 2 }       // 箭头函数 (热加载 hook 常用写法)

addsub = func(a, b) { return a + b, a - b }   // 多返回值
s, d = addsub(7, 3)                            // 多重赋值

makeCounter = func() {                 // 闭包: 捕获并保持状态
    n = 0
    return func() { n++; return n }
}

sumAll = func(args...) {               // 可变参数
    t = 0
    for v in args { t += v }
    return t
}

The hot-loading hook is exactly "assigning a function to a variable with the agreed name", for example:

beforeRequest = func(https, originReq, req) { return req }
hijackHTTPRequest = (isHttps, url, req, forward, drop) => { forward(req) }

Complete runnable example:examples/syntax-tour.yak

4. String templates and error handling

f-string interpolation

line = f"user=${user} port=${port}"   // -> "user=admin port=8080"
msg = sprintf("%d-%s", 7, "x")        // -> "7-x"

The three-pronged error handling (key point)

Yaklang library functions generally agree that the last return value is error. Three equivalent ways to handle it:

// 1) 手动判断 (最显式, 可自定义降级)
ret, err = codec.DecodeBase64(s)
if err != nil { /* 降级或 return */ }

// 2) die: err 非 nil 才 panic
ret, err = codec.DecodeBase64(s)
die(err)

// 3) ~ 波浪号 (WavyCall): 出错即自动 panic, "出错就该终止"时最简洁
ret = codec.DecodeBase64(s)~

For crash capture use defer + recover:

defer func {
    e = recover()
    if e != nil { log.error("caught: %v", e) }
}

Complete runnable example:examples/error-handling.yak

5. Real "pitfalls" (must-read before writing Yaklang)

These were discovered through actual testing; AI is extremely prone to errors when writing Yaklang:

Pitfall Incorrect way Correct way
Using _ as a placeholder in for-range makes the value undefined for _, v in slice { total += v } for v in slice { ... }(a single variable is the element value) or for i, v in slice use a real index name
Arrow function expression bodies are not parsed f = (x) => x * 2 f = (x) => { return x * 2 }
double etc. may be built-in identifiers double = ... triggers a compile error Rename, e.g. twice / dbl
The built-in random bytes function is not called RandomBytes codec.RandomBytes(n) Use alternatives such as codec.Md5(sprintf("%d", time.Now().UnixNano())) or construct it yourself
After recover, you want to return a value, but panic has already skipped the return In the outer defer, recover and then return result(will not execute) Put the crash-prone logic in an inner run(), recover catches it in the inner layer, and the outer layer returns as usual

When unsure about an API/syntax, use desc(对象) in the script to inspect its methods, or go run common/yak/cmd/yak.go xxx.yak to try directly. Take pride in carefully consulting references; be ashamed of guessing interfaces blindly.

6. Verification

cd /Users/v1ll4n/Projects/yaklang
go run common/yak/cmd/yak.go skills/yaklang-syntax/examples/syntax-tour.yak
go run common/yak/cmd/yak.go skills/yaklang-syntax/examples/error-handling.yak

Each example should: all asserts pass, all logs in English, and ... self test passed。

Reference sources

  • yaklang-ai-training-materials/basic-syntax: cap3 variables and expressions / cap4 control flow / cap5 functions / cap6-2 error handling / cap6-5 fuzztag
  • yaklang.github.io official syntax documentation