@overmvp/kumi 0.0.0-stage → 0.1.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.
Files changed (205) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +14 -2
  3. package/animation/color-transition.ts +196 -0
  4. package/animation/cycle.ts +151 -0
  5. package/animation/ease.ts +29 -0
  6. package/animation/index.ts +13 -0
  7. package/animation/package.json +12 -0
  8. package/animation/presets.ts +376 -0
  9. package/animation/spec.ts +197 -0
  10. package/builder/Cargo.lock +192 -0
  11. package/builder/Cargo.toml +7 -0
  12. package/builder/css-v1.mjs +334 -0
  13. package/builder/css-v1.test.mjs +321 -0
  14. package/builder/generated-output.mjs +61 -0
  15. package/builder/generated-output.test.mjs +132 -0
  16. package/builder/jsx-form.mjs +93 -0
  17. package/builder/jsx-form.test.mjs +48 -0
  18. package/builder/jsx-lists.mjs +209 -0
  19. package/builder/link-addon-package.mjs +86 -0
  20. package/builder/lua-assets.mjs +74 -0
  21. package/builder/lua-builtin-values.mjs +57 -0
  22. package/builder/lua-builtin-values.test.mjs +155 -0
  23. package/builder/lua-loop-closures.mjs +183 -0
  24. package/builder/lua-loop-closures.test.mjs +89 -0
  25. package/builder/lua-truthiness.mjs +61 -0
  26. package/builder/lua-truthiness.test.mjs +113 -0
  27. package/builder/module-declarations.mjs +594 -0
  28. package/builder/module-declarations.test.mjs +444 -0
  29. package/builder/native-kernels.mjs +60 -0
  30. package/builder/native-lua.d.ts +57 -0
  31. package/builder/native-routes.mjs +51 -0
  32. package/builder/no-static-ref-read.mjs +93 -0
  33. package/builder/no-static-ref-read.test.mjs +181 -0
  34. package/builder/secure-snippet.mjs +317 -0
  35. package/builder/secure-snippet.test.mjs +101 -0
  36. package/builder/shared-lua-runtime.mjs +150 -0
  37. package/builder/src/addon-link.lua +29 -0
  38. package/builder/src/arrays.lua +260 -0
  39. package/builder/src/assets.rs +177 -0
  40. package/builder/src/classes.lua +75 -0
  41. package/builder/src/collections.lua +190 -0
  42. package/builder/src/compiler.rs +2164 -0
  43. package/builder/src/config.rs +42 -0
  44. package/builder/src/entries.rs +166 -0
  45. package/builder/src/errors.lua +15 -0
  46. package/builder/src/lua_data.rs +231 -0
  47. package/builder/src/main.rs +367 -0
  48. package/builder/src/native_ir.rs +65 -0
  49. package/builder/src/native_signal.rs +47 -0
  50. package/builder/src/numbers.lua +62 -0
  51. package/builder/src/project-front.mjs +3331 -0
  52. package/builder/src/records.lua +75 -0
  53. package/builder/src/routes.rs +127 -0
  54. package/builder/src/signal-kernel.fingerprint +1 -0
  55. package/builder/src/strings.lua +103 -0
  56. package/builder/src/ts-lower.mjs +68 -0
  57. package/builder/src/wow_client.rs +253 -0
  58. package/builder/src/wow_types.rs +564 -0
  59. package/builder/style-states.mjs +100 -0
  60. package/builder/style-states.test.mjs +103 -0
  61. package/builder/vite-assets.mjs +53 -0
  62. package/builder/vite-project.mjs +10 -0
  63. package/config.ts +17 -0
  64. package/form/index.ts +522 -0
  65. package/form/package.json +13 -0
  66. package/motion/index.ts +2 -0
  67. package/motion/package.json +10 -0
  68. package/package.json +22 -4
  69. package/router/index.ts +43 -0
  70. package/router/package.json +12 -0
  71. package/router/routes.ts +64 -0
  72. package/scripts/kumi-cli.mjs +70 -0
  73. package/scripts/link-addons.mjs +51 -0
  74. package/src/bindings.ts +35 -0
  75. package/src/context.ts +15 -0
  76. package/src/css-tokens.ts +234 -0
  77. package/src/css-v1.ts +58 -0
  78. package/src/cvars.ts +91 -0
  79. package/src/element-node.ts +32 -0
  80. package/src/elements.ts +479 -0
  81. package/src/feature-scope.ts +82 -0
  82. package/src/flex-layout.ts +807 -0
  83. package/src/frame-scheduler.ts +334 -0
  84. package/src/grid-tracks.ts +165 -0
  85. package/src/image-imports.d.ts +24 -0
  86. package/src/images.ts +79 -0
  87. package/src/index.ts +28 -0
  88. package/src/jsx-dev-runtime.ts +2 -0
  89. package/src/jsx-runtime.ts +22 -0
  90. package/src/jsx.d.ts +12 -0
  91. package/src/keyed-list.ts +363 -0
  92. package/src/media-query.ts +144 -0
  93. package/src/module.ts +277 -0
  94. package/src/node-selectors.ts +114 -0
  95. package/src/owned-collections.ts +44 -0
  96. package/src/providers.ts +235 -0
  97. package/src/reactive-scope.ts +34 -0
  98. package/src/reactivity.ts +254 -0
  99. package/src/result.ts +58 -0
  100. package/src/runtime.ts +52 -0
  101. package/src/scheduler.ts +185 -0
  102. package/src/signal-kernel.ts +30 -0
  103. package/src/style-classes.ts +51 -0
  104. package/src/style-states.ts +134 -0
  105. package/src/style-variables.ts +53 -0
  106. package/src/text-children.ts +42 -0
  107. package/src/theme.ts +50 -0
  108. package/src/transition.ts +18 -0
  109. package/state/index.ts +3 -0
  110. package/state/package.json +12 -0
  111. package/state/store-bindings.ts +25 -0
  112. package/state/store.ts +82 -0
  113. package/styles/_layers.scss +14 -0
  114. package/templates/addon/README.md +14 -0
  115. package/templates/addon/__ADDON_NAME__.toc +4 -0
  116. package/templates/addon/eslint.config.mjs +12 -0
  117. package/templates/addon/gitignore +8 -0
  118. package/templates/addon/package.json +21 -0
  119. package/templates/addon/scripts/build.mjs +25 -0
  120. package/templates/addon/src/app/main.tsx +13 -0
  121. package/templates/addon/tsconfig.json +24 -0
  122. package/translate/index.ts +14 -0
  123. package/translate/package.json +9 -0
  124. package/utils/colors.ts +76 -0
  125. package/utils/format.ts +37 -0
  126. package/utils/index.ts +4 -0
  127. package/utils/number.ts +17 -0
  128. package/utils/package.json +7 -0
  129. package/utils/text.ts +6 -0
  130. package/validate/index.ts +119 -0
  131. package/validate/package.json +9 -0
  132. package/wow/absolute-position.ts +142 -0
  133. package/wow/animation.ts +428 -0
  134. package/wow/aura-button.ts +76 -0
  135. package/wow/aura-container.ts +591 -0
  136. package/wow/aura-countdown.ts +201 -0
  137. package/wow/aura-slot.ts +153 -0
  138. package/wow/bar-shade.ts +93 -0
  139. package/wow/borrowed-slot.ts +216 -0
  140. package/wow/button-drag.ts +48 -0
  141. package/wow/cast-clock.ts +153 -0
  142. package/wow/cast-text.ts +83 -0
  143. package/wow/class-colors.ts +126 -0
  144. package/wow/clock.ts +7 -0
  145. package/wow/color-picker.ts +128 -0
  146. package/wow/commands.ts +17 -0
  147. package/wow/contained-frame.ts +128 -0
  148. package/wow/contract.ts +42 -0
  149. package/wow/css-box.ts +110 -0
  150. package/wow/css-color.ts +12 -0
  151. package/wow/css-style.ts +109 -0
  152. package/wow/css-surfaces.ts +398 -0
  153. package/wow/css-text.ts +399 -0
  154. package/wow/cvar-schema.ts +32 -0
  155. package/wow/cvars.ts +98 -0
  156. package/wow/dropdown-art.ts +39 -0
  157. package/wow/element-click.ts +20 -0
  158. package/wow/element-event-coordinator.ts +219 -0
  159. package/wow/element-events.ts +317 -0
  160. package/wow/event-dispatcher.ts +151 -0
  161. package/wow/events.ts +50 -0
  162. package/wow/font-cache.ts +92 -0
  163. package/wow/frame-access.ts +31 -0
  164. package/wow/frame-layer.ts +5 -0
  165. package/wow/frames.ts +236 -0
  166. package/wow/heal-prediction.ts +305 -0
  167. package/wow/image-layers.ts +55 -0
  168. package/wow/index.ts +97 -0
  169. package/wow/layout-view.ts +651 -0
  170. package/wow/lua-string.ts +18 -0
  171. package/wow/lua-table.ts +18 -0
  172. package/wow/macro-book.ts +84 -0
  173. package/wow/map-position.ts +27 -0
  174. package/wow/media-query.ts +65 -0
  175. package/wow/module-events.ts +11 -0
  176. package/wow/native-hooks.ts +168 -0
  177. package/wow/native-placement.ts +88 -0
  178. package/wow/native.ts +135 -0
  179. package/wow/number-format.ts +8 -0
  180. package/wow/number-input.ts +10 -0
  181. package/wow/protect.ts +24 -0
  182. package/wow/protected-layout.ts +133 -0
  183. package/wow/range-art.ts +74 -0
  184. package/wow/reparent-frame.ts +99 -0
  185. package/wow/rounded-texture.ts +156 -0
  186. package/wow/saved-variables.ts +60 -0
  187. package/wow/scroll-view.ts +64 -0
  188. package/wow/secret-ref.ts +14 -0
  189. package/wow/secure-bindings.ts +89 -0
  190. package/wow/secure-clicks.ts +432 -0
  191. package/wow/secure-snippet.ts +235 -0
  192. package/wow/secure-state.ts +130 -0
  193. package/wow/secure-target-visibility.ts +89 -0
  194. package/wow/secure-transaction.ts +331 -0
  195. package/wow/special-window.ts +269 -0
  196. package/wow/start-addon.ts +99 -0
  197. package/wow/state-paint.ts +256 -0
  198. package/wow/transition.ts +86 -0
  199. package/wow/unit-button.ts +39 -0
  200. package/wow/unit-cast.ts +92 -0
  201. package/wow/unit-health-text.ts +47 -0
  202. package/wow/view-nodes.ts +304 -0
  203. package/wow/view.ts +1746 -0
  204. package/wow/visible-frame-job.ts +34 -0
  205. package/wow/width-reserve.ts +108 -0
@@ -0,0 +1,42 @@
1
+ use std::io;
2
+ use std::path::{Path, PathBuf};
3
+ use std::process::Command;
4
+
5
+ pub fn addons_dir(project: &Path) -> io::Result<Option<PathBuf>> {
6
+ let path = project.join("kumi.config.ts");
7
+ if !path.try_exists()? {
8
+ return Ok(None);
9
+ }
10
+ let output = Command::new("node")
11
+ .current_dir(project)
12
+ .args(["--input-type=module", "-e"])
13
+ .arg(
14
+ r#"
15
+ import { pathToFileURL } from "node:url";
16
+ const { default: config } = await import(pathToFileURL(process.argv[1]).href);
17
+ const directory = config?.build?.addonsDir;
18
+ if (directory !== undefined) {
19
+ if (typeof directory !== "string" || !directory.trim() || directory.includes("\0")) {
20
+ throw new Error("build.addonsDir must be a non-empty path");
21
+ }
22
+ }
23
+ process.stdout.write("\0" + (directory ?? ""));
24
+ "#,
25
+ )
26
+ .arg(path)
27
+ .output()?;
28
+ if !output.status.success() {
29
+ return Err(io::Error::other(format!(
30
+ "Could not load kumi.config.ts: {}",
31
+ String::from_utf8_lossy(&output.stderr).trim()
32
+ )));
33
+ }
34
+ let output = String::from_utf8(output.stdout).map_err(io::Error::other)?;
35
+ let (_, directory) = output.rsplit_once('\0').ok_or_else(|| {
36
+ io::Error::new(
37
+ io::ErrorKind::InvalidData,
38
+ "Config loader returned no result",
39
+ )
40
+ })?;
41
+ Ok((!directory.is_empty()).then(|| PathBuf::from(directory)))
42
+ }
@@ -0,0 +1,166 @@
1
+ use std::collections::BTreeMap;
2
+ use std::fs;
3
+ use std::io;
4
+ use std::path::{Component, Path, PathBuf};
5
+ use std::process::Command;
6
+
7
+ fn json(text: &str) -> String {
8
+ let mut result = String::from("\"");
9
+ for character in text.chars() {
10
+ match character {
11
+ '"' => result.push_str("\\\""),
12
+ '\\' => result.push_str("\\\\"),
13
+ '\n' => result.push_str("\\n"),
14
+ '\r' => result.push_str("\\r"),
15
+ '\t' => result.push_str("\\t"),
16
+ c if c.is_control() => result.push_str(&format!("\\u{:04x}", c as u32)),
17
+ c => result.push(c),
18
+ }
19
+ }
20
+ result.push('"');
21
+ result
22
+ }
23
+
24
+ fn normalized(path: &Path) -> io::Result<String> {
25
+ path.to_str()
26
+ .map(|path| path.replace('\\', "/"))
27
+ .ok_or_else(|| io::Error::other("Bundle paths must be UTF-8"))
28
+ }
29
+
30
+ fn write_generated(file: &Path, source: &str, check: bool) -> io::Result<()> {
31
+ if fs::read_to_string(file).ok().as_deref() == Some(source) {
32
+ return Ok(());
33
+ }
34
+ if check {
35
+ return Err(io::Error::other(format!(
36
+ "{} is stale; run kumi-pack build",
37
+ file.display()
38
+ )));
39
+ }
40
+ fs::write(file, source)
41
+ }
42
+
43
+ pub fn generate(
44
+ workspace: &Path,
45
+ project: &Path,
46
+ output: &Path,
47
+ selected: &[String],
48
+ check: bool,
49
+ ) -> io::Result<BTreeMap<String, PathBuf>> {
50
+ let config = project.join("kumi.config.ts");
51
+ if !config.try_exists()? {
52
+ return Ok(BTreeMap::new());
53
+ }
54
+ let result = Command::new("node")
55
+ .current_dir(project)
56
+ .args(["--input-type=module", "-e"])
57
+ .arg(
58
+ r#"
59
+ import { readFileSync } from "node:fs";
60
+ import { relative, resolve } from "node:path";
61
+ import { pathToFileURL } from "node:url";
62
+
63
+ const { default: config } = await import(pathToFileURL(process.argv[1]).href);
64
+ const workspace = process.argv[2];
65
+ const selected = new Set(process.argv.slice(3));
66
+ const seen = new Set();
67
+ const records = [];
68
+ for (const entry of config.build?.imports ?? []) {
69
+ const { bundle, mode } = entry;
70
+ if (typeof bundle !== "string" || !/^[a-z][a-z0-9-]*$/.test(bundle) || seen.has(bundle)) {
71
+ throw new Error("Invalid or duplicate generated bundle: " + bundle);
72
+ }
73
+ seen.add(bundle);
74
+ if (entry.entry === undefined || !selected.has(bundle)) continue;
75
+ if (entry.entry !== "module" || (mode !== "plugin" && mode !== "embedded")) {
76
+ throw new Error(bundle + ": expected entry: 'module' and mode: 'plugin' or 'embedded'");
77
+ }
78
+ const manifest = JSON.parse(readFileSync("modules/" + bundle + ".module.json", "utf8"));
79
+ if (mode === "embedded" && manifest.embeddable !== true) {
80
+ throw new Error(bundle + ": embedding is not supported by its addon manifest");
81
+ }
82
+ const lua = relative(workspace, resolve(manifest.output)).replaceAll("\\", "/");
83
+ const addon = /^plugins\/([^/]+)\//.exec(lua)?.[1];
84
+ if (!addon || !lua.endsWith(".lua")) throw new Error(bundle + ": expected a plugin Lua output");
85
+ const toc = readFileSync(resolve(workspace, "plugins", addon, addon + ".toc"), "utf8");
86
+ const dependencies = (/^##\s*(?:Dependencies|RequiredDeps):[^\S\r\n]*(.*)$/m.exec(toc)?.[1] ?? "")
87
+ .split(/[,\s]+/).filter(Boolean);
88
+ records.push(bundle, mode, lua, dependencies.join(","));
89
+ }
90
+ process.stdout.write("\0" + records.join("\0") + "\0");
91
+ "#,
92
+ )
93
+ .arg(config)
94
+ .arg(workspace)
95
+ .args(selected)
96
+ .output()?;
97
+ if !result.status.success() {
98
+ return Err(io::Error::other(format!(
99
+ "Could not resolve bundle entries from kumi.config.ts: {}",
100
+ String::from_utf8_lossy(&result.stderr).trim()
101
+ )));
102
+ }
103
+ let text = String::from_utf8(result.stdout).map_err(io::Error::other)?;
104
+ let fields = text
105
+ .split_once('\0')
106
+ .and_then(|(_, text)| text.strip_suffix('\0'))
107
+ .ok_or_else(|| io::Error::other("Invalid bundle configuration output"))?;
108
+ if fields.is_empty() {
109
+ return Ok(BTreeMap::new());
110
+ }
111
+ let fields = fields.split('\0').collect::<Vec<_>>();
112
+ let project_path = project.strip_prefix(workspace).map_err(io::Error::other)?;
113
+ if project_path
114
+ .components()
115
+ .any(|part| !matches!(part, Component::Normal(_)))
116
+ {
117
+ return Err(io::Error::other(
118
+ "Expected a project path inside the workspace",
119
+ ));
120
+ }
121
+ let directory = output.join("entries");
122
+ if !check {
123
+ fs::create_dir_all(&directory)?;
124
+ }
125
+
126
+ let mut entries = BTreeMap::new();
127
+ for record in fields.chunks(4) {
128
+ let [bundle, mode, lua, requires] = record else {
129
+ return Err(io::Error::other("Incomplete bundle configuration"));
130
+ };
131
+ let declaration = project_path.join(format!("src/modules/{bundle}/{bundle}.module.ts"));
132
+ if !workspace.join(&declaration).is_file() {
133
+ return Err(io::Error::other(format!(
134
+ "{bundle}: expected source declaration {}",
135
+ declaration.display()
136
+ )));
137
+ }
138
+ let source = normalized(&declaration.with_extension(""))?;
139
+ let input = directory.join(format!("{bundle}.ts"));
140
+ let manifest = directory.join(format!("{bundle}.json"));
141
+ let entry = format!(
142
+ "// Generated by kumi-pack. Edit the source module.\nimport {{ activate }} from {};\n\nactivate();\n",
143
+ json(&format!("../../{source}"))
144
+ );
145
+ let dependencies = requires
146
+ .split(',')
147
+ .filter(|name| !name.is_empty())
148
+ .map(json)
149
+ .collect::<Vec<_>>()
150
+ .join(", ");
151
+ let plan = format!(
152
+ "{{\n \"module\": {},\n \"mode\": {},\n \"declaration\": {},\n \"entry\": {},\n \"lua\": {},\n \"dependencies\": [{}]\n}}\n",
153
+ json(bundle),
154
+ json(mode),
155
+ json(&normalized(&declaration)?),
156
+ json(&normalized(input.strip_prefix(workspace).map_err(io::Error::other)?)?),
157
+ json(&format!("lua/{lua}")),
158
+ dependencies
159
+ );
160
+ write_generated(&input, &entry, check)?;
161
+ write_generated(&manifest, &plan, check)?;
162
+ println!("{bundle} ({mode}) -> lua/{lua}");
163
+ entries.insert((*bundle).to_owned(), input);
164
+ }
165
+ Ok(entries)
166
+ }
@@ -0,0 +1,15 @@
1
+ local errorMeta = {}
2
+
3
+ function errorMeta.__tostring(value)
4
+ local name = value.name
5
+ local message = value.message
6
+ if message ~= "" then return name .. ": " .. message end
7
+ return name
8
+ end
9
+
10
+ local function createError(message)
11
+ local stack
12
+ if debug and debug.traceback then stack = debug.traceback("", 2):sub(2) end
13
+ if message == nil then message = "" end
14
+ return setmetatable({ name = "Error", message = message, stack = stack }, errorMeta)
15
+ end
@@ -0,0 +1,231 @@
1
+ use std::collections::BTreeMap;
2
+
3
+ #[derive(Debug, Default)]
4
+ pub struct Table {
5
+ fields: BTreeMap<String, Value>,
6
+ pub entries: Vec<Value>,
7
+ }
8
+
9
+ #[derive(Debug)]
10
+ pub enum Value {
11
+ Text(String),
12
+ Boolean(bool),
13
+ Table(Table),
14
+ Other,
15
+ }
16
+
17
+ impl Value {
18
+ pub fn table(&self) -> Option<&Table> {
19
+ match self {
20
+ Self::Table(table) => Some(table),
21
+ _ => None,
22
+ }
23
+ }
24
+ }
25
+
26
+ impl Table {
27
+ pub fn text(&self, key: &str) -> Option<&str> {
28
+ match self.fields.get(key)? {
29
+ Value::Text(text) => Some(text),
30
+ _ => None,
31
+ }
32
+ }
33
+
34
+ pub fn flag(&self, key: &str) -> bool {
35
+ matches!(self.fields.get(key), Some(Value::Boolean(true)))
36
+ }
37
+
38
+ pub fn has(&self, key: &str) -> bool {
39
+ self.fields.contains_key(key)
40
+ }
41
+
42
+ pub fn has_prefix(&self, prefix: &str) -> bool {
43
+ self.fields
44
+ .iter()
45
+ .any(|(key, value)| key.starts_with(prefix) && !matches!(value, Value::Boolean(false)))
46
+ }
47
+
48
+ pub fn list(&self, key: &str) -> impl Iterator<Item = &Table> {
49
+ self.fields
50
+ .get(key)
51
+ .and_then(Value::table)
52
+ .into_iter()
53
+ .flat_map(|table| &table.entries)
54
+ .filter_map(Value::table)
55
+ }
56
+ }
57
+
58
+ #[derive(Debug, PartialEq)]
59
+ enum Token {
60
+ Word(String),
61
+ Text(String),
62
+ Punct(u8),
63
+ }
64
+
65
+ fn long_bracket(bytes: &[u8], start: usize) -> Option<(usize, usize)> {
66
+ if bytes.get(start) != Some(&b'[') {
67
+ return None;
68
+ }
69
+ let mut open = start + 1;
70
+ while bytes.get(open) == Some(&b'=') {
71
+ open += 1;
72
+ }
73
+ if bytes.get(open) != Some(&b'[') {
74
+ return None;
75
+ }
76
+ let width = open - start + 1;
77
+ for end in open + 1..bytes.len() {
78
+ let close = bytes.get(end..end + width);
79
+ if close.is_some_and(|part| {
80
+ part[0] == b']'
81
+ && part[width - 1] == b']'
82
+ && part[1..width - 1].iter().all(|byte| *byte == b'=')
83
+ }) {
84
+ return Some((open + 1, end));
85
+ }
86
+ }
87
+ None
88
+ }
89
+
90
+ fn tokens(text: &str) -> Result<Vec<Token>, String> {
91
+ let bytes = text.as_bytes();
92
+ let mut output = Vec::new();
93
+ let mut index = 0;
94
+ while index < bytes.len() {
95
+ let start = index;
96
+ let byte = bytes[index];
97
+ index += 1;
98
+ match byte {
99
+ b if b.is_ascii_whitespace() => {}
100
+ b'-' if bytes.get(index) == Some(&b'-') => {
101
+ index += 1;
102
+ if let Some((first, last)) = long_bracket(bytes, index) {
103
+ index = last + first - index;
104
+ } else {
105
+ while index < bytes.len() && bytes[index] != b'\n' {
106
+ index += 1;
107
+ }
108
+ }
109
+ }
110
+ b'\'' | b'"' => {
111
+ while let Some(next) = bytes.get(index) {
112
+ if *next == byte {
113
+ break;
114
+ }
115
+ index += if *next == b'\\' { 2 } else { 1 };
116
+ }
117
+ let string = text.get(start + 1..index).ok_or("invalid quoted string")?;
118
+ if index == bytes.len() {
119
+ return Err("unterminated quoted string".into());
120
+ }
121
+ output.push(Token::Text(string.to_owned()));
122
+ index += 1;
123
+ }
124
+ b'[' if long_bracket(bytes, start).is_some() => {
125
+ let (first, last) = long_bracket(bytes, start).unwrap();
126
+ output.push(Token::Text(text[first..last].to_owned()));
127
+ index = last + first - start;
128
+ }
129
+ b if b.is_ascii_alphanumeric() || b == b'_' => {
130
+ while bytes
131
+ .get(index)
132
+ .is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_')
133
+ {
134
+ index += 1;
135
+ }
136
+ output.push(Token::Word(text[start..index].to_owned()));
137
+ }
138
+ b => output.push(Token::Punct(b)),
139
+ }
140
+ }
141
+ Ok(output)
142
+ }
143
+
144
+ struct Parser<'a> {
145
+ tokens: &'a [Token],
146
+ index: usize,
147
+ }
148
+
149
+ impl Parser<'_> {
150
+ fn punct(&mut self, symbol: u8) -> bool {
151
+ if self.tokens.get(self.index) != Some(&Token::Punct(symbol)) {
152
+ return false;
153
+ }
154
+ self.index += 1;
155
+ true
156
+ }
157
+
158
+ fn table(&mut self) -> Result<Table, String> {
159
+ let mut table = Table::default();
160
+ while !self.punct(b'}') {
161
+ if self.index >= self.tokens.len() {
162
+ return Err("unterminated table".into());
163
+ }
164
+ let key = match self.tokens.get(self.index..self.index + 2) {
165
+ Some([Token::Word(key), Token::Punct(b'=')]) => {
166
+ self.index += 2;
167
+ Some(key.clone())
168
+ }
169
+ _ => None,
170
+ };
171
+ let value = self.value()?;
172
+ if let Some(key) = key {
173
+ table.fields.insert(key, value);
174
+ } else {
175
+ table.entries.push(value);
176
+ }
177
+ if !self.punct(b',')
178
+ && !self.punct(b';')
179
+ && self.tokens.get(self.index) != Some(&Token::Punct(b'}'))
180
+ {
181
+ return Err(format!(
182
+ "expected a table separator near token {}",
183
+ self.index
184
+ ));
185
+ }
186
+ }
187
+ Ok(table)
188
+ }
189
+
190
+ fn value(&mut self) -> Result<Value, String> {
191
+ if self.punct(b'{') {
192
+ return self.table().map(Value::Table);
193
+ }
194
+ let start = self.index;
195
+ let mut nesting = 0;
196
+ while let Some(token) = self.tokens.get(self.index) {
197
+ match token {
198
+ Token::Punct(b',' | b';' | b'}') if nesting == 0 => break,
199
+ Token::Punct(b'(' | b'[' | b'{') => nesting += 1,
200
+ Token::Punct(b')' | b']' | b'}') => nesting -= 1,
201
+ _ => {}
202
+ }
203
+ self.index += 1;
204
+ }
205
+ Ok(match &self.tokens[start..self.index] {
206
+ [Token::Text(text)] => Value::Text(text.clone()),
207
+ [Token::Word(word)] if word == "true" => Value::Boolean(true),
208
+ [Token::Word(word)] if word == "false" => Value::Boolean(false),
209
+ [] => return Err("missing table value".into()),
210
+ _ => Value::Other,
211
+ })
212
+ }
213
+ }
214
+
215
+ pub fn documentation(text: &str) -> Result<Table, String> {
216
+ let tokens = tokens(text)?;
217
+ for (index, pattern) in tokens.windows(4).enumerate() {
218
+ if matches!(pattern, [Token::Word(local), Token::Word(_), Token::Punct(b'='), Token::Punct(b'{')] if local == "local")
219
+ {
220
+ let mut parser = Parser {
221
+ tokens: &tokens,
222
+ index: index + 4,
223
+ };
224
+ let table = parser.table()?;
225
+ if table.has("Functions") || table.has("Events") || table.has("Tables") {
226
+ return Ok(table);
227
+ }
228
+ }
229
+ }
230
+ Err("Blizzard documentation table was not found".into())
231
+ }