@tishlang/tish-format 1.0.12 → 1.0.13

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 (164) hide show
  1. package/Cargo.toml +49 -0
  2. package/LICENSE +13 -0
  3. package/README.md +138 -0
  4. package/bin/tish-format +0 -0
  5. package/crates/js_to_tish/Cargo.toml +11 -0
  6. package/crates/js_to_tish/README.md +18 -0
  7. package/crates/js_to_tish/src/error.rs +55 -0
  8. package/crates/js_to_tish/src/lib.rs +11 -0
  9. package/crates/js_to_tish/src/span_util.rs +35 -0
  10. package/crates/js_to_tish/src/transform/expr.rs +610 -0
  11. package/crates/js_to_tish/src/transform/stmt.rs +503 -0
  12. package/crates/js_to_tish/src/transform.rs +60 -0
  13. package/crates/tish/Cargo.toml +54 -0
  14. package/crates/tish/src/cargo_native_registry.rs +32 -0
  15. package/crates/tish/src/cli_help.rs +565 -0
  16. package/crates/tish/src/main.rs +781 -0
  17. package/crates/tish/src/repl_completion.rs +200 -0
  18. package/crates/tish/tests/cargo_example_compile.rs +67 -0
  19. package/crates/tish/tests/fixtures/cargo_example_project/Cargo.toml +3 -0
  20. package/crates/tish/tests/fixtures/cargo_example_project/crates/demo-shim/Cargo.toml +11 -0
  21. package/crates/tish/tests/fixtures/cargo_example_project/crates/demo-shim/src/lib.rs +12 -0
  22. package/crates/tish/tests/fixtures/cargo_example_project/package.json +10 -0
  23. package/crates/tish/tests/fixtures/cargo_example_project/src/main.tish +3 -0
  24. package/crates/tish/tests/integration_test.rs +1095 -0
  25. package/crates/tish/tests/run_optimize_stdout_parity.rs +50 -0
  26. package/crates/tish/tests/shortcircuit.rs +65 -0
  27. package/crates/tish_ast/Cargo.toml +9 -0
  28. package/crates/tish_ast/src/ast.rs +620 -0
  29. package/crates/tish_ast/src/lib.rs +5 -0
  30. package/crates/tish_build_utils/Cargo.toml +11 -0
  31. package/crates/tish_build_utils/src/lib.rs +577 -0
  32. package/crates/tish_builtins/Cargo.toml +20 -0
  33. package/crates/tish_builtins/src/array.rs +441 -0
  34. package/crates/tish_builtins/src/construct.rs +159 -0
  35. package/crates/tish_builtins/src/globals.rs +213 -0
  36. package/crates/tish_builtins/src/helpers.rs +35 -0
  37. package/crates/tish_builtins/src/lib.rs +16 -0
  38. package/crates/tish_builtins/src/math.rs +89 -0
  39. package/crates/tish_builtins/src/object.rs +36 -0
  40. package/crates/tish_builtins/src/string.rs +647 -0
  41. package/crates/tish_builtins/src/symbol.rs +83 -0
  42. package/crates/tish_bytecode/Cargo.toml +17 -0
  43. package/crates/tish_bytecode/src/chunk.rs +96 -0
  44. package/crates/tish_bytecode/src/compiler.rs +1760 -0
  45. package/crates/tish_bytecode/src/encoding.rs +100 -0
  46. package/crates/tish_bytecode/src/lib.rs +19 -0
  47. package/crates/tish_bytecode/src/opcode.rs +142 -0
  48. package/crates/tish_bytecode/src/peephole.rs +189 -0
  49. package/crates/tish_bytecode/src/serialize.rs +163 -0
  50. package/crates/tish_bytecode/tests/break_continue_bytecode.rs +44 -0
  51. package/crates/tish_bytecode/tests/constant_folding.rs +84 -0
  52. package/crates/tish_bytecode/tests/sort_optimization.rs +31 -0
  53. package/crates/tish_compile/Cargo.toml +26 -0
  54. package/crates/tish_compile/src/codegen.rs +5332 -0
  55. package/crates/tish_compile/src/infer.rs +292 -0
  56. package/crates/tish_compile/src/lib.rs +164 -0
  57. package/crates/tish_compile/src/resolve.rs +1388 -0
  58. package/crates/tish_compile/src/types.rs +501 -0
  59. package/crates/tish_compile_js/Cargo.toml +18 -0
  60. package/crates/tish_compile_js/examples/jsx_vdom_smoke.tish +8 -0
  61. package/crates/tish_compile_js/src/codegen.rs +871 -0
  62. package/crates/tish_compile_js/src/error.rs +20 -0
  63. package/crates/tish_compile_js/src/lib.rs +26 -0
  64. package/crates/tish_compile_js/src/tests_jsx.rs +350 -0
  65. package/crates/tish_compiler_wasm/Cargo.toml +21 -0
  66. package/crates/tish_compiler_wasm/src/lib.rs +57 -0
  67. package/crates/tish_compiler_wasm/src/resolve_virtual.rs +473 -0
  68. package/crates/tish_core/Cargo.toml +26 -0
  69. package/crates/tish_core/src/console_style.rs +160 -0
  70. package/crates/tish_core/src/json.rs +387 -0
  71. package/crates/tish_core/src/lib.rs +17 -0
  72. package/crates/tish_core/src/macros.rs +36 -0
  73. package/crates/tish_core/src/uri.rs +118 -0
  74. package/crates/tish_core/src/value.rs +696 -0
  75. package/crates/tish_core/src/vmref.rs +178 -0
  76. package/crates/tish_cranelift/Cargo.toml +19 -0
  77. package/crates/tish_cranelift/src/lib.rs +43 -0
  78. package/crates/tish_cranelift/src/link.rs +117 -0
  79. package/crates/tish_cranelift/src/lower.rs +85 -0
  80. package/crates/tish_cranelift_runtime/Cargo.toml +25 -0
  81. package/crates/tish_cranelift_runtime/src/lib.rs +45 -0
  82. package/crates/tish_eval/Cargo.toml +45 -0
  83. package/crates/tish_eval/src/eval.rs +3717 -0
  84. package/crates/tish_eval/src/http.rs +188 -0
  85. package/crates/tish_eval/src/lib.rs +99 -0
  86. package/crates/tish_eval/src/natives.rs +399 -0
  87. package/crates/tish_eval/src/promise.rs +179 -0
  88. package/crates/tish_eval/src/regex.rs +299 -0
  89. package/crates/tish_eval/src/timers.rs +120 -0
  90. package/crates/tish_eval/src/value.rs +318 -0
  91. package/crates/tish_eval/src/value_convert.rs +111 -0
  92. package/crates/tish_fmt/Cargo.toml +16 -0
  93. package/crates/tish_fmt/src/bin/tish-fmt.rs +41 -0
  94. package/crates/tish_fmt/src/lib.rs +2101 -0
  95. package/crates/tish_jsx_web/Cargo.toml +9 -0
  96. package/crates/tish_jsx_web/README.md +5 -0
  97. package/crates/tish_jsx_web/src/lib.rs +2 -0
  98. package/crates/tish_lexer/Cargo.toml +9 -0
  99. package/crates/tish_lexer/src/lib.rs +716 -0
  100. package/crates/tish_lexer/src/token.rs +163 -0
  101. package/crates/tish_lint/Cargo.toml +18 -0
  102. package/crates/tish_lint/src/bin/tish-lint.rs +195 -0
  103. package/crates/tish_lint/src/lib.rs +289 -0
  104. package/crates/tish_llvm/Cargo.toml +13 -0
  105. package/crates/tish_llvm/src/lib.rs +115 -0
  106. package/crates/tish_lsp/Cargo.toml +25 -0
  107. package/crates/tish_lsp/README.md +26 -0
  108. package/crates/tish_lsp/src/builtin_goto.rs +362 -0
  109. package/crates/tish_lsp/src/import_goto.rs +562 -0
  110. package/crates/tish_lsp/src/main.rs +1046 -0
  111. package/crates/tish_native/Cargo.toml +16 -0
  112. package/crates/tish_native/src/build.rs +427 -0
  113. package/crates/tish_native/src/config.rs +48 -0
  114. package/crates/tish_native/src/lib.rs +416 -0
  115. package/crates/tish_opt/Cargo.toml +13 -0
  116. package/crates/tish_opt/src/lib.rs +943 -0
  117. package/crates/tish_parser/Cargo.toml +11 -0
  118. package/crates/tish_parser/src/lib.rs +332 -0
  119. package/crates/tish_parser/src/parser.rs +2304 -0
  120. package/crates/tish_pg/Cargo.toml +34 -0
  121. package/crates/tish_pg/README.md +38 -0
  122. package/crates/tish_pg/src/error.rs +52 -0
  123. package/crates/tish_pg/src/lib.rs +955 -0
  124. package/crates/tish_resolve/Cargo.toml +13 -0
  125. package/crates/tish_resolve/src/lib.rs +3561 -0
  126. package/crates/tish_resolve/src/pos.rs +141 -0
  127. package/crates/tish_runtime/Cargo.toml +96 -0
  128. package/crates/tish_runtime/src/http.rs +1298 -0
  129. package/crates/tish_runtime/src/http_fetch.rs +471 -0
  130. package/crates/tish_runtime/src/http_hyper.rs +418 -0
  131. package/crates/tish_runtime/src/http_prefork.rs +189 -0
  132. package/crates/tish_runtime/src/lib.rs +1192 -0
  133. package/crates/tish_runtime/src/native_promise.rs +15 -0
  134. package/crates/tish_runtime/src/promise.rs +248 -0
  135. package/crates/tish_runtime/src/promise_io.rs +38 -0
  136. package/crates/tish_runtime/src/timers.rs +166 -0
  137. package/crates/tish_runtime/src/ws.rs +761 -0
  138. package/crates/tish_runtime/tests/fetch_readable_stream.rs +102 -0
  139. package/crates/tish_ui/Cargo.toml +17 -0
  140. package/crates/tish_ui/src/jsx.rs +682 -0
  141. package/crates/tish_ui/src/lib.rs +20 -0
  142. package/crates/tish_ui/src/runtime/hooks.rs +569 -0
  143. package/crates/tish_ui/src/runtime/mod.rs +180 -0
  144. package/crates/tish_vm/Cargo.toml +47 -0
  145. package/crates/tish_vm/src/lib.rs +39 -0
  146. package/crates/tish_vm/src/vm.rs +2192 -0
  147. package/crates/tish_vm/tests/fixtures/or_string_cmd.tish +2 -0
  148. package/crates/tish_vm/tests/lexical_scope_declare.rs +34 -0
  149. package/crates/tish_vm/tests/peephole_jump_chain_logical_or.rs +150 -0
  150. package/crates/tish_wasm/Cargo.toml +15 -0
  151. package/crates/tish_wasm/src/lib.rs +424 -0
  152. package/crates/tish_wasm_runtime/Cargo.toml +37 -0
  153. package/crates/tish_wasm_runtime/src/gpu.rs +413 -0
  154. package/crates/tish_wasm_runtime/src/lib.rs +42 -0
  155. package/crates/tishlang_cargo_bindgen/Cargo.toml +26 -0
  156. package/crates/tishlang_cargo_bindgen/src/classify.rs +263 -0
  157. package/crates/tishlang_cargo_bindgen/src/discover.rs +125 -0
  158. package/crates/tishlang_cargo_bindgen/src/infer.rs +382 -0
  159. package/crates/tishlang_cargo_bindgen/src/lib.rs +349 -0
  160. package/crates/tishlang_cargo_bindgen/src/main.rs +167 -0
  161. package/crates/tishlang_cargo_bindgen/src/metadata.rs +117 -0
  162. package/justfile +268 -0
  163. package/package.json +1 -1
  164. package/platform/darwin-arm64/tish-fmt +0 -0
@@ -0,0 +1,387 @@
1
+ //! JSON parsing and stringification for Tish values.
2
+
3
+ use crate::{Value, VmRef};
4
+ use std::sync::Arc;
5
+
6
+ /// Parse JSON string into a Value.
7
+ pub fn json_parse(json: &str) -> Result<Value, String> {
8
+ let json = json.trim();
9
+ if json.is_empty() {
10
+ return Err("SyntaxError: Unexpected end of JSON input".to_string());
11
+ }
12
+ let (value, rest) = parse_value(json)?;
13
+ if !rest.trim().is_empty() {
14
+ return Err("SyntaxError: Unexpected token at end of JSON".to_string());
15
+ }
16
+ Ok(value)
17
+ }
18
+
19
+ /// Stringify a Value to JSON.
20
+ ///
21
+ /// Single-buffer write strategy: all nested values append into one
22
+ /// `String` via [`json_stringify_into`], so we never allocate a transient
23
+ /// per-node `String` only to copy + drop it on the way back up. For a
24
+ /// 20-row TFB `/queries` response (~40 numbers, 2 keys × 20 = ~80 string
25
+ /// ops) that saves dozens of small allocations per request.
26
+ pub fn json_stringify(value: &Value) -> String {
27
+ // 256 B is enough for typical TFB responses (`/db` is 31 B,
28
+ // `/queries=20` is ~700 B). Larger payloads reallocate normally.
29
+ let mut buf = String::with_capacity(256);
30
+ json_stringify_into(&mut buf, value);
31
+ buf
32
+ }
33
+
34
+ /// Append a JSON-stringified `value` to `buf`. Used by JSON.stringify for
35
+ /// the recursive case so we don't pay for an intermediate `String` per
36
+ /// node.
37
+ pub fn json_stringify_into(buf: &mut String, value: &Value) {
38
+ match value {
39
+ Value::Null => buf.push_str("null"),
40
+ Value::Bool(true) => buf.push_str("true"),
41
+ Value::Bool(false) => buf.push_str("false"),
42
+ Value::Number(n) => {
43
+ if n.is_nan() || n.is_infinite() {
44
+ buf.push_str("null");
45
+ } else {
46
+ // `write!` avoids the heap allocation that `to_string`
47
+ // produces. The f64 → decimal formatter is the same
48
+ // either way (`std::fmt::Display`).
49
+ use std::fmt::Write;
50
+ let _ = write!(buf, "{}", n);
51
+ }
52
+ }
53
+ Value::String(s) => {
54
+ buf.push('"');
55
+ escape_json_string_into(buf, s);
56
+ buf.push('"');
57
+ }
58
+ Value::Array(arr) => {
59
+ let borrowed = arr.borrow();
60
+ buf.push('[');
61
+ for (i, item) in borrowed.iter().enumerate() {
62
+ if i > 0 {
63
+ buf.push(',');
64
+ }
65
+ json_stringify_into(buf, item);
66
+ }
67
+ buf.push(']');
68
+ }
69
+ Value::Object(obj) => {
70
+ let borrowed = obj.borrow();
71
+ // Sort keys for deterministic output. Pre-allocate to avoid
72
+ // a fresh `Vec` realloc inside `keys().collect()`.
73
+ let mut keys: Vec<&Arc<str>> = Vec::with_capacity(borrowed.strings.len());
74
+ keys.extend(borrowed.strings.keys());
75
+ keys.sort_unstable_by(|a, b| a.as_ref().cmp(b.as_ref()));
76
+ buf.push('{');
77
+ for (i, key) in keys.into_iter().enumerate() {
78
+ if i > 0 {
79
+ buf.push(',');
80
+ }
81
+ buf.push('"');
82
+ escape_json_string_into(buf, key);
83
+ buf.push_str("\":");
84
+ json_stringify_into(buf, borrowed.strings.get(key).unwrap());
85
+ }
86
+ buf.push('}');
87
+ }
88
+ Value::Function(_) | Value::Promise(_) | Value::Opaque(_) | Value::Symbol(_) => {
89
+ buf.push_str("null");
90
+ }
91
+ #[cfg(feature = "regex")]
92
+ Value::RegExp(_) => buf.push_str("null"),
93
+ }
94
+ }
95
+
96
+ /// Append an escaped JSON string body (without the surrounding quotes)
97
+ /// to `buf`. Optimised for the common case where the input is ASCII and
98
+ /// contains no characters that need escaping — we fast-pass the bytes
99
+ /// straight through, only falling into the per-char path on a hit.
100
+ fn escape_json_string_into(buf: &mut String, s: &str) {
101
+ let bytes = s.as_bytes();
102
+ let mut start = 0usize;
103
+ for (i, &b) in bytes.iter().enumerate() {
104
+ // Anything < 0x20 is a JSON control char that must be escaped;
105
+ // 0x22 (`"`) and 0x5C (`\`) also need an explicit escape; bytes
106
+ // ≥ 0x80 are the start of a multi-byte UTF-8 sequence, which is
107
+ // valid JSON as-is.
108
+ if b < 0x20 || b == b'"' || b == b'\\' {
109
+ // Flush the run of clean bytes before this one in one push.
110
+ if start < i {
111
+ // SAFETY: `s` is `&str`, every byte in `start..i` was a
112
+ // single-byte ASCII char (we only stop on ASCII triggers
113
+ // below 0x80), so the slice is a valid `&str`.
114
+ buf.push_str(&s[start..i]);
115
+ }
116
+ match b {
117
+ b'"' => buf.push_str("\\\""),
118
+ b'\\' => buf.push_str("\\\\"),
119
+ b'\n' => buf.push_str("\\n"),
120
+ b'\r' => buf.push_str("\\r"),
121
+ b'\t' => buf.push_str("\\t"),
122
+ b'\x08' => buf.push_str("\\b"),
123
+ b'\x0c' => buf.push_str("\\f"),
124
+ _ => {
125
+ use std::fmt::Write;
126
+ let _ = write!(buf, "\\u{:04x}", b as u32);
127
+ }
128
+ }
129
+ start = i + 1;
130
+ }
131
+ }
132
+ if start < bytes.len() {
133
+ buf.push_str(&s[start..]);
134
+ }
135
+ }
136
+
137
+ #[allow(dead_code)]
138
+ fn escape_json_string(s: &str) -> String {
139
+ let mut buf = String::with_capacity(s.len());
140
+ escape_json_string_into(&mut buf, s);
141
+ buf
142
+ }
143
+
144
+ fn parse_value(input: &str) -> Result<(Value, &str), String> {
145
+ let input = input.trim_start();
146
+ if input.is_empty() {
147
+ return Err("Unexpected end of JSON input".to_string());
148
+ }
149
+
150
+ match input.chars().next().unwrap() {
151
+ 'n' => parse_null(input),
152
+ 't' | 'f' => parse_bool(input),
153
+ '"' => parse_string(input),
154
+ '[' => parse_array(input),
155
+ '{' => parse_object(input),
156
+ c if c == '-' || c.is_ascii_digit() => parse_number(input),
157
+ c => Err(format!("Unexpected character '{}' in JSON", c)),
158
+ }
159
+ }
160
+
161
+ fn parse_null(input: &str) -> Result<(Value, &str), String> {
162
+ if let Some(rest) = input.strip_prefix("null") {
163
+ Ok((Value::Null, rest))
164
+ } else {
165
+ Err("Expected 'null'".to_string())
166
+ }
167
+ }
168
+
169
+ fn parse_bool(input: &str) -> Result<(Value, &str), String> {
170
+ if let Some(rest) = input.strip_prefix("true") {
171
+ Ok((Value::Bool(true), rest))
172
+ } else if let Some(rest) = input.strip_prefix("false") {
173
+ Ok((Value::Bool(false), rest))
174
+ } else {
175
+ Err("Expected 'true' or 'false'".to_string())
176
+ }
177
+ }
178
+
179
+ fn parse_string(input: &str) -> Result<(Value, &str), String> {
180
+ let input = &input[1..]; // skip opening quote
181
+ let mut result = String::new();
182
+ let mut chars = input.chars().peekable();
183
+ let mut byte_count = 0;
184
+
185
+ loop {
186
+ match chars.next() {
187
+ None => return Err("Unterminated string".to_string()),
188
+ Some('"') => {
189
+ byte_count += 1;
190
+ break;
191
+ }
192
+ Some('\\') => {
193
+ byte_count += 1;
194
+ match chars.next() {
195
+ Some('n') => {
196
+ result.push('\n');
197
+ byte_count += 1;
198
+ }
199
+ Some('r') => {
200
+ result.push('\r');
201
+ byte_count += 1;
202
+ }
203
+ Some('t') => {
204
+ result.push('\t');
205
+ byte_count += 1;
206
+ }
207
+ Some('\\') => {
208
+ result.push('\\');
209
+ byte_count += 1;
210
+ }
211
+ Some('"') => {
212
+ result.push('"');
213
+ byte_count += 1;
214
+ }
215
+ Some('/') => {
216
+ result.push('/');
217
+ byte_count += 1;
218
+ }
219
+ Some('u') => {
220
+ byte_count += 1;
221
+ let mut hex = String::new();
222
+ for _ in 0..4 {
223
+ if let Some(c) = chars.next() {
224
+ hex.push(c);
225
+ byte_count += c.len_utf8();
226
+ }
227
+ }
228
+ if let Ok(n) = u32::from_str_radix(&hex, 16) {
229
+ if let Some(c) = char::from_u32(n) {
230
+ result.push(c);
231
+ }
232
+ }
233
+ }
234
+ Some(c) => {
235
+ result.push(c);
236
+ byte_count += c.len_utf8();
237
+ }
238
+ None => return Err("Unterminated escape sequence".to_string()),
239
+ }
240
+ }
241
+ Some(c) => {
242
+ result.push(c);
243
+ byte_count += c.len_utf8();
244
+ }
245
+ }
246
+ }
247
+
248
+ Ok((Value::String(result.into()), &input[byte_count..]))
249
+ }
250
+
251
+ fn parse_number(input: &str) -> Result<(Value, &str), String> {
252
+ let mut end = 0;
253
+ let chars: Vec<char> = input.chars().collect();
254
+
255
+ if chars.get(end) == Some(&'-') {
256
+ end += 1;
257
+ }
258
+
259
+ while end < chars.len() && chars[end].is_ascii_digit() {
260
+ end += 1;
261
+ }
262
+
263
+ if chars.get(end) == Some(&'.') {
264
+ end += 1;
265
+ while end < chars.len() && chars[end].is_ascii_digit() {
266
+ end += 1;
267
+ }
268
+ }
269
+
270
+ if chars.get(end) == Some(&'e') || chars.get(end) == Some(&'E') {
271
+ end += 1;
272
+ if chars.get(end) == Some(&'+') || chars.get(end) == Some(&'-') {
273
+ end += 1;
274
+ }
275
+ while end < chars.len() && chars[end].is_ascii_digit() {
276
+ end += 1;
277
+ }
278
+ }
279
+
280
+ let num_str: String = chars[..end].iter().collect();
281
+ let byte_len: usize = chars[..end].iter().map(|c| c.len_utf8()).sum();
282
+
283
+ num_str
284
+ .parse::<f64>()
285
+ .map(|n| (Value::Number(n), &input[byte_len..]))
286
+ .map_err(|_| format!("Invalid number: {}", num_str))
287
+ }
288
+
289
+ fn parse_array(input: &str) -> Result<(Value, &str), String> {
290
+ let mut input = &input[1..]; // skip '['
291
+ let mut items = Vec::new();
292
+
293
+ input = input.trim_start();
294
+ if let Some(rest) = input.strip_prefix(']') {
295
+ return Ok((Value::Array(VmRef::new(items)), rest));
296
+ }
297
+
298
+ loop {
299
+ let (value, rest) = parse_value(input)?;
300
+ items.push(value);
301
+ input = rest.trim_start();
302
+
303
+ match input.chars().next() {
304
+ Some(',') => input = &input[1..],
305
+ Some(']') => return Ok((Value::Array(VmRef::new(items)), &input[1..])),
306
+ _ => return Err("Expected ',' or ']' in array".to_string()),
307
+ }
308
+ }
309
+ }
310
+
311
+ fn parse_object(input: &str) -> Result<(Value, &str), String> {
312
+ let mut input = &input[1..]; // skip '{'
313
+ let mut map = crate::ObjectMap::default();
314
+
315
+ input = input.trim_start();
316
+ if let Some(rest) = input.strip_prefix('}') {
317
+ return Ok((
318
+ Value::Object(VmRef::new(crate::ObjectData::from_strings(map))),
319
+ rest,
320
+ ));
321
+ }
322
+
323
+ loop {
324
+ input = input.trim_start();
325
+ if !input.starts_with('"') {
326
+ return Err("Expected string key in object".to_string());
327
+ }
328
+
329
+ let (key_val, rest) = parse_string(input)?;
330
+ let key: Arc<str> = match key_val {
331
+ Value::String(s) => s,
332
+ _ => unreachable!(),
333
+ };
334
+
335
+ input = rest.trim_start();
336
+ if !input.starts_with(':') {
337
+ return Err("Expected ':' after key in object".to_string());
338
+ }
339
+ input = &input[1..];
340
+
341
+ let (value, rest) = parse_value(input)?;
342
+ map.insert(key, value);
343
+ input = rest.trim_start();
344
+
345
+ match input.chars().next() {
346
+ Some(',') => input = &input[1..],
347
+ Some('}') => {
348
+ return Ok((
349
+ Value::Object(VmRef::new(crate::ObjectData::from_strings(map))),
350
+ &input[1..],
351
+ ));
352
+ }
353
+ _ => return Err("Expected ',' or '}' in object".to_string()),
354
+ }
355
+ }
356
+ }
357
+
358
+ #[cfg(test)]
359
+ mod tests {
360
+ use super::*;
361
+
362
+ #[test]
363
+ fn test_parse_primitives() {
364
+ assert!(matches!(json_parse("null").unwrap(), Value::Null));
365
+ assert!(matches!(json_parse("true").unwrap(), Value::Bool(true)));
366
+ assert!(matches!(json_parse("false").unwrap(), Value::Bool(false)));
367
+ assert!(matches!(json_parse("42").unwrap(), Value::Number(n) if n == 42.0));
368
+ assert!(
369
+ matches!(json_parse("\"hello\"").unwrap(), Value::String(s) if s.as_ref() == "hello")
370
+ );
371
+ }
372
+
373
+ #[test]
374
+ fn test_roundtrip() {
375
+ let original = "{\"name\":\"test\",\"count\":42}";
376
+ let value = json_parse(original).unwrap();
377
+ let stringified = json_stringify(&value);
378
+ let reparsed = json_parse(&stringified).unwrap();
379
+
380
+ match (&value, &reparsed) {
381
+ (Value::Object(a), Value::Object(b)) => {
382
+ assert_eq!(a.borrow().len_entries(), b.borrow().len_entries());
383
+ }
384
+ _ => panic!("Expected objects"),
385
+ }
386
+ }
387
+ }
@@ -0,0 +1,17 @@
1
+ //! Tish Core - Shared types and utilities for the Tish language.
2
+ //!
3
+ //! This crate provides the unified Value type and utilities used by both
4
+ //! the interpreter (tishlang_eval) and compiled runtime (tishlang_runtime).
5
+
6
+ mod console_style;
7
+ mod json;
8
+ mod macros;
9
+ mod uri;
10
+ mod value;
11
+ mod vmref;
12
+
13
+ pub use console_style::{format_value_styled, format_values_for_console, use_console_colors};
14
+ pub use json::{json_parse, json_stringify, json_stringify_into};
15
+ pub use uri::{percent_decode, percent_encode};
16
+ pub use value::*;
17
+ pub use vmref::{VmReadGuard, VmRef, VmWriteGuard};
@@ -0,0 +1,36 @@
1
+ //! Macros for building Tish native modules.
2
+
3
+ /// Build a Tish module object from method name => function pairs.
4
+ ///
5
+ /// Each function must have signature `fn(&[Value]) -> Value` (or equivalent closure).
6
+ /// Pass either a `fn` pointer or a closure; the macro wraps them in `Rc::new`.
7
+ ///
8
+ /// # Example
9
+ ///
10
+ /// ```ignore
11
+ /// use tishlang_core::{tish_module, Value};
12
+ ///
13
+ /// pub fn my_object() -> Value {
14
+ /// tish_module! {
15
+ /// "run" => |args: &[Value]| {
16
+ /// // ...
17
+ /// Value::Null
18
+ /// },
19
+ /// "read_csv" => my_read_csv_fn,
20
+ /// }
21
+ /// }
22
+ /// ```
23
+ #[macro_export]
24
+ macro_rules! tish_module {
25
+ ($($name:expr => $fn:expr),* $(,)?) => {{
26
+ use std::sync::Arc;
27
+ use $crate::{ObjectMap, Value};
28
+ let mut map = ObjectMap::default();
29
+ $(
30
+ // `Value::native` picks the right Rc / Arc wrapper depending on
31
+ // whether the `send-values` feature is enabled upstream.
32
+ map.insert(Arc::from($name), Value::native($fn));
33
+ )*
34
+ Value::object(map)
35
+ }};
36
+ }
@@ -0,0 +1,118 @@
1
+ //! URI encoding/decoding utilities.
2
+
3
+ /// Percent-decode a string (for decodeURI).
4
+ /// Does NOT decode reserved URI characters: ; / ? : @ & = + $ , #
5
+ /// These are characters that encodeURI does not encode, so decodeURI won't decode them.
6
+ pub fn percent_decode(input: &str) -> Result<String, String> {
7
+ // Reserved characters that decodeURI should NOT decode (because encodeURI doesn't encode them)
8
+ const RESERVED_ENCODED: &[&str] = &[
9
+ "%3B", "%3b", // ;
10
+ "%2F", "%2f", // /
11
+ "%3F", "%3f", // ?
12
+ "%3A", "%3a", // :
13
+ "%40", // @
14
+ "%26", // &
15
+ "%3D", "%3d", // =
16
+ "%2B", "%2b", // +
17
+ "%24", // $
18
+ "%2C", "%2c", // ,
19
+ "%23", // #
20
+ ];
21
+
22
+ let mut result = String::with_capacity(input.len());
23
+ let mut chars = input.chars().peekable();
24
+
25
+ while let Some(c) = chars.next() {
26
+ if c == '%' {
27
+ // Peek at the next two characters to check if this is a reserved sequence
28
+ let mut hex = String::new();
29
+ let mut peek_chars = Vec::new();
30
+ for _ in 0..2 {
31
+ match chars.next() {
32
+ Some(h) if h.is_ascii_hexdigit() => {
33
+ hex.push(h);
34
+ peek_chars.push(h);
35
+ }
36
+ Some(h) => {
37
+ // Not a valid hex sequence, push as-is
38
+ result.push('%');
39
+ for pc in peek_chars {
40
+ result.push(pc);
41
+ }
42
+ result.push(h);
43
+ hex.clear();
44
+ break;
45
+ }
46
+ None => return Err("URIError: malformed URI sequence".to_string()),
47
+ }
48
+ }
49
+
50
+ if hex.len() == 2 {
51
+ let encoded = format!("%{}", hex);
52
+ // Check if this is a reserved character that should NOT be decoded
53
+ if RESERVED_ENCODED
54
+ .iter()
55
+ .any(|r| r.eq_ignore_ascii_case(&encoded))
56
+ {
57
+ result.push_str(&encoded);
58
+ } else if let Ok(byte) = u8::from_str_radix(&hex, 16) {
59
+ result.push(byte as char);
60
+ }
61
+ }
62
+ } else {
63
+ result.push(c);
64
+ }
65
+ }
66
+
67
+ Ok(result)
68
+ }
69
+
70
+ /// Percent-encode a string (for encodeURI).
71
+ /// Preserves: A-Z a-z 0-9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , #
72
+ pub fn percent_encode(input: &str) -> String {
73
+ const UNRESERVED: &[char] = &[
74
+ '-', '_', '.', '!', '~', '*', '\'', '(', ')', ';', '/', '?', ':', '@', '&', '=', '+', '$',
75
+ ',', '#',
76
+ ];
77
+
78
+ let mut result = String::with_capacity(input.len());
79
+ for c in input.chars() {
80
+ if c.is_ascii_alphanumeric() || UNRESERVED.contains(&c) {
81
+ result.push(c);
82
+ } else {
83
+ for byte in c.to_string().as_bytes() {
84
+ result.push_str(&format!("%{:02X}", byte));
85
+ }
86
+ }
87
+ }
88
+ result
89
+ }
90
+
91
+ #[cfg(test)]
92
+ mod tests {
93
+ use super::*;
94
+
95
+ fn percent_encode_component(input: &str) -> String {
96
+ const UNRESERVED: &[char] = &['-', '_', '.', '!', '~', '*', '\'', '(', ')'];
97
+ let mut result = String::new();
98
+ for c in input.chars() {
99
+ if c.is_ascii_alphanumeric() || UNRESERVED.contains(&c) {
100
+ result.push(c);
101
+ } else {
102
+ for byte in c.to_string().as_bytes() {
103
+ result.push_str(&format!("%{:02X}", byte));
104
+ }
105
+ }
106
+ }
107
+ result
108
+ }
109
+
110
+ #[test]
111
+ fn test_encode_decode_roundtrip() {
112
+ let original = "hello world";
113
+ let encoded = percent_encode_component(original);
114
+ assert_eq!(encoded, "hello%20world");
115
+ let decoded = percent_decode(&encoded).unwrap();
116
+ assert_eq!(decoded, original);
117
+ }
118
+ }