/
script_object.cpp
3175 lines (2775 loc) · 90.7 KB
/
script_object.cpp
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
#include "stdafx.h" // pre-compiled headers
#include "defines.h"
#include "globaldata.h"
#include "script.h"
#include "application.h"
#include "script_object.h"
#include "script_func_impl.h"
#include "input_object.h"
#include <errno.h> // For ERANGE.
#include <initializer_list>
//
// CallMethod - Invoke a method with no parameters, discarding the result.
//
ResultType CallMethod(IObject *aInvokee, IObject *aThis, LPTSTR aMethodName
, ExprTokenType *aParamValue, int aParamCount, __int64 *aRetVal // For event handlers.
, int aExtraFlags) // For Object.__Delete().
{
ResultToken result_token;
TCHAR result_buf[MAX_NUMBER_SIZE];
result_token.InitResult(result_buf);
ExprTokenType this_token(aThis);
ExprTokenType **param = (ExprTokenType **)_alloca(aParamCount * sizeof(ExprTokenType *));
for (int i = 0; i < aParamCount; ++i)
param[i] = aParamValue + i;
ResultType result = aInvokee->Invoke(result_token, IT_CALL | aExtraFlags, aMethodName, this_token, param, aParamCount);
// Exceptions are thrown by Invoke for too few/many parameters, but not for non-existent method.
// Check for that here, with the exception that objects are permitted to lack a __Delete method.
if (result == INVOKE_NOT_HANDLED && !(aExtraFlags & IF_BYPASS_METAFUNC))
result = ResultToken().UnknownMemberError(this_token, IT_CALL, aMethodName);
if (result != EARLY_EXIT && result != FAIL)
{
// Indicate to caller whether an integer value was returned (for MsgMonitor()).
result = TokenIsEmptyString(result_token) ? OK : EARLY_RETURN;
}
if (aRetVal) // Always set this as some callers don't initialize it:
*aRetVal = result == EARLY_RETURN ? TokenToInt64(result_token) : 0;
result_token.Free();
return result;
}
//
// Object::Create - Create a new Object given an array of property name/value pairs.
//
Object *Object::Create()
{
Object *obj = new Object();
obj->SetBase(Object::sPrototype);
return obj;
}
Object *Object::Create(ExprTokenType *aParam[], int aParamCount, ResultToken *apResultToken)
{
if (aParamCount & 1)
{
apResultToken->Error(ERR_PARAM_COUNT_INVALID);
return NULL; // Odd number of parameters - reserved for future use.
}
Object *obj = Object::Create();
if (aParamCount)
{
if (aParamCount > 8)
// Set initial capacity to avoid multiple expansions.
// For simplicity, failure is handled by the loop below.
obj->SetInternalCapacity(aParamCount >> 1);
// Otherwise, there are 4 or less key-value pairs. When the first
// item is inserted, a default initial capacity of 4 will be set.
TCHAR buf[MAX_NUMBER_SIZE];
for (int i = 0; i + 1 < aParamCount; i += 2)
{
if (aParam[i]->symbol == SYM_MISSING || aParam[i+1]->symbol == SYM_MISSING)
continue; // For simplicity.
auto name = TokenToString(*aParam[i], buf);
if (!_tcsicmp(name, _T("Base")) && apResultToken)
{
auto base = dynamic_cast<Object *>(TokenToObject(*aParam[i + 1]));
if (!obj->SetBase(base, *apResultToken))
{
obj->Release();
return nullptr;
}
continue;
}
if (!obj->SetOwnProp(name, *aParam[i + 1]))
{
if (apResultToken)
apResultToken->MemoryError();
obj->Release();
return NULL;
}
}
}
return obj;
}
//
// Map::Create - Create a new Map given an array of key/value pairs.
// Map::SetItems - Add or set items given an array of key/value pairs.
//
Map *Map::Create(ExprTokenType *aParam[], int aParamCount)
{
ASSERT(!(aParamCount & 1));
Map *map = new Map();
map->SetBase(Map::sPrototype);
if (aParamCount && !map->SetItems(aParam, aParamCount))
{
// Out of memory.
map->Release();
return NULL;
}
return map;
}
ResultType Map::SetItems(ExprTokenType *aParam[], int aParamCount)
{
ASSERT(!(aParamCount & 1)); // Caller should verify and throw.
if (!aParamCount)
return OK;
// Calculate the maximum number of items that will exist after all items are added.
// There may be an excess if some items already exist, so instead of allocating this
// exact amount up front, postpone it until the last possible moment.
index_t max_capacity_required = mCapacity + (aParamCount >> 1);
for (int i = 0; i + 1 < aParamCount; i += 2)
{
if (aParam[i]->symbol == SYM_MISSING || aParam[i+1]->symbol == SYM_MISSING)
continue; // For simplicity.
// See comments above. HasItem() is checked so that the capacity won't be expanded
// unnecessarily if all of the remaining items already exist. This produces smaller
// code than inlining FindItem()/Assign() here and benchmarks faster than allowing
// unnecessary expansion for a case like Map('c',x,'b',x,'a',x).set('a',y,'b',y).
if (mCapacity == mCount && !HasItem(*aParam[i]))
SetInternalCapacity(max_capacity_required);
if (!SetItem(*aParam[i], *aParam[i + 1]))
return FAIL; // Out of memory.
}
return OK;
}
//
// Cloning
//
// Helper function for temporary implementation of Clone by Object and subclasses.
// Should be eliminated once revision of the object model is complete.
Object *Object::CloneTo(Object &obj)
{
// Allocate space in destination object.
auto field_count = mFields.Length();
if (!obj.SetInternalCapacity(field_count))
{
obj.Release();
return NULL;
}
int failure_count = 0; // See comment below.
index_t i;
obj.mFields.Length() = field_count;
for (i = 0; i < field_count; ++i)
{
FieldType &dst = obj.mFields[i];
FieldType &src = mFields[i];
// Copy name.
dst.key_c = src.key_c;
if ( !(dst.name = _tcsdup(src.name)) )
{
// Rather than trying to set up the object so that what we have
// so far is valid in order to break out of the loop, continue,
// make all fields valid and then allow them to be freed.
++failure_count;
}
// Copy value.
if (!dst.InitCopy(src))
++failure_count;
}
if (failure_count)
{
// One or more memory allocations failed. It seems best to return a clear failure
// indication rather than an incomplete copy. Now that the loop above has finished,
// the object's contents are at least valid and it is safe to free the object:
obj.Release();
return NULL;
}
if (mBase)
obj.SetBase(mBase);
return &obj;
}
Map *Map::CloneTo(Map &obj)
{
Object::CloneTo(obj);
if (!obj.SetInternalCapacity(mCount))
{
obj.Release();
return NULL;
}
int failure_count = 0; // See Object::CloneT() for comments.
index_t i;
obj.mFlags = obj.mFlags;
obj.mCount = mCount;
obj.mKeyOffsetObject = mKeyOffsetObject;
obj.mKeyOffsetString = mKeyOffsetString;
if (obj.mKeyOffsetObject < 0) // Currently might always evaluate to false.
{
obj.mKeyOffsetObject = 0; // aStartOffset excluded all integer and some or all object keys.
if (obj.mKeyOffsetString < 0)
obj.mKeyOffsetString = 0; // aStartOffset also excluded some string keys.
}
//else no need to check mKeyOffsetString since it should always be >= mKeyOffsetObject.
for (i = 0; i < mCount; ++i)
{
Pair &dst = obj.mItem[i];
Pair &src = mItem[i];
// Copy key.
if (i >= obj.mKeyOffsetString)
{
dst.key_c = src.key_c;
if ( !(dst.key.s = _tcsdup(src.key.s)) )
{
// Key allocation failed. At this point, all int and object keys
// have been set and values for previous items have been copied.
++failure_count;
}
}
else
{
// Copy whole key; search "(IntKeyType)(INT_PTR)" for comments.
dst.key = src.key;
if (i >= obj.mKeyOffsetObject)
dst.key.p->AddRef();
}
// Copy value.
if (!dst.InitCopy(src))
++failure_count;
}
if (failure_count)
{
obj.Release();
return NULL;
}
return &obj;
}
//
// Array::ToParams - Used for variadic function-calls.
//
// Copies this array's elements into the parameter list.
// Caller has ensured param_list can fit aParamCount + Length().
void Array::ToParams(ExprTokenType *token, ExprTokenType **param_list, ExprTokenType **aParam, int aParamCount)
{
for (index_t i = 0; i < mLength; ++i)
mItem[i].ToToken(token[i]);
ExprTokenType **param_ptr = param_list;
for (int i = 0; i < aParamCount; ++i)
*param_ptr++ = aParam[i]; // Caller-supplied param token.
for (index_t i = 0; i < mLength; ++i)
*param_ptr++ = &token[i]; // New param.
}
ResultType GetEnumerator(IObject *&aEnumerator, ExprTokenType &aEnumerable, int aVarCount, bool aDisplayError)
{
FuncResult result_token;
ExprTokenType t_count(aVarCount), *param[] = { &t_count };
IObject *invokee = TokenToObject(aEnumerable);
if (!invokee)
invokee = Object::ValueBase(aEnumerable);
// enum := object.__Enum(number of vars)
// IF_NEWENUM causes ComObjects to invoke a _NewEnum method or property.
// IF_BYPASS_METAFUNC causes Objects to skip the __Call meta-function if __Enum is not found.
auto result = invokee->Invoke(result_token, IT_CALL | IF_NEWENUM | IF_BYPASS_METAFUNC, _T("__Enum"), aEnumerable, param, 1);
if (result == FAIL || result == EARLY_EXIT)
return result;
if (result == INVOKE_NOT_HANDLED)
{
aEnumerator = invokee;
aEnumerator->AddRef();
return OK;
}
aEnumerator = TokenToObject(result_token);
if (aEnumerator)
return OK;
result_token.Free();
if (aDisplayError)
g_script.RuntimeError(ERR_TYPE_MISMATCH, _T("__Enum"), FAIL, nullptr, ErrorPrototype::Type);
return FAIL;
}
ResultType CallEnumerator(IObject *aEnumerator, ExprTokenType *aParam[], int aParamCount, bool aDisplayError)
{
FuncResult result_token;
ExprTokenType t_this(aEnumerator);
auto result = aEnumerator->Invoke(result_token, IT_CALL, nullptr, t_this, aParam, aParamCount);
if (result == FAIL || result == EARLY_EXIT || result == INVOKE_NOT_HANDLED)
{
if (result == INVOKE_NOT_HANDLED && aDisplayError)
return g_script.RuntimeError(ERR_NOT_ENUMERABLE, nullptr, FAIL, nullptr, ErrorPrototype::Type); // Object not callable -> wrong type of object.
return result;
}
result = TokenToBOOL(result_token) ? CONDITION_TRUE : CONDITION_FALSE;
result_token.Free();
return result;
}
// Calls an Enumerator repeatedly and returns an Array of all first-arg values.
// This is used in conjunction with Array::ToParams to support other objects.
Array *Array::FromEnumerable(ExprTokenType &aEnumerable)
{
IObject *enumerator;
auto result = GetEnumerator(enumerator, aEnumerable, 1, true);
if (result == FAIL || result == EARLY_EXIT)
return nullptr;
auto varref = new VarRef();
ExprTokenType tvar { varref }, *param = &tvar;
Array *vargs = Array::Create();
for (;;)
{
auto result = CallEnumerator(enumerator, ¶m, 1, true);
if (result == FAIL)
{
vargs->Release();
vargs = nullptr;
break;
}
if (result != CONDITION_TRUE)
break;
ExprTokenType value;
varref->ToTokenSkipAddRef(value);
vargs->Append(value);
}
varref->Release();
enumerator->Release();
return vargs;
}
//
// Array::ToStrings - Used by BIF_StrSplit.
//
ResultType Array::ToStrings(LPTSTR *aStrings, int &aStringCount, int aStringsMax)
{
for (index_t i = 0; i < mLength; ++i)
if (SYM_STRING == mItem[i].symbol)
aStrings[i] = mItem[i].string;
else
return FAIL;
aStringCount = mLength;
return OK;
}
//
// Object::Delete - Called immediately before the object is deleted.
// Returns false if object should not be deleted yet.
//
bool Object::Delete()
{
if (mBase)
{
if (FindField(_T("__Class")))
// This object appears to be a class definition, so it would probably be
// undesirable to call the super-class' __Delete() meta-function for this.
return ObjectBase::Delete();
// L33: Privatize the last recursion layer's deref buffer in case it is in use by our caller.
// It's done here rather than in Var::FreeAndRestoreFunctionVars (even though the below might
// not actually call any script functions) because this function is probably executed much
// less often in most cases.
PRIVATIZE_S_DEREF_BUF;
Line *curr_line = g_script.mCurrLine;
// If an exception has been thrown, temporarily clear it for execution of __Delete.
ResultToken *exc = g->ThrownToken;
g->ThrownToken = NULL;
// This prevents an erroneous "The current thread will exit" message when an error occurs,
// by causing LineError() to throw an exception:
int outer_excptmode = g->ExcptMode;
g->ExcptMode |= EXCPTMODE_DELETE;
{
FuncResult rt;
CallMeta(_T("__Delete"), rt, ExprTokenType(this), nullptr, 0);
rt.Free();
}
g->ExcptMode = outer_excptmode;
// Exceptions thrown by __Delete are reported immediately because they would not be handled
// consistently by the caller (they would typically be "thrown" by the next function call),
// and because the caller must be allowed to make additional __Delete calls.
if (g->ThrownToken)
g_script.FreeExceptionToken(g->ThrownToken);
// If an exception has been thrown by our caller, it's likely that it can and should be handled
// reliably by our caller, so restore it.
if (exc)
g->ThrownToken = exc;
g_script.mCurrLine = curr_line; // Prevent misleading error reports/Exception() stack trace.
DEPRIVATIZE_S_DEREF_BUF; // L33: See above.
// Above may pass the script a reference to this object to allow cleanup routines to free any
// associated resources. Deleting it is only safe if the script no longer holds any references
// to it. Since cleanup routines may (intentionally or unintentionally) copy this reference,
// ensure this object really has no more references before proceeding with deletion:
if (mRefCount > 1)
return false;
}
return ObjectBase::Delete();
}
Object::~Object()
{
if (mBase)
mBase->Release();
}
void Map::Clear()
{
while (mCount)
{
--mCount;
// Copy key before Free() since it might cause re-entry via __delete.
auto key = mItem[mCount].key;
mItem[mCount].Free();
if (mCount >= mKeyOffsetString)
free(key.s);
else
{
--mKeyOffsetString;
if (mCount >= mKeyOffsetObject)
key.p->Release(); // Might also cause re-entry.
else
--mKeyOffsetObject;
}
}
}
//
// Invoke - dynamic dispatch
//
ObjectMember Object::sMembers[] =
{
Object_Method1(Clone, 0, 0),
Object_Method1(DefineProp, 2, 2),
Object_Method1(DeleteProp, 1, 1),
Object_Method1(GetOwnPropDesc, 1, 1),
Object_Method1(HasOwnProp, 1, 1),
Object_Method1(OwnProps, 0, 0)
};
LPTSTR Object::sMetaFuncName[] = { _T("__Get"), _T("__Set"), _T("__Call") };
ResultType Object::Invoke(IObject_Invoke_PARAMS_DECL)
{
// In debug mode, verify aResultToken has been initialized correctly.
ASSERT(aResultToken.symbol == SYM_STRING && aResultToken.marker && !*aResultToken.marker);
ASSERT(aResultToken.Result() == OK);
name_t name;
if (!aName)
{
name = IS_INVOKE_CALL ? _T("Call") : _T("__Item");
aFlags |= IF_BYPASS_METAFUNC;
}
else
name = aName;
auto actual_param = aParam; // Actual first parameter between [] or ().
int actual_param_count = aParamCount; // Actual number of parameters between [] or ().
bool hasprop = false; // Whether any kind of property was found.
bool setting = IS_INVOKE_SET;
bool calling = IS_INVOKE_CALL;
bool handle_params_recursively = calling;
ResultToken token_for_recursion;
IObject *etter = nullptr, *method = nullptr;
Variant *field = nullptr;
index_t insert_pos, other_pos;
Object *that;
if (setting)
{
// Due to the way expression parsing works, the result should never be negative
// (and any direct callers of Invoke must always pass aParamCount >= 1):
ASSERT(actual_param_count > 0);
--actual_param_count;
}
for (that = this; that; that = that->mBase)
{
// Search each object from this to its most distance base, but set insert_pos only when
// searching this object, since it needs to be the position we can insert a new field at.
field = that->FindField(name, that == this ? insert_pos : other_pos);
if (!field) // 'that' has no own property.
continue;
if (field->symbol != SYM_DYNAMIC) // 'that' has a value property.
{
if (hasprop && setting)
// This value property has been overridden with a getter, but no setter.
// Treat it as read-only rather than allowing the getter to implicitly be overridden.
field = nullptr;
hasprop = true;
// This value property takes precedence over any getter, setter or method defined in a base.
break;
}
hasprop = true;
// Since above did not break or continue, 'that' has a dynamic property.
if (calling)
{
if (method = field->prop->Method())
{
etter = nullptr; // Method takes precedence.
break;
}
// Record the first (most derived) getter, if any, in case there is no method:
if (!etter)
etter = field->prop->Getter();
field = nullptr;
continue;
}
if (actual_param_count > 0 && field->prop->MaxParams == 0) // Prop cannot accept parameters.
{
setting = false; // GET this property's value.
handle_params_recursively = true; // Apply parameters by passing them to value->Invoke().
}
// Can this Property actually handle this operation?
if (setting)
etter = field->prop->Setter();
else if ( !(etter = field->prop->Getter()) && !method )
method = field->prop->Method(); // Fall back to returning this if no getter is found.
// Reset field to simplify detection of dynamic property vs. value.
// Note that field would be reset by the next iteration, if there is one.
field = nullptr;
if (etter)
break;
// This part of the property isn't implemented here, so keep searching.
continue;
} // for (that = each base)
if (!hasprop && aName)
{
// Invoke a meta-function in place of this non-existent property.
auto result = CallMetaVarg(aFlags, aName, aResultToken, aThisToken, actual_param, actual_param_count);
if (result != INVOKE_NOT_HANDLED)
return result;
}
if (etter) // Property with getter/setter.
{
// Prepare the parameter list: this, [value,] actual_param*
ExprTokenType this_etter(etter);
ExprTokenType **prop_param = (ExprTokenType **)_malloca((actual_param_count + 2) * sizeof(ExprTokenType *));
if (!prop_param)
return aResultToken.MemoryError();
prop_param[0] = &aThisToken; // For the hidden "this" parameter in the getter/setter.
int prop_param_count = 1;
if (setting)
{
// Put the setter's hidden "value" parameter before the other parameters.
prop_param[prop_param_count++] = actual_param[actual_param_count];
}
if (!handle_params_recursively)
{
memcpy(prop_param + prop_param_count, actual_param, actual_param_count * sizeof(ExprTokenType *));
prop_param_count += actual_param_count;
}
auto caller_line = g_script.mCurrLine;
// Call getter/setter.
auto result = etter->Invoke(aResultToken, IT_CALL, nullptr, this_etter, prop_param, prop_param_count);
_freea(prop_param);
if (result == INVOKE_NOT_HANDLED)
return aResultToken.UnknownMemberError(this_etter, IT_CALL, nullptr);
if ((!handle_params_recursively && !calling) || result == FAIL || result == EARLY_EXIT)
return result;
// Otherwise, handle_params_recursively || calling.
g_script.mCurrLine = caller_line; // For error-reporting.
token_for_recursion.CopyValueFrom(aResultToken);
token_for_recursion.mem_to_free = aResultToken.mem_to_free;
aResultToken.mem_to_free = nullptr;
aResultToken.SetValue(_T(""));
}
if (calling)
{
ExprTokenType func_token;
if (etter)
func_token.CopyValueFrom(token_for_recursion);
else if (!field)
return INVOKE_NOT_HANDLED;
else if (field->symbol == SYM_DYNAMIC)
func_token.SetValue(field->prop->Method());
else
field->ToToken(func_token);
auto result = CallAsMethod(func_token, aResultToken, aThisToken, actual_param, actual_param_count);
if (etter)
token_for_recursion.Free();
return result;
}
if (actual_param_count > 0)
{
// This section handles parameters being passed to a property, such as this.x[y],
// when that property doesn't accept parameters (i.e. none were declared, or the
// property is undefined or just a value).
if (!etter)
{
if (field)
field->ToToken(token_for_recursion);
else if (method)
token_for_recursion.SetValue(method);
else
return INVOKE_NOT_HANDLED;
}
if (IS_INVOKE_SET)
++actual_param_count; // Fix the parameter count.
IObject *obj_for_recursion = TokenToObject(token_for_recursion);
if (!obj_for_recursion)
{
obj_for_recursion = ValueBase(token_for_recursion);
aFlags |= IF_NO_SET_PROPVAL;
}
// Recursively invoke obj_for_recursion, passing remaining parameters:
auto result = obj_for_recursion->Invoke(aResultToken, (aFlags & IT_BITMASK)
, nullptr, token_for_recursion, actual_param, actual_param_count);
if (aResultToken.symbol == SYM_STRING && !aResultToken.mem_to_free && aResultToken.marker != aResultToken.buf)
{
// Before releasing obj_for_recursion, make a copy of the string in case it points
// to memory contained by obj_for_recursion, which might be deleted via Release().
if (!TokenSetResult(aResultToken, aResultToken.marker, aResultToken.marker_length))
result = FAIL;
}
if (result == INVOKE_NOT_HANDLED)
{
// Something like obj.x[y] where obj.x exists but obj.x[y] does not. Throw here
// to override the default error message, which would indicate that "x" is unknown.
result = aResultToken.UnknownMemberError(token_for_recursion, aFlags, nullptr);
}
if (etter)
token_for_recursion.Free();
return result;
}
// SET
else if (setting)
{
if (!field && hasprop) // Property with getter but no setter.
return aResultToken.Error(ERR_PROPERTY_READONLY, name);
if (aFlags & IF_NO_SET_PROPVAL) // Changing value properties not permitted ("".foo := bar).
return INVOKE_NOT_HANDLED;
if (((field && this == that) // A field already exists in this object.
|| (field = Insert(name, insert_pos))) // A new field is inserted.
&& field->Assign(**actual_param))
return OK;
return aResultToken.MemoryError();
}
// GET
else
{
if (field)
{
// Caller takes care of copying the result into persistent memory when necessary, and must
// ensure this is done before they Release() this object. For ExpandExpression(), there are
// two different danger scenarios:
// 1) Fn {value:"string"}.value ; Temporary object could be released prematurely.
// 2) Fn( obj.value, obj := "" ) ; Object is freed by the assignment.
// For both cases, the value is copied immediately after we return, because the result of any
// BIF is assumed to be volatile if expression eval isn't finished. The function call in #1
// is handled by ExpandExpression() since commit 2a276145.
field->ReturnRef(aResultToken);
return OK;
}
else if (method)
{
method->AddRef();
return aResultToken.Return(method);
}
}
// Fell through from one of the sections above: invocation was not handled.
return INVOKE_NOT_HANDLED;
}
ResultType ObjectBase::Invoke(IObject_Invoke_PARAMS_DECL)
{
if (auto base = Base())
{
aFlags |= IF_NO_SET_PROPVAL;
return base->Invoke(IObject_Invoke_PARAMS);
}
return INVOKE_NOT_HANDLED;
}
void Object::CallBuiltin(int aID, ResultToken &aResultToken, ExprTokenType *aParam[], int aParamCount)
{
switch (aID)
{
case FID_ObjOwnPropCount: return PropCount(aResultToken, 0, IT_CALL, aParam, aParamCount);
case FID_ObjHasOwnProp: return HasOwnProp(aResultToken, 0, IT_CALL, aParam, aParamCount);
case FID_ObjGetCapacity: return GetCapacity(aResultToken, 0, IT_CALL, aParam, aParamCount);
case FID_ObjSetCapacity: return SetCapacity(aResultToken, 0, IT_CALL, aParam, aParamCount);
case FID_ObjOwnProps: return OwnProps(aResultToken, 0, IT_CALL, aParam, aParamCount);
}
}
ObjectMember Map::sMembers[] =
{
Object_Member(__Item, __Item, 0, IT_SET, 1, 1),
Object_Member(Capacity, Capacity, 0, IT_SET),
Object_Member(CaseSense, CaseSense, 0, IT_SET),
Object_Member(Count, Count, 0, IT_GET),
Object_Method1(__Enum, 0, 1),
Object_Member(__New, Set, 0, IT_CALL, 0, MAXP_VARIADIC),
Object_Method1(Clear, 0, 0),
Object_Method1(Clone, 0, 0),
Object_Method1(Delete, 1, 1),
Object_Member(Get, __Item, 0, IT_CALL, 1, 2),
Object_Method1(Has, 1, 1),
Object_Method1(Set, 0, MAXP_VARIADIC) // Allow 0 for flexibility with variadic calls.
};
void Map::__Item(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount)
{
if (!IS_INVOKE_SET) // Get or call.
{
if (!GetItem(aResultToken, *aParam[0]))
{
if (ParamIndexIsOmitted(1))
{
auto result = Invoke(aResultToken, IT_GET, _T("Default"), ExprTokenType { this }, nullptr, 0);
if (result == INVOKE_NOT_HANDLED)
_o_throw(ERR_NO_KEY, ParamIndexToString(0, _f_number_buf), ErrorPrototype::Key);
return;
}
// Otherwise, caller provided a default value.
aResultToken.CopyValueFrom(*aParam[1]);
}
if (aResultToken.symbol == SYM_OBJECT)
aResultToken.object->AddRef();
return;
}
else
{
if (!SetItem(*aParam[1], *aParam[0]))
_o_throw_oom;
}
}
void Map::Set(ResultToken &aResultToken, int aID, int aFlags, ExprTokenType *aParam[], int aParamCount)
{
if (aParamCount & 1)
_o_throw(ERR_PARAM_COUNT_INVALID);
if (!SetItems(aParam, aParamCount))
_o_throw_oom;
AddRef();
_o_return(this);
}
//
// Internal
//
ResultType Object::CallAsMethod(ExprTokenType &aFunc, ResultToken &aResultToken, ExprTokenType &aThisToken, ExprTokenType *aParam[], int aParamCount)
{
auto func = TokenToObject(aFunc);
if (!func)
func = ValueBase(aFunc);
ExprTokenType **param = (ExprTokenType **)_malloca((aParamCount + 1) * sizeof(ExprTokenType *));
if (!param)
return aResultToken.MemoryError();
param[0] = &aThisToken;
memcpy(param + 1, aParam, aParamCount * sizeof(ExprTokenType *));
// return %func%(this, aParam*)
auto invoke_result = func->Invoke(aResultToken, IT_CALL, nullptr, aFunc, param, aParamCount + 1);
_freea(param);
return invoke_result;
}
ResultType Object::CallMeta(LPTSTR aName, ResultToken &aResultToken, ExprTokenType &aThisToken, ExprTokenType *aParam[], int aParamCount)
{
IObject *method;
if (method = GetMethod(aName))
{
return CallAsMethod(ExprTokenType(method), aResultToken, aThisToken, aParam, aParamCount);
}
return INVOKE_NOT_HANDLED;
}
ResultType Object::CallMetaVarg(int aFlags, LPTSTR aName, ResultToken &aResultToken, ExprTokenType &aThisToken, ExprTokenType *aParam[], int aParamCount)
{
auto func = GetMethod(sMetaFuncName[INVOKE_TYPE]);
if (!func)
return INVOKE_NOT_HANDLED;
auto vargs = Array::Create(aParam, aParamCount);
if (!vargs)
return aResultToken.MemoryError();
ExprTokenType name_token(aName), args_token(vargs), *param[4];
param[0] = &aThisToken; // this
param[1] = &name_token; // name
param[2] = &args_token; // args
int param_count = 3;
if (IS_INVOKE_SET)
param[param_count++] = aParam[aParamCount]; // value
// return %func%(this, name, args [, value])
ResultType aResult = func->Invoke(aResultToken, IT_CALL, nullptr, ExprTokenType(func), param, param_count);
vargs->Release();
return aResult;
}
//
// Helper function for WinMain()
//
Array *Array::FromArgV(LPTSTR *aArgV, int aArgC)
{
ExprTokenType *token = (ExprTokenType *)_alloca(aArgC * sizeof(ExprTokenType));
ExprTokenType **param = (ExprTokenType **)_alloca(aArgC * sizeof(ExprTokenType*));
for (int j = 0; j < aArgC; ++j)
{
token[j].SetValue(aArgV[j]);
param[j] = &token[j];
}
return Create(param, aArgC);
}
//
// Helper function for StrSplit/WinGetList/WinGetControls
//
bool Array::Append(ExprTokenType &aValue)
{
if (mLength == MaxIndex || !EnsureCapacity(mLength + 1))
return false;
auto &item = mItem[mLength++];
item.Minit();
return item.Assign(aValue);
}
//
// Helper function used with class definitions.
//
void Object::EndClassDefinition()
{
auto &obj = *(Object *)GetOwnPropObj(_T("Prototype"));
// Each variable declaration created a 'missing' property in the class or prototype object to prevent
// duplicate or conflicting declarations. Remove them now so that the declaration acts like a normal
// assignment (i.e. invokes property setters and __Set), for flexibility and consistency; and so that
// SYM_MISSING doesn't need special handling at runtime.
RemoveMissingProperties();
obj.RemoveMissingProperties();
}
void Object::RemoveMissingProperties()
{
for (index_t i = mFields.Length(); i > 0; )
{
i--;
if (mFields[i].symbol == SYM_MISSING)
mFields.Remove(i, 1);
}
}
bool ObjectBase::IsOfType(Object *aPrototype)
{
auto base = Base();
return base == aPrototype || base->IsDerivedFrom(aPrototype);
}
bool Object::IsOfType(Object *aPrototype)
{
return aPrototype == Object::sPrototype || (!IsClassPrototype() && IsDerivedFrom(aPrototype));
}
bool Object::IsDerivedFrom(IObject *aBase)
{
Object *base;
for (base = mBase; base; base = base->mBase)
if (base == aBase)
return true;
return false;
}
Object *Object::GetNativeBase()
{
Object *base;
for (base = mBase; base; base = base->mBase)
if (base->IsNativeClassPrototype())
return base;
return nullptr;
}
bool Object::CanSetBase(Object *aBase)
{
auto new_native_base = (!aBase || aBase->IsNativeClassPrototype())
? aBase : aBase->GetNativeBase();
return new_native_base == GetNativeBase() // Cannot change native type.
&& !aBase->IsDerivedFrom(this); // Cannot create loops.
}
ResultType Object::SetBase(Object *aNewBase, ResultToken &aResultToken)
{
if (!CanSetBase(aNewBase))
return aResultToken.ValueError(ERR_INVALID_BASE);
SetBase(aNewBase);
return OK;
}
//
// Object::Type() - Returns the object's type/class name.
//
LPTSTR Object::Type()
{
Object *base;
ExprTokenType value;
if (GetOwnProp(value, _T("__Class")))
return _T("Prototype"); // This object is a prototype.
for (base = mBase; base; base = base->mBase)
if (base->GetOwnProp(value, _T("__Class")))
return TokenToString(value); // This object is an instance of that class.
return _T("Object"); // Provide a default in case __Class has been removed from all of the base objects.
}