@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,1192 @@
1
+ //! Minimal runtime for Tish compiled output.
2
+ //!
3
+ //! Re-exports core types from tishlang_core and provides console, Math,
4
+ //! and other builtin functions for compiled Tish programs.
5
+
6
+ use std::fmt;
7
+ use std::sync::OnceLock;
8
+ use tishlang_builtins::helpers::extract_num;
9
+ #[cfg(feature = "fs")]
10
+ use tishlang_builtins::helpers::make_error_value;
11
+
12
+ pub use tishlang_builtins::symbol::symbol_object;
13
+ pub use tishlang_core::ObjectMap;
14
+ pub use tishlang_core::Value;
15
+ /// Used by native codegen for `f()` / `obj()` dispatch (`Value::Function` or `__call` on objects).
16
+ pub use tishlang_core::value_call;
17
+ // Re-export the shared-mutable wrapper so the Rust code emitted by
18
+ // `tishlang_compile::codegen` can write `VmRef::new(...)` without needing
19
+ // a direct dependency on `tishlang_core` from the generated crate.
20
+ pub use tishlang_core::{VmReadGuard, VmRef, VmWriteGuard};
21
+
22
+ pub use tishlang_builtins::construct::{
23
+ audio_context_constructor_value as tish_audio_context_constructor, construct as tish_construct,
24
+ uint8_array_constructor_value as tish_uint8_array_constructor,
25
+ };
26
+
27
+ // Re-export array methods from tishlang_builtins
28
+ pub use tishlang_builtins::array::{
29
+ concat as array_concat_impl, every as array_every, filter as array_filter, find as array_find,
30
+ find_index as array_find_index, flat as array_flat_impl, flat_map as array_flat_map,
31
+ for_each as array_for_each, includes as array_includes_impl, index_of as array_index_of_impl,
32
+ join as array_join_impl, map as array_map, pop as array_pop, push as array_push_impl,
33
+ reduce as array_reduce, reverse as array_reverse, shift as array_shift,
34
+ shuffle as array_shuffle, slice as array_slice_impl, some as array_some,
35
+ sort_default as array_sort_default, sort_numeric_asc as array_sort_numeric_asc,
36
+ sort_numeric_desc as array_sort_numeric_desc,
37
+ sort_with_comparator as array_sort_with_comparator, splice as array_splice_impl,
38
+ unshift as array_unshift_impl,
39
+ };
40
+
41
+ // Re-export string methods from tishlang_builtins
42
+ pub use tishlang_builtins::string::{
43
+ char_at as string_char_at_impl, char_code_at as string_char_code_at_impl,
44
+ ends_with as string_ends_with_impl, escape_html as string_escape_html_impl,
45
+ includes as string_includes_impl, index_of as string_index_of_impl,
46
+ last_index_of as string_last_index_of_impl, pad_end as string_pad_end_impl,
47
+ pad_start as string_pad_start_impl, repeat as string_repeat_impl,
48
+ replace as string_replace_impl, replace_all as string_replace_all_impl,
49
+ slice as string_slice_impl, split as string_split_impl,
50
+ starts_with as string_starts_with_impl, substr as string_substr_impl,
51
+ substring as string_substring_impl,
52
+ to_lower_case as string_to_lower_case, to_upper_case as string_to_upper_case,
53
+ trim as string_trim,
54
+ };
55
+
56
+ // Wrapper functions to maintain API compatibility
57
+ pub fn array_push(arr: &Value, args: &[Value]) -> Value {
58
+ array_push_impl(arr, args)
59
+ }
60
+ pub fn array_unshift(arr: &Value, args: &[Value]) -> Value {
61
+ array_unshift_impl(arr, args)
62
+ }
63
+ pub fn array_index_of(arr: &Value, search: &Value) -> Value {
64
+ array_index_of_impl(arr, search)
65
+ }
66
+ pub fn array_includes(arr: &Value, search: &Value, from: &Value) -> Value {
67
+ array_includes_impl(arr, search, Some(from))
68
+ }
69
+ pub fn array_join(arr: &Value, sep: &Value) -> Value {
70
+ array_join_impl(arr, sep)
71
+ }
72
+ pub fn array_splice(
73
+ arr: &Value,
74
+ start: &Value,
75
+ delete_count: Option<&Value>,
76
+ items: &[Value],
77
+ ) -> Value {
78
+ array_splice_impl(arr, start, delete_count, items)
79
+ }
80
+ pub fn array_slice(arr: &Value, start: &Value, end: &Value) -> Value {
81
+ array_slice_impl(arr, start, end)
82
+ }
83
+ pub fn array_concat(arr: &Value, args: &[Value]) -> Value {
84
+ array_concat_impl(arr, args)
85
+ }
86
+ pub fn array_flat(arr: &Value, depth: &Value) -> Value {
87
+ array_flat_impl(arr, depth)
88
+ }
89
+
90
+ pub fn array_sort(arr: &Value, comparator: Option<&Value>) -> Value {
91
+ match comparator {
92
+ Some(cmp) => array_sort_with_comparator(arr, cmp),
93
+ None => array_sort_default(arr),
94
+ }
95
+ }
96
+
97
+ pub fn string_index_of(s: &Value, search: &Value, from: &Value) -> Value {
98
+ string_index_of_impl(s, search, Some(from))
99
+ }
100
+ pub fn string_includes(s: &Value, search: &Value, from: &Value) -> Value {
101
+ string_includes_impl(s, search, Some(from))
102
+ }
103
+ pub fn string_slice(s: &Value, start: &Value, end: &Value) -> Value {
104
+ string_slice_impl(s, start, end)
105
+ }
106
+ pub fn string_substring(s: &Value, start: &Value, end: &Value) -> Value {
107
+ string_substring_impl(s, start, end)
108
+ }
109
+ pub fn string_substr(s: &Value, start: &Value, length: &Value) -> Value {
110
+ string_substr_impl(s, start, length)
111
+ }
112
+ pub fn string_split(s: &Value, sep: &Value) -> Value {
113
+ string_split_impl(s, sep)
114
+ }
115
+ pub fn string_starts_with(s: &Value, search: &Value) -> Value {
116
+ string_starts_with_impl(s, search)
117
+ }
118
+ pub fn string_ends_with(s: &Value, search: &Value) -> Value {
119
+ string_ends_with_impl(s, search)
120
+ }
121
+ pub fn string_replace(s: &Value, search: &Value, replacement: &Value) -> Value {
122
+ #[cfg(feature = "regex")]
123
+ if matches!(search, Value::RegExp(_)) {
124
+ return string_replace_regex_or_callback(s, search, replacement);
125
+ }
126
+ string_replace_impl(s, search, replacement)
127
+ }
128
+ pub fn string_replace_all(s: &Value, search: &Value, replacement: &Value) -> Value {
129
+ string_replace_all_impl(s, search, replacement)
130
+ }
131
+ pub fn string_char_at(s: &Value, idx: &Value) -> Value {
132
+ string_char_at_impl(s, idx)
133
+ }
134
+ pub fn string_char_code_at(s: &Value, idx: &Value) -> Value {
135
+ string_char_code_at_impl(s, idx)
136
+ }
137
+ pub fn string_repeat(s: &Value, count: &Value) -> Value {
138
+ string_repeat_impl(s, count)
139
+ }
140
+ pub fn string_pad_start(s: &Value, target_len: &Value, pad: &Value) -> Value {
141
+ string_pad_start_impl(s, target_len, pad)
142
+ }
143
+ pub fn string_pad_end(s: &Value, target_len: &Value, pad: &Value) -> Value {
144
+ string_pad_end_impl(s, target_len, pad)
145
+ }
146
+ pub fn string_last_index_of(s: &Value, search: &Value, position: &Value) -> Value {
147
+ string_last_index_of_impl(s, search, position)
148
+ }
149
+
150
+ /// Number.prototype.toFixed(digits) - format number with fixed decimal places (0-20)
151
+ pub fn number_to_fixed(n: &Value, digits: &Value) -> Value {
152
+ let num = match n {
153
+ Value::Number(x) => *x,
154
+ _ => f64::NAN,
155
+ };
156
+ let d = match digits {
157
+ Value::Number(x) => (*x as i32).clamp(0, 20),
158
+ _ => 0,
159
+ };
160
+ Value::String(format!("{:.*}", d as usize, num).into())
161
+ }
162
+
163
+ /// Operators module for compound assignment operations
164
+ pub mod ops {
165
+ use tishlang_core::Value;
166
+
167
+ #[inline]
168
+ pub fn add(left: &Value, right: &Value) -> Result<Value, Box<dyn std::error::Error>> {
169
+ match (left, right) {
170
+ (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a + b)),
171
+ (Value::String(a), Value::String(b)) => {
172
+ let mut s = String::with_capacity(a.len() + b.len());
173
+ s.push_str(a);
174
+ s.push_str(b);
175
+ Ok(Value::String(s.into()))
176
+ }
177
+ (Value::String(a), b) => {
178
+ let b_str = b.to_display_string();
179
+ let mut s = String::with_capacity(a.len() + b_str.len());
180
+ s.push_str(a);
181
+ s.push_str(&b_str);
182
+ Ok(Value::String(s.into()))
183
+ }
184
+ (a, Value::String(b)) => {
185
+ let a_str = a.to_display_string();
186
+ let mut s = String::with_capacity(a_str.len() + b.len());
187
+ s.push_str(&a_str);
188
+ s.push_str(b);
189
+ Ok(Value::String(s.into()))
190
+ }
191
+ _ => Err(format!("Cannot add {:?} and {:?}", left, right).into()),
192
+ }
193
+ }
194
+
195
+ #[inline]
196
+ pub fn sub(left: &Value, right: &Value) -> Result<Value, Box<dyn std::error::Error>> {
197
+ match (left, right) {
198
+ (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a - b)),
199
+ _ => Err(format!("Cannot subtract {:?} from {:?}", right, left).into()),
200
+ }
201
+ }
202
+
203
+ #[inline]
204
+ pub fn mul(left: &Value, right: &Value) -> Result<Value, Box<dyn std::error::Error>> {
205
+ match (left, right) {
206
+ (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a * b)),
207
+ _ => Err(format!("Cannot multiply {:?} and {:?}", left, right).into()),
208
+ }
209
+ }
210
+
211
+ #[inline]
212
+ pub fn div(left: &Value, right: &Value) -> Result<Value, Box<dyn std::error::Error>> {
213
+ match (left, right) {
214
+ (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a / b)),
215
+ _ => Err(format!("Cannot divide {:?} by {:?}", left, right).into()),
216
+ }
217
+ }
218
+
219
+ /// Compare two values for <. Supports number vs number and string vs string.
220
+ #[inline]
221
+ pub fn lt(left: &Value, right: &Value) -> Value {
222
+ let b = match (left, right) {
223
+ (Value::Number(a), Value::Number(b)) => a < b,
224
+ (Value::String(a), Value::String(b)) => a.as_ref() < b.as_ref(),
225
+ _ => false,
226
+ };
227
+ Value::Bool(b)
228
+ }
229
+
230
+ #[inline]
231
+ pub fn le(left: &Value, right: &Value) -> Value {
232
+ let b = match (left, right) {
233
+ (Value::Number(a), Value::Number(b)) => a <= b,
234
+ (Value::String(a), Value::String(b)) => a.as_ref() <= b.as_ref(),
235
+ _ => false,
236
+ };
237
+ Value::Bool(b)
238
+ }
239
+
240
+ #[inline]
241
+ pub fn gt(left: &Value, right: &Value) -> Value {
242
+ let b = match (left, right) {
243
+ (Value::Number(a), Value::Number(b)) => a > b,
244
+ (Value::String(a), Value::String(b)) => a.as_ref() > b.as_ref(),
245
+ _ => false,
246
+ };
247
+ Value::Bool(b)
248
+ }
249
+
250
+ #[inline]
251
+ pub fn ge(left: &Value, right: &Value) -> Value {
252
+ let b = match (left, right) {
253
+ (Value::Number(a), Value::Number(b)) => a >= b,
254
+ (Value::String(a), Value::String(b)) => a.as_ref() >= b.as_ref(),
255
+ _ => false,
256
+ };
257
+ Value::Bool(b)
258
+ }
259
+
260
+ #[inline]
261
+ pub fn modulo(left: &Value, right: &Value) -> Result<Value, Box<dyn std::error::Error>> {
262
+ match (left, right) {
263
+ (Value::Number(a), Value::Number(b)) => Ok(Value::Number(a % b)),
264
+ _ => Err(format!("Cannot modulo {:?} by {:?}", left, right).into()),
265
+ }
266
+ }
267
+ }
268
+
269
+ use tishlang_builtins::globals::{
270
+ array_is_array as builtins_array_is_array, boolean as builtins_boolean,
271
+ decode_uri as builtins_decode_uri, encode_uri as builtins_encode_uri,
272
+ is_finite as builtins_is_finite, is_nan as builtins_is_nan,
273
+ object_assign as builtins_object_assign, object_entries as builtins_object_entries,
274
+ object_from_entries as builtins_object_from_entries, object_keys as builtins_object_keys,
275
+ object_values as builtins_object_values,
276
+ string_from_char_code as builtins_string_from_char_code,
277
+ };
278
+ use tishlang_core::{json_parse as core_json_parse, json_stringify as core_json_stringify};
279
+
280
+ /// Public JSON helpers used by codegen-emitted code (specifically the
281
+ /// `_tish_write_json` impls on user-declared `type` aliases). Re-exporting
282
+ /// from the runtime keeps the generated source decoupled from
283
+ /// `tishlang_core` — generated code only ever names `tishlang_runtime`.
284
+ pub mod json {
285
+ pub use tishlang_core::json_stringify_into as stringify_into;
286
+ /// Append the JSON-escaped contents of `s` (without surrounding
287
+ /// quotes) to `buf`. Used by typed-struct serialisers for `String`
288
+ /// fields. Falls through to `tishlang_core::json_stringify_into`'s
289
+ /// internal helper via a `Value::String` round-trip when the inner
290
+ /// helper isn't directly exposed.
291
+ pub fn escape_into(buf: &mut String, s: &str) {
292
+ // Inline the same escape rules as tishlang_core::json::
293
+ // `escape_json_string_into`. Kept locally so we don't widen
294
+ // tishlang_core's public surface unnecessarily.
295
+ let bytes = s.as_bytes();
296
+ let mut start = 0usize;
297
+ for (i, &b) in bytes.iter().enumerate() {
298
+ if b < 0x20 || b == b'"' || b == b'\\' {
299
+ if start < i {
300
+ buf.push_str(&s[start..i]);
301
+ }
302
+ match b {
303
+ b'"' => buf.push_str("\\\""),
304
+ b'\\' => buf.push_str("\\\\"),
305
+ b'\n' => buf.push_str("\\n"),
306
+ b'\r' => buf.push_str("\\r"),
307
+ b'\t' => buf.push_str("\\t"),
308
+ b'\x08' => buf.push_str("\\b"),
309
+ b'\x0c' => buf.push_str("\\f"),
310
+ _ => {
311
+ use std::fmt::Write;
312
+ let _ = write!(buf, "\\u{:04x}", b as u32);
313
+ }
314
+ }
315
+ start = i + 1;
316
+ }
317
+ }
318
+ if start < bytes.len() {
319
+ buf.push_str(&s[start..]);
320
+ }
321
+ }
322
+ }
323
+
324
+ /// Error type for Tish throw/catch.
325
+ #[derive(Debug, Clone)]
326
+ pub enum TishError {
327
+ Throw(Value),
328
+ }
329
+
330
+ impl fmt::Display for TishError {
331
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
332
+ match self {
333
+ TishError::Throw(v) => write!(f, "{}", v.to_display_string()),
334
+ }
335
+ }
336
+ }
337
+
338
+ impl std::error::Error for TishError {}
339
+
340
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
341
+ enum LogLevel {
342
+ Debug = 0,
343
+ Info = 1,
344
+ Log = 2,
345
+ Warn = 3,
346
+ Error = 4,
347
+ }
348
+
349
+ static LOG_LEVEL: OnceLock<LogLevel> = OnceLock::new();
350
+
351
+ fn get_log_level() -> LogLevel {
352
+ *LOG_LEVEL.get_or_init(|| match std::env::var("TISH_LOG_LEVEL").as_deref() {
353
+ Ok("debug") => LogLevel::Debug,
354
+ Ok("info") => LogLevel::Info,
355
+ Ok("warn") => LogLevel::Warn,
356
+ Ok("error") => LogLevel::Error,
357
+ _ => LogLevel::Log,
358
+ })
359
+ }
360
+
361
+ fn format_args(args: &[Value]) -> String {
362
+ tishlang_core::format_values_for_console(args, tishlang_core::use_console_colors())
363
+ }
364
+
365
+ pub fn console_debug(args: &[Value]) {
366
+ if get_log_level() <= LogLevel::Debug {
367
+ println!("{}", format_args(args));
368
+ }
369
+ }
370
+
371
+ pub fn console_info(args: &[Value]) {
372
+ if get_log_level() <= LogLevel::Info {
373
+ println!("{}", format_args(args));
374
+ }
375
+ }
376
+
377
+ pub fn console_log(args: &[Value]) {
378
+ if get_log_level() <= LogLevel::Log {
379
+ println!("{}", format_args(args));
380
+ }
381
+ }
382
+
383
+ pub fn console_warn(args: &[Value]) {
384
+ if get_log_level() <= LogLevel::Warn {
385
+ eprintln!("{}", format_args(args));
386
+ }
387
+ }
388
+
389
+ pub fn console_error(args: &[Value]) {
390
+ eprintln!("{}", format_args(args));
391
+ }
392
+
393
+ pub fn parse_int(args: &[Value]) -> Value {
394
+ tishlang_builtins::globals::parse_int(args)
395
+ }
396
+
397
+ pub fn parse_float(args: &[Value]) -> Value {
398
+ tishlang_builtins::globals::parse_float(args)
399
+ }
400
+
401
+ pub fn is_finite(args: &[Value]) -> Value {
402
+ builtins_is_finite(args)
403
+ }
404
+
405
+ pub fn is_nan(args: &[Value]) -> Value {
406
+ builtins_is_nan(args)
407
+ }
408
+
409
+ pub fn boolean(args: &[Value]) -> Value {
410
+ builtins_boolean(args)
411
+ }
412
+
413
+ pub fn decode_uri(args: &[Value]) -> Value {
414
+ builtins_decode_uri(args)
415
+ }
416
+
417
+ pub fn encode_uri(args: &[Value]) -> Value {
418
+ builtins_encode_uri(args)
419
+ }
420
+
421
+ // Math functions - use tishlang_builtins::math
422
+ pub use tishlang_builtins::math::{
423
+ abs as tish_math_abs_impl, ceil as tish_math_ceil_impl, cos as tish_math_cos_impl,
424
+ exp as tish_math_exp_impl, floor as tish_math_floor_impl, max as tish_math_max_impl,
425
+ min as tish_math_min_impl, pow as tish_math_pow_impl, random as tish_math_random_impl,
426
+ round as tish_math_round_impl, sign as tish_math_sign_impl, sin as tish_math_sin_impl,
427
+ imul as tish_math_imul_impl,
428
+ sqrt as tish_math_sqrt_impl, tan as tish_math_tan_impl, trunc as tish_math_trunc_impl,
429
+ };
430
+
431
+ // Wrapper functions to maintain API (existing callers use math_* naming)
432
+ pub fn math_abs(args: &[Value]) -> Value {
433
+ tish_math_abs_impl(args)
434
+ }
435
+ pub fn math_sqrt(args: &[Value]) -> Value {
436
+ tish_math_sqrt_impl(args)
437
+ }
438
+ pub fn math_floor(args: &[Value]) -> Value {
439
+ tish_math_floor_impl(args)
440
+ }
441
+ pub fn math_ceil(args: &[Value]) -> Value {
442
+ tish_math_ceil_impl(args)
443
+ }
444
+ pub fn math_round(args: &[Value]) -> Value {
445
+ tish_math_round_impl(args)
446
+ }
447
+ pub fn math_min(args: &[Value]) -> Value {
448
+ tish_math_min_impl(args)
449
+ }
450
+ pub fn math_max(args: &[Value]) -> Value {
451
+ tish_math_max_impl(args)
452
+ }
453
+ pub fn math_sin(args: &[Value]) -> Value {
454
+ tish_math_sin_impl(args)
455
+ }
456
+ pub fn math_cos(args: &[Value]) -> Value {
457
+ tish_math_cos_impl(args)
458
+ }
459
+ pub fn math_tan(args: &[Value]) -> Value {
460
+ tish_math_tan_impl(args)
461
+ }
462
+ pub fn math_exp(args: &[Value]) -> Value {
463
+ tish_math_exp_impl(args)
464
+ }
465
+ pub fn math_trunc(args: &[Value]) -> Value {
466
+ tish_math_trunc_impl(args)
467
+ }
468
+ pub fn math_imul(args: &[Value]) -> Value {
469
+ tish_math_imul_impl(args)
470
+ }
471
+ pub fn math_pow(args: &[Value]) -> Value {
472
+ tish_math_pow_impl(args)
473
+ }
474
+ pub fn math_sign(args: &[Value]) -> Value {
475
+ tish_math_sign_impl(args)
476
+ }
477
+ pub fn math_random(args: &[Value]) -> Value {
478
+ tish_math_random_impl(args)
479
+ }
480
+
481
+ pub fn math_log(args: &[Value]) -> Value {
482
+ let n = extract_num(args.first()).unwrap_or(f64::NAN);
483
+ Value::Number(n.ln())
484
+ }
485
+
486
+ pub fn json_stringify(args: &[Value]) -> Value {
487
+ let v = args.first().cloned().unwrap_or(Value::Null);
488
+ Value::String(core_json_stringify(&v).into())
489
+ }
490
+
491
+ pub fn json_parse(args: &[Value]) -> Value {
492
+ let s = args
493
+ .first()
494
+ .map(|v| v.to_display_string())
495
+ .unwrap_or_default();
496
+ core_json_parse(&s).unwrap_or(Value::Null)
497
+ }
498
+
499
+ pub fn date_now(_args: &[Value]) -> Value {
500
+ use std::time::{SystemTime, UNIX_EPOCH};
501
+ let now = SystemTime::now()
502
+ .duration_since(UNIX_EPOCH)
503
+ .map(|d| d.as_millis() as f64)
504
+ .unwrap_or(0.0);
505
+ Value::Number(now)
506
+ }
507
+
508
+ pub fn array_is_array(args: &[Value]) -> Value {
509
+ builtins_array_is_array(args)
510
+ }
511
+
512
+ pub fn string_from_char_code(args: &[Value]) -> Value {
513
+ builtins_string_from_char_code(args)
514
+ }
515
+
516
+ #[cfg(feature = "process")]
517
+ pub fn process_exit(args: &[Value]) -> Value {
518
+ let code = args
519
+ .first()
520
+ .and_then(|v| match v {
521
+ Value::Number(n) => Some(*n as i32),
522
+ _ => None,
523
+ })
524
+ .unwrap_or(0);
525
+ std::process::exit(code);
526
+ }
527
+
528
+ #[cfg(feature = "process")]
529
+ pub fn process_cwd(_args: &[Value]) -> Value {
530
+ let cwd = std::env::current_dir()
531
+ .map(|p| p.display().to_string())
532
+ .unwrap_or_default();
533
+ Value::String(cwd.into())
534
+ }
535
+
536
+ #[cfg(feature = "process")]
537
+ pub fn process_exec(args: &[Value]) -> Value {
538
+ use std::process::Command;
539
+ let cmd = args
540
+ .first()
541
+ .map(|v| v.to_display_string())
542
+ .unwrap_or_default();
543
+ if cmd.is_empty() {
544
+ return Value::Number(0.0);
545
+ }
546
+ match Command::new("sh").arg("-c").arg(&cmd).status() {
547
+ Ok(status) => Value::Number(status.code().unwrap_or(1) as f64),
548
+ Err(_) => Value::Number(1.0),
549
+ }
550
+ }
551
+
552
+ #[cfg(feature = "fs")]
553
+ pub fn read_file(args: &[Value]) -> Value {
554
+ let path = args
555
+ .first()
556
+ .map(|v| v.to_display_string())
557
+ .unwrap_or_default();
558
+ match std::fs::read_to_string(&path) {
559
+ Ok(content) => Value::String(content.into()),
560
+ Err(e) => make_error_value(e),
561
+ }
562
+ }
563
+
564
+ #[cfg(feature = "fs")]
565
+ pub fn write_file(args: &[Value]) -> Value {
566
+ let path = args
567
+ .first()
568
+ .map(|v| v.to_display_string())
569
+ .unwrap_or_default();
570
+ let content = args
571
+ .get(1)
572
+ .map(|v| v.to_display_string())
573
+ .unwrap_or_default();
574
+ match std::fs::write(&path, &content) {
575
+ Ok(()) => Value::Bool(true),
576
+ Err(e) => make_error_value(e),
577
+ }
578
+ }
579
+
580
+ #[cfg(feature = "fs")]
581
+ pub fn file_exists(args: &[Value]) -> Value {
582
+ let path = args
583
+ .first()
584
+ .map(|v| v.to_display_string())
585
+ .unwrap_or_default();
586
+ Value::Bool(std::path::Path::new(&path).exists())
587
+ }
588
+
589
+ #[cfg(feature = "fs")]
590
+ pub fn is_dir(args: &[Value]) -> Value {
591
+ let path = args
592
+ .first()
593
+ .map(|v| v.to_display_string())
594
+ .unwrap_or_default();
595
+ Value::Bool(std::path::Path::new(&path).is_dir())
596
+ }
597
+
598
+ #[cfg(feature = "fs")]
599
+ pub fn read_dir(args: &[Value]) -> Value {
600
+ let path = args
601
+ .first()
602
+ .map(|v| v.to_display_string())
603
+ .unwrap_or_else(|| ".".to_string());
604
+ match std::fs::read_dir(&path) {
605
+ Ok(entries) => {
606
+ let files: Vec<Value> = entries
607
+ .filter_map(|e| e.ok())
608
+ .map(|e| Value::String(e.file_name().to_string_lossy().into()))
609
+ .collect();
610
+ Value::Array(VmRef::new(files))
611
+ }
612
+ Err(e) => make_error_value(e),
613
+ }
614
+ }
615
+
616
+ #[cfg(feature = "fs")]
617
+ pub fn mkdir(args: &[Value]) -> Value {
618
+ let path = args
619
+ .first()
620
+ .map(|v| v.to_display_string())
621
+ .unwrap_or_default();
622
+ match std::fs::create_dir_all(&path) {
623
+ Ok(()) => Value::Bool(true),
624
+ Err(e) => make_error_value(e),
625
+ }
626
+ }
627
+
628
+ use std::sync::Arc;
629
+
630
+ #[inline]
631
+ pub fn get_prop(obj: &Value, key: impl AsRef<str>) -> Value {
632
+ let key = key.as_ref();
633
+ match obj {
634
+ Value::Object(map) => {
635
+ // The map's key type is `Arc<str>`, which implements
636
+ // `Borrow<str>` — so we can look up with a borrowed `&str`
637
+ // directly. Previously we allocated a fresh `Arc<str>` on
638
+ // every call (one heap alloc per `r.field` read in tight
639
+ // handler loops); this version is alloc-free on the hit path.
640
+ map.borrow().strings.get(key).cloned().unwrap_or(Value::Null)
641
+ }
642
+ Value::Array(arr) => {
643
+ if key == "length" {
644
+ Value::Number(arr.borrow().len() as f64)
645
+ } else if let Ok(idx) = key.parse::<usize>() {
646
+ arr.borrow().get(idx).cloned().unwrap_or(Value::Null)
647
+ } else {
648
+ Value::Null
649
+ }
650
+ }
651
+ Value::String(s) => {
652
+ if key == "length" {
653
+ Value::Number(s.chars().count() as f64)
654
+ } else {
655
+ Value::Null
656
+ }
657
+ }
658
+ #[cfg(feature = "regex")]
659
+ Value::RegExp(re) => {
660
+ let re = re.clone();
661
+ if key == "exec" {
662
+ Value::native(move |args: &[Value]| {
663
+ let input = args.first().unwrap_or(&Value::Null);
664
+ regexp_exec(&Value::RegExp(re.clone()), input)
665
+ })
666
+ } else if key == "test" {
667
+ Value::native(move |args: &[Value]| {
668
+ let input = args.first().unwrap_or(&Value::Null);
669
+ regexp_test(&Value::RegExp(re.clone()), input)
670
+ })
671
+ } else {
672
+ Value::Null
673
+ }
674
+ }
675
+ Value::Opaque(o) => o
676
+ .get_method(key)
677
+ .map(Value::Function)
678
+ .unwrap_or(Value::Null),
679
+ _ => Value::Null,
680
+ }
681
+ }
682
+
683
+ #[inline]
684
+ pub fn get_index(obj: &Value, index: &Value) -> Value {
685
+ match obj {
686
+ Value::Array(arr) => {
687
+ let idx = match index {
688
+ Value::Number(n) => *n as usize,
689
+ _ => return Value::Null,
690
+ };
691
+ arr.borrow().get(idx).cloned().unwrap_or(Value::Null)
692
+ }
693
+ Value::Object(_) => tishlang_core::object_get(obj, index).unwrap_or(Value::Null),
694
+ _ => Value::Null,
695
+ }
696
+ }
697
+
698
+ #[inline]
699
+ pub fn set_prop(obj: &Value, key: &str, val: Value) -> Value {
700
+ match obj {
701
+ Value::Object(map) => {
702
+ // Try the in-place update path first: if the key already
703
+ // exists we re-use the existing `Arc<str>` and skip the
704
+ // alloc. Only newly-inserted keys pay for `Arc::from(key)`.
705
+ let mut m = map.borrow_mut();
706
+ if let Some(slot) = m.strings.get_mut(key) {
707
+ *slot = val.clone();
708
+ } else {
709
+ m.strings.insert(Arc::from(key), val.clone());
710
+ }
711
+ val
712
+ }
713
+ _ => panic!("Cannot assign property on non-object"),
714
+ }
715
+ }
716
+
717
+ #[inline]
718
+ pub fn set_index(obj: &Value, idx: &Value, val: Value) -> Value {
719
+ match obj {
720
+ Value::Array(arr) => {
721
+ let index = match idx {
722
+ Value::Number(n) => *n as usize,
723
+ _ => panic!("Array index must be number"),
724
+ };
725
+ let mut arr_mut = arr.borrow_mut();
726
+ while arr_mut.len() <= index {
727
+ arr_mut.push(Value::Null);
728
+ }
729
+ arr_mut[index] = val.clone();
730
+ val
731
+ }
732
+ Value::Object(_) => {
733
+ tishlang_core::object_set(obj, idx, val.clone()).expect("object set");
734
+ val
735
+ }
736
+ _ => panic!("Cannot index assign on non-array/object"),
737
+ }
738
+ }
739
+
740
+ pub fn in_operator(key: &Value, obj: &Value) -> Value {
741
+ match obj {
742
+ Value::Object(_) => Value::Bool(tishlang_core::object_has(obj, key)),
743
+ Value::Array(arr) => {
744
+ let key_str: Arc<str> = match key {
745
+ Value::String(s) => Arc::clone(s),
746
+ Value::Number(n) => n.to_string().into(),
747
+ _ => return Value::Bool(false),
748
+ };
749
+ let result = key_str.as_ref() == "length"
750
+ || key_str
751
+ .parse::<usize>()
752
+ .ok()
753
+ .map(|i| i < arr.borrow().len())
754
+ .unwrap_or(false);
755
+ Value::Bool(result)
756
+ }
757
+ _ => Value::Bool(false),
758
+ }
759
+ }
760
+
761
+ // Object functions - delegate to tishlang_builtins::globals
762
+ pub fn object_assign(args: &[Value]) -> Value {
763
+ builtins_object_assign(args)
764
+ }
765
+
766
+ pub fn object_keys(args: &[Value]) -> Value {
767
+ builtins_object_keys(args)
768
+ }
769
+
770
+ pub fn object_values(args: &[Value]) -> Value {
771
+ builtins_object_values(args)
772
+ }
773
+
774
+ pub fn object_entries(args: &[Value]) -> Value {
775
+ builtins_object_entries(args)
776
+ }
777
+
778
+ pub fn object_from_entries(args: &[Value]) -> Value {
779
+ builtins_object_from_entries(args)
780
+ }
781
+
782
+ // HTTP Support
783
+ #[cfg(feature = "http")]
784
+ mod promise_io;
785
+
786
+ #[cfg(feature = "http")]
787
+ mod http;
788
+
789
+ #[cfg(feature = "http")]
790
+ mod http_prefork;
791
+
792
+ #[cfg(feature = "http-io-uring")]
793
+ mod http_io_uring;
794
+
795
+ #[cfg(feature = "http-hyper")]
796
+ mod http_hyper;
797
+
798
+ #[cfg(feature = "http")]
799
+ mod http_fetch;
800
+
801
+ mod timers;
802
+
803
+ #[cfg(any(feature = "http", feature = "promise"))]
804
+ mod promise;
805
+
806
+ #[cfg(feature = "http")]
807
+ mod native_promise;
808
+
809
+ #[cfg(feature = "ws")]
810
+ mod ws;
811
+
812
+ #[cfg(feature = "ws")]
813
+ pub use ws::{
814
+ web_socket_client, web_socket_server_accept, web_socket_server_construct,
815
+ web_socket_server_listen, ws_broadcast_native, ws_send_native,
816
+ };
817
+
818
+ #[cfg(feature = "http")]
819
+ pub use http::{
820
+ await_fetch as http_await_fetch, await_fetch_all as http_await_fetch_all,
821
+ register_static_route,
822
+ };
823
+
824
+ // `serve` is the user-facing entry point for Tish's HTTP server. By default
825
+ // it uses the tiny_http + SO_REUSEPORT path in `http.rs`. When compiled with
826
+ // `--features http-hyper` and the `TISH_HTTP_BACKEND=hyper` env var is set
827
+ // at runtime, it dispatches to the hyper backend in `http_hyper.rs`.
828
+ //
829
+ // The env-var switch (rather than a cargo feature switch) means one built
830
+ // binary can toggle backends for A/B benchmarking and production rollout
831
+ // without rebuilding. When `http-hyper` is not compiled in, the switch is a
832
+ // no-op and the tiny_http path is used unconditionally.
833
+ #[cfg(feature = "http")]
834
+ pub fn http_serve<F>(args: &[tishlang_core::Value], handler: F) -> tishlang_core::Value
835
+ where
836
+ F: Fn(&[tishlang_core::Value]) -> tishlang_core::Value + Send + Sync + 'static,
837
+ {
838
+ #[cfg(feature = "http-hyper")]
839
+ {
840
+ if http_hyper::is_enabled_via_env() {
841
+ return http_hyper::serve(args, handler);
842
+ }
843
+ }
844
+ http::serve(args, handler)
845
+ }
846
+
847
+ /// `serve(port, { onWorker: (workerId) => handler })` — the object form of
848
+ /// `serve`. Picks up `onWorker`, invokes it once per HTTP accept thread to
849
+ /// build that thread's handler, then enters the normal parallel accept
850
+ /// loop. See [`http::serve_per_worker`] for the full doc.
851
+ ///
852
+ /// This is broadly useful for any Tish app that wants per-worker state —
853
+ /// DB connection pools, in-process caches, counters, etc. — without a
854
+ /// global `RwLock` or forcing everything through the single-thread
855
+ /// dispatcher. It also plays nicely with prefork: `onWorker` sees global
856
+ /// worker ids across processes so logs and sharded state are easy to key.
857
+ #[cfg(feature = "http")]
858
+ pub fn http_serve_per_worker(
859
+ args: &[tishlang_core::Value],
860
+ factory_value: tishlang_core::Value,
861
+ ) -> tishlang_core::Value {
862
+ use tishlang_core::Value;
863
+ // factory_value should be Value::Function (passed down by codegen after
864
+ // extracting `onWorker` from the options object).
865
+ let Value::Function(factory) = factory_value else {
866
+ eprintln!("[tish http] serve: onWorker must be a function (id) => handler");
867
+ return Value::Null;
868
+ };
869
+ let factory: tishlang_core::NativeFn = factory;
870
+ http::serve_per_worker(args, move |worker_id| {
871
+ let handler_val = factory(&[Value::Number(worker_id as f64)]);
872
+ match handler_val {
873
+ Value::Function(f) => f,
874
+ _ => panic!(
875
+ "onWorker returned {:?} for worker {}; must return a function",
876
+ handler_val, worker_id
877
+ ),
878
+ }
879
+ })
880
+ }
881
+
882
+ pub use timers::{
883
+ clear_interval as timer_clear_interval, clear_timeout as timer_clear_timeout, drain_timers,
884
+ set_interval as timer_set_interval, set_timeout as timer_set_timeout,
885
+ };
886
+
887
+ #[cfg(any(feature = "http", feature = "promise"))]
888
+ pub use promise::{await_promise, promise_instance_catch, promise_instance_then, promise_object};
889
+
890
+ #[cfg(feature = "http")]
891
+ pub use native_promise::{fetch_all_promise, fetch_async_promise, fetch_promise};
892
+
893
+ // RegExp Support
894
+ #[cfg(feature = "regex")]
895
+ pub use tishlang_core::{RegExpFlags, TishRegExp};
896
+
897
+ #[cfg(feature = "regex")]
898
+ pub fn regexp_new(args: &[Value]) -> Value {
899
+ let pattern = match args.first() {
900
+ Some(Value::String(s)) => s.to_string(),
901
+ Some(v) => v.to_display_string(),
902
+ None => String::new(),
903
+ };
904
+
905
+ let flags = match args.get(1) {
906
+ Some(Value::String(s)) => s.to_string(),
907
+ Some(Value::Null) | None => String::new(),
908
+ Some(v) => v.to_display_string(),
909
+ };
910
+
911
+ match TishRegExp::new(&pattern, &flags) {
912
+ Ok(re) => Value::RegExp(VmRef::new(re)),
913
+ Err(e) => {
914
+ eprintln!("RegExp error: {}", e);
915
+ Value::Null
916
+ }
917
+ }
918
+ }
919
+
920
+ #[cfg(feature = "regex")]
921
+ pub fn regexp_test(re: &Value, input: &Value) -> Value {
922
+ if let Value::RegExp(re) = re {
923
+ let input_str = input.to_display_string();
924
+ Value::Bool(re.borrow_mut().test(&input_str))
925
+ } else {
926
+ Value::Bool(false)
927
+ }
928
+ }
929
+
930
+ #[cfg(feature = "regex")]
931
+ pub fn regexp_exec(re: &Value, input: &Value) -> Value {
932
+ if let Value::RegExp(re) = re {
933
+ let input_str = input.to_display_string();
934
+ regexp_exec_impl(&mut re.borrow_mut(), &input_str)
935
+ } else {
936
+ Value::Null
937
+ }
938
+ }
939
+
940
+ #[cfg(feature = "regex")]
941
+ fn regexp_exec_impl(re: &mut tishlang_core::TishRegExp, input: &str) -> Value {
942
+ use tishlang_core::ObjectMap;
943
+
944
+ let start = if re.flags.global || re.flags.sticky {
945
+ re.last_index
946
+ } else {
947
+ 0
948
+ };
949
+
950
+ let char_count = input.chars().count();
951
+ if start > char_count {
952
+ if re.flags.global || re.flags.sticky {
953
+ re.last_index = 0;
954
+ }
955
+ return Value::Null;
956
+ }
957
+
958
+ let byte_start: usize = input.chars().take(start).map(|c| c.len_utf8()).sum();
959
+ let search_str = &input[byte_start..];
960
+
961
+ match re.regex.captures(search_str) {
962
+ Ok(Some(caps)) => {
963
+ let full_match = caps.get(0).unwrap();
964
+
965
+ if re.flags.sticky && full_match.start() != 0 {
966
+ re.last_index = 0;
967
+ return Value::Null;
968
+ }
969
+
970
+ let match_byte_start = byte_start + full_match.start();
971
+ let match_char_index = input[..match_byte_start].chars().count();
972
+
973
+ let mut obj: ObjectMap = ObjectMap::default();
974
+ obj.insert(Arc::from("0"), Value::String(full_match.as_str().into()));
975
+ for i in 1..caps.len() {
976
+ let val = match caps.get(i) {
977
+ Some(m) => Value::String(m.as_str().into()),
978
+ None => Value::Null,
979
+ };
980
+ obj.insert(Arc::from(i.to_string().as_str()), val);
981
+ }
982
+ obj.insert(Arc::from("index"), Value::Number(match_char_index as f64));
983
+
984
+ if re.flags.global || re.flags.sticky {
985
+ let match_end_chars = input[..byte_start + full_match.end()].chars().count();
986
+ re.last_index = if full_match.start() == full_match.end() {
987
+ match_end_chars + 1
988
+ } else {
989
+ match_end_chars
990
+ };
991
+ }
992
+
993
+ Value::object(obj)
994
+ }
995
+ Ok(None) | Err(_) => {
996
+ if re.flags.global || re.flags.sticky {
997
+ re.last_index = 0;
998
+ }
999
+ Value::Null
1000
+ }
1001
+ }
1002
+ }
1003
+
1004
+ #[cfg(feature = "regex")]
1005
+ pub fn string_split_regex(s: &Value, separator: &Value, limit: Option<usize>) -> Value {
1006
+ let input = match s {
1007
+ Value::String(s) => s.as_ref(),
1008
+ _ => return Value::Array(VmRef::new(vec![s.clone()])),
1009
+ };
1010
+
1011
+ let max = limit.unwrap_or(usize::MAX);
1012
+ if max == 0 {
1013
+ return Value::Array(VmRef::new(Vec::new()));
1014
+ }
1015
+
1016
+ match separator {
1017
+ Value::RegExp(re) => {
1018
+ let re = re.borrow();
1019
+ let mut result = Vec::new();
1020
+ let mut last_end = 0;
1021
+
1022
+ for mat in re.regex.find_iter(input) {
1023
+ match mat {
1024
+ Ok(m) => {
1025
+ if result.len() >= max - 1 {
1026
+ break;
1027
+ }
1028
+ result.push(Value::String(input[last_end..m.start()].into()));
1029
+ last_end = m.end();
1030
+ }
1031
+ Err(_) => break,
1032
+ }
1033
+ }
1034
+
1035
+ if result.len() < max {
1036
+ result.push(Value::String(input[last_end..].into()));
1037
+ }
1038
+
1039
+ Value::Array(VmRef::new(result))
1040
+ }
1041
+ Value::String(sep) => {
1042
+ let parts: Vec<Value> = input
1043
+ .splitn(max, sep.as_ref())
1044
+ .map(|s| Value::String(s.into()))
1045
+ .collect();
1046
+ Value::Array(VmRef::new(parts))
1047
+ }
1048
+ _ => Value::Array(VmRef::new(vec![Value::String(input.into())])),
1049
+ }
1050
+ }
1051
+
1052
+ #[cfg(feature = "regex")]
1053
+ pub fn string_match_regex(s: &Value, regexp: &Value) -> Value {
1054
+ let input = match s {
1055
+ Value::String(s) => s.as_ref(),
1056
+ _ => return Value::Null,
1057
+ };
1058
+
1059
+ match regexp {
1060
+ Value::RegExp(re) => {
1061
+ let mut re = re.borrow_mut();
1062
+
1063
+ if re.flags.global {
1064
+ let mut matches = Vec::new();
1065
+ re.last_index = 0;
1066
+
1067
+ while let Ok(Some(m)) = re.regex.find_from_pos(input, re.last_index) {
1068
+ matches.push(Value::String(m.as_str().into()));
1069
+ if m.start() == m.end() {
1070
+ re.last_index = m.end() + 1;
1071
+ } else {
1072
+ re.last_index = m.end();
1073
+ }
1074
+ if re.last_index > input.len() {
1075
+ break;
1076
+ }
1077
+ }
1078
+
1079
+ re.last_index = 0;
1080
+
1081
+ if matches.is_empty() {
1082
+ Value::Null
1083
+ } else {
1084
+ Value::Array(VmRef::new(matches))
1085
+ }
1086
+ } else {
1087
+ regexp_exec_impl(&mut re, input)
1088
+ }
1089
+ }
1090
+ Value::String(pattern) => match tishlang_core::TishRegExp::new(pattern, "") {
1091
+ Ok(mut re) => regexp_exec_impl(&mut re, input),
1092
+ Err(_) => Value::Null,
1093
+ },
1094
+ _ => Value::Null,
1095
+ }
1096
+ }
1097
+
1098
+ #[cfg(feature = "regex")]
1099
+ fn string_replace_regex_or_callback(s: &Value, search: &Value, replacement: &Value) -> Value {
1100
+ let input = match s {
1101
+ Value::String(s) => s.as_ref(),
1102
+ _ => return s.clone(),
1103
+ };
1104
+
1105
+ let Value::RegExp(re) = search else {
1106
+ return s.clone();
1107
+ };
1108
+ let re_guard = re.borrow();
1109
+
1110
+ if let Value::Function(cb) = replacement {
1111
+ let limit = if re_guard.flags.global { usize::MAX } else { 1 };
1112
+ let mut result = String::new();
1113
+ let mut last_end: usize = 0;
1114
+ for (count, cap_result) in re_guard.regex.captures_iter(input).enumerate() {
1115
+ if count >= limit {
1116
+ break;
1117
+ }
1118
+ let Ok(caps) = cap_result else {
1119
+ break;
1120
+ };
1121
+ let full = caps.get(0).unwrap();
1122
+ let match_str = full.as_str();
1123
+ let byte_start = full.start();
1124
+ let char_index = input[..byte_start].chars().count();
1125
+
1126
+ let mut args = vec![Value::String(match_str.into())];
1127
+ for i in 1..caps.len() {
1128
+ let val = match caps.get(i) {
1129
+ Some(m) => Value::String(m.as_str().into()),
1130
+ None => Value::Null,
1131
+ };
1132
+ args.push(val);
1133
+ }
1134
+ args.push(Value::Number(char_index as f64));
1135
+ args.push(Value::String(input.into()));
1136
+
1137
+ let repl_val = cb(&args);
1138
+ let repl_str = repl_val.to_display_string();
1139
+ result.push_str(&input[last_end..byte_start]);
1140
+ result.push_str(&repl_str);
1141
+ last_end = full.end();
1142
+ }
1143
+
1144
+ result.push_str(&input[last_end..]);
1145
+ Value::String(result.into())
1146
+ } else {
1147
+ let replacement_str = replacement.to_display_string();
1148
+ if re_guard.flags.global {
1149
+ match re_guard.regex.replace_all(input, replacement_str.as_str()) {
1150
+ std::borrow::Cow::Borrowed(x) => Value::String(x.into()),
1151
+ std::borrow::Cow::Owned(x) => Value::String(x.into()),
1152
+ }
1153
+ } else {
1154
+ match re_guard.regex.replace(input, replacement_str.as_str()) {
1155
+ std::borrow::Cow::Borrowed(x) => Value::String(x.into()),
1156
+ std::borrow::Cow::Owned(x) => Value::String(x.into()),
1157
+ }
1158
+ }
1159
+ }
1160
+ }
1161
+
1162
+ #[cfg(feature = "regex")]
1163
+ pub fn string_search_regex(s: &Value, regexp: &Value) -> Value {
1164
+ let input = match s {
1165
+ Value::String(s) => s.as_ref(),
1166
+ _ => return Value::Number(-1.0),
1167
+ };
1168
+
1169
+ match regexp {
1170
+ Value::RegExp(re) => {
1171
+ let re = re.borrow();
1172
+ match re.regex.find(input) {
1173
+ Ok(Some(m)) => {
1174
+ let char_index = input[..m.start()].chars().count();
1175
+ Value::Number(char_index as f64)
1176
+ }
1177
+ _ => Value::Number(-1.0),
1178
+ }
1179
+ }
1180
+ Value::String(pattern) => match tishlang_core::TishRegExp::new(pattern, "") {
1181
+ Ok(re) => match re.regex.find(input) {
1182
+ Ok(Some(m)) => {
1183
+ let char_index = input[..m.start()].chars().count();
1184
+ Value::Number(char_index as f64)
1185
+ }
1186
+ _ => Value::Number(-1.0),
1187
+ },
1188
+ Err(_) => Value::Number(-1.0),
1189
+ },
1190
+ _ => Value::Number(-1.0),
1191
+ }
1192
+ }