pipa-js 0.1.6

A fast, minimal ES2023 JavaScript runtime built in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use crate::runtime::context::JSContext;
use crate::value::JSValue;

pub fn global_parseint(ctx: &mut JSContext, args: &[JSValue]) -> JSValue {
    if args.is_empty() {
        return JSValue::new_float(f64::NAN);
    }

    let input_val = &args[0];
    let s = if input_val.is_string() {
        ctx.get_atom_str(input_val.get_atom()).to_string()
    } else if input_val.is_int() {
        input_val.get_int().to_string()
    } else if input_val.is_float() {
        let f = input_val.get_float();
        if f.is_nan() || f.is_infinite() {
            return JSValue::new_float(f64::NAN);
        }
        let truncated = f.trunc();
        if truncated == 0.0 {
            return JSValue::new_int(0);
        }
        format!("{}", truncated as i64)
    } else if input_val.is_bool() {
        if input_val.get_bool() {
            "true".to_string()
        } else {
            "false".to_string()
        }
    } else if input_val.is_null() {
        "null".to_string()
    } else if input_val.is_undefined() {
        "undefined".to_string()
    } else if input_val.is_object() {
        let obj = input_val.as_object();
        let mut prim: Option<Option<String>> = None;
        if let Some(to_str) = obj.get(ctx.intern("toString")) {
            if to_str.is_function() {
                if let Some(ptr) = ctx.get_register_vm_ptr() {
                    let vm = unsafe { &mut *(ptr as *mut crate::runtime::vm::VM) };
                    match vm.call_function_with_this(ctx, to_str, *input_val, &[]) {
                        Ok(result) if result.is_string() => {
                            prim = Some(Some(ctx.get_atom_str(result.get_atom()).to_string()));
                        }
                        Ok(result) if result.is_int() => {
                            prim = Some(Some(result.get_int().to_string()));
                        }
                        Ok(result) if result.is_float() => {
                            prim = Some(Some(result.get_float().to_string()));
                        }
                        Ok(_) => {
                            prim = Some(None);
                        }
                        _ => {}
                    }
                }
            }
        }
        if let Some(Some(_)) = prim {
        } else {
            if let Some(val_of) = obj.get(ctx.intern("valueOf")) {
                if val_of.is_function() {
                    if let Some(ptr) = ctx.get_register_vm_ptr() {
                        let vm = unsafe { &mut *(ptr as *mut crate::runtime::vm::VM) };
                        match vm.call_function_with_this(ctx, val_of, *input_val, &[]) {
                            Ok(result) if result.is_string() => {
                                prim = Some(Some(ctx.get_atom_str(result.get_atom()).to_string()));
                            }
                            Ok(result) if result.is_int() => {
                                prim = Some(Some(result.get_int().to_string()));
                            }
                            Ok(result) if result.is_float() => {
                                prim = Some(Some(result.get_float().to_string()));
                            }
                            Ok(_) => {
                                prim = Some(None);
                            }
                            _ => {}
                        }
                    }
                }
            }
        }
        match prim {
            Some(Some(s)) => s,
            _ => {
                return crate::builtins::global::throw_type_error(
                    ctx,
                    "Cannot convert object to primitive value",
                );
            }
        }
    } else {
        return JSValue::new_float(f64::NAN);
    };

    let mut input = s.trim_start();
    let mut sign = 1f64;
    if let Some(rest) = input.strip_prefix('-') {
        sign = -1.0;
        input = rest;
    } else if let Some(rest) = input.strip_prefix('+') {
        input = rest;
    }

    let radix_arg = args.get(1);
    let mut radix = if let Some(ra) = radix_arg {
        let n = if ra.is_int() {
            ra.get_int() as f64
        } else if ra.is_float() {
            ra.get_float()
        } else if ra.is_bool() {
            if ra.get_bool() { 1.0 } else { 0.0 }
        } else if ra.is_null() {
            0.0
        } else if ra.is_undefined() {
            0.0
        } else if ra.is_string() {
            let s = ctx.get_atom_str(ra.get_atom());
            if s.trim().is_empty() {
                0.0
            } else {
                match s.trim().parse::<f64>() {
                    Ok(v) if v.is_nan() => 0.0,
                    Ok(v) => v,
                    Err(_) => 0.0,
                }
            }
        } else if ra.is_object() {
            let obj = ra.as_object();
            let mut radix_num = None;
            if let Some(val_of) = obj.get(ctx.intern("valueOf")) {
                if val_of.is_function() {
                    if let Some(ptr) = ctx.get_register_vm_ptr() {
                        let vm = unsafe { &mut *(ptr as *mut crate::runtime::vm::VM) };
                        match vm.call_function_with_this(ctx, val_of, *ra, &[]) {
                            Ok(result) if result.is_int() => {
                                radix_num = Some(result.get_int() as f64)
                            }
                            Ok(result) if result.is_float() => radix_num = Some(result.get_float()),
                            Ok(result) if result.is_bool() => {
                                radix_num = Some(if result.get_bool() { 1.0 } else { 0.0 });
                            }
                            _ => {}
                        }
                        if ctx.pending_exception.is_some() {
                            return JSValue::undefined();
                        }
                    }
                }
            }
            if radix_num.is_none() {
                if let Some(to_str) = obj.get(ctx.intern("toString")) {
                    if to_str.is_function() {
                        if let Some(ptr) = ctx.get_register_vm_ptr() {
                            let vm = unsafe { &mut *(ptr as *mut crate::runtime::vm::VM) };
                            match vm.call_function_with_this(ctx, to_str, *ra, &[]) {
                                Ok(result) if result.is_string() => {
                                    let s = ctx.get_atom_str(result.get_atom());
                                    if let Ok(v) = s.trim().parse::<f64>() {
                                        radix_num = Some(v);
                                    }
                                }
                                Ok(result) if result.is_int() => {
                                    radix_num = Some(result.get_int() as f64)
                                }
                                Ok(result) if result.is_float() => {
                                    radix_num = Some(result.get_float())
                                }
                                _ => {}
                            }
                        }
                    }
                }
            }
            if ctx.pending_exception.is_some() {
                return JSValue::undefined();
            }
            match radix_num {
                Some(v) => v,
                None => {
                    return crate::builtins::global::throw_type_error(
                        ctx,
                        "Cannot convert object to primitive value",
                    );
                }
            }
        } else {
            0.0
        };
        if n.is_nan() || n.is_infinite() {
            0
        } else {
            let r = (n.trunc() as i64 & 0xFFFFFFFF) as i32;
            if r == 1 {
                return JSValue::new_float(f64::NAN);
            }
            r
        }
    } else {
        0
    };

    if radix != 0 && !(2..=36).contains(&radix) {
        return JSValue::new_float(f64::NAN);
    }

    if radix == 0 {
        if input.starts_with("0x") || input.starts_with("0X") {
            radix = 16;
            input = &input[2..];
        } else {
            radix = 10;
        }
    } else if radix == 16 && (input.starts_with("0x") || input.starts_with("0X")) {
        input = &input[2..];
    }

    let mut result: f64 = 0.0;
    let mut has_digits = false;
    for ch in input.chars() {
        if let Some(d) = ch.to_digit(radix as u32) {
            result = result * (radix as f64) + (d as f64);
            has_digits = true;
        } else {
            break;
        }
    }

    if !has_digits {
        return JSValue::new_float(f64::NAN);
    }

    let final_val = sign * result;
    if final_val >= -(1i64 << 47) as f64
        && final_val < (1i64 << 47) as f64
        && final_val == final_val.trunc()
    {
        JSValue::new_int(final_val as i64)
    } else {
        JSValue::new_float(final_val)
    }
}

pub fn global_parsefloat(ctx: &mut JSContext, args: &[JSValue]) -> JSValue {
    if args.is_empty() {
        return JSValue::new_float(f64::NAN);
    }

    let input = &args[0];

    if input.is_symbol() {
        if let Some(ptr) = ctx.get_register_vm_ptr() {
            let vm = unsafe { &mut *(ptr as *mut crate::runtime::vm::VM) };
            let msg_atom = ctx.intern("TypeError: Cannot convert Symbol to string");
            vm.pending_throw = Some(JSValue::new_string(msg_atom));
        }
        return JSValue::undefined();
    }

    if input.is_float() {
        let f = input.get_float();
        if f == 0.0 {
            return JSValue::new_int(0);
        }
        return *input;
    }
    if input.is_int() {
        return *input;
    }

    let s = if input.is_string() {
        ctx.get_atom_str(input.get_atom()).to_string()
    } else if input.is_object() {
        let obj = input.as_object();
        let mut result_str: Option<String> = None;
        if let Some(to_str) = obj.get(ctx.intern("toString")) {
            if to_str.is_function() {
                if let Some(ptr) = ctx.get_register_vm_ptr() {
                    let vm = unsafe { &mut *(ptr as *mut crate::runtime::vm::VM) };
                    match vm.call_function_with_this(ctx, to_str, *input, &[]) {
                        Ok(result) => {
                            if result.is_string() {
                                result_str = Some(ctx.get_atom_str(result.get_atom()).to_string());
                            } else if result.is_int() {
                                result_str = Some(result.get_int().to_string());
                            } else if result.is_float() {
                                result_str = Some(result.get_float().to_string());
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
        if result_str.is_none() {
            if let Some(value_of) = obj.get(ctx.intern("valueOf")) {
                if value_of.is_function() {
                    if let Some(ptr) = ctx.get_register_vm_ptr() {
                        let vm = unsafe { &mut *(ptr as *mut crate::runtime::vm::VM) };
                        match vm.call_function_with_this(ctx, value_of, *input, &[]) {
                            Ok(result) => {
                                if result.is_string() {
                                    result_str =
                                        Some(ctx.get_atom_str(result.get_atom()).to_string());
                                } else if result.is_int() {
                                    result_str = Some(result.get_int().to_string());
                                } else if result.is_float() {
                                    result_str = Some(result.get_float().to_string());
                                }
                            }
                            _ => {}
                        }
                    }
                }
            }
        }
        match result_str {
            Some(s) => s,
            None => {
                if let Some(ptr) = ctx.get_register_vm_ptr() {
                    let vm = unsafe { &mut *(ptr as *mut crate::runtime::vm::VM) };
                    let mut err = crate::object::object::JSObject::new_typed(
                        crate::object::object::ObjectType::Error,
                    );
                    err.set(
                        ctx.common_atoms.message,
                        JSValue::new_string(ctx.intern("Cannot convert object to primitive value")),
                    );
                    err.set(
                        ctx.common_atoms.name,
                        JSValue::new_string(ctx.intern("TypeError")),
                    );
                    if let Some(proto) = ctx.get_type_error_prototype() {
                        err.prototype = Some(proto);
                    }
                    let err_ptr = Box::into_raw(Box::new(err)) as usize;
                    ctx.runtime_mut().gc_heap_mut().track(err_ptr);
                    vm.pending_throw = Some(JSValue::new_object(err_ptr));
                }
                return JSValue::undefined();
            }
        }
    } else {
        return JSValue::new_float(f64::NAN);
    };

    let trimmed = s.trim_start();

    if trimmed.is_empty() {
        return JSValue::new_float(f64::NAN);
    }

    let bytes = trimmed.as_bytes();
    let mut pos = 0;

    if pos < bytes.len() && (bytes[pos] == b'+' || bytes[pos] == b'-') {
        pos += 1;
    }

    let start_num = pos;

    while pos < bytes.len() && bytes[pos].is_ascii_digit() {
        pos += 1;
    }

    if pos < bytes.len() && bytes[pos] == b'.' {
        pos += 1;
        while pos < bytes.len() && bytes[pos].is_ascii_digit() {
            pos += 1;
        }
    }

    if pos < bytes.len() && (bytes[pos] == b'e' || bytes[pos] == b'E') {
        let e_pos = pos;
        pos += 1;
        if pos < bytes.len() && (bytes[pos] == b'+' || bytes[pos] == b'-') {
            pos += 1;
        }
        if pos < bytes.len() && bytes[pos].is_ascii_digit() {
            while pos < bytes.len() && bytes[pos].is_ascii_digit() {
                pos += 1;
            }
        } else {
            pos = e_pos;
        }
    }

    if pos == start_num {
        let rest = trimmed;
        if rest.starts_with("Infinity") || rest.starts_with("+Infinity") {
            return JSValue::new_float(f64::INFINITY);
        }
        if rest.starts_with("-Infinity") {
            return JSValue::new_float(f64::NEG_INFINITY);
        }
        return JSValue::new_float(f64::NAN);
    }

    let num_str = &trimmed[..pos];

    if num_str == "Infinity" || num_str == "+Infinity" {
        return JSValue::new_float(f64::INFINITY);
    }
    if num_str == "-Infinity" {
        return JSValue::new_float(f64::NEG_INFINITY);
    }

    match num_str.parse::<f64>() {
        Ok(v) if v == 0.0 => JSValue::new_int(0),
        Ok(v) => JSValue::new_float(v),
        Err(_) => JSValue::new_float(f64::NAN),
    }
}