### Import module syntax examples Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Shows three import forms: whole module, selected names, and alias. Import paths start at the project root; `import main;` imports the entry module and cycles are allowed. ```mclang import lib::math; // whole module ``` ```mclang import lib::strings::{banner, on_fire}; // selected names ``` ```mclang import lib::strings::{banner as wel}; // alias ``` -------------------------------- ### serve Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/lib.md Starts the language server, providing IDE features such as diagnostics and completion. ```APIDOC ## [Rust] serve ### Description Starts the language server, providing IDE features such as diagnostics and completion. ### Signature ```rust pub fn serve() -> Result<(), Error> ``` ### Returns - **Result<(), Error>** - Ok if the server runs successfully, or an error if it fails. ``` -------------------------------- ### Raw native command execution example Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_zh.txt Shows how to execute native commands directly and via execute string, and return a native command result. These raw usages are rejected by --deny-raw. ```mclang 命名空间 raw_demo; 计分 uses = 0; @加载 函数 load() { 原生命令 "say direct native command"; 执行 "as @a at @s" { 原生命令 "particle minecraft:happy_villager ~ ~1 ~ 0.2 0.2 0.2 0 3"; } uses += 1; } 函数 raw_return() -> 计分 { 返回 原生命令 "time query gametime"; } ``` -------------------------------- ### Execute demo namespace setup Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Defines the execute_demo namespace with objectives and queries for players and zombies. ```mclang namespace execute_demo; objective cleared; query players = entity("minecraft:player") {} query zombies = entity("minecraft:zombie") { within(16); } query one_zombie = entity("minecraft:zombie") { limit(1); } item token = item_stack("minecraft:gold_nugget") { count = 3; } ``` -------------------------------- ### Using snapshot() and VERSION Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/version-snapshot.md Example usage of the snapshot module: prints the target version and checks whether the `give` root command exists. Requires importing `mclang::version::snapshot`. ```rust use mclang::version::snapshot::{snapshot, VERSION}; println!("目标版本:{VERSION}"); let snapshot = snapshot(); assert!(snapshot.has_root_command("give")); ``` -------------------------------- ### Item and storage setup for entities_demo Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Defines a diamond item with custom properties and a storage list for saving entity data. Used as a template for entity interactions. ```mclang item gift = item_stack("minecraft:diamond") { count = 1; custom_name = "Gift"; lore("From entities_demo"); enchantment("minecraft:unbreaking", 1); rarity = rare; } storage saved = item_list("entities_demo:state", "saved"); data_slot stash = entity_data("stash"); ``` -------------------------------- ### Advancement and Resource Example (08_advancement.mcl) Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Shows MCLang code for defining items, resources (predicate, loot table, recipe), and an advancement with criteria, rewards, and display. Includes a tick function to grant the advancement. ```mclang namespace quest_demo; item medal = item_stack("minecraft:emerald") { count = 2; custom_name = "Medal"; custom_data = nbt { serial = "quest_demo-1"; }; } item badge_icon = item_stack("minecraft:crying_obsidian") {} resource predicate lucky = """{"type":"minecraft:random_chance","chance":0.5}"""; resource loot_table trophy = """{"type":"minecraft:generic","pools":[]}"""; resource recipe token = """{"type":"minecraft:crafting_shapeless","ingredients":["minecraft:stone"],"result":{"id":"minecraft:emerald","count":1}}"""; query players = entity("minecraft:player") {} fn on_placed() {} @player fn on_self_placed() { advancement.revoke(self, portal_frame); message.self("Core placed", gold); } advancement root_adv { criterion placed { trigger = placed_block; conditions = """{"location":{"type":"minecraft:match_block","blocks":"minecraft:obsidian"}}"""; } reward { function = on_placed; experience = 5; loot = trophy; recipe = token; } display { icon = badge_icon; title = "Root"; description = "Place obsidian."; frame = goal; background = "minecraft:textures/block/obsidian.png"; show_toast = true; announce_to_chat = false; } } advancement portal_frame { parent = root_adv; criterion placed { trigger = placed_block; } criterion ticked { trigger = tick; conditions = """{}"""; } criterion slain { trigger = player_killed_entity; conditions = """{"entity":{"type":"minecraft:entity_properties","entity":"this","predicate":{"minecraft:entity_type":"minecraft:zombie"}}}"""; } requirements = any; reward { function = on_self_placed; } display { icon = medal; title = "Portal frame"; description = "Place obsidian."; frame = goal; } } @tick fn lucky_tick() { if predicate(lucky) { advancement.grant(players, portal_frame); } } ``` -------------------------------- ### check_file basic usage example Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/lib.md Example of calling check_file with a project directory path. On success, prints the number of functions and raw statements; on error, prints the rendered diagnostics to stderr. ```rust use std::path::PathBuf; use mclang::check_file; match check_file(&PathBuf::from("examples/portable_chest")) { Ok(summary) => println!("functions={} raw={}", summary.functions, summary.raw_statements), Err(rendered) => eprintln!("{rendered}"), } ``` -------------------------------- ### World Manipulation Example (prepare, audit, landmarks) Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Shows MCLang functions for world manipulation: filling blocks, placing structures, managing time/weather, and querying game state. Includes @load and @tick annotations. ```mclang @load fn prepare() { fill(pos(0, 64, 0), pos(8, 64, 8), block_state("minecraft:stone_bricks")); fill(pos(0, 65, 0), pos(8, 65, 8), block_state("minecraft:oak_planks"), replace, block_state("#minecraft:planks")); fill(pos(0, 66, 0), pos(8, 66, 8), block_state("minecraft:glass"), outline); set_block(pos(4, 65, 4), block_state("minecraft:oak_stairs") { facing = "south"; half = "bottom"; }, keep); set_block(pos(4, 66, 4), block_state("minecraft:glass"), strict); set_block(pos(5, 66, 4), block_state("minecraft:chest"), nbt { name = "storage"; }); fill_biome(pos(0, 64, 0), pos(16, 64, 16), "minecraft:plains"); clone(pos(0, 64, 0), pos(8, 64, 8), pos(20, 64, 0), masked, force); clone(pos(0, 64, 0), pos(8, 64, 8), pos(40, 64, 0), filtered, block_state("#minecraft:logs"), move, strict); clone(pos(0, 64, 0), pos(8, 64, 8), pos(60, 64, 0), from_dimension("minecraft:the_nether"), to_dimension("minecraft:overworld")); place.feature("minecraft:oak", pos(0, 64, 20)); place.feature(nbt { type = "minecraft:simple_block"; to_place = { id = "minecraft:stone"; }; }, pos(1, 64, 20)); place.structure("minecraft:village_plains", pos(32, 64, 20)); place.jigsaw("minecraft:village/plains/houses", "minecraft:bottom", 4, pos(64, 64, 20)); place.template("minecraft:empty", pos(96, 64, 20), clockwise_90, none, 1.0, 7, strict); forceload.add(column(0, 0), column(31, 31)); weather.clear(); time.set(6000, t); worldborder.set(100, 5 s); worldborder.warning_distance(10); worldborder.warning_time(20 s); gamerule.set("random_tick_speed", 5); phase = 1; } @tick fn audit() { border = worldborder.get(); if border < 1000 { worldborder.add(10, 1 s); } if time.query() >= 13000 { time.set(1000, t, "minecraft:overworld"); } } fn landmarks() { locate.biome("#minecraft:is_forest"); locate.structure("minecraft:village_plains"); locate.poi("minecraft:home"); if gamerule.query("keep_inventory") == 1 { weather.thunder(1, d); } time.rate(1.5); time.pause(); time.resume(); time.add(1, d); weather.rain(10 s); worldborder.damage_amount(0.5); worldborder.damage_buffer(5); worldborder.center(0, 0); border = time.query_gametime(); forceload.query(); forceload.remove(column(0, 0)); forceload.remove_all(); } ``` -------------------------------- ### Check and build portable_chest with Mclang Source: https://github.com/ahasasjeb/mclang/blob/main/examples/portable_chest/PROJECT.md Run Mclang's check and build commands on the portable_chest example with --deny-raw to verify and compile the data pack. The default output is placed in build/portable_chest. ```powershell target/release/mclang.exe check examples/portable_chest --deny-raw ``` ```powershell target/release/mclang.exe build examples/portable_chest --deny-raw ``` -------------------------------- ### Import and export declaration examples Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Shows import of a whole module, selected names with alias, and export of declarations. Imported names can be used anywhere; local declarations with the same name win. ```mclang import a::b; whole module ``` ```mclang import a::b::{name, other as alias}; selected names ``` ```mclang export fn ...; export score ...; ... expose a declaration ``` -------------------------------- ### Inventory Management in Mclang Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Shows give, clear, and item predicate usage in inventory management. Includes examples of giving items with custom data, clearing with predicates, and checking equipped items. ```mclang fn inventory() { give(players, item_stack("minecraft:stone") { components = nbt { "minecraft:max_stack_size" = 99; "minecraft:custom_data" = { group = "building"; }; }; }, 9900); give(players, tool); clear(players, item_predicate("*") { has("minecraft:custom_data"); !has("minecraft:damage") || equals("minecraft:damage", 0); matches("minecraft:custom_data", nbt { owner = "Alex"; }); matches("minecraft:count", nbt { min = 1; max = 64; }); }, 0); clear(players, "#minecraft:logs", 10); clear(equipped); if items(entity, players, "weapon.mainhand", item_predicate("*") { equals("minecraft:damage", 0); }) { message.all("Ready"); } } ``` -------------------------------- ### check_file error handling example Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/lib.md Example of handling the error case from check_file, where the returned String contains rendered multi-line diagnostics. Prints the diagnostics to stderr. ```rust use mclang::check_file; let result = check_file(&PathBuf::from("tests/invalid/items.mcl")); if let Err(diagnostics) = result { // diagnostics 是已渲染的多行文本,直接交给终端 eprintln!("检查失败:\n{diagnostics}"); } ``` -------------------------------- ### Summarize program macros and tick functions Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/ast-declarations.md Example of traversing a Program to count functions with macro signatures and functions with the Tick attribute. Use this between analyze() and compile() when Program is the sole program model. ```rust use mclang::ast::{Program, Attribute}; fn summarize(program: &Program) -> (usize, usize) { let macros = program.functions.iter() .filter(|f| f.macro_signature.is_some()) .count(); let tick_fn = program.functions.iter() .filter(|f| f.attributes.contains(&Attribute::Tick)) .count(); (macros, tick_fn) } // analyze() 之后、compile() 之前,Program 是唯一的程序模型: // - module 限定名(a/b::f)在 ast::Program 上仍可见 // - function.body: Vec 进入语句层(见 ast-statements.md) // - item_stack.custom_data: Option 进入值层(见 ast-values.md) ``` -------------------------------- ### initialize Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/endpoints.md Initializes the language server with workspace folders or root URI, returning server capabilities and server info. ```APIDOC ## initialize ### Description Initializes the language server with workspace folders or root URI, returning server capabilities and server info. ### Method Request ### Parameters #### Request Body - **workspaceFolders** (array) - Optional - List of workspace folders. - **rootUri** (string) - Optional - Root URI of the workspace. ### Response #### Success Response - **capabilities** (object) - Server capabilities. - **serverInfo** (object) - Server information. ### Response Example ```json { "capabilities": {}, "serverInfo": {} } ``` ``` -------------------------------- ### scoreboard.get Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Gets the score of a holder in a declared objective. ```APIDOC ## scoreboard.get ### Description Gets the score of a holder in a declared objective. ### Parameters - **holder** (limit(1)) - Required - The score holder (must match exactly one). - **objective** (declared) - Required - The objective to query. ### Return Value Returns the score value. A missing score reads as 0. ### Usage `let = scoreboard.get(, );` ``` -------------------------------- ### Items demo namespace, queries, and item predicates Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_zh.txt Sets up the items_demo namespace, queries all players and players with a mainhand item matching an item predicate that requires custom_data. ```mclang 命名空间 items_demo; 查询 players = 实体("minecraft:player") {} 查询 equipped = 实体("minecraft:player") { 物品("weapon.mainhand") { 类型 = 物品谓词("*") { 存在("minecraft:custom_data"); }; } } ``` -------------------------------- ### UI demo namespace, targets, queries, and dialog resource Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_zh.txt Sets up the ui_demo namespace, defines a scoreboard objective 'points', queries all players and one player (with limit 1), and defines a server_links dialog resource 'links'. ```mclang 命名空间 ui_demo; 目标 points; 查询 all_players = 实体("minecraft:player") {} 查询 one_player = 实体("minecraft:player") { 上限(1); } 资源 对话框 links = """{"type":"minecraft:server_links","title":{"text":"Links"},"external_title":{"text":"Links"}}"""; ``` -------------------------------- ### bossbar.get Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Gets a property of a bossbar (value, max, visible, or players). ```APIDOC ## bossbar.get ### Description Gets a property of a bossbar (value, max, visible, or players). ### Parameters - **id** (string) - Required - The unique identifier of the bossbar. - **property** (enum) - Required - One of: value, max, visible, players. ### Return Value Returns the requested property value. ### Usage `let = bossbar.get("", value|max|visible|players);` ``` -------------------------------- ### Chinese identifier usage example Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_zh.txt Demonstrates legal Chinese identifiers that are stably aliased by the compiler. ```mclang 命名空间 chinese_id; 计分 次数 = 0; 计分 ascii_counter = 0; 函数 计时() -> 计分 { 次数 += 1; ascii_counter = 次数; 返回 ascii_counter; } ``` -------------------------------- ### Attribute commands Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Get, set, reset, and modify attributes and modifiers. Includes base and modifier value getters. ```mclang let v = attribute.get(, ""[, ]); // also attribute.base.get ``` ```mclang attribute.base.set(, "", ); attribute.base.reset(, ""); ``` ```mclang attribute.modifier.add(, "", "", , ); ``` ```mclang attribute.modifier.remove(, "", ""); ``` ```mclang let v = attribute.modifier.value.get(, "", ""[, ]); ``` -------------------------------- ### Call a macro with storage data Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Demonstrates calling the 'welcome' macro using storage data from a specific path. Useful for passing dynamic data from storage. ```mclang fn dynamic() { call welcome with(storage, "macro_demo:args", "payload"); } ``` -------------------------------- ### Use Chinese identifiers in mclang Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Demonstrates that Chinese identifiers are legal and get compiler-aliased. Defines a function '计时' that increments a Chinese-named score and returns an ASCII-named score. ```mclang namespace chinese_id; score 次数 = 0; score ascii_counter = 0; fn 计时() -> score { 次数 += 1; ascii_counter = 次数; return ascii_counter; } ``` -------------------------------- ### Query snapshot interfaces Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/version-snapshot.md Demonstrates querying registry IDs, checking enums, verifying root commands, and interacting with slot names. ```rust use mclang::version::snapshot::snapshot; let snap = snapshot(); // 注册表:方块 id 存在性与拼写建议 if let Some(found) = snap.registry_contains("block", "minecraft:oak_stairs") { println!("block registry contains = {found}"); } let suggestion = snap.suggest_registry_id("block", "minecraft:oak_stair"); println!("你是否想写:{suggestion}"); // 枚举与命令 assert!(snap.enum_contains("difficulty", "hard")); assert!(snap.has_root_command("advancement")); println!("advancement 权限等级:{}", snap.root_command_level("advancement")); // 槽位 let slots = snap.slots(); assert!(slots.accepts("weapon.*")); for name in slots.names().into_iter().take(3) { println!("{name}"); } ``` -------------------------------- ### 01_hello.mcl: Minimal complete program with @load/@tick, score, query, each Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Minimal complete Mclang program demonstrating namespace, score variables, query definition, @load and @tick functions, message sending, sound, and each loop. Uses query all_players to target players and sends a message after 100 ticks. ```mcl namespace hello; score ticks = 0; query all_players = entity("minecraft:player") {} @load fn load() { message.all("Hello from Mclang", green); } @tick fn tick() { ticks += 1; if ticks >= 100 { each(all_players) { message.self("Five seconds passed.", gold); sound.self("minecraft:block.note_block.pling", master); } ticks = 0; } } ``` -------------------------------- ### Load and ensure watch functions Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Initializes the entities_demo module and ensures a stopwatch is created for timing. ```mclang @load fn load() { message.all("entities_demo loaded", green); call ensure_watch(); } fn ensure_watch() { if ready == 0 { ready = 1; stopwatch.create("entities_demo:timer"); } } ``` -------------------------------- ### Define a macro function with parameters and conditional logic Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Defines a macro function 'welcome' that takes a text label, integer, and decimal. Uses macro expansion for parameters and conditional message sending. Demonstrates macro syntax with 'macro' keyword and 'vec3' for coordinates. ```mclang macro fn welcome(text label, integer x, decimal z) { message.all(text("Hello $(label)")); teleport(players, vec3(macro(x), 64, macro(z))); if active == 1 { message.all(text("$(label) arrived")); } } ``` -------------------------------- ### Macro Demo with Raw Runtime Call in Mclang Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Shows a macro demo with namespace, query, and score declaration. Includes a comment about raw runtime with call being rejected by --deny-raw. ```mclang namespace macro_demo; query players = entity("minecraft:player") {} score active = 1; ``` -------------------------------- ### Test commands Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Run, verify, locate, reset, and create tests. Includes multiple variants for running tests. ```mclang test.run(""[, [, [, [, ]]]]); ``` ```mclang test.runmultiple(""[, ]); test.runthese(...); test.runclosest(...); ``` ```mclang test.runthat(...); test.runfailed([, ...]); test.verify(""); ``` ```mclang test.locate(""); test.resetclosest/resetthese/resetthat/clearthat/clearthese/stop(); ``` ```mclang test.clearall([]); test.pos([""]); test.create(""[, [, , ]]); ``` -------------------------------- ### Capture diagnostics via mclang::check_file Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/errors.md Use the top-level mclang::check_file API to get a rendered String on error, which already includes line/column and source excerpts. The Ok variant returns a summary with raw_statements. ```rust // 顶层 API:String 是渲染好的整页诊断 match mclang::check_file(&path) { Ok(summary) => println!("OK raw_statements={}", summary.raw_statements), Err(rendered) => eprintln!("检查失败:\n{rendered}"), // 已含行列与源码摘录 } ``` -------------------------------- ### serve 函数签名 Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/lsp.md 启动标准输入输出上的语言服务器,直到客户端发送 exit。返回 io::Result<()>,正常流程在收到 exit 通知后返回 Ok(()),stdio 读写失败返回 io::Error。 ```rust /// 启动标准输入输出上的语言服务器,直到客户端发送 `exit`。 pub fn serve() -> io::Result<()> // src/lsp/server.rs:22 ``` -------------------------------- ### Process diagnostics via mclang::compiler::compile Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/errors.md Use the structured path with mclang::compiler::compile to get a Vec for individual processing. Each diagnostic's span contains source index and byte range start/end. ```rust // 结构化路径:Vec 可逐条处理 use mclang::compiler::compile; let result = compile(&mut program, &CompileOptions { description: "x".into() }); if let Err(diagnostics) = result { for diagnostic in diagnostics { match diagnostic.span { // span.source 是源文件下标,span.start/end 是字节范围 _ => eprintln!("[{}-{}] {}", diagnostic.span.start, diagnostic.span.end, diagnostic.message), } } } ``` -------------------------------- ### Module Demo Main File in Mclang Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Main module file demonstrating imports, exports, and load function. Imports sum and product from lib::math, toggle from std::state, and exports a score variable. ```mclang namespace module_demo; import lib::math::{sum, product}; import std::state::{toggle}; export score total = 0; score enabled = 0; @load fn load() { message.all("module demo loaded", green); total = sum(1, 2) + product(3, 4); enabled = toggle(enabled); } ``` -------------------------------- ### Help, version, seed commands Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Display help, version, or the world seed. ```mclang help([""]); version(); seed(); ``` -------------------------------- ### World state operation enums Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/ast-actions.md Defines enums for world state operations: `ForceLoadOperation` for `forceload`, `TimeOperation` for `time` (non-query), `WeatherKind`, `GameRuleValue` for `gamerule`, `WorldBorderOperation` for `worldborder` (non-`get`), and `LocateKind` for `locate`. Includes `as_str()` mappings for `WeatherKind` and `LocateKind`. ```rust /// `forceload` 的四种操作。 #[derive(Debug)] pub enum ForceLoadOperation { // src/ast/actions.rs:82 Add { from: ColumnPosition, to: Option, }, Remove { from: ColumnPosition, to: Option, }, RemoveAll, Query { pos: Option, }, } /// `time` 的无返回值操作;查询在表达式中使用。 #[derive(Debug)] pub enum TimeOperation { // src/ast/actions.rs:98 Set(String), Add(String), Pause, Resume, Rate(String), } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum WeatherKind { Clear, Rain, Thunder } // as_str(): "clear" | "rain" | "thunder" /// `gamerule` 的取值:布尔规则或整数规则。 #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum GameRuleValue { Bool(bool), Integer(i32) } // src/ast/actions.rs:113 /// `worldborder` 的无返回值操作;`get` 在表达式中使用。 #[derive(Debug)] pub enum WorldBorderOperation { // src/ast/actions.rs:116 Add { distance: String, time: Option, }, Set { distance: String, time: Option, }, Center(Vec2Value), DamageAmount(String), DamageBuffer(String), WarningDistance(u32), WarningTime(String), } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum LocateKind { Structure, Biome, Poi } // as_str(): "structure" | "biome" | "poi" ``` -------------------------------- ### fn serve Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/lsp.md 启动标准输入输出上的语言服务器,直到客户端发送 exit。返回 io::Result<()>,正常流程在收到 exit 通知后返回 Ok(()),stdio 读写失败返回 io::Error。 ```APIDOC ## fn serve ### Description 启动标准输入输出上的语言服务器,直到客户端发送 `exit`。 ### Signature ```rust pub fn serve() -> io::Result<()> ``` ### Parameters 无 ### Returns - `io::Result<()>`:正常流程在收到 `exit` 通知后返回 `Ok(())`;stdio 读写失败返回 `io::Error`(命令行 `mclang lsp` 包装为 `"语言服务器退出:{error}"`)。 ### Behavior 从 `stdin` 逐条读取 JSON-RPC 消息;每条消息经 `Session::handle` 处理后,先写出服务器主动推送的通知(`textDocument/publishDiagnostics`),再写出响应(若有);`session.exiting` 为真时退出循环。 ### Errors `rpc::read_message` 在 `Content-Length` 缺失/非法、消息不是合法 JSON、流结束时抛 `io::Error`(`InvalidData`;流结束是正常返回 `None`)。 ### Example ```rust use mclang::serve; // 标准用法:进程的 stdin/stdout 已被编辑器接管 match serve() { Ok(()) => println!("语言服务器正常退出"), Err(error) => eprintln!("语言服务器退出:{error}"), } ``` ``` -------------------------------- ### Mclang example: score, query, item_stack, tick function Source: https://github.com/ahasasjeb/mclang/blob/main/README.md A complete Mclang program that increments a score each tick, gives a reward item to all players after 100 ticks, and resets the score. Uses the 'namespace', 'score', 'query', 'item_stack', '@tick', 'fn', 'give', and 'if' constructs. ```mcl namespace demo; score ticks = 0; query players = entity("minecraft:player") {} item reward = item_stack("minecraft:emerald") { count = 1; custom_name = "计时奖励"; } @tick fn tick() { ticks += 1; if ticks >= 100 { give(players, reward); ticks = 0; } } ``` -------------------------------- ### Define draw_ui function for screen titles, boss bars, and dialogs Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_zh.txt Defines 'draw_ui' which sends screen titles (title, subtitle, actionbar, times, clear, reset), manipulates a boss bar 'ui_demo:task' (add, set name/color/style/value/max/visible/player list, get values, list, remove), and shows/clears the dialog. ```mclang 函数 draw_ui() { 屏幕标题.屏幕标题(all_players, 文本("Welcome") { 颜色 = "gold"; 粗体 = 真; }); 屏幕标题.副标题(all_players, 翻译("menu.singleplayer")); 屏幕标题.动作栏(all_players, "Status updated"); 屏幕标题.显示时间(all_players, 10 刻, 3 秒, 1 秒); 屏幕标题.清除(all_players); 屏幕标题.重置(all_players); Boss栏.添加("ui_demo:task", 文本("Task") { 颜色 = "yellow"; }); Boss栏.设置.名称("ui_demo:task", "Phase one"); Boss栏.设置.颜色("ui_demo:task", 紫色); Boss栏.设置.样式("ui_demo:task", 十格); Boss栏.设置.数值("ui_demo:task", 4); Boss栏.设置.最大值("ui_demo:task", 10); Boss栏.设置.可见("ui_demo:task", 真); Boss栏.设置.玩家列表("ui_demo:task", all_players); Boss栏.设置.玩家列表("ui_demo:task"); 令 current_value = Boss栏.取("ui_demo:task", 数值); 令 maximum = Boss栏.取("ui_demo:task", 最大值); 令 visible = Boss栏.取("ui_demo:task", 可见); 令 audience = Boss栏.取("ui_demo:task", 玩家列表); Boss栏.列出(); Boss栏.移除("ui_demo:task"); 对话框.显示对话框(all_players, links); 对话框.清除(all_players); } ``` -------------------------------- ### BuildOptions Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/lib.md Configuration options for building projects. ```APIDOC ## [Rust] BuildOptions ### Description Configuration options for building projects. ### Fields - **description** (`String`) - Default: `"Generated by mclang"` - Writes to `pack.mcmeta`'s `pack.description`; overrides the description in `assets/pack.mcmeta` if provided. - **deny_raw** (`bool`) - Default: `false` - Strict mode: when `true`, any `run`, string-form `execute`, `return run`, runtime `with` macro call, or macro function declaring an `nbt` parameter causes the build to fail. ### Default ```rust impl Default for BuildOptions { fn default() -> Self { Self { description: "Generated by mclang".into(), deny_raw: false, } } } ``` ``` -------------------------------- ### NBT Merge Syntax Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Merges NBT data into the current entity (non-player context). Generates `data merge entity @s {...}`. Top-level keys are validated against the entity tag snapshot; unknown keys get a nearest-candidate hint. Common entity keys have Chinese aliases; custom_data and item components are user data and not translated. ```mclang nbt { = ; ... } ``` -------------------------------- ### 嵌入式启动 serve 示例 Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/lsp.md 标准用法:进程的 stdin/stdout 已被编辑器接管。匹配 serve() 的返回值并打印相应消息。 ```rust use mclang::serve; // 标准用法:进程的 stdin/stdout 已被编辑器接管 match serve() { Ok(()) => println!("语言服务器正常退出"), Err(error) => eprintln!("语言服务器退出:{error}"), } ``` -------------------------------- ### Module demo lib/math.mcl with public functions Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_zh.txt Defines public functions sum and product that return scoreboard values. ```mclang 公开 函数 sum(left, right) -> 计分 { 返回 left + right; } 公开 函数 product(left, right) -> 计分 { 返回 left * right; } ``` -------------------------------- ### Module demo main.mcl with imports and public scoreboard Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_zh.txt Defines a namespace, imports functions from lib::math and std::state, declares a public scoreboard, and uses them in a load function. ```mclang 命名空间 module_demo; 导入 lib::math::{sum, product}; 导入 std::state::{toggle}; 公开 计分 total = 0; 计分 enabled = 0; @加载 函数 load() { 消息.全部("module demo loaded", 绿色); total = sum(1, 2) + product(3, 4); enabled = toggle(enabled); } ``` -------------------------------- ### Recipe commands Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Give or take recipes from a holder. Use * to represent all recipes. ```mclang recipe.give(, |*); recipe.take(, |*); ``` -------------------------------- ### 编译器接口命令 Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_zh.txt Mclang 编译器提供的命令行接口,包括 build、check、lsp、help 和 version。build 会先检查再输出数据包,check 只检查不写文件。 ```text mclang build <源文件.mcl|项目目录> [-o <输出>] [--zip] [--description <文本>] [--deny-raw] mclang check <源文件.mcl|项目目录> [--deny-raw] mclang lsp mclang help | mclang version ``` -------------------------------- ### 定义 CompileOptions 结构体 Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/compiler.md 公开结构体,包含编译选项。`description` 为必填字段,写入 `pack.mcmeta` 的 `pack.description`;命令行或 `check_file` 默认使用 `"Generated by mclang"`。`codegen` 完成后由 `Compiler::finish` 使用。 ```rust /// 编译选项。 pub struct CompileOptions { // src/compiler/mod.rs:48 /// 写入 `pack.mcmeta` 的描述。 pub description: String, } ``` -------------------------------- ### execute 命令示例:execute_demo 命名空间 Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_zh.txt 展示了 mclang 中 execute 命令的结构化执行修饰符、条件与存值。包含命名空间、目标、查询和物品定义。 ```mclang --- 05_execute.mcl:结构化执行的修饰符、条件与存值 --- 命名空间 execute_demo; 目标 cleared; 查询 players = 实体("minecraft:player") {} 查询 zombies = 实体("minecraft:zombie") { 范围(16); } 查询 one_zombie = 实体("minecraft:zombie") { 上限(1); } 物品 token = 物品堆("minecraft:gold_nugget") { 数量 = 3; } ``` -------------------------------- ### Basic `analyze` call with diagnostics and symbols Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/analysis.md Basic call to `analyze` for editor/CI integration. Creates `SourceFile` entries from raw text, runs the analysis, prints each diagnostic with path and span, then iterates `analysis.symbols` to drive completion. Requires `mclang::analysis::{SourceFile, analyze}` and `std::path::PathBuf`. ```rust use mclang::analysis::{SourceFile, analyze}; use std::path::PathBuf; let sources = vec![ SourceFile { path: PathBuf::from("main.mcl"), text: "namespace demo; score ticks = 0; fn main() { ticks += 1; }", }, ]; let analysis = analyze(&sources); for diagnostic in analysis.diagnostics { eprintln!("{}:{}:{} {}", diagnostic.path.display(), diagnostic.span.start, diagnostic.span.end, diagnostic.message); } // symbols 可以直接驱动补全:遍历 analysis.symbols 取 name/kind/detail for symbol in analysis.symbols { println!("{}({})", symbol.name, symbol.kind.label()); } ``` -------------------------------- ### Macro demo with runtime macro invocation Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_zh.txt Defines a macro function welcome, a function tag, and an invoke function that calls macros with data and scheduling. Note that runtime macro calls using 用 are rejected by --deny-raw. ```mclang 命名空间 macro_demo; 查询 players = 实体("minecraft:player") {} 计分 active = 1; 宏 函数 welcome(文本 label, 整数 x, 小数 z) { 消息.全部(文本("Hello $(label)")); 传送(players, 精确坐标(宏(x), 64, 宏(z))); 如果 active == 1 { 消息.全部(文本("$(label) arrived")); } } 函数标签 greetings { 值(welcome); } 函数 invoke() { 调用 welcome(数据 { label = "Alex"; x = 5; z = 0.5d; }); 调用 #greetings(数据 { label = "Steve"; x = 6; z = 1.5d; }); 调用 "external:plain"(); 调度 "external:plain"() 延后 1 秒; 调度.清除("external:plain"); } 函数 dynamic() { 调用 welcome 用(存储, "macro_demo:args", "payload"); } ``` -------------------------------- ### 构建和运行 mclang 命令 Source: https://github.com/ahasasjeb/mclang/blob/main/README.md 用于构建编译器并运行 check、build 命令。构建产物在 target/release/mclang.exe。check 只做静态检查不写文件;build 编译为数据包,默认输出到 build/<项目名>;--zip 直接生成 ZIP。 ```powershell # 构建编译器(可执行文件在 target/release/mclang.exe) cargo build --release # 静态检查,不写文件 cargo run -- check examples/portable_chest --deny-raw # 编译为数据包,默认输出到 build/<项目名> cargo run -- build examples/portable_chest --deny-raw # 直接生成 build/portable_chest.zip cargo run --bin mclang -- build examples/portable_chest --zip --deny-raw ``` -------------------------------- ### 用法摘要(print_help) Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/cli.md 打印 `mclang` 命令的用法摘要,包含 `build`、`check`、`lsp`、`help`、`version` 子命令及其参数。 ```text mclang build <源文件.mcl|项目目录> [-o <输出路径>] [--zip] [--description <文本>] [--deny-raw] mclang check <源文件.mcl|项目目录> [--deny-raw] mclang lsp mclang help mclang version ``` -------------------------------- ### Box preparation and destruction functions Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Prepares a box entity with tags and invulnerability, and destroys boxes while preserving items. ```mclang @non_player fn prepare_box() { self.add_tag("box"); self.set_invulnerable(true); self.restore_items(saved); } fn destroy_box() { each(boxes) { self.remove_preserving_items(stash, target); } } ``` -------------------------------- ### 使用 suggest() 进行拼写修复提示 Source: https://github.com/ahasasjeb/mclang/blob/main/_autodocs/api-reference/version-entity-nbt.md 示例演示如何使用 suggest() 获取接近候选以提示用户修正拼写错误。 ```rust use mclang::version::entity_nbt::catalog; let catalog = catalog(); let bad = "NoAi"; match catalog.suggest(bad, None) { Some(suggestion) => eprintln!("命名键 `{bad}` 不存在;你是不是想写 {suggestion}"), None => eprintln!("没有接近的候选"), } // 输出:命名键 `NoAi` 不存在;你是不是想写 `NoAI` ``` -------------------------------- ### 01_hello.mcl:最小完整程序 Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_zh.txt 完整项目示例,使用中文关键词。包含 @加载 和 @每刻 函数,计分板 ticks 和查询 all_players。每 100 tick 向所有玩家发送消息和声音。 ```mclang 命名空间 hello; 计分 ticks = 0; 查询 all_players = 实体("minecraft:player") {} @加载 函数 load() { 消息.全部("Hello from Mclang", 绿色); } @每刻 函数 tick() { ticks += 1; 如果 ticks >= 100 { 遍历(all_players) { 消息.自身("Five seconds passed.", 金色); 声音.自身("minecraft:block.note_block.pling", 主音量); } ticks = 0; } } ``` -------------------------------- ### 常用开发命令 Source: https://github.com/ahasasjeb/mclang/blob/main/AGNETS.md 用于格式化、检查、编译示例和测试语料的命令。包含 `cargo fmt`、`cargo clippy --all-targets` 和 `cargo run -- <子命令>` 的用法。 ```powershell cargo fmt cargo clippy --all-targets # 编译并检查示例 cargo run -- build examples/portable_chest cargo run -- check examples/multi_counter --deny-raw cargo run -- build examples/give_reward.mcl -o build/give_reward --description "奖励示例" # 编译测试语料 cargo run -- build tests/valid/language -o build/tests/language --deny-raw cargo run -- check tests/invalid/items.mcl ``` -------------------------------- ### UI Demo (09_ui.mcl) Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt Shows MCLang code for UI features: defining an objective, queries, and a resource for server links. ```mclang --- 09_ui.mcl: text styles, title, bossbar, dialog, particle, posteffect, chat --- namespace ui_demo; objective_dummy; query all_players = entity("minecraft:player") {} query one_player = entity("minecraft:player") { limit(1); } resource dialog links = """{"type":"minecraft:server_links","title":{"text":"Links"},"external_title":{"text":"Links"}}"""; ``` -------------------------------- ### 构建 VSCode 插件 Source: https://github.com/ahasasjeb/mclang/blob/main/README.md 构建并安装 VSCode 插件,需要先构建编译器。 ```powershell cargo build --release cd editors/vscode npm install npx vsce package code --install-extension mclang-0.5.0.vsix ``` -------------------------------- ### List command Source: https://github.com/ahasasjeb/mclang/blob/main/mclang_llm_en.txt List entities, optionally returning UUIDs. ```mclang let n = list([]); ```