-
-
Notifications
You must be signed in to change notification settings - Fork 601
Expand file tree
/
Copy pathmod.rs
More file actions
1940 lines (1716 loc) · 72.3 KB
/
mod.rs
File metadata and controls
1940 lines (1716 loc) · 72.3 KB
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Boa's implementation of ECMAScript's `Date` object.
//!
//! More information:
//! - [ECMAScript reference][spec]
//! - [MDN documentation][mdn]
//!
//! [spec]: https://tc39.es/ecma262/#sec-date-objects
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
use crate::{
Context, JsArgs, JsData, JsResult, JsString,
builtins::{
BuiltInBuilder, BuiltInConstructor, BuiltInObject, IntrinsicObject,
date::utils::{
MS_PER_MINUTE, date_from_time, date_string, day, hour_from_time, local_time, make_date,
make_day, make_full_year, make_time, min_from_time, month_from_time, ms_from_time,
pad_five, pad_four, pad_six, pad_three, pad_two, parse_date, sec_from_time, time_clip,
time_string, time_within_day, time_zone_string, to_date_string_t, utc_t, week_day,
year_from_time,
},
},
context::intrinsics::{Intrinsics, StandardConstructor, StandardConstructors},
error::JsNativeError,
js_error, js_string,
object::{JsObject, internal_methods::get_prototype_from_constructor},
property::Attribute,
realm::Realm,
string::StaticJsStrings,
symbol::JsSymbol,
value::{JsValue, PreferredType},
};
use boa_gc::{Finalize, Trace};
use boa_macros::js_str;
pub(crate) mod utils;
#[cfg(test)]
mod tests;
/// The internal representation of a `Date` object.
#[derive(Debug, Copy, Clone, Trace, Finalize, JsData)]
#[boa_gc(empty_trace)]
pub struct Date(f64);
impl Date {
/// Creates a new `Date`.
pub(crate) const fn new(dt: f64) -> Self {
Self(dt)
}
/// Creates a new `Date` from the current UTC time of the host.
pub(crate) fn utc_now(context: &mut Context) -> Self {
Self(context.clock().system_time_millis() as f64)
}
}
impl IntrinsicObject for Date {
fn init(realm: &Realm) {
let to_utc_string = BuiltInBuilder::callable(realm, Self::to_utc_string)
.name(js_string!("toUTCString"))
.length(0)
.build();
let to_primitive = BuiltInBuilder::callable(realm, Self::to_primitive)
.name(js_string!("[Symbol.toPrimitive]"))
.length(1)
.build();
let builder = BuiltInBuilder::from_standard_constructor::<Self>(realm)
.static_method(Self::now, js_string!("now"), 0)
.static_method(Self::parse, js_string!("parse"), 1)
.static_method(Self::utc, js_string!("UTC"), 7)
.method(Self::get_date::<true>, js_string!("getDate"), 0)
.method(Self::get_day::<true>, js_string!("getDay"), 0)
.method(Self::get_full_year::<true>, js_string!("getFullYear"), 0)
.method(Self::get_hours::<true>, js_string!("getHours"), 0)
.method(
Self::get_milliseconds::<true>,
js_string!("getMilliseconds"),
0,
)
.method(Self::get_minutes::<true>, js_string!("getMinutes"), 0)
.method(Self::get_month::<true>, js_string!("getMonth"), 0)
.method(Self::get_seconds::<true>, js_string!("getSeconds"), 0)
.method(Self::get_time, js_string!("getTime"), 0)
.method(
Self::get_timezone_offset,
js_string!("getTimezoneOffset"),
0,
)
.method(Self::get_date::<false>, js_string!("getUTCDate"), 0)
.method(Self::get_day::<false>, js_string!("getUTCDay"), 0)
.method(
Self::get_full_year::<false>,
js_string!("getUTCFullYear"),
0,
)
.method(Self::get_hours::<false>, js_string!("getUTCHours"), 0)
.method(
Self::get_milliseconds::<false>,
js_string!("getUTCMilliseconds"),
0,
)
.method(Self::get_minutes::<false>, js_string!("getUTCMinutes"), 0)
.method(Self::get_month::<false>, js_string!("getUTCMonth"), 0)
.method(Self::get_seconds::<false>, js_string!("getUTCSeconds"), 0)
.method(Self::get_year, js_string!("getYear"), 0)
.method(Self::set_date::<true>, js_string!("setDate"), 1)
.method(Self::set_full_year::<true>, js_string!("setFullYear"), 3)
.method(Self::set_hours::<true>, js_string!("setHours"), 4)
.method(
Self::set_milliseconds::<true>,
js_string!("setMilliseconds"),
1,
)
.method(Self::set_minutes::<true>, js_string!("setMinutes"), 3)
.method(Self::set_month::<true>, js_string!("setMonth"), 2)
.method(Self::set_seconds::<true>, js_string!("setSeconds"), 2)
.method(Self::set_time, js_string!("setTime"), 1)
.method(Self::set_date::<false>, js_string!("setUTCDate"), 1)
.method(
Self::set_full_year::<false>,
js_string!("setUTCFullYear"),
3,
)
.method(Self::set_hours::<false>, js_string!("setUTCHours"), 4)
.method(
Self::set_milliseconds::<false>,
js_string!("setUTCMilliseconds"),
1,
)
.method(Self::set_minutes::<false>, js_string!("setUTCMinutes"), 3)
.method(Self::set_month::<false>, js_string!("setUTCMonth"), 2)
.method(Self::set_seconds::<false>, js_string!("setUTCSeconds"), 2)
.method(Self::set_year, js_string!("setYear"), 1)
.method(Self::to_date_string, js_string!("toDateString"), 0)
.method(Self::to_iso_string, js_string!("toISOString"), 0)
.method(Self::to_json, js_string!("toJSON"), 1)
.method(
Self::to_locale_date_string,
js_string!("toLocaleDateString"),
0,
)
.method(Self::to_locale_string, js_string!("toLocaleString"), 0)
.method(
Self::to_locale_time_string,
js_string!("toLocaleTimeString"),
0,
)
.method(Self::to_string, js_string!("toString"), 0)
.method(Self::to_time_string, js_string!("toTimeString"), 0)
.method(Self::value_of, js_string!("valueOf"), 0)
.property(
js_string!("toGMTString"),
to_utc_string.clone(),
Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
)
.property(
js_string!("toUTCString"),
to_utc_string,
Attribute::WRITABLE | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
)
.property(
JsSymbol::to_primitive(),
to_primitive,
Attribute::READONLY | Attribute::NON_ENUMERABLE | Attribute::CONFIGURABLE,
);
#[cfg(feature = "temporal")]
let builder = builder.method(
Self::to_temporal_instant,
js_string!("toTemporalInstant"),
0,
);
builder.build();
}
fn get(intrinsics: &Intrinsics) -> JsObject {
Self::STANDARD_CONSTRUCTOR(intrinsics.constructors()).constructor()
}
}
impl BuiltInObject for Date {
const NAME: JsString = StaticJsStrings::DATE;
}
impl BuiltInConstructor for Date {
const CONSTRUCTOR_ARGUMENTS: usize = 7;
const PROTOTYPE_STORAGE_SLOTS: usize = 48;
const CONSTRUCTOR_STORAGE_SLOTS: usize = 3;
const STANDARD_CONSTRUCTOR: fn(&StandardConstructors) -> &StandardConstructor =
StandardConstructors::date;
/// [`Date ( ...values )`][spec]
///
/// - When called as a function, returns a string displaying the current time in the UTC timezone.
/// - When called as a constructor, it returns a new `Date` object from the provided arguments.
/// The [MDN documentation][mdn] has a more extensive explanation on the usages and return
/// values for all possible arguments.
///
/// [spec]: https://tc39.es/ecma262/#sec-date-constructor
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
fn constructor(
new_target: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. If NewTarget is undefined, then
if new_target.is_undefined() {
// a. Let now be the time value (UTC) identifying the current time.
let now = context.clock().system_time_millis();
// b. Return ToDateString(now).
return Ok(JsValue::from(to_date_string_t(
now as f64,
context.host_hooks().as_ref(),
)));
}
// 2. Let numberOfArgs be the number of elements in values.
let dv = match args {
// 3. If numberOfArgs = 0, then
[] => {
// a. Let dv be the time value (UTC) identifying the current time.
Self::utc_now(context)
}
// 4. Else if numberOfArgs = 1, then
// a. Let value be values[0].
[value] => {
// b. If value is an Object and value has a [[DateValue]] internal slot, then
let object = value.as_object();
let tv =
if let Some(date) = object.as_ref().and_then(JsObject::downcast_ref::<Self>) {
// i. Let tv be value.[[DateValue]].
date.0
}
// c. Else,
else {
// i. Let v be ? ToPrimitive(value).
let v = value.to_primitive(context, PreferredType::Default)?;
// ii. If v is a String, then
if let Some(v) = v.as_string() {
// 1. Assert: The next step never returns an abrupt completion because v is a String.
// 2. Let tv be the result of parsing v as a date, in exactly the same manner as for the parse method (21.4.3.2).
let tv = parse_date(&v, context.host_hooks().as_ref());
if let Some(tv) = tv {
tv as f64
} else {
f64::NAN
}
}
// iii. Else,
else {
// 1. Let tv be ? ToNumber(v).
v.to_number(context)?
}
};
// d. Let dv be TimeClip(tv).
Self(time_clip(tv))
}
// 5. Else,
_ => {
// Separating this into its own function to simplify the logic.
//let dt = Self::construct_date(args, context)?
// .and_then(|dt| context.host_hooks().local_from_naive_local(dt).earliest());
//Self(dt.map(|dt| dt.timestamp_millis()))
// a. Assert: numberOfArgs ≥ 2.
// b. Let y be ? ToNumber(values[0]).
let y = args.get_or_undefined(0).to_number(context)?;
// c. Let m be ? ToNumber(values[1]).
let m = args.get_or_undefined(1).to_number(context)?;
// d. If numberOfArgs > 2, let dt be ? ToNumber(values[2]); else let dt be 1𝔽.
let dt = args.get(2).map_or(Ok(1.0), |n| n.to_number(context))?;
// e. If numberOfArgs > 3, let h be ? ToNumber(values[3]); else let h be +0𝔽.
let h = args.get(3).map_or(Ok(0.0), |n| n.to_number(context))?;
// f. If numberOfArgs > 4, let min be ? ToNumber(values[4]); else let min be +0𝔽.
let min = args.get(4).map_or(Ok(0.0), |n| n.to_number(context))?;
// g. If numberOfArgs > 5, let s be ? ToNumber(values[5]); else let s be +0𝔽.
let s = args.get(5).map_or(Ok(0.0), |n| n.to_number(context))?;
// h. If numberOfArgs > 6, let milli be ? ToNumber(values[6]); else let milli be +0𝔽.
let milli = args.get(6).map_or(Ok(0.0), |n| n.to_number(context))?;
// i. Let yr be MakeFullYear(y).
let yr = make_full_year(y);
// j. Let finalDate be MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli)).
let final_date = make_date(make_day(yr, m, dt), make_time(h, min, s, milli));
// k. Let dv be TimeClip(UTC(finalDate)).
Self(time_clip(utc_t(final_date, context.host_hooks().as_ref())))
}
};
// 6. Let O be ? OrdinaryCreateFromConstructor(NewTarget, "%Date.prototype%", « [[DateValue]] »).
let prototype =
get_prototype_from_constructor(new_target, StandardConstructors::date, context)?;
// 7. Set O.[[DateValue]] to dv.
let obj =
JsObject::from_proto_and_data_with_shared_shape(context.root_shape(), prototype, dv);
// 8. Return O.
Ok(obj.into())
}
}
impl Date {
/// `Date.now()`
///
/// The static `Date.now()` method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.now
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
#[allow(clippy::unnecessary_wraps)]
pub(crate) fn now(_: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
Ok(JsValue::new(context.clock().system_time_millis()))
}
/// `Date.parse()`
///
/// The `Date.parse()` method parses a string representation of a date, and returns the number of milliseconds since
/// January 1, 1970, 00:00:00 UTC or `NaN` if the string is unrecognized or, in some cases, contains illegal date
/// values.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.parse
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
pub(crate) fn parse(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
let date = args.get_or_undefined(0).to_string(context)?;
Ok(parse_date(&date, context.host_hooks().as_ref())
.map_or(JsValue::from(f64::NAN), JsValue::from))
}
/// `Date.UTC()`
///
/// The `Date.UTC()` method accepts parameters similar to the `Date` constructor, but treats them as UTC.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.utc
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC
pub(crate) fn utc(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
// 1. Let y be ? ToNumber(year).
let y = args.get_or_undefined(0).to_number(context)?;
// 2. If month is present, let m be ? ToNumber(month); else let m be +0𝔽.
let m = args
.get(1)
.map_or(Ok(0f64), |value| value.to_number(context))?;
// 3. If date is present, let dt be ? ToNumber(date); else let dt be 1𝔽.
let dt = args
.get(2)
.map_or(Ok(1f64), |value| value.to_number(context))?;
// 4. If hours is present, let h be ? ToNumber(hours); else let h be +0𝔽.
let h = args
.get(3)
.map_or(Ok(0f64), |value| value.to_number(context))?;
// 5. If minutes is present, let min be ? ToNumber(minutes); else let min be +0𝔽.
let min = args
.get(4)
.map_or(Ok(0f64), |value| value.to_number(context))?;
// 6. If seconds is present, let s be ? ToNumber(seconds); else let s be +0𝔽.
let s = args
.get(5)
.map_or(Ok(0f64), |value| value.to_number(context))?;
// 7. If ms is present, let milli be ? ToNumber(ms); else let milli be +0𝔽.
let milli = args
.get(6)
.map_or(Ok(0f64), |value| value.to_number(context))?;
// 8. Let yr be MakeFullYear(y).
let yr = make_full_year(y);
// 9. Return TimeClip(MakeDate(MakeDay(yr, m, dt), MakeTime(h, min, s, milli))).
Ok(JsValue::from(time_clip(make_date(
make_day(yr, m, dt),
make_time(h, min, s, milli),
))))
}
/// [`Date.prototype.getDate ( )`][local] and
/// [`Date.prototype.getUTCDate ( )`][utc].
///
/// The `getDate()` method returns the day of the month for the specified date.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.getdate
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutcdate
pub(crate) fn get_date<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::new(f64::NAN));
}
if LOCAL {
// 5. Return DateFromTime(LocalTime(t)).
Ok(JsValue::from(date_from_time(local_time(
t,
context.host_hooks().as_ref(),
))))
} else {
// 5. Return DateFromTime(t).
Ok(JsValue::from(date_from_time(t)))
}
}
/// [`Date.prototype.getDay ( )`][local] and
/// [`Date.prototype.getUTCDay ( )`][utc].
///
/// The `getDay()` method returns the day of the week for the specified date, where 0 represents
/// Sunday.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.getday
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutcday
pub(crate) fn get_day<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
}
if LOCAL {
// 5. Return WeekDay(LocalTime(t)).
Ok(JsValue::from(week_day(local_time(
t,
context.host_hooks().as_ref(),
))))
} else {
// 5. Return WeekDay(t).
Ok(JsValue::from(week_day(t)))
}
}
/// [`Date.prototype.getYear()`][spec].
///
/// The `getYear()` method returns the year in the specified date according to local time.
/// Because `getYear()` does not return full years ("year 2000 problem"), it is no longer used
/// and has been replaced by the `getFullYear()` method.
///
/// More information:
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.getyear
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getYear
pub(crate) fn get_year(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
}
// 5. Return YearFromTime(LocalTime(t)) - 1900𝔽.
Ok(JsValue::from(
year_from_time(local_time(t, context.host_hooks().as_ref())) - 1900,
))
}
/// [`Date.prototype.getFullYear ( )`][local] and
/// [`Date.prototype.getUTCFullYear ( )`][utc].
///
/// The `getFullYear()` method returns the year of the specified date.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.getfullyear
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutcfullyear
pub(crate) fn get_full_year<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
}
if LOCAL {
// 5. Return YearFromTime(LocalTime(t)).
Ok(JsValue::from(year_from_time(local_time(
t,
context.host_hooks().as_ref(),
))))
} else {
// 5. Return YearFromTime(t).
Ok(JsValue::from(year_from_time(t)))
}
}
/// [`Date.prototype.getHours ( )`][local] and
/// [`Date.prototype.getUTCHours ( )`][utc].
///
/// The `getHours()` method returns the hour for the specified date.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.gethours
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutchours
pub(crate) fn get_hours<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
}
if LOCAL {
// 5. Return HourFromTime(LocalTime(t)).
Ok(JsValue::from(hour_from_time(local_time(
t,
context.host_hooks().as_ref(),
))))
} else {
// 5. Return HourFromTime(t).
Ok(JsValue::from(hour_from_time(t)))
}
}
/// [`Date.prototype.getMilliseconds ( )`][local] and
/// [`Date.prototype.getUTCMilliseconds ( )`][utc].
///
/// The `getMilliseconds()` method returns the milliseconds in the specified date.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.getmilliseconds
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutcmilliseconds
pub(crate) fn get_milliseconds<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
}
if LOCAL {
// 5. Return msFromTime(LocalTime(t)).
Ok(JsValue::from(ms_from_time(local_time(
t,
context.host_hooks().as_ref(),
))))
} else {
// 5. Return msFromTime(t).
Ok(JsValue::from(ms_from_time(t)))
}
}
/// [`Date.prototype.getMinutes ( )`][local] and
/// [`Date.prototype.getUTCMinutes ( )`][utc].
///
/// The `getMinutes()` method returns the minutes in the specified date.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.getminutes
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutcminutes
pub(crate) fn get_minutes<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
}
if LOCAL {
// 5. Return MinFromTime(LocalTime(t)).
Ok(JsValue::from(min_from_time(local_time(
t,
context.host_hooks().as_ref(),
))))
} else {
// 5. Return MinFromTime(t).
Ok(JsValue::from(min_from_time(t)))
}
}
/// [`Date.prototype.getMonth ( )`][local] and
/// [`Date.prototype.getUTCMonth ( )`][utc].
///
/// The `getMonth()` method returns the month in the specified date, as a zero-based value
/// (where zero indicates the first month of the year).
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.getmonth
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutcmonth
pub(crate) fn get_month<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
}
if LOCAL {
// 5. Return MonthFromTime(LocalTime(t)).
Ok(JsValue::from(month_from_time(local_time(
t,
context.host_hooks().as_ref(),
))))
} else {
// 5. Return MonthFromTime(t).
Ok(JsValue::from(month_from_time(t)))
}
}
/// [`Date.prototype.getSeconds ( )`][local] and
/// [`Date.prototype.getUTCSeconds ( )`][utc].
///
/// The `getSeconds()` method returns the seconds in the specified date.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.getseconds
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.getutcseconds
pub(crate) fn get_seconds<const LOCAL: bool>(
this: &JsValue,
_args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
}
if LOCAL {
// 5. Return SecFromTime(LocalTime(t)).
Ok(JsValue::from(sec_from_time(local_time(
t,
context.host_hooks().as_ref(),
))))
} else {
// 5. Return SecFromTime(t).
Ok(JsValue::from(sec_from_time(t)))
}
}
/// `Date.prototype.getTime()`.
///
/// The `getTime()` method returns the number of milliseconds since the Unix Epoch.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.gettime
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
pub(crate) fn get_time(
this: &JsValue,
_args: &[JsValue],
_context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Return dateObject.[[DateValue]].
Ok(this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0
.into())
}
/// `Date.prototype.getTimeZoneOffset()`.
///
/// The `getTimezoneOffset()` method returns the time zone difference, in minutes, from current locale (host system
/// settings) to UTC.
///
/// More information:
/// - [ECMAScript reference][spec]
/// - [MDN documentation][mdn]
///
/// [spec]: https://tc39.es/ecma262/#sec-date.prototype.gettimezoneoffset
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset
pub(crate) fn get_timezone_offset(
this: &JsValue,
_: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
// 3. Let t be dateObject.[[DateValue]].
let t = this
.as_object()
.and_then(|obj| obj.downcast_ref::<Date>().as_deref().copied())
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?
.0;
// 4. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
}
// 5. Return (t - LocalTime(t)) / msPerMinute.
Ok(JsValue::from(
(t - local_time(t, context.host_hooks().as_ref())) / MS_PER_MINUTE,
))
}
/// [`Date.prototype.setDate ( date )`][local] and
/// [`Date.prototype.setUTCDate ( date )`][utc].
///
/// The `setDate()` method sets the day of the `Date` object relative to the beginning of the
/// currently set month.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.setdate
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.setutcdate
pub(crate) fn set_date<const LOCAL: bool>(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
let object = this.as_object();
let date = object
.as_ref()
.and_then(JsObject::downcast_ref::<Date>)
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?;
// 3. Let t be dateObject.[[DateValue]].
let mut t = date.0;
// NOTE (nekevss): `downcast_ref` is used and then dropped for a short lived borrow.
// ToNumber() may call userland code which can modify the underlying date
// which will cause a panic. In order to avoid this, we drop the borrow,
// here and only `downcast_mut` when date will be modified.
drop(date);
// 4. Let dt be ? ToNumber(date).
let dt = args.get_or_undefined(0).to_number(context)?;
// 5. If t is NaN, return NaN.
if t.is_nan() {
return Ok(JsValue::from(f64::NAN));
}
if LOCAL {
// 6. Set t to LocalTime(t).
t = local_time(t, context.host_hooks().as_ref());
}
// 7. Let newDate be MakeDate(MakeDay(YearFromTime(t), MonthFromTime(t), dt), TimeWithinDay(t)).
let new_date = make_date(
make_day(year_from_time(t).into(), month_from_time(t).into(), dt),
time_within_day(t),
);
let u = if LOCAL {
// 8. Let u be TimeClip(UTC(newDate)).
time_clip(utc_t(new_date, context.host_hooks().as_ref()))
} else {
// 8. Let v be TimeClip(newDate).
time_clip(new_date)
};
let object = this.as_object();
let mut date_mut = object
.as_ref()
.and_then(JsObject::downcast_mut::<Date>)
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?;
// 9. Set dateObject.[[DateValue]] to u.
date_mut.0 = u;
// 10. Return u.
Ok(JsValue::from(u))
}
/// [`Date.prototype.setFullYear ( year [ , month [ , date ] ] )`][local] and
/// [Date.prototype.setUTCFullYear ( year [ , month [ , date ] ] )][utc].
///
/// The `setFullYear()` method sets the full year for a specified date and returns the new
/// timestamp.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.setfullyear
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.setutcfullyear
pub(crate) fn set_full_year<const LOCAL: bool>(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
let object = this.as_object();
let date = object
.as_ref()
.and_then(JsObject::downcast_ref::<Date>)
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?;
// 3. Let t be dateObject.[[DateValue]].
let t = date.0;
// NOTE (nekevss): `downcast_ref` is used and then dropped for a short lived borrow.
// ToNumber() may call userland code which can modify the underlying date
// which will cause a panic. In order to avoid this, we drop the borrow,
// here and only `downcast_mut` when date will be modified.
drop(date);
let t = if LOCAL {
// 5. If t is NaN, set t to +0𝔽; otherwise, set t to LocalTime(t).
if t.is_nan() {
0.0
} else {
local_time(t, context.host_hooks().as_ref())
}
} else {
// 4. If t is NaN, set t to +0𝔽.
if t.is_nan() { 0.0 } else { t }
};
// 4. Let y be ? ToNumber(year).
let y = args.get_or_undefined(0).to_number(context)?;
// 6. If month is not present, let m be MonthFromTime(t); otherwise, let m be ? ToNumber(month).
let m = if let Some(month) = args.get(1) {
month.to_number(context)?
} else {
month_from_time(t).into()
};
// 7. If date is not present, let dt be DateFromTime(t); otherwise, let dt be ? ToNumber(date).
let dt = if let Some(date) = args.get(2) {
date.to_number(context)?
} else {
date_from_time(t).into()
};
// 8. Let newDate be MakeDate(MakeDay(y, m, dt), TimeWithinDay(t)).
let new_date = make_date(make_day(y, m, dt), time_within_day(t));
let u = if LOCAL {
// 9. Let u be TimeClip(UTC(newDate)).
time_clip(utc_t(new_date, context.host_hooks().as_ref()))
} else {
// 9. Let u be TimeClip(newDate).
time_clip(new_date)
};
let object = this.as_object();
let mut date_mut = object
.as_ref()
.and_then(JsObject::downcast_mut::<Date>)
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?;
// 10. Set dateObject.[[DateValue]] to u.
date_mut.0 = u;
// 11. Return u.
Ok(JsValue::from(u))
}
/// [`Date.prototype.setHours ( hour [ , min [ , sec [ , ms ] ] ] )`][local] and
/// [`Date.prototype.setUTCHours ( hour [ , min [ , sec [ , ms ] ] ] )`][utc].
///
/// The `setHours()` method sets the hours for a specified date, and returns the number
/// of milliseconds since January 1, 1970 00:00:00 UTC until the time represented by the
/// updated `Date` instance.
///
/// [local]: https://tc39.es/ecma262/#sec-date.prototype.sethours
/// [utc]: https://tc39.es/ecma262/#sec-date.prototype.setutchours
#[allow(clippy::many_single_char_names)]
pub(crate) fn set_hours<const LOCAL: bool>(
this: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
// 1. Let dateObject be the this value.
// 2. Perform ? RequireInternalSlot(dateObject, [[DateValue]]).
let object = this.as_object();
let date = object
.as_ref()
.and_then(JsObject::downcast_ref::<Date>)
.ok_or_else(|| JsNativeError::typ().with_message("'this' is not a Date"))?;
// 3. Let t be dateObject.[[DateValue]].
let mut t = date.0;
// NOTE (nekevss): `downcast_ref` is used and then dropped for a short lived borrow.
// ToNumber() may call userland code which can modify the underlying date
// which will cause a panic. In order to avoid this, we drop the borrow,
// here and only `downcast_mut` when date will be modified.
drop(date);
// 4. Let h be ? ToNumber(hour).
let h = args.get_or_undefined(0).to_number(context)?;
// 5. If min is present, let m be ? ToNumber(min).
let m = args.get(1).map(|v| v.to_number(context)).transpose()?;