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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! [`JSValue`] in general; [`JSString`], [`JSNumber`], etc.

use core::{
    borrow::Borrow,
    convert::Infallible,
    ops::Deref,
    str::Chars,
};

use crate::{
    prelude::*,
    CallContext,
    Exception,
    Heap,
    Interpreted,
    JSObject,
    JSRef,
    JSResult,
};

pub type JSON = serde_json::Value;

pub type JSNumber = f64;

/// A Javascript string value.
///
/// Why not `std::string::String`?
/// - Javascript strings are immutable. There is no point in cloning a string content.
/// - Ideally they should be a sequence of addressable 16-bit UTF-16 "code points" (potentially broken).
///   TODO: Indexing a Rust `String` over chars brings an unknown overhead of linear scanning.
#[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Eq, Hash)]
#[repr(transparent)]
pub struct JSString(Rc<str>);

impl JSString {
    pub fn as_str(&self) -> &str {
        self.0.as_ref()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn chars(&self) -> Chars {
        self.0.chars()
    }
}

impl Default for JSString {
    fn default() -> Self {
        JSString(Rc::from(""))
    }
}

impl Borrow<str> for JSString {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl Deref for JSString {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.0.as_ref()
    }
}

impl fmt::Display for JSString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl FromStr for JSString {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<JSString, Self::Err> {
        Ok(JSString(Rc::from(s)))
    }
}

impl From<String> for JSString {
    fn from(s: String) -> JSString {
        JSString(Rc::from(s.into_boxed_str()))
    }
}

impl From<&str> for JSString {
    fn from(s: &str) -> JSString {
        JSString(Rc::from(s))
    }
}

#[cfg(test)]
mod test_strings {
    use core::hash::{
        Hash,
        Hasher,
    };
    use std::collections::hash_map::DefaultHasher;

    use super::JSString;

    #[test]
    fn eq() {
        let s1 = JSString::from("hello");
        let s2 = JSString::from("hello");
        assert_eq!(s1, s2);
        assert_ne!(s1.as_ptr(), s2.as_ptr());

        let s3 = s2.clone();
        assert_eq!(s2.as_ptr(), s3.as_ptr());
    }

    fn get_hash<T: Hash>(t: &T) -> u64 {
        let mut h = DefaultHasher::new();
        t.hash(&mut h);
        h.finish()
    }

    #[test]
    fn hash() {
        let s1 = JSString::from("hello");
        let s2 = JSString::from("hello");
        assert_eq!(get_hash(&s1), get_hash(&s2));
    }

    #[test]
    fn ord() {
        assert!(JSString::from("a") < JSString::from("b"));
        assert!(JSString::from("a") < JSString::from("aa"));

        let mut v = Vec::from_iter(["aa", "a", "", "Aa", "!"].map(JSString::from));
        v.sort();
        assert_eq!(&v, &["", "!", "Aa", "a", "aa"].map(JSString::from));
    }
}

/// A `JSValue` is either a primitive value or a reference to an object.
#[derive(Debug, Clone, PartialEq)]
pub enum JSValue {
    Undefined,
    Bool(bool),
    Number(JSNumber),
    String(JSString),
    //Symbol(String)
    Ref(JSRef),
}

impl JSValue {
    pub const NULL: JSValue = JSValue::Ref(Heap::NULL);

    /// to_ref() tries to return the underlying object reference, if any.
    /// Throws Exception::ReferenceNotAnObject if it's not a reference.
    /// Checking if a JSValue is a reference: `val.to_ref().is_ok()`.
    pub fn to_ref(&self) -> JSResult<JSRef> {
        match self {
            JSValue::Ref(objref) => Ok(*objref),
            _ => {
                let what = Interpreted::Value(self.clone());
                Err(Exception::ReferenceNotAnObject(what))
            }
        }
    }

    pub fn to_json(&self, heap: &Heap) -> JSResult<JSON> {
        match self {
            JSValue::Undefined => Ok(JSON::Null),
            JSValue::Bool(b) => Ok(JSON::from(*b)),
            JSValue::Number(n) => Ok(JSON::from(*n)),
            JSValue::String(s) => Ok(JSON::from(s.as_str())),
            JSValue::Ref(Heap::NULL) => Ok(JSON::Null),
            JSValue::Ref(href) => heap.get(*href).to_json(heap),
        }
    }

    /// `to_string()` makes a human-readable string representation of the value:
    /// ```
    /// # use serde_json::json;
    /// # use sljs::{JSValue, Heap};
    /// # let mut heap = Heap::new();
    /// assert_eq!(
    ///     JSValue::from("1").to_string(&mut heap).unwrap().as_str(),
    ///     "\"1\""
    /// );
    /// assert_eq!(
    ///     JSValue::from(1).to_string(&mut heap).unwrap().as_str(),
    ///     "1"
    /// );
    ///
    /// let json_object = json!({"one": 1});
    /// let example_object = heap.object_from_json(&json_object);
    /// assert_eq!(
    ///     example_object.to_string(&mut heap).unwrap().as_str(),
    ///     "{ one: 1 }"
    /// );
    ///
    /// let json_array = json!([1, 2]);
    /// let example_array = heap.object_from_json(&json_array);
    /// assert_eq!(
    ///     example_array.to_string(&mut heap).unwrap().as_str(),
    ///     "[1, 2]"
    /// );
    /// ```
    pub fn to_string(&self, heap: &mut Heap) -> JSResult<JSString> {
        match self {
            JSValue::String(s) => {
                let jstr = JSON::from(s.as_str());
                Ok(JSString::from(jstr.to_string()))
            }
            JSValue::Ref(heapref) => {
                // without `.clone()` `heap` cannot be borrowed in both places
                heap.get(*heapref).clone().to_string(heap)
            }
            _ => self.stringify(heap),
        }
    }

    /// stringify() makes everything into a string
    /// used for evaluation in a string context.
    /// It corresponds to .toString() in JavaScript
    pub fn stringify(&self, heap: &mut Heap) -> JSResult<JSString> {
        match self {
            JSValue::Undefined => Ok("undefined".into()),
            JSValue::Bool(b) => Ok(b.to_string().into()),
            JSValue::Number(n) => Ok(n.to_string().into()),
            JSValue::String(s) => Ok(s.clone()),
            JSValue::Ref(r) if r == &Heap::NULL => Ok(JSString::from("null")),
            JSValue::Ref(r) => match heap.lookup_protochain(*r, "toString") {
                Some(to_string) => {
                    let funcref = to_string.to_ref(heap)?;
                    let result = heap.execute(
                        funcref,
                        CallContext {
                            this_ref: *r,
                            method_name: "toString".into(),
                            arguments: vec![],
                            loc: None,
                        },
                    )?;
                    Ok(result.to_value(heap)?.stringify(heap)?)
                }
                None => Ok("[object Object]".into()),
            },
        }
    }

    /// numberify() tries to make everything into a numeric value
    /// for evalation in a numeric context.
    /// It is slightly more strict than `+value` in JavaScript: only
    /// `value.numberify().unwrap_or(f64::NAN)` corresponds to `+value` in JavaScript.
    pub fn numberify(&self, heap: &Heap) -> Option<JSNumber> {
        match self {
            JSValue::Undefined => None, // Some(f64::NAN),
            JSValue::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
            JSValue::Number(n) => Some(*n),
            JSValue::String(s) => s.as_str().parse::<JSNumber>().ok(),
            JSValue::Ref(Heap::NULL) => Some(0.0),
            JSValue::Ref(r) => {
                let object = heap.get(*r);
                if let Some(array) = object.as_array() {
                    match &array.storage[..] {
                        [] => Some(0.0),              // +[]  == 0
                        [val] => val.numberify(heap), // +[x] == x
                        _ => None,                    // +[x, y, ..] == NaN
                    }
                } else {
                    object.to_primitive().and_then(|v| v.numberify(heap))
                }
            }
        }
    }

    /// boolify() treats everythings as a truthy value.
    /// ES5: ToBoolean
    pub fn boolify(&self, heap: &Heap) -> bool {
        match self {
            JSValue::Undefined => false,
            JSValue::String(s) => !s.as_str().is_empty(),
            JSValue::Ref(Heap::NULL) => false,
            JSValue::Ref(_) => true,
            _ => {
                if let Some(n) = self.numberify(heap) {
                    !(n == 0.0 || f64::is_nan(n))
                } else {
                    true
                }
            }
        }
    }

    /// objectify() wraps a primitive into its object:
    /// - `undefined` becomes `null`
    /// - `bool`/`number`/`string` becomes `Boolean`/`Number`/`String`
    /// - objects just return their reference.
    pub fn objectify(&self, heap: &mut Heap) -> JSRef {
        match self {
            JSValue::Undefined => Heap::NULL,
            JSValue::Bool(b) => heap.alloc(JSObject::from_bool(*b)),
            JSValue::Number(_n) => {
                let _ = crate::source::print_callstack(heap);
                todo!(); // TODO: Number object
            }
            JSValue::String(s) => heap.alloc(JSObject::from(s.clone())),
            JSValue::Ref(r) => *r,
        }
    }

    /// Javascript's `typeof`
    pub fn type_of(&self, heap: &Heap) -> &'static str {
        match self {
            JSValue::Undefined => "undefined",
            JSValue::String(_) => "string",
            JSValue::Number(_) => "number",
            JSValue::Bool(_) => "boolean",
            JSValue::Ref(r) => match heap.get(*r).is_callable() {
                true => "function",
                false => "object",
            },
        }
    }

    /// Abstract Equality Comparison, `==`:
    /// <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using_>
    pub fn loose_eq(&self, other: &JSValue, heap: &Heap) -> bool {
        let lval = if self == &JSValue::NULL {
            &JSValue::Undefined
        } else {
            self
        };
        let rval = if other == &JSValue::NULL {
            &JSValue::Undefined
        } else {
            other
        };
        match (lval, rval) {
            (JSValue::Undefined, JSValue::Undefined) => true,
            (JSValue::Undefined, _) | (_, JSValue::Undefined) => false,
            (JSValue::Number(_), JSValue::Number(_))
            | (JSValue::String(_), JSValue::String(_))
            | (JSValue::Bool(_), JSValue::Bool(_)) => self == other,
            (JSValue::Ref(lref), JSValue::Ref(rref)) if lref == rref => true,
            (JSValue::Ref(lref), JSValue::Ref(rref)) => match (
                heap.get(*lref).to_primitive(),
                heap.get(*rref).to_primitive(),
            ) {
                (Some(lval), Some(rval)) => lval == rval,
                _ => false,
            },
            _ => match (self.numberify(heap), other.numberify(heap)) {
                (Some(lnum), Some(rnum)) => lnum == rnum,
                _ => false,
            },
        }
    }

    /// Strict Equality, `===`
    /// <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#strict_equality_using>
    pub fn strict_eq(&self, other: &JSValue, _heap: &Heap) -> bool {
        self == other
    }

    pub fn numerically<F>(&self, other: &JSValue, heap: &Heap, op: F) -> JSValue
    where
        F: Fn(f64, f64) -> f64,
    {
        let val = match (self.numberify(heap), other.numberify(heap)) {
            (Some(lnum), Some(rnum)) => op(lnum, rnum),
            _ => f64::NAN,
        };
        JSValue::Number(val)
    }

    /// Addition operator:
    /// <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition>
    pub fn plus(&self, other: &JSValue, heap: &mut Heap) -> JSResult<JSValue> {
        if let (JSValue::String(lstr), JSValue::String(rstr)) = (self, other) {
            return Ok(JSValue::from(lstr.to_string() + rstr.as_str()));
        }
        if let (Some(lnum), Some(rnum)) = (self.numberify(heap), other.numberify(heap)) {
            return Ok(JSValue::from(lnum + rnum));
        }
        let lvalstr = self.stringify(heap)?;
        let rvalstr = other.stringify(heap)?;
        Ok(JSValue::from(lvalstr.to_string() + rvalstr.as_str()))
    }

    /// Subtraction operator:
    /// <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction>
    pub fn minus(&self, other: &JSValue, heap: &Heap) -> JSResult<JSValue> {
        Ok(JSValue::numerically(self, other, heap, |a, b| a - b))
    }

    pub fn compare<StrCmpFn: Fn(&str, &str) -> bool, NumCmpFn: Fn(f64, f64) -> bool>(
        &self,
        other: &JSValue,
        heap: &Heap,
        stringly: StrCmpFn,
        numberly: NumCmpFn,
    ) -> JSValue {
        // TODO: Abstract Relational Comparison
        if let (JSValue::String(lstr), JSValue::String(rstr)) = (self, other) {
            return JSValue::from(stringly(lstr.as_str(), rstr.as_str()));
        };
        let lnum = self.numberify(heap).unwrap_or(f64::NAN);
        let rnum = other.numberify(heap).unwrap_or(f64::NAN);
        JSValue::from(numberly(lnum, rnum))
    }
}

impl From<bool> for JSValue {
    fn from(b: bool) -> Self {
        JSValue::Bool(b)
    }
}

impl From<JSNumber> for JSValue {
    fn from(number: JSNumber) -> Self {
        JSValue::Number(number)
    }
}

impl From<i64> for JSValue {
    fn from(number: i64) -> Self {
        JSValue::Number(number as JSNumber)
    }
}

impl<S> From<S> for JSValue
where
    JSString: From<S>,
{
    fn from(s: S) -> Self {
        JSValue::String(JSString::from(s))
    }
}

impl From<JSRef> for JSValue {
    fn from(r: JSRef) -> Self {
        JSValue::Ref(r)
    }
}

impl TryFrom<&JSON> for JSValue {
    type Error = ();

    /// Constructs a pure value (without references), if possible.
    /// Excludes objects and arrays.
    fn try_from(json: &JSON) -> Result<JSValue, Self::Error> {
        let value = if json.is_null() {
            JSValue::NULL
        } else if let Some(b) = json.as_bool() {
            JSValue::from(b)
        } else if let Some(n) = json.as_f64() {
            JSValue::from(n)
        } else if let Some(s) = json.as_str() {
            JSValue::from(s)
        } else {
            return Err(());
        };
        Ok(value)
    }
}

#[test]
fn test_numberify() {
    let dummy = Heap::new();
    assert_eq!(JSValue::from("5").numberify(&dummy), Some(5.0));
}

#[test]
fn test_boolify() {
    let dummy = Heap::new();

    // true
    assert!(JSValue::from(true).boolify(&dummy));
    assert!(JSValue::from(1).boolify(&dummy));
    assert!(JSValue::from("0").boolify(&dummy));
    //assert!( JSValue::from(json!([])).boolify(&dummy) );

    // false
    assert!(!JSValue::from(false).boolify(&dummy));
    assert!(!JSValue::from(0).boolify(&dummy));
    assert!(!JSValue::from(f64::NAN).boolify(&dummy));
    assert!(!JSValue::from("").boolify(&dummy));
    assert!(!JSValue::NULL.boolify(&dummy));
}