-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTypes.cs
More file actions
1176 lines (1125 loc) · 45.3 KB
/
Copy pathTypes.cs
File metadata and controls
1176 lines (1125 loc) · 45.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Diagnostics;
using JavaScriptInterpreter;
namespace ES
{
public static class EcmaTypes
{
public static ES.Boolean Equal(LanguageType lval, LanguageType rval)
{
if (lval.GetType().Equals(rval.GetType()))
{
if (lval is ES.Undefined)
{
return new ES.Boolean(true);
}
if (lval is ES.Null)
{
return new ES.Boolean(true);
}
if (lval is ES.Number)
{
var x = lval as ES.Number;
var y = rval as ES.Number;
if (double.IsNaN(x.Value))
{
return new ES.Boolean(false);
}
if (double.IsNaN(y.Value))
{
return new ES.Boolean(false);
}
if (x.Value == y.Value)
{
return new ES.Boolean(true);
}
return new ES.Boolean(false);
}
if (lval is ES.String)
{
var x = lval as ES.String;
var y = rval as ES.String;
return new ES.Boolean(x.Value.Equals(y.Value));
}
if (lval is ES.Boolean)
{
var x = lval as ES.Boolean;
var y = rval as ES.Boolean;
return new ES.Boolean(x.Value == y.Value);
}
if (lval is ES.Object)
{
throw new NotImplementedException();
}
}
if (lval is ES.Null && rval is ES.Undefined) return new ES.Boolean(true);
if (lval is ES.Undefined && rval is ES.Null) return new ES.Boolean(true);
if (lval is ES.Number && rval is ES.String)
{
return EcmaTypes.Equal(lval, ES.Convert.ToNumber(rval));
}
if (lval is ES.String && rval is ES.Number)
{
return EcmaTypes.Equal(ES.Convert.ToNumber(lval), rval);
}
if (lval is ES.Boolean)
{
return EcmaTypes.Equal(ES.Convert.ToNumber(lval), rval);
}
if (rval is ES.Boolean)
{
return EcmaTypes.Equal(lval, ES.Convert.ToNumber(rval));
}
if ((lval is ES.String) || (lval is ES.Number) && rval is Object)
{
return EcmaTypes.Equal(lval, ES.Convert.ToPrimitive(rval, null));
}
if (lval is ES.Object && (rval is ES.String || rval is ES.Number))
{
return EcmaTypes.Equal(ES.Convert.ToPrimitive(lval, null), rval);
}
return new ES.Boolean(false);
}
public static ES.LanguageType Less(ES.LanguageType lval, ES.LanguageType rval, bool leftFirst)
{
ES.LanguageType x, y;
if (leftFirst == true)
{
x = ES.Convert.ToPrimitive(lval, "Number");
y = ES.Convert.ToPrimitive(rval, "Number");
}
else
{
y = ES.Convert.ToPrimitive(rval, "Number");
x = ES.Convert.ToPrimitive(lval, "Number");
}
if (!(x is ES.String && y is ES.String))
{
var nx = ES.Convert.ToNumber(x);
var ny = ES.Convert.ToNumber(y);
if (double.IsNaN(nx.Value)) return ES.Undefined.Value;
if (double.IsNaN(ny.Value)) return ES.Undefined.Value;
if (nx.Value == ny.Value) return new ES.Boolean(false);
return new ES.Boolean(nx.Value < ny.Value);
}
throw new NotImplementedException();
//var sx = ES.Convert.ToString(x);
//var sy = ES.Convert.ToString(y);
//return new ES.Boolean(sx.Value < sy.Value);
}
//public static bool SameValue(object x, object y)
//{
// if (!x.GetType().Equals(y.GetType())) return false; // QUESTION TODO TEST
// if (x.Equals(Undefined.Value)) return true;
// if (x.Equals(ES.Null.Value)) return true;
// if (x is ES.Number)
// {
// return ((Number)x).Value == ((Number)y).Value;
// }
// if (x is string)
// {
// return x.Equals(y);
// }
// if (IsBooleanType(x))
// {
// if ((x.Equals(ES.Boolean.True) && y.Equals(ES.Boolean.True))
// || (x.Equals(ES.Boolean.False) && y.Equals(ES.Boolean.False)))
// {
// return true;
// }
// else
// {
// return false;
// }
// }
// else
// {
// // TODO: отнсоятся к одному и то му же объекту
// return x.GetType().Equals(y.GetType());
// }
//}
//public static bool IsBooleanType(object value)
//{
// return value.Equals(ES.Boolean.True) || value.Equals(ES.Boolean.False);
//}
}
public abstract class Type { }
#region Language_types
public abstract class LanguageType : Type
{ }
public class Undefined : LanguageType
{
static Undefined value = null;
private Undefined() { }
public static Undefined Value
{
get
{
if (value == null)
{
value = new Undefined();
}
return value;
}
}
public override string ToString()
{
return "undefined";
}
}
public class Null : LanguageType
{
private static Null value = null;
private Null() { }
public static Null Value
{
get
{
if (value == null)
{
value = new Null();
}
return value;
}
}
}
public class Boolean : LanguageType
{
public bool Value;
public Boolean (bool value)
{
this.Value = value;
}
public override string ToString()
{
return Value.ToString();
}
}
public class Number : LanguageType
{
public double Value;
//private bool posInfinity;
//private bool negInfinity;
//private bool NaN;
// TODO: подумать над реализацией специальных значений
// положительная бесконечность, отриц. бесконечность,
// Not a Number (NaN)
public Number(double value)
{
this.Value = value;
}
public override string ToString()
{
return Value.ToString();
}
}
public class String : LanguageType
{
public string Value;
public String(string value)
{
this.Value = value;
}
public override string ToString()
{
return "'" + Value + "'";
}
}
public class Array : Object
{
public Array() : base()
{
InternalProperties["class"] = "Array";
InternalProperties["prototype"] = ES.Null.Value;
Put("length", new ES.Number(0), false);
}
public override bool DefineOwnProperty(string propertyName, PropertyDescriptor descriptor, bool needThrow)
{
if (!HasProperty(propertyName) && propertyName != "length")
{
var oldLength = ((ES.Number)Get("length")).Value;
var newLength = new ES.Number(oldLength + 1);
Put("length", newLength, false);
}
return base.DefineOwnProperty(propertyName, descriptor, needThrow);
}
public override string ToString()
{
string result = "[";
List<string> sorted_keys = namedProperties.Keys.ToList();
sorted_keys.Sort();
foreach (var key in sorted_keys)
{
if (key != "length")
{
result += Get(key) + ", ";
}
}
if (result.Length > 1)
{
result = result.Remove(result.Length - 2);
}
result += "]";
return result;
}
}
public class Object : LanguageType
{
// QUESTION m.b. Dicitipnary<string, PropertyDescriptroType> ??!??
protected Dictionary<string, PropertyDescriptor> namedProperties; // ассоциирует имя со значением и набором булевых атрибутов
public Dictionary<string, object> InternalProperties; // внутренние свойства
/* Внутренние свойства каждого объекта */
/*private EcmaType prototype; // Прототип данного объекта [Object/NULL]
private string __class__; // Классифицаия объектов
private bool extensible; // Если true, к объекту могут быть добавлены собственные свойства*/
/* ------------------------------------*/
public Object()
{
namedProperties = new Dictionary<string, PropertyDescriptor>();
namedProperties.Add("_proto_", new PropertyDescriptor(JSInterpreter.prototypeObject));
InternalProperties = new Dictionary<string, object>();
InternalProperties["extensible"] = true;
InternalProperties["class"] = "Object";
}
public override string ToString()
{
//string result = base.ToString();
string result = InternalProperties["class"] as string;
result += " {";
foreach (KeyValuePair<string, PropertyDescriptor> kvp in namedProperties)
{
if (!kvp.Key.StartsWith("_")) // внутренние свойства не печатаем
{
result += kvp.Key + ": " + kvp.Value + ", ";
}
}
if (namedProperties.Count > 1)
{
result = result.Remove(result.Length - 2);
}
result += "}";
return result;
}
/* Внутренние методы каждого объекта */
/// <summary>
/// Возвращает дескриптор именнованного свойства данного объекта
/// или undefined (в случае отсутствия)
/// </summary>
/// <param name="propertyName">Название свойства</param>
/// <returns>UNDEFINED/PROPERTY_DESCRIPTOR</returns>
public Type GetOwnProperty(string propertyName) // возвращает дескриптор свойства
{
if (!namedProperties.ContainsKey(propertyName))
return Undefined.Value;
PropertyDescriptor property, result;
property = namedProperties[propertyName];
result = new PropertyDescriptor();
if (PropertyDescriptor.IsDataDescriptor(property))
{
result.Attributes["value"] = property.Attributes["value"];
result.Attributes["writable"] = property.Attributes["writable"];
}
else
{
result.Attributes["get"] = property.Attributes["get"];
result.Attributes["set"] = property.Attributes["set"];
}
result.Attributes["enumerable"] = property.Attributes["enumerable"];
result.Attributes["configurable"] = property.Attributes["configurable"];
return result;
}
/// <summary>
/// Возвращает полностью заполненный дескриптор свойства данного объекта
/// или undefined (в случае отсутствия)
/// </summary>
/// <param name="propertyName">Название свойства</param>
/// <returns>Undefined/PropertyDescriptorType</returns>
public Type GetProperty(string propertyName)
{
var property = GetOwnProperty(propertyName);
if (!(property is Undefined))
{
return property;
}
else
{
//var prototype = InternalProperties["prototype"];
var prototype = namedProperties["_proto_"].Attributes["value"];
//if (property is Undefined)
//{
// return Undefined.Value;
//}
if (prototype.Equals(ES.Null.Value))
{
return Undefined.Value;
}
return ((ES.Object)prototype).GetProperty(propertyName);
}
}
// get - возвращает значение именнованного свойства
/// <summary>
/// Возвращает значение свойства
/// </summary>
/// <param name="propertyName">Имя свойства</param>
/// <returns></returns>
public LanguageType Get(string propertyName)
{
var desc = GetProperty(propertyName);
if (desc is Undefined) return Undefined.Value;
if (PropertyDescriptor.IsDataDescriptor(desc))
{
return (LanguageType)((PropertyDescriptor)desc).Attributes["value"];
}
else //if (EcmaScript.IsAcessorDescriptor(desc))
{
throw new NotImplementedException("Get for acessor descriptor");
//var getter = ((PropertyDescriptor)desc).Attributes["get"];
//if (getter is Undefined) return Undefined.Value;
//return null; // TODO: вызвать внутренний метод CALL для getter передавая О в качестве значения this и непередавая никаких аргументов
}
}
// canPut - Возвращает булево значение, означающее возможность выполнения операции Put с именем свойства propertyName.
/// <summary>
/// Проверяет можно ли выполнить операцию Put с аргументом propertyName
/// </summary>
/// <param name="propertyName">Имя свойства</param>
/// <returns>true/false</returns>
public bool CanPut(string propertyName)
{
var desc = GetOwnProperty(propertyName);
if (!(desc is Undefined))
{
if (PropertyDescriptor.IsAcessorDescriptor(desc))
{
if (((PropertyDescriptor)desc).Attributes["set"] is Undefined)
{
return false;
}
else
{
return true;
}
}
else
{
return (bool)((PropertyDescriptor)desc).Attributes["writable"];
}
}
var prototype = InternalProperties["prototype"];
if (prototype is ES.Null)
{
return (bool)InternalProperties["extensible"];
}
var inherited = ((ES.Object)prototype).GetProperty(propertyName);
if (inherited is Undefined)
{
return (bool)InternalProperties["extensible"];
}
if (PropertyDescriptor.IsAcessorDescriptor(inherited))
{
throw new NotImplementedException("Can put for acessor descriptor");
//if (((PropertyDescriptor)inherited).Attributes["set"] is Undefined)
//{
// return false;
//}
//else
//{
// return true;
//}
}
else
{
if ((bool)InternalProperties["extensible"] == false)
{
return false;
}
else
{
return (bool)((PropertyDescriptor)inherited).Attributes["writable"];
}
}
}
/// <summary>
/// Присваивает значение именнованному свойству
/// </summary>
/// <param name="propertyName">Имя свойства</param>
/// <param name="value">Значение</param>
/// <param name="needThrow">Обработка отказов</param>
/// <returns>Результат</returns>
public bool Put(string propertyName, LanguageType value, bool needThrow)
{
bool possibleToPut = CanPut(propertyName);
if (!possibleToPut)
{
if (needThrow)
{
throw new Exception("TypeError");
}
else
{
return possibleToPut;
}
}
var ownDesc = GetOwnProperty(propertyName);
if (PropertyDescriptor.IsDataDescriptor(ownDesc))
{
PropertyDescriptor valueDesc = new PropertyDescriptor();
valueDesc.Attributes["value"] = value;
return DefineOwnProperty(propertyName, valueDesc, needThrow);
}
var desc = GetProperty(propertyName);
if (PropertyDescriptor.IsAcessorDescriptor(desc))
{
throw new NotImplementedException("Put for acessor descrptor");
//var setter = ((PropertyDescriptor)desc).Attributes["set"];
//// QUESTION: почему setter не может быть undefined?
//// TODO 8.12.5 5 пункт
//return false; // NOT IMPLEMENTED!!
}
else
{
PropertyDescriptor newDesc = new PropertyDescriptor();
newDesc.Attributes["value"] = value;
newDesc.Attributes["writable"] = true;
newDesc.Attributes["enumerable"] = true;
newDesc.Attributes["configurable"] = true;
return DefineOwnProperty(propertyName, newDesc, needThrow);
}
}
/// <summary>
/// Есть ли у данного объекта свойство с таким именем
/// </summary>
/// <param name="propertyName">Имя свойства</param>
/// <returns></returns>
public bool HasProperty(string propertyName)
{
var desc = GetProperty(propertyName);
if (desc is Undefined) return false;
return true;
}
/// <summary>
/// Удаляет из объекта указанное именнованное свойство
/// </summary>
/// <param name="propertyName">Имя свойства</param>
/// <param name="needThrow">Обработка отказов</param>
/// <returns></returns>
public bool Delete(string propertyName, bool needThrow)
{
var desc = GetOwnProperty(propertyName);
if (desc is Undefined) return true;
if ((bool)((PropertyDescriptor)desc).Attributes["configurable"])
{
namedProperties.Remove(propertyName);
return true;
}
else
{
if (needThrow) throw new Exception("TypeError");
}
return false;
}
/// <summary>
/// </summary>
/// <param name="hint">Подсказка</param>
/// <returns>Значение по умолчанию для данного объекта</returns>
public object DefaultValue(string hint)
{
// TODO результат вызова 8.12.8
return null;
}
// TODO: 8.12.9
// defineOwnProperty - алгоритм содержит шаги, проверяющие различны поля Desc Property Descriptor
// на наличие определенных значений. Проверяемые таким образом поля не обязательно должны существовать в Desc.
// Если поле отсутствует, его значение считается false.
/// <summary>
/// Создает или изменяет именнованное собственное свойство так, чтобы оно имело состояние описанное
/// дискриптором свойства.
/// </summary>
/// <param name="propertyName">Имя свойства</param>
/// <param name="descriptor">Дескриптор свойства</param>
/// <param name="needThrow">Обработка отказов</param>
/// <returns></returns>
public virtual bool DefineOwnProperty(string propertyName, PropertyDescriptor descriptor, bool needThrow)
{
Type current = GetOwnProperty(propertyName);
bool extensible = (bool)InternalProperties["extensible"];
if (current is Undefined && extensible == false)
{
if (needThrow) throw new Exception("TypeError");
return false;
}
if (current is Undefined && extensible)
{
PropertyDescriptor newDescriptor;
if (PropertyDescriptor.IsGenericDescriptor(descriptor) || PropertyDescriptor.IsDataDescriptor(descriptor))
{
newDescriptor = new PropertyDescriptor();
var value = descriptor.Attributes["value"];
var writable = descriptor.Attributes["writable"];
if (value != null)
{
newDescriptor.Attributes["value"] = value;
}
else
{
newDescriptor.SetDefaultValue("value");
}
if (writable != null)
{
newDescriptor.Attributes["writable"] = writable;
}
else
{
newDescriptor.SetDefaultValue("writable");
}
}
else
{
throw new NotImplementedException("DefineOwnProperty for acessors descriptor");
//newDescriptor = new PropertyDescriptor(DescriptorType.ACCESSOR);
//PropertyDescriptor acessorDescriptor = new PropertyDescriptor(DescriptorType.ACCESSOR);
//var get = descriptor.Attributes["get"];
//var set = descriptor.Attributes["set"];
//if (get != null) newDescriptor.Attributes["get"] = get;
//if (set != null) newDescriptor.Attributes["set"] = set;
}
var enumerable = descriptor.Attributes["enumerable"];
var configurable = descriptor.Attributes["configurable"];
if (enumerable != null)
{
newDescriptor.Attributes["enumerable"] = enumerable;
}
else
{
newDescriptor.SetDefaultValue("enumerable");
}
if (configurable != null)
{
newDescriptor.Attributes["configurable"] = configurable;
}
else
{
newDescriptor.SetDefaultValue("configurable");
}
namedProperties.Add(propertyName, newDescriptor);
return true;
}
if (descriptor.Attributes.Count == 0)
{
return true;
}
// same - true, если все поля в descriptor также встречаются в current,
// и значение каждого поля в Desc оказывается таким же,
// что и у соответствующего поля в current (TODO? при сравнении с помощью алгоритма SameValue (9.12).)
// QUESTION TODO TEST! Срочно проверить будет ли работать
bool same = descriptor.Attributes.Cast<DictionaryEntry>()
.Union(((PropertyDescriptor)current).Attributes.Cast<DictionaryEntry>()).Count() == descriptor.Attributes.Count;
if (same) return true;
if ((bool)((PropertyDescriptor)current).Attributes["configurable"] == false)
{
if (descriptor.Attributes.ContainsKey("configurable")
&& (bool)descriptor.Attributes["configurable"])
{
if (needThrow) throw new Exception("TypeError");
return false;
}
// Булево отрицание = просто неравенство двух значений?
if (descriptor.Attributes.ContainsKey("enumerable")
&& ((PropertyDescriptor)current).Attributes["enumerable"] != descriptor.Attributes["enumerable"])
{
if (needThrow) throw new Exception("TypeError");
return false;
}
}
if (!PropertyDescriptor.IsGenericDescriptor(descriptor))
{
if (PropertyDescriptor.IsDataDescriptor(current) != PropertyDescriptor.IsDataDescriptor(descriptor))
{
if ((bool)((PropertyDescriptor)current).Attributes["configurable"] == false)
{
if (needThrow) throw new Exception("TypeError");
return false;
}
throw new NotImplementedException("Transfer from DataDescrpitor to Acessor descriptor");
//// QUESTION TEST
//PropertyDescriptor oldDescriptor = (PropertyDescriptor)GetProperty(propertyName);
//PropertyDescriptor newDescriptor;
//Delete(propertyName, needThrow); // QUESTION TEST
//if (PropertyDescriptor.IsDataDescriptor(current))
//{
// newDescriptor = new PropertyDescriptor(DescriptorType.ACCESSOR);
//}
//else
//{
// newDescriptor = new PropertyDescriptor(DescriptorType.DATA);
//}
//newDescriptor.Attributes["configurable"] = oldDescriptor.Attributes["configurable"];
//newDescriptor.Attributes["enumerable"] = oldDescriptor.Attributes["enumerable"];
}
else if (PropertyDescriptor.IsDataDescriptor(current) && PropertyDescriptor.IsDataDescriptor(descriptor))
{
if ((bool)((PropertyDescriptor)current).Attributes["configurable"] == false)
{
if ((bool)((PropertyDescriptor)current).Attributes["writable"] == false
&& (bool)((PropertyDescriptor)descriptor).Attributes["writable"] == true)
{
if (needThrow) throw new Exception("TypeError");
return false;
}
if ((bool)((PropertyDescriptor)current).Attributes["writable"] == false)
{
throw new NotImplementedException("TEST SAME VALUE!");
//// SameValue or Equal??
//// TODO !!!
//if (descriptor.Attributes["value"] != null
// && EcmaTypes.SameValue(descriptor.Attributes["value"], ((PropertyDescriptor)current).Attributes["value"]) == false)
//{
// if (needThrow) throw new Exception("TypeError");
// return false;
//}
}
}
}
else if (PropertyDescriptor.IsAcessorDescriptor(current) && PropertyDescriptor.IsAcessorDescriptor(descriptor))
{
throw new NotImplementedException("DefineOwnProperty for acessors descriptor");
//if ((bool)((PropertyDescriptor)current).Attributes["configurable"] == false)
//{
// if (descriptor.Attributes["set"] != null
// && EcmaTypes.SameValue(descriptor.Attributes["set"], ((PropertyDescriptor)current).Attributes["set"]) == false)
// {
// if (needThrow) throw new Exception("TypeError");
// return false;
// }
// if (descriptor.Attributes["get"] != null
// && EcmaTypes.SameValue(descriptor.Attributes["get"], ((PropertyDescriptor)current).Attributes["get"]) == false)
// {
// if (needThrow) throw new Exception("TypeError");
// return false;
// }
//}
}
}
PropertyDescriptor prop = namedProperties[propertyName];
foreach(string key in descriptor.Attributes.Keys)
{
prop.Attributes[key] = descriptor.Attributes[key];
}
return true;
}
/* ------------------------------------*/
}
#endregion
#region Specification_types
public abstract class SpecificationType : Type { }
public class PropertyDescriptor : SpecificationType
{
public Hashtable Attributes;
public PropertyDescriptor()
{
Attributes = new Hashtable();
}
public PropertyDescriptor(ES.Type value)
{
Attributes = new Hashtable();
Attributes["value"] = value;
Attributes["enumerable"] = false;
Attributes["configurable"] = true;
Attributes["writable"] = true;
}
public void SetDefaultValue(string attribute)
{
switch (attribute)
{
case "enumerable": // Если true, данное свойство можно перечислить с помощью for-in
{
Attributes["enumerable"] = false;
break;
}
case "configurable": // Если false, нельзя будет удалить данное свойство, измнеить его, сделав свойством-аксессором или изменить его атрибуты (кроме Value)
{
Attributes["configurable"] = false;
break;
}
case "value":
{
Attributes["value"] = Undefined.Value;
break;
}
case "writable":
{
Attributes["writable"] = false;
break;
}
case "get":
{
Attributes["get"] = Undefined.Value;
break;
}
case "set":
{
Attributes["set"] = Undefined.Value;
break;
}
default:
throw new Exception("Error: Have not a default value for attribute: " + attribute);
}
}
public override string ToString()
{
object value = Attributes["value"];
if (Attributes["value"] != null)
{
if (value is ES.Object && !(value is ES.Array))
{
return base.ToString();
}
else
{
return value.ToString();
}
}
return base.ToString();
}
// ------------------------ Работа с дексрипторами --------------------------------//
public static bool IsDataDescriptor(Type desc)
{
if (desc is Undefined)
{
return false;
}
PropertyDescriptor propDesc = (PropertyDescriptor)desc;
if (propDesc.Attributes["value"] == null && propDesc.Attributes["writable"] == null)
{
return false;
}
return true;
}
public static bool IsAcessorDescriptor(Type desc)
{
if (desc is Undefined)
{
return false;
}
PropertyDescriptor propDesc = (PropertyDescriptor)desc;
if (propDesc.Attributes["get"] == null && propDesc.Attributes["set"] == null)
{
return false;
}
return true;
}
public static bool IsGenericDescriptor(Type desc)
{
if (desc is Undefined)
{
return false;
}
PropertyDescriptor propDesc = (PropertyDescriptor)desc;
if (IsDataDescriptor(propDesc) == false
&& IsAcessorDescriptor(propDesc) == false)
{
return true;
}
return false;
}
}
public class Reference : SpecificationType
{
private Type baseValue; // база Undefined, BooleanType, StringType, NumberType, или EnvironmentRecord
private string referenceName; // имя ссылки
private bool strictReference; // строгая ссылка
public Reference(Type baseValue, string referenceName, bool strictReference)
{
this.baseValue = baseValue;
this.referenceName = referenceName;
this.strictReference = strictReference;
}
public override string ToString()
{
var value = baseValue as LanguageType;
if (value != null)
{
if (value is ES.Object)
{
var baseValueObj = baseValue as ES.Object;
return baseValueObj.Get(referenceName).ToString();
}
return ES.Convert.ToPrimitive(value, null).ToString();
}
else
{
var objectEnvironment = baseValue as ObjectEnviroment;
if (objectEnvironment != null)
{
return objectEnvironment.BindingObject.Get(referenceName).ToString();
}
return base.ToString();
}
}
//public object BaseValue { get; set; }
//public string ReferenceName { get; set; }
//public bool StrictReference { get; set; }
// ------------------------ Работа со ссылками --------------------------------//
public Type GetBase()
{
return baseValue;
}
public string GetReferenceName()
{
return referenceName;
}
public bool IsStrictReference()
{
return strictReference;
}
public bool HasPrimitiveBase()
{
return baseValue is ES.Boolean || baseValue is ES.String || baseValue is ES.Number;
}
public bool IsPropertyReference()
{
return this.GetBase() is ES.Object || this.HasPrimitiveBase();
}
public bool IsUnresolvableReference()
{
return this.GetBase() is Undefined;
}
}
public abstract class Binding : SpecificationType
{
public LanguageType Value;
public Binding(LanguageType value)
{
this.Value = value;
}
}
public class MutableBinding : Binding
{
protected bool canBeDeleted;
public MutableBinding(LanguageType value, bool canBeDeleted)
: base(value)
{
this.canBeDeleted = canBeDeleted;
}
public bool CanBeDeleted { get; set; }
}
public class ImmutableBinding : Binding
{
protected bool initialized;
public ImmutableBinding(LanguageType value)
: base(value)
{
this.initialized = false;
}
public bool Initialized { get; set; }
}
public abstract class EnvironmentRecord : SpecificationType
{
/// <summary>
/// Ссылка на внешнее окружение
/// </summary>
public EnvironmentRecord Outer;
/// <summary>
/// Определяет, имеет ли запись окружения привязку к индентификатору
/// </summary>
/// <param name="name">Текст индентификатора</param>
/// <returns></returns>
public abstract bool HasBinding(string name);
/// <summary>
/// Создает в записи окружения новую изменяемую привязку.
/// </summary>
/// <param name="name">Привязанное имя</param>
/// <param name="delete">Привязка в последствии может быть удалена</param>
/// <returns></returns>
public abstract void CreateMutableBinding(string name, bool delete);
/// <summary>
/// Присваивает значение уже существующей в записи окружения изменяемой привязки
/// </summary>
/// <param name="name">Имя</param>
/// <param name="value">Значение</param>
/// <param name="s">Ссылка в сторогом режиме</param>
public abstract void SetMutableBinding(string name, LanguageType value, bool strict);
/// <summary>
/// Возврщает из записи окружения значение уже существующей привязки.
/// </summary>
/// <param name="name">Имя привязки</param>
/// <param name="strict">Ссылка в сторогом режиме</param>
public abstract LanguageType GetBindingValue(string name, bool strict);
/// <summary>
/// Удаляет привязку из записи окружения
/// </summary>
/// <param name="name">Имя</param>
public abstract bool DeleteBinding(string name);
/// <summary>
/// Возвращает значение, которое будет использоваться в качестве значения this при вызове
/// объектов функции, получаемых в качестве значений привязки из этой записи окружения
/// </summary>
public abstract object ImplicitThisValue();
}