/
pxtbase.h
1242 lines (1032 loc) · 32.1 KB
/
pxtbase.h
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
#ifndef __PXTBASE_H
#define __PXTBASE_H
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wformat"
#pragma GCC diagnostic ignored "-Warray-bounds"
// needed for gcc6; not sure why
#undef min
#undef max
#define NOLOG(...) \
do { \
} while (0)
#define MEMDBG NOLOG
//#define MEMDBG DMESG
#define MEMDBG2 NOLOG
#include "pxtconfig.h"
#include "configkeys.h"
#ifndef PXT_UTF8
#define PXT_UTF8 0
#endif
#if defined(PXT_VM)
#include <stdint.h>
#if UINTPTR_MAX == 0xffffffff
#define PXT32 1
#elif UINTPTR_MAX == 0xffffffffffffffff
#define PXT64 1
#else
#error "UINTPTR_MAX has invalid value"
#endif
#endif
#define intcheck(...) check(__VA_ARGS__)
//#define intcheck(...) do {} while (0)
#ifdef PXT_USE_FLOAT
#define NUMBER float
#else
#define NUMBER double
#endif
#include <string.h>
#include <stdint.h>
#include <math.h>
#ifdef POKY
void *operator new(size_t size, void *ptr);
void *operator new(size_t size);
#else
#include <new>
#endif
#include "platform.h"
#include "pxtcore.h"
#ifndef PXT_REGISTER_RESET
#define PXT_REGISTER_RESET(fn) ((void)0)
#endif
#define PXT_REFCNT_FLASH 0xfffe
#define CONCAT_1(a, b) a##b
#define CONCAT_0(a, b) CONCAT_1(a, b)
// already provided in some platforms, like mbedos
#ifndef STATIC_ASSERT
#define STATIC_ASSERT(e) enum { CONCAT_0(_static_assert_, __LINE__) = 1 / ((e) ? 1 : 0) };
#endif
#ifndef ramint_t
// this type limits size of arrays
#if defined(__linux__) || defined(PXT_VM)
// TODO fix the inline array accesses to take note of this!
#define ramint_t uint32_t
#else
#define ramint_t uint16_t
#endif
#endif
#ifndef PXT_IN_ISR
#define PXT_IN_ISR() (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk)
#endif
#ifdef POKY
inline void *operator new(size_t, void *p) {
return p;
}
inline void *operator new[](size_t, void *p) {
return p;
}
#endif
namespace pxt {
template <typename T> inline const T &max(const T &a, const T &b) {
if (a < b)
return b;
return a;
}
template <typename T> inline const T &min(const T &a, const T &b) {
if (a < b)
return a;
return b;
}
template <typename T> inline void swap(T &a, T &b) {
T tmp = a;
a = b;
b = tmp;
}
//
// Tagged values (assume 4 bytes for now, Cortex-M0)
//
struct TValueStruct {};
typedef TValueStruct *TValue;
typedef TValue TNumber;
typedef TValue Action;
typedef TValue ImageLiteral;
// To be implemented by the target
extern "C" void target_panic(int error_code);
extern "C" void target_reset();
void sleep_ms(unsigned ms);
void sleep_us(uint64_t us);
void releaseFiber();
uint64_t current_time_us();
int current_time_ms();
void initRuntime();
void initSystemTimer();
void sendSerial(const char *data, int len);
void setSendToUART(void (*f)(const char *, int));
uint64_t getLongSerialNumber();
void registerWithDal(int id, int event, Action a, int flags = 16); // EVENT_LISTENER_DEFAULT_FLAGS
void runInParallel(Action a);
void runForever(Action a);
void waitForEvent(int id, int event);
//%
unsigned afterProgramPage();
//%
void dumpDmesg();
uint32_t hash_fnv1(const void *data, unsigned len);
// also defined DMESG macro
// end
#define TAGGED_SPECIAL(n) (TValue)(void *)((n << 2) | 2)
#define TAG_FALSE TAGGED_SPECIAL(2) // 10
#define TAG_TRUE TAGGED_SPECIAL(16) // 66
#define TAG_UNDEFINED (TValue)0
#define TAG_NULL TAGGED_SPECIAL(1) // 6
#define TAG_NAN TAGGED_SPECIAL(3) // 14
#define TAG_NUMBER(n) (TNumber)(void *)(((uintptr_t)(uint32_t)(n) << 1) | 1)
#define TAG_NON_VALUE TAGGED_SPECIAL(4) // 18; doesn't represent any JS value
#ifdef PXT_VM
inline bool isEncodedDouble(uint64_t v) {
return (v >> 48) != 0;
}
#endif
inline bool isDouble(TValue v) {
#ifdef PXT64
return ((uintptr_t)v >> 48) != 0;
#else
(void)v;
return false;
#endif
}
inline bool isPointer(TValue v) {
return !isDouble(v) && v != 0 && ((intptr_t)v & 3) == 0;
}
inline bool isTagged(TValue v) {
return (!isDouble(v) && ((intptr_t)v & 3)) || !v;
}
inline bool isInt(TValue v) {
return !isDouble(v) && ((intptr_t)v & 1);
}
inline bool isSpecial(TValue v) {
return !isDouble(v) && ((intptr_t)v & 2);
}
inline bool bothNumbers(TValue a, TValue b) {
return !isDouble(a) && !isDouble(b) && ((intptr_t)a & (intptr_t)b & 1);
}
inline int numValue(TValue n) {
return (int)((intptr_t)n >> 1);
}
inline bool canBeTagged(int v) {
(void)v;
#ifdef PXT_BOX_DEBUG
return false;
#elif defined(PXT64)
return true;
#else
return (v << 1) >> 1 == v;
#endif
}
// see https://anniecherkaev.com/the-secret-life-of-nan
#define NanBoxingOffset 0x1000000000000LL
template <typename TO, typename FROM> TO bitwise_cast(FROM in) {
STATIC_ASSERT(sizeof(TO) == sizeof(FROM));
union {
FROM from;
TO to;
} u;
u.from = in;
return u.to;
}
inline double decodeDouble(uint64_t v) {
return bitwise_cast<double>(v - NanBoxingOffset);
}
#ifdef PXT64
STATIC_ASSERT(sizeof(void *) == 8);
inline double doubleVal(TValue v) {
return bitwise_cast<double>((uint64_t)v - NanBoxingOffset);
}
inline TValue tvalueFromDouble(double d) {
return (TValue)(bitwise_cast<uint64_t>(d) + NanBoxingOffset);
}
#else
STATIC_ASSERT(sizeof(void *) == 4);
#endif
// keep in sym with sim/control.ts
typedef enum {
PANIC_CODAL_OOM = 20,
PANIC_GC_OOM = 21,
PANIC_GC_TOO_BIG_ALLOCATION = 22,
PANIC_CODAL_HEAP_ERROR = 30,
PANIC_CODAL_NULL_DEREFERENCE = 40,
PANIC_CODAL_USB_ERROR = 50,
PANIC_CODAL_HARDWARE_CONFIGURATION_ERROR = 90,
PANIC_INVALID_BINARY_HEADER = 901,
PANIC_OUT_OF_BOUNDS = 902,
PANIC_REF_DELETED = 903,
PANIC_SIZE = 904,
PANIC_INVALID_VTABLE = 905,
PANIC_INTERNAL_ERROR = 906,
PANIC_NO_SUCH_CONFIG = 907,
PANIC_NO_SUCH_PIN = 908,
PANIC_INVALID_ARGUMENT = 909,
PANIC_MEMORY_LIMIT_EXCEEDED = 910,
PANIC_SCREEN_ERROR = 911,
PANIC_MISSING_PROPERTY = 912,
PANIC_INVALID_IMAGE = 913,
PANIC_CALLED_FROM_ISR = 914,
PANIC_HEAP_DUMPED = 915,
PANIC_STACK_OVERFLOW = 916,
PANIC_BLOCKING_TO_STRING = 917,
PANIC_VM_ERROR = 918,
PANIC_SETTINGS_CLEARED = 920,
PANIC_SETTINGS_OVERLOAD = 921,
PANIC_SETTINGS_SECRET_MISSING = 922,
PANIC_DELETE_ON_CLASS = 923,
PANIC_OUT_OF_TIMERS = 924,
PANIC_JACDAC = 925,
PANIC_MICROPHONE_MISSING = 926,
PANIC_VARIANT_NOT_SUPPORTED = 927,
PANIC_CAST_FIRST = 980,
PANIC_CAST_FROM_UNDEFINED = 980,
PANIC_CAST_FROM_BOOLEAN = 981,
PANIC_CAST_FROM_NUMBER = 982,
PANIC_CAST_FROM_STRING = 983,
PANIC_CAST_FROM_OBJECT = 984,
PANIC_CAST_FROM_FUNCTION = 985,
PANIC_CAST_FROM_NULL = 989,
PANIC_UNHANDLED_EXCEPTION = 999,
} PXT_PANIC;
extern const uintptr_t functionsAndBytecode[];
extern TValue *globals;
extern uint16_t *bytecode;
class RefRecord;
// Utility functions
typedef TValue (*RunActionType)(Action a, TValue arg0, TValue arg1, TValue arg2);
#define asmRunAction3 ((RunActionType)(((uintptr_t *)bytecode)[12]))
static inline TValue runAction3(Action a, TValue arg0, TValue arg1, TValue arg2) {
return asmRunAction3(a, arg0, arg1, 0);
}
static inline TValue runAction2(Action a, TValue arg0, TValue arg1) {
return asmRunAction3(a, arg0, arg1, 0);
}
static inline TValue runAction1(Action a, TValue arg0) {
return asmRunAction3(a, arg0, 0, 0);
}
static inline TValue runAction0(Action a) {
return asmRunAction3(a, 0, 0, 0);
}
class RefAction;
class BoxedString;
struct VTable;
//%
Action mkAction(int totallen, RefAction *act);
//% expose
int templateHash();
//% expose
int programHash();
//% expose
BoxedString *programName();
//% expose
unsigned programSize();
//%
int getNumGlobals();
//%
RefRecord *mkClassInstance(VTable *vt);
//%
void debugMemLeaks();
//%
void anyPrint(TValue v);
//%
int getConfig(int key, int defl = -1);
//%
int toInt(TNumber v);
//%
unsigned toUInt(TNumber v);
//%
NUMBER toDouble(TNumber v);
//%
float toFloat(TNumber v);
//%
TNumber fromDouble(NUMBER r);
//%
TNumber fromFloat(float r);
//%
TNumber fromInt(int v);
//%
TNumber fromUInt(unsigned v);
//%
TValue fromBool(bool v);
//%
bool eq_bool(TValue a, TValue b);
//%
bool eqq_bool(TValue a, TValue b);
//%
void failedCast(TValue v, void *addr = NULL);
//%
void missingProperty(TValue v);
void error(PXT_PANIC code, int subcode = 0);
void exec_binary(unsigned *pc);
void start();
struct HandlerBinding {
HandlerBinding *next;
int source;
int value;
Action action;
#ifndef PXT_CODAL
uint32_t flags;
struct Event *pending;
#endif
};
HandlerBinding *findBinding(int source, int value);
HandlerBinding *nextBinding(HandlerBinding *curr, int source, int value);
void setBinding(int source, int value, Action act);
// Legacy stuff; should no longer be used
//%
TValue incr(TValue e);
//%
void decr(TValue e);
inline TValue incr(TValue e) {
return e;
}
inline void decr(TValue e) {}
class RefObject;
static inline RefObject *incrRC(RefObject *r) {
return r;
}
static inline void decrRC(RefObject *) {}
inline void *ptrOfLiteral(int offset) {
return &bytecode[offset];
}
// Checks if object is ref-counted, and has a custom PXT vtable in front
// TODO
inline bool isRefCounted(TValue e) {
return isPointer(e);
}
inline void check(int cond, PXT_PANIC code, int subcode = 0) {
if (!cond)
error(code, subcode);
}
inline void oops(int subcode = 0) {
target_panic(800 + subcode);
}
class RefObject;
typedef void (*RefObjectMethod)(RefObject *self);
typedef unsigned (*RefObjectSizeMethod)(RefObject *self);
typedef void *PVoid;
typedef void **PPVoid;
typedef void *Object_;
#define VTABLE_MAGIC 0xF9
#define VTABLE_MAGIC2 0xF8
enum class ValType : uint8_t {
Undefined,
Boolean,
Number,
String,
Object,
Function,
};
// keep in sync with pxt-core (search for the type name)
enum class BuiltInType : uint16_t {
BoxedString = 1,
BoxedNumber = 2,
BoxedBuffer = 3,
RefAction = 4,
RefImage = 5,
RefCollection = 6,
RefRefLocal = 7,
RefMap = 8,
RefMImage = 9, // microbit-specific
MMap = 10, // linux, mostly ev3
BoxedString_SkipList = 11, // used by VM bytecode representation only
BoxedString_ASCII = 12, // ditto
ZPin = 13,
User0 = 16,
};
struct VTable {
uint16_t numbytes;
ValType objectType;
uint8_t magic;
#ifdef PXT_VM
uint16_t ifaceHashEntries;
BuiltInType lastClassNo;
#else
PVoid *ifaceTable;
#endif
BuiltInType classNo;
uint16_t reserved;
uint32_t ifaceHashMult;
// we only use the first few methods here; pxt will generate more
PVoid methods[8];
};
//%
extern const VTable string_inline_ascii_vt;
#if PXT_UTF8
//%
extern const VTable string_inline_utf8_vt;
//%
extern const VTable string_cons_vt;
//%
extern const VTable string_skiplist16_vt;
//%
extern const VTable string_skiplist16_packed_vt;
#endif
//%
extern const VTable buffer_vt;
//%
extern const VTable number_vt;
//%
extern const VTable RefAction_vtable;
#ifndef PXT_IS_READONLY
// assume ARM - ram addresses are 0x2000_0000+; flash is either 0x0+ or 0x0800_0000+
#define PXT_IS_READONLY(v) (isTagged(v) || !((uintptr_t)v >> 28))
#endif
inline bool isReadOnly(TValue v) {
return PXT_IS_READONLY(v);
}
// A base abstract class for ref-counted objects.
class RefObject {
public:
const VTable *vtable;
RefObject(const VTable *vt) {
#if defined(PXT32) && defined(PXT_VM) && !defined(PXT_ESP32)
if ((uint32_t)vt & 0xf0000000)
target_panic(PANIC_INVALID_VTABLE);
#endif
vtable = vt;
}
void destroyVT();
void printVT();
inline uintptr_t vt() { return (uintptr_t)vtable; }
inline void setVT(uintptr_t v) { vtable = (const VTable *)v; }
inline void ref() {}
inline void unref() {}
inline bool isReadOnly() { return pxt::isReadOnly((TValue)this); }
};
class Segment {
private:
TValue *data;
ramint_t length;
ramint_t size;
// this just gives max value of ramint_t
void growByMin(ramint_t minSize);
void ensure(ramint_t newSize);
public:
static constexpr ramint_t MaxSize = (((1U << (8 * sizeof(ramint_t) - 1)) - 1) << 1) + 1;
static constexpr TValue DefaultValue = TAG_UNDEFINED; // == NULL
Segment() : data(nullptr), length(0), size(0) {}
TValue get(unsigned i) { return i < length ? data[i] : NULL; }
void set(unsigned i, TValue value);
unsigned getLength() { return length; };
void setLength(unsigned newLength);
void push(TValue value) { set(length, value); }
TValue pop();
TValue remove(unsigned i);
void insert(unsigned i, TValue value);
void destroy();
void print();
TValue *getData() { return data; }
};
// Low-Level segment using system malloc
class LLSegment {
private:
TValue *data;
ramint_t length;
ramint_t size;
public:
LLSegment() : data(nullptr), length(0), size(0) {}
void set(unsigned idx, TValue v);
void push(TValue value) { set(length, value); }
TValue pop();
void destroy();
void setLength(unsigned newLen);
TValue get(unsigned i) { return i < length ? data[i] : NULL; }
unsigned getLength() { return length; };
TValue *getData() { return data; }
};
// A ref-counted collection of either primitive or ref-counted objects (String, Image,
// user-defined record, another collection)
class RefCollection : public RefObject {
public:
Segment head;
RefCollection();
static void destroy(RefCollection *coll);
static void scan(RefCollection *coll);
static unsigned gcsize(RefCollection *coll);
static void print(RefCollection *coll);
unsigned length() { return head.getLength(); }
void setLength(unsigned newLength) { head.setLength(newLength); }
TValue getAt(int i) { return head.get(i); }
TValue *getData() { return head.getData(); }
};
class RefMap : public RefObject {
public:
Segment keys;
Segment values;
RefMap();
static void destroy(RefMap *map);
static void scan(RefMap *map);
static unsigned gcsize(RefMap *coll);
static void print(RefMap *map);
int findIdx(BoxedString *key);
};
// A ref-counted, user-defined JS object.
class RefRecord : public RefObject {
public:
// The object is allocated, so that there is space at the end for the fields.
TValue fields[];
RefRecord(VTable *v) : RefObject(v) {}
TValue ld(int idx);
TValue ldref(int idx);
void st(int idx, TValue v);
void stref(int idx, TValue v);
};
static inline VTable *getVTable(RefObject *r) {
return (VTable *)(r->vt() & ~1);
}
static inline VTable *getAnyVTable(TValue v) {
if (!isRefCounted(v))
return NULL;
auto vt = getVTable((RefObject *)v);
if (vt->magic == VTABLE_MAGIC)
return vt;
return NULL;
}
// these are needed when constructing vtables for user-defined classes
//%
void RefRecord_destroy(RefRecord *r);
//%
void RefRecord_print(RefRecord *r);
//%
void RefRecord_scan(RefRecord *r);
//%
unsigned RefRecord_gcsize(RefRecord *r);
typedef TValue (*ActionCB)(TValue *captured, TValue arg0, TValue arg1, TValue arg2);
// Ref-counted function pointer.
class RefAction : public RefObject {
public:
uint16_t len;
uint16_t numArgs;
#ifdef PXT_VM
uint16_t initialLen;
uint16_t flags;
uintptr_t func;
#else
ActionCB func; // The function pointer
#endif
// fields[] contain captured locals
TValue fields[];
static void destroy(RefAction *act);
static void scan(RefAction *act);
static unsigned gcsize(RefAction *coll);
static void print(RefAction *act);
RefAction();
inline void stCore(int idx, TValue v) {
// DMESG("ST [%d] = %d ", idx, v); this->print();
intcheck(0 <= idx && idx < len, PANIC_OUT_OF_BOUNDS, 10);
intcheck(fields[idx] == 0, PANIC_OUT_OF_BOUNDS, 11); // only one assignment permitted
fields[idx] = v;
}
};
// These two are used to represent locals written from inside inline functions
class RefRefLocal : public RefObject {
public:
TValue v;
static void destroy(RefRefLocal *l);
static void scan(RefRefLocal *l);
static unsigned gcsize(RefRefLocal *l);
static void print(RefRefLocal *l);
RefRefLocal();
};
typedef int color;
// note: this is hardcoded in PXT (hexfile.ts)
class BoxedNumber : public RefObject {
public:
NUMBER num;
BoxedNumber() : RefObject(&number_vt) {}
} __attribute__((packed));
class BoxedString : public RefObject {
public:
union {
struct {
uint16_t length; // ==size
char data[0];
} ascii;
#if PXT_UTF8
struct {
uint16_t size;
char data[0];
} utf8;
struct {
BoxedString *left;
BoxedString *right;
} cons;
struct {
uint16_t size; // in bytes
uint16_t length; // in characters
uint16_t *list;
} skip;
struct {
uint16_t size; // in bytes
uint16_t length; // in characters
uint16_t list[0];
} skip_pack;
#endif
};
#if PXT_UTF8
uintptr_t runMethod(int idx) {
return ((uintptr_t(*)(BoxedString *))vtable->methods[idx])(this);
}
const char *getUTF8Data() { return (const char *)runMethod(4); }
uint32_t getUTF8Size() { return (uint32_t)runMethod(5); }
// in characters
uint32_t getLength() { return (uint32_t)runMethod(6); }
const char *getUTF8DataAt(uint32_t pos) {
auto meth = ((const char *(*)(BoxedString *, uint32_t))vtable->methods[7]);
return meth(this, pos);
}
#else
const char *getUTF8Data() { return ascii.data; }
uint32_t getUTF8Size() { return ascii.length; }
uint32_t getLength() { return ascii.length; }
const char *getUTF8DataAt(uint32_t pos) { return pos < ascii.length ? ascii.data + pos : NULL; }
#endif
TNumber charCodeAt(int pos);
BoxedString(const VTable *vt) : RefObject(vt) {}
};
// cross version compatible way of accessing string data
#ifndef PXT_STRING_DATA
#define PXT_STRING_DATA(str) str->getUTF8Data()
#endif
// cross version compatible way of accessing string length
#ifndef PXT_STRING_DATA_LENGTH
#define PXT_STRING_DATA_LENGTH(str) str->getUTF8Size()
#endif
class BoxedBuffer : public RefObject {
public:
// data needs to be word-aligned, so we use 32 bits for length
int length;
uint8_t data[0];
BoxedBuffer() : RefObject(&buffer_vt) {}
static bool isInstance(TValue v);
};
// cross version compatible way of access data field
#ifndef PXT_BUFFER_DATA
#define PXT_BUFFER_DATA(buffer) buffer->data
#endif
// cross version compatible way of access data length
#ifndef PXT_BUFFER_LENGTH
#define PXT_BUFFER_LENGTH(buffer) buffer->length
#endif
#ifndef PXT_CREATE_BUFFER
#define PXT_CREATE_BUFFER(data, len) pxt::mkBuffer(data, len)
#endif
// Legacy format:
// the first byte of data indicates the format - currently 0xE1 or 0xE4 to 1 or 4 bit bitmaps
// second byte indicates width in pixels
// third byte indicates the height (which should also match the size of the buffer)
// just like ordinary buffers, these can be layed out in flash
// Current format:
// 87 BB WW WW HH HH 00 00 DATA
// that is: 0x87, 0x01 or 0x04 - bpp, width in little endian, height, 0x00, 0x00 followed by data
// for 4 bpp images, rows are word-aligned (as in legacy)
#define IMAGE_HEADER_MAGIC 0x87
struct ImageHeader {
uint8_t magic;
uint8_t bpp;
uint16_t width;
uint16_t height;
uint16_t padding;
uint8_t pixels[0];
};
class RefImage : public RefObject {
public:
BoxedBuffer *buffer;
uint32_t revision;
RefImage(BoxedBuffer *buf);
RefImage(uint32_t sz);
void setBuffer(BoxedBuffer *b);
uint8_t *data() { return buffer->data; }
int length() { return (int)buffer->length; }
ImageHeader *header() { return (ImageHeader *)buffer->data; }
int pixLength() { return length() - sizeof(ImageHeader); }
int width() { return header()->width; }
int height() { return header()->height; }
int wordHeight();
int bpp() { return header()->bpp; }
bool hasPadding() { return (height() & 0x7) != 0; }
uint8_t *pix() { return header()->pixels; }
int byteHeight() {
if (bpp() == 1)
return (height() + 7) >> 3;
else if (bpp() == 4)
return ((height() * 4 + 31) >> 5) << 2;
else {
oops(21);
return -1;
}
}
uint8_t *pix(int x, int y) {
uint8_t *d = &pix()[byteHeight() * x];
if (y) {
if (bpp() == 1)
d += y >> 3;
else if (bpp() == 4)
d += y >> 1;
}
return d;
}
uint8_t fillMask(color c);
bool inRange(int x, int y);
void clamp(int *x, int *y);
void makeWritable();
static void destroy(RefImage *t);
static void scan(RefImage *t);
static unsigned gcsize(RefImage *t);
static void print(RefImage *t);
};
RefImage *mkImage(int w, int h, int bpp);
typedef BoxedBuffer *Buffer;
typedef BoxedString *String;
typedef RefImage *Image_;
uint32_t toRealUTF8(String str, uint8_t *dst);
// keep in sync with github/pxt/pxtsim/libgeneric.ts
enum class NumberFormat {
Int8LE = 1,
UInt8LE,
Int16LE,
UInt16LE,
Int32LE,
Int8BE,
UInt8BE,
Int16BE,
UInt16BE,
Int32BE,
UInt32LE,
UInt32BE,
Float32LE,
Float64LE,
Float32BE,
Float64BE,
};
// this will, unlike mkStringCore, UTF8-canonicalize the data
String mkString(const char *data, int len = -1);
// data can be NULL in both cases
Buffer mkBuffer(const void *data, int len);
String mkStringCore(const char *data, int len = -1);
TNumber getNumberCore(uint8_t *buf, int size, NumberFormat format);
void setNumberCore(uint8_t *buf, int size, NumberFormat format, TNumber value);
void seedRandom(unsigned seed);
void seedAddRandom(unsigned seed);
// max is inclusive
unsigned getRandom(unsigned max);
ValType valType(TValue v);
// this is equivalent to JS `throw v`; it will leave
// the current function(s), all the way until the nearest try block and
// ignore all destructors (think longjmp())
void throwValue(TValue v);
void registerGC(TValue *root, int numwords = 1);
void unregisterGC(TValue *root, int numwords = 1);
void registerGCPtr(TValue ptr);
void unregisterGCPtr(TValue ptr);
static inline void registerGCObj(RefObject *ptr) {
registerGCPtr((TValue)ptr);
}
static inline void unregisterGCObj(RefObject *ptr) {
unregisterGCPtr((TValue)ptr);
}
void gc(int flags);
struct StackSegment {
void *top;
void *bottom;
StackSegment *next;
};
#define NUM_TRY_FRAME_REGS 3
struct TryFrame {
TryFrame *parent;
uintptr_t registers[NUM_TRY_FRAME_REGS];
};
struct ThreadContext {
TValue *globals;
StackSegment stack;
TryFrame *tryFrame;
TValue thrownValue;
#ifdef PXT_GC_THREAD_LIST
ThreadContext *next;
ThreadContext *prev;
#endif
};
#ifdef PXT_GC_THREAD_LIST
extern ThreadContext *threadContexts;
void *threadAddressFor(ThreadContext *, void *sp);
#endif
void releaseThreadContext(ThreadContext *ctx);
ThreadContext *getThreadContext();
void setThreadContext(ThreadContext *ctx);
#ifndef PXT_GC_THREAD_LIST
void gcProcessStacks(int flags);
#endif
void gcProcess(TValue v);
void gcFreeze();
#ifdef PXT_VM
void gcStartup();
void gcPreStartup();
#endif
void coreReset();
void gcReset();
void systemReset();
void doNothing();
void *gcAllocate(int numbytes);
void *gcAllocateArray(int numbytes);
extern "C" void *app_alloc(int numbytes);
extern "C" void *app_free(void *ptr);
extern "C" void *app_alloc_at(void *at, int numbytes);
void gcPreAllocateBlock(uint32_t sz);
int redirectSamples(int16_t *dst, int numsamples, int samplerate);