-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
p44script.cpp
10335 lines (8925 loc) · 317 KB
/
p44script.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
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Copyright (c) 2017-2024 plan44.ch / Lukas Zeller, Zurich, Switzerland
//
// Author: Lukas Zeller <[email protected]>
//
// This file is part of p44utils.
//
// p44utils is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// p44utils is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with p44utils. If not, see <http://www.gnu.org/licenses/>.
//
// File scope debugging options
// - Set ALWAYS_DEBUG to 1 to enable DBGLOG output even in non-DEBUG builds of this file
#define ALWAYS_DEBUG 0
// - set FOCUSLOGLEVEL to non-zero log level (usually, 5,6, or 7==LOG_DEBUG) to get focus (extensive logging) for this file
// Note: must be before including "logger.hpp" (or anything that includes "logger.hpp")
#define FOCUSLOGLEVEL 0
// - log level for thread and context lifecycle debugging, 0 = off
#if DEBUG
#define P44SCRIPT_LIFECYCLE_DBG 0
#endif
#include "p44script.hpp"
#if ENABLE_P44SCRIPT
#include "math.h"
#if ENABLE_JSON_APPLICATION && SCRIPTING_JSON_SUPPORT || ENABLE_APPLICATION_SUPPORT
#include "application.hpp"
#include <sys/stat.h> // for mkdir
#include <stdio.h>
#endif
#if P44SCRIPT_FULL_SUPPORT && ENABLE_P44LRGRAPHICS
#include "colorutils.hpp"
#endif // P44SCRIPT_FULL_SUPPORT
#if P44SCRIPT_OTHER_SOURCES
#include "fnv.hpp"
#endif
#ifndef ALWAYS_ALLOW_SYSTEM_FUNC
#define ALWAYS_ALLOW_SYSTEM_FUNC 0
#endif
#ifndef ALWAYS_ALLOW_ALL_FILES
#define ALWAYS_ALLOW_ALL_FILES 0
#endif
#if P44SCRIPT_LIFECYCLE_DBG
#define LCDBG(...) LOG(P44SCRIPT_LIFECYCLE_DBG, ##__VA_ARGS__)
#else
#define LCDBG(...)
#endif
using namespace p44;
using namespace p44::P44Script;
// MARK: - script error
ErrorPtr ScriptError::err(ErrorCodes aErrCode, const char *aFmt, ...)
{
Error *errP = new ScriptError(aErrCode);
va_list args;
va_start(args, aFmt);
errP->setFormattedMessage(aFmt, args);
va_end(args);
return ErrorPtr(errP);
}
// MARK: - EventSink
EventSink::~EventSink()
{
// clear references in all sources
clearSources();
}
void EventSink::clearSources()
{
while (!mEventSources.empty()) {
EventSource *src = *(mEventSources.begin());
mEventSources.erase(mEventSources.begin());
src->mEventSinks.erase(this);
src->mSinksModified = true;
}
}
// MARK: - EventHandler
void EventHandler::setHandler(EventHandlingCB aEventHandlingCB)
{
mEventHandlingCB = aEventHandlingCB;
}
void EventHandler::processEvent(ScriptObjPtr aEvent, EventSource &aSource, intptr_t aRegId)
{
if (mEventHandlingCB) {
mEventHandlingCB(aEvent, aSource, aRegId);
}
}
// MARK: - EventSource
EventSource::~EventSource()
{
// clear references in all sinks
while (!mEventSinks.empty()) {
EventSink *sink = mEventSinks.begin()->first;
mEventSinks.erase(mEventSinks.begin());
sink->mEventSources.erase(this);
}
mEventSinks.clear();
mSinksModified = true;
}
void EventSource::registerForEvents(EventSink* aEventSink, intptr_t aRegId, EventFilterPtr aFilter)
{
if (aEventSink) {
registerForEvents(*aEventSink, aRegId, aFilter);
}
}
void EventSource::registerForEvents(EventSink& aEventSink, intptr_t aRegId, EventFilterPtr aFilter)
{
mSinksModified = true;
mEventSinks[&aEventSink] = { aRegId, aFilter }; // multiple registrations are possible, counted only once, only last aRegId/aFilter stored
aEventSink.mEventSources.insert(this);
}
void EventSource::unregisterFromEvents(EventSink *aEventSink)
{
if (aEventSink) {
unregisterFromEvents(*aEventSink);
}
}
void EventSource::unregisterFromEvents(EventSink& aEventSink)
{
mSinksModified = true;
mEventSinks.erase(&aEventSink);
aEventSink.mEventSources.erase(this);
}
bool EventSource::sendEvent(ScriptObjPtr aEvent)
{
if (mEventSinks.empty()) return false; // optimisation
// note: duplicate notification is possible when sending event causes event sink changes and restarts
// TODO: maybe fix this if it turns out to be a problem
// (should not, because entire triggering is designed to re-evaluate events after triggering)
bool sentAtLeastOne = false;
do {
mSinksModified = false;
for (EventSinkMap::iterator pos=mEventSinks.begin(); pos!=mEventSinks.end(); ++pos) {
ScriptObjPtr tbSent = aEvent;
if (!pos->second.eventFilter || pos->second.eventFilter->filteredEventObj(tbSent)) {
// no filter, or event object passes filter
pos->first->processEvent(tbSent, *this, pos->second.regId);
sentAtLeastOne = true;
if (mSinksModified) break;
}
}
} while(mSinksModified);
return sentAtLeastOne;
}
void EventSource::copySinksFrom(EventSource* aOtherSource)
{
if (!aOtherSource) return;
for (EventSinkMap::iterator pos=aOtherSource->mEventSinks.begin(); pos!=aOtherSource->mEventSinks.end(); ++pos) {
mSinksModified = true;
registerForEvents(pos->first, pos->second.regId, pos->second.eventFilter);
}
}
// MARK: - ScriptObj
#if FOCUSLOGGING
#define FOCUSLOGCLEAR(p) \
if (FOCUSLOGENABLED) { string s = string_format("CLEARING %s@%pX", p, this); FOCUSLOG("%60s", s.c_str() ); }
#define FOCUSLOGCALLER(p) \
if (FOCUSLOGENABLED) { string s = string_format("calling@%pX for %s", this, p); FOCUSLOG("%60s : calling...", s.c_str() ); }
#define FOCUSLOGLOOKUP(p) \
if (FOCUSLOGENABLED) { string s = string_format("searching %s@%pX for '%s'", p, this, aName.c_str()); FOCUSLOG("%60s : requirements=0x%08x", s.c_str(), aMemberAccessFlags ); }
#define FOCUSLOGSTORE(p) \
if (FOCUSLOGENABLED) { string s = string_format("setting '%s' in %s@%pX", aName.c_str(), p, this); FOCUSLOG("%60s : value = %s", s.c_str(), ScriptObj::describe(aMember).c_str()); }
#else
#define FOCUSLOGCLEAR(p)
#define FOCUSLOGCALLER(p)
#define FOCUSLOGLOOKUP(p)
#define FOCUSLOGSTORE(p)
#endif // FOCUSLOGGING
ErrorPtr ScriptObj::setMemberByName(const string aName, const ScriptObjPtr aMember)
{
FOCUSLOGSTORE("ScriptObj")
return ScriptError::err(ScriptError::NotCreated, "cannot assign to '%s'", aName.c_str());
}
ErrorPtr ScriptObj::setMemberAtIndex(size_t aIndex, const ScriptObjPtr aMember, const string aName)
{
return ScriptError::err(ScriptError::NotFound, "cannot assign at %zu", aIndex);
}
ValueIteratorPtr ScriptObj::newIterator(TypeInfo aTypeRequirements) const
{
// by default, iterate by index, types ignored
return new IndexedValueIterator(this);
}
void ScriptObj::makeValid(EvaluationCB aEvaluationCB)
{
// I am already valid - just return myself via callback
if (aEvaluationCB) aEvaluationCB(ScriptObjPtr(this));
}
void ScriptObj::assignLValue(EvaluationCB aEvaluationCB, ScriptObjPtr aNewValue)
{
if (aEvaluationCB) aEvaluationCB(new ErrorValue(ScriptError::err(ScriptError::NotLvalue, "not assignable")));
}
ScriptObjPtr ScriptObj::assignmentValue() const
{
const_cast<ScriptObj *>(this)->mAssignmentRefCount++;
LCDBG("obj %p : assignment added, now: %d - %s", this, mAssignmentRefCount, describe(this).c_str());
return ScriptObjPtr(const_cast<ScriptObj*>(this));
}
void ScriptObj::deactivateAssignment()
{
if (mAssignmentRefCount>0) mAssignmentRefCount--;
LCDBG("obj %p : assignment removed, now: %d - %s", this, mAssignmentRefCount, describe(this).c_str());
if (mAssignmentRefCount<=0) deactivate();
}
string ScriptObj::typeDescription(TypeInfo aInfo, bool aTerse)
{
string s;
if ((aInfo & anyvalid)==anyvalid) {
if (aTerse) {
s = "any";
}
else {
s = "any value";
if ((aInfo & (null|error))!=(null|error)) {
s += " but not";
if ((aInfo & null)==0) {
s += " undefined";
if ((aInfo & error)==0) s += " or";
}
if ((aInfo & error)==0) s += " error";
}
}
}
else {
// structure
const char* commasep = aTerse ? "|" : ", ";
const char* orsep = aTerse ? "|" : " or ";
if (aInfo & objectvalue) {
// identify structured values that are both object and array just as object
s = "object";
}
if (aInfo & arrayvalue) {
if (!s.empty()) s += "/";
s += "array";
}
// special
if (aInfo & threadref) {
if (!s.empty()) s += commasep;
s += "thread";
}
if (aInfo & executable) {
if (!s.empty()) s += commasep;
s += "executable";
}
// scalar
if (aInfo & numeric) {
if (!s.empty()) s += commasep;
s += "numeric";
}
if (aInfo & text) {
if (!s.empty()) s += commasep;
s += "string";
}
// alternatives
if (aInfo & error) {
if (!s.empty()) s += orsep;
s += "error";
}
if (aInfo & null) {
if (!s.empty()) s += orsep;
s += "undefined";
}
if (aInfo & lvalue) {
if (!s.empty()) s += orsep;
s += "lvalue";
}
}
return s;
}
string ScriptObj::describe(const ScriptObj* aObj)
{
if (!aObj) return "<none>";
string n = aObj->getIdentifier();
if (!n.empty()) n.insert(0, " named ");
ScriptObjPtr valObj = aObj->actualValue();
ScriptObjPtr calcObj;
if (valObj) calcObj = valObj->calculationValue();
string ty = typeDescription(aObj->getTypeInfo(), false);
string ann;
if (calcObj) ann = calcObj->getAnnotation();
else ann = aObj->getAnnotation();
string v;
if (calcObj) {
v = calcObj->stringValue();
if (calcObj->hasType(text)) v = cstringQuote(v);
}
else {
v = "<no value>";
}
if (ann==ty || ann==v) ann = ""; else ann.insert(0, " // ");
return string_format(
"%s [%s%s]%s",
v.c_str(),
ty.c_str(),
n.c_str(),
ann.c_str()
);
}
bool ScriptObj::typeRequirementMet(TypeInfo aInfo, TypeInfo aRequirements)
{
if (aRequirements & attrMask) {
// there are attribute requirements: at least one of the required flags must be set
if ((aInfo & aRequirements & attrMask)==0) return false;
}
if (aRequirements & checkedTypesMask) {
// there are type requirements
// - any outside the allowed?
if ((aRequirements & nonebut) && (aInfo & checkedTypesMask & ~aRequirements)!=0) return false;
if (aRequirements & allof) {
return (aInfo & checkedTypesMask & aRequirements) == (aRequirements & checkedTypesMask);
}
else {
return (aInfo & checkedTypesMask & aRequirements) != 0;
}
}
// no checks at all
return true;
}
int ScriptObj::getLogLevelOffset()
{
if (logLevelOffset==0) {
// no own offset - inherit context's
if (loggingContext()) return loggingContext()->getLogLevelOffset();
return 0;
}
return inherited::getLogLevelOffset();
}
string ScriptObj::logContextPrefix()
{
string prefix;
if (loggingContext()) {
prefix = loggingContext()->logContextPrefix();
}
return prefix;
}
// MARK: Generic Operators
bool ScriptObj::operator!() const
{
return !boolValue();
}
bool ScriptObj::operator&&(const ScriptObj& aRightSide) const
{
return boolValue() && aRightSide.boolValue();
}
bool ScriptObj::operator||(const ScriptObj& aRightSide) const
{
return boolValue() || aRightSide.boolValue();
}
// MARK: Equality Operator (all value classes)
bool ScriptObj::operator==(const ScriptObj& aRightSide) const
{
return
(this==&aRightSide) || // object _instance_ identity...
(undefined() && aRightSide.undefined()); // ..or both sides are really null/undefined
}
bool NumericValue::operator==(const ScriptObj& aRightSide) const
{
if (undefined()) return inherited::operator==(aRightSide); // derived numerics might be null
if (aRightSide.undefined()) return false; // a number (especially: zero) is never equal with undefined
return doubleValue()==aRightSide.doubleValue();
}
bool StringValue::operator==(const ScriptObj& aRightSide) const
{
if (undefined()) return inherited::operator==(aRightSide); // derived strings might be null
if (aRightSide.undefined()) return false; // a string (especially: empty) is never equal with undefined
return stringValue()==aRightSide.stringValue();
}
bool ErrorValue::operator==(const ScriptObj& aRightSide) const
{
ErrorPtr e = aRightSide.errorValue();
return errorValue()->isError(e->domain(), e->getErrorCode());
}
// MARK: Less-Than Operator (all value classes)
bool ScriptObj::operator<(const ScriptObj& aRightSide) const
{
return false; // undefined comparisons are always false
}
bool NumericValue::operator<(const ScriptObj& aRightSide) const
{
if (undefined()) return inherited::operator<(aRightSide); // derived numerics might be null
return doubleValue()<aRightSide.doubleValue();
}
bool StringValue::operator<(const ScriptObj& aRightSide) const
{
if (undefined()) return inherited::operator<(aRightSide); // derived strings might be null
return stringValue()<aRightSide.stringValue();
}
// MARK: Derived boolean operators
bool ScriptObj::operator!=(const ScriptObj& aRightSide) const
{
return !operator==(aRightSide);
}
bool ScriptObj::operator>=(const ScriptObj& aRightSide) const
{
return !operator<(aRightSide);
}
bool ScriptObj::operator>(const ScriptObj& aRightSide) const
{
return !operator<(aRightSide) && !operator==(aRightSide);
}
bool ScriptObj::operator<=(const ScriptObj& aRightSide) const
{
return operator==(aRightSide) || operator<(aRightSide);
}
// MARK: Arithmetic Operators (all value classes)
ScriptObjPtr NumericValue::operator+(const ScriptObj& aRightSide) const
{
return new NumericValue(doubleValue() + aRightSide.doubleValue());
}
ScriptObjPtr StringValue::operator+(const ScriptObj& aRightSide) const
{
return new StringValue(stringValue() + aRightSide.stringValue());
}
ScriptObjPtr NumericValue::operator-(const ScriptObj& aRightSide) const
{
return new NumericValue(doubleValue() - aRightSide.doubleValue());
}
ScriptObjPtr NumericValue::operator*(const ScriptObj& aRightSide) const
{
return new NumericValue(doubleValue() * aRightSide.doubleValue());
}
ScriptObjPtr NumericValue::operator/(const ScriptObj& aRightSide) const
{
if (aRightSide.doubleValue()==0) {
return new ErrorValue(ScriptError::DivisionByZero, "division by zero");
}
else {
return new NumericValue(doubleValue() / aRightSide.doubleValue());
}
}
ScriptObjPtr NumericValue::operator%(const ScriptObj& aRightSide) const
{
if (aRightSide.doubleValue()==0) {
return new ErrorValue(ScriptError::DivisionByZero, "modulo by zero");
}
else {
// modulo allowing float dividend and divisor, really meaning "remainder"
double a = doubleValue();
double b = aRightSide.doubleValue();
int64_t q = a/b;
return new NumericValue(a-b*q);
}
}
ScriptObjPtr IntegerValue::operator+(const ScriptObj& aRightSide) const
{
const IntegerValue* i = dynamic_cast<const IntegerValue*>(&aRightSide);
if (i) return new IntegerValue(int64Value() + aRightSide.int64Value());
return inherited::operator+(aRightSide);
}
ScriptObjPtr IntegerValue::operator-(const ScriptObj& aRightSide) const
{
const IntegerValue* i = dynamic_cast<const IntegerValue*>(&aRightSide);
if (i) return new IntegerValue(int64Value() - aRightSide.int64Value());
return inherited::operator-(aRightSide);
}
ScriptObjPtr IntegerValue::operator*(const ScriptObj& aRightSide) const
{
const IntegerValue* i = dynamic_cast<const IntegerValue*>(&aRightSide);
if (i) return new IntegerValue(int64Value() * aRightSide.int64Value());
return inherited::operator*(aRightSide);
}
// MARK: - iterator
IndexedValueIterator::IndexedValueIterator(const ScriptObj* aObj) :
mIteratedObj(const_cast<ScriptObj*>(aObj)),
mCurrentIndex(0)
{
}
void IndexedValueIterator::reset()
{
mCurrentIndex = 0;
}
void IndexedValueIterator::next()
{
if (validIndex()) mCurrentIndex += 1;
}
bool IndexedValueIterator::validIndex()
{
return mCurrentIndex<mIteratedObj->numIndexedMembers();
}
ScriptObjPtr IndexedValueIterator::obtainKey(bool aNumericPreferred)
{
if (!validIndex()) return nullptr;
return new IntegerValue(mCurrentIndex);
}
ScriptObjPtr IndexedValueIterator::obtainValue(TypeInfo aMemberAccessFlags)
{
if (!validIndex()) return nullptr;
return mIteratedObj->memberAtIndex(mCurrentIndex, aMemberAccessFlags);
}
// MARK: - lvalues
void ScriptLValue::makeValid(EvaluationCB aEvaluationCB)
{
if (aEvaluationCB) {
if (!mCurrentValue) aEvaluationCB(new ErrorValue(ScriptError::NotFound, "lvalue does not yet exist"));
else aEvaluationCB(mCurrentValue);
}
}
StandardLValue::StandardLValue(ScriptObjPtr aContainer, const string aMemberName, ScriptObjPtr aCurrentValue) :
inherited(aCurrentValue),
mContainer(aContainer),
mMemberName(aMemberName),
mMemberIndex(0)
{
}
StandardLValue::StandardLValue(ScriptObjPtr aContainer, size_t aMemberIndex, ScriptObjPtr aCurrentValue) :
inherited(aCurrentValue),
mContainer(aContainer),
mMemberName(""),
mMemberIndex(aMemberIndex)
{
}
void StandardLValue::assignLValue(EvaluationCB aEvaluationCB, ScriptObjPtr aNewValue)
{
if (mContainer) {
ErrorPtr err;
if (mMemberName.empty()) {
err = mContainer->setMemberAtIndex(mMemberIndex, aNewValue);
}
else {
err = mContainer->setMemberByName(mMemberName, aNewValue);
}
if (Error::notOK(err)) {
aNewValue = new ErrorValue(err);
}
else {
// if the current value is a placeholder, pass its sinks to the new value before replacing the old value
if (mCurrentValue) mCurrentValue->passSinksToReplacementSource(aNewValue);
// previous value can now be overwritten
mCurrentValue = aNewValue;
}
}
if (aEvaluationCB) {
aEvaluationCB(aNewValue);
}
}
// MARK: - Special NULL values
EventPlaceholderNullValue::EventPlaceholderNullValue(string aAnnotation) :
inherited(aAnnotation)
{
}
void EventPlaceholderNullValue::registerForFilteredEvents(EventSink* aEventSink, intptr_t aRegId)
{
// register with my built-in event source
registerForEvents(aEventSink, aRegId);
}
void EventPlaceholderNullValue::passSinksToReplacementSource(ScriptObjPtr aReplacementSource)
{
// This object is a placeholder possibly already having event sink registrations.
// If the new value is a event source, too the new value must inherit those sinks.
// The ONLY application is that a global on() handlers might
// get declared (at compile time) watching a declared global (which is created as EventPlaceholderNullValue)
// but will only at script run time get the actual value to watch, e.g. a socket or similar.
// This is a use case of early p44script days, when non-global, run-time-defined handlers did not yet
// exist - so declaring a global and then a handler on it and THEN then running code that assigns a socket
// to that global was the ONLY way.
// Before 2022-10-16 this was not limited to EventPlaceholderNullValue, which caused unwanted
// accumulation of event sinks and really hard-to-explain outcomes.
if (!aReplacementSource) return; // nothing to pass to
EventSource* replacementSource = dynamic_cast<EventSource*>(aReplacementSource.get());
if (replacementSource) {
// copy my sinks
replacementSource->copySinksFrom(this);
}
}
OneShotEventNullValue::OneShotEventNullValue(EventSource *aEventSource, string aAnnotation, EventFilterPtr aFilter) :
inherited(aAnnotation),
mEventSource(aEventSource),
mFilter(aFilter)
{
}
bool OneShotEventNullValue::isEventSource() const
{
return mEventSource; // yes, if it is set
}
void OneShotEventNullValue::registerForFilteredEvents(EventSink* aEventSink, intptr_t aRegId)
{
// register with my built-in event source and possibly filters created by a subclass of mine
if (mEventSource) mEventSource->registerForEvents(aEventSink, aRegId, eventFilter());
}
// MARK: - Error Values
ErrorValue::ErrorValue(ScriptError::ErrorCodes aErrCode, const char *aFmt, ...) :
mCaught(false)
{
mErr = new ScriptError(aErrCode);
va_list args;
va_start(args, aFmt);
mErr->setFormattedMessage(aFmt, args);
va_end(args);
}
ErrorValue::ErrorValue(ScriptObjPtr aErrVal)
{
ErrorValue* eP = dynamic_cast<ErrorValue *>(aErrVal.get());
if (eP) {
mErr = eP->mErr;
mCaught = eP->mCaught;
}
else {
mErr = Error::ok();
}
}
ScriptObjPtr ErrorValue::trueOrError(ErrorPtr aError)
{
// return a ErrorValue if aError is set and not OK, a true value otherwise
if (Error::notOK(aError)) return new ErrorValue(aError);
return new BoolValue(true);
}
ScriptObjPtr ErrorValue::nothingOrError(ErrorPtr aError)
{
// return a ErrorValue if aError is set and not OK, nothing otherwise
if (Error::notOK(aError)) return new ErrorValue(aError);
return nullptr;
}
ErrorPosValue::ErrorPosValue(const SourceCursor &aCursor, ErrorPtr aError) :
inherited(aError),
mSourceCursor(aCursor)
{
}
ErrorPosValue::ErrorPosValue(const SourceCursor &aCursor, ScriptObjPtr aErrValue) :
inherited(aErrValue),
mSourceCursor(aCursor)
{
}
ErrorPosValue::ErrorPosValue(const SourceCursor &aCursor, ScriptError::ErrorCodes aErrCode, const char *aFmt, ...) :
inherited(new ScriptError(aErrCode)),
mSourceCursor(aCursor)
{
va_list args;
va_start(args, aFmt);
mErr->setFormattedMessage(aFmt, args);
va_end(args);
}
string ErrorPosValue::stringValue() const
{
return string_format(
"(%s:%zu,%zu): %s",
mSourceCursor.originLabel(),
mSourceCursor.lineno()+1,
mSourceCursor.charpos()+1,
Error::text(mErr)
);
}
#if P44SCRIPT_FULL_SUPPORT
// MARK: - ThreadValue
ThreadValue::ThreadValue(ScriptCodeThreadPtr aThread) : mThread(aThread)
{
// register myself so I can capture the exit value
if (mThread) mThread->registerForEvents(this); // no filters
}
void ThreadValue::deactivate()
{
mThreadExitValue.reset();
if (mThread) mThread->unregisterFromEvents(this);
mThread.reset();
inherited::deactivate();
}
void ThreadValue::processEvent(ScriptObjPtr aEvent, EventSource &aSource, intptr_t aRegId)
{
// event is always the exit value
mThreadExitValue = aEvent->calculationValue(); // capture it
// detach as much as possible
if (mThread) {
mThread->unregisterFromEvents(this);
mThread.reset();
}
}
ScriptObjPtr ThreadValue::calculationValue()
{
if (mThread && mThread->isRunning()) return new AnnotatedNullValue("running thread");
if (!mThreadExitValue) return new AnnotatedNullValue("terminated thread without result");
return mThreadExitValue;
}
TypeInfo ThreadValue::getTypeInfo() const
{
return threadref|keeporiginal|oneshot|(!mThread ? nowait : 0);
}
bool ThreadValue::isEventSource() const
{
return mThread ? true : false; // yes if there is a thread
}
void ThreadValue::registerForFilteredEvents(EventSink* aEventSink, intptr_t aRegId)
{
if (mThread) mThread->registerForEvents(aEventSink, aRegId); // no filters
}
#endif // P44SCRIPT_FULL_SUPPORT
// MARK: - Conversions
double StringValue::doubleValue() const
{
SourceCursor cursor(stringValue());
cursor.skipWhiteSpace();
ScriptObjPtr n = cursor.parseNumericLiteral();
// note: like parseInt/Float in JS we allow trailing garbage
// but UNLIKE JS we don't return NaN here, just 0 if there's no conversion to number
if (n->isErr()) return 0; // otherwise we'd get error
return n->doubleValue();
}
bool StringValue::boolValue() const
{
// Like in JS, empty strings are false, non-empty ones are true
return !stringValue().empty();
}
#if SCRIPTING_JSON_SUPPORT
// MARK: - Json conversions
// JSON from base object
JsonObjectPtr ScriptObj::jsonValue(bool aDescribeNonJSON) const
{
// we get here only when no subclass has a real implementation of jsonValue(), i.e. as fallback
if (aDescribeNonJSON && getTypeInfo()!=null) {
// describe the object by returning the annotation as JSON string
return JsonObject::newString(getAnnotation());
}
if (getTypeInfo() & structured) {
// a structured value but none that can actually reveal it's structure as JSON -> show as empty obj
return JsonObject::newObj();
}
return JsonObject::newNull();
}
// object factory from JSON
ScriptObjPtr ScriptObj::valueFromJSON(JsonObjectPtr aJson)
{
ScriptObjPtr o;
if (aJson) {
switch(aJson->type()) {
case json_type_null:
break;
case json_type_boolean:
o = new BoolValue(aJson->boolValue());
break;
case json_type_double:
o = new NumericValue(aJson->doubleValue());
break;
case json_type_int:
o = new IntegerValue(aJson->int64Value());
break;
case json_type_string:
o = new StringValue(aJson->stringValue());
break;
case json_type_object:
o = new ObjectValue(aJson);
break;
case json_type_array:
o = new ArrayValue(aJson);
break;
}
}
if (!o) {
o = new AnnotatedNullValue("JSON null");
}
return o;
}
// array constructor from JSON
ArrayValue::ArrayValue(JsonObjectPtr aJsonObject)
{
for (int i=0; i<aJsonObject->arrayLength(); i++) {
ScriptObjPtr e = ScriptObj::valueFromJSON(aJsonObject->arrayGet(i));
if (e) mElements.push_back(e);
}
}
// object constructor from JSON
ObjectValue::ObjectValue(JsonObjectPtr aJsonObject)
{
aJsonObject->resetKeyIteration();
JsonObjectPtr f;
string fn;
while(aJsonObject->nextKeyValue(fn, f)) {
mFields[fn] = ScriptObj::valueFromJSON(f);
}
}
JsonObjectPtr ErrorValue::jsonValue(bool aDescribeNonJSON) const
{
JsonObjectPtr j;
if (mErr) {
j = JsonObject::newObj();
j->add("ErrorCode", JsonObject::newInt32((int32_t)mErr->getErrorCode()));
j->add("ErrorDomain", JsonObject::newString(mErr->getErrorDomain()));
j->add("ErrorMessage", JsonObject::newString(mErr->getErrorMessage()));
}
return j;
}
JsonObjectPtr StringValue::jsonValue(bool aDescribeNonJSON) const
{
// old version did parse strings for json, but that's ambiguous, so
// we just return a json string now
return JsonObject::newString(stringValue());
}
string StructuredValue::stringValue() const
{
// json representation with non-JSON objects described as strings
return jsonValue(true)->json_str();
}
bool StructuredValue::boolValue() const
{
return true; // bool value of arrays and objects, even empty ones, is always true
}