This repository was archived by the owner on Aug 31, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 224
Expand file tree
/
Copy pathemit.cpp
More file actions
2613 lines (2111 loc) · 81 KB
/
Copy pathemit.cpp
File metadata and controls
2613 lines (2111 loc) · 81 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
/* Copyright (C) 2003-2016 LiveCode Ltd.
This file is part of LiveCode.
LiveCode is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License v3 as published by the Free
Software Foundation.
LiveCode 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 LiveCode. If not see <http://www.gnu.org/licenses/>. */
#include "foundation.h"
#include "foundation-auto.h"
#include "libscript/script.h"
#include "libscript/script-auto.h"
#include <output.h>
#include <allocate.h>
#include <position.h>
#include <report.h>
#include <literal.h>
#include "outputfile.h"
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/stat.h>
#ifndef WIN32
#include <unistd.h>
#endif
extern "C" int OutputFileAsC;
int OutputFileAsC = 0;
extern "C" int OutputFileAsAuxC;
int OutputFileAsAuxC = 0;
extern "C" int OutputFileAsBytecode;
int OutputFileAsBytecode = 0;
extern "C" void EmitStart(void);
extern "C" void EmitFinish(void);
extern "C" void EmitBeginModule(NameRef name, intptr_t& r_index);
extern "C" void EmitBeginWidgetModule(NameRef name, intptr_t& r_index);
extern "C" void EmitBeginLibraryModule(NameRef name, intptr_t& r_index);
extern "C" void EmitEndModule(void);
extern "C" void EmitModuleDependency(NameRef name, intptr_t& r_index);
extern "C" void EmitImportedType(intptr_t module_index, NameRef name, intptr_t type_index, intptr_t& r_index);
extern "C" void EmitImportedConstant(intptr_t module_index, NameRef name, intptr_t type_index, intptr_t& r_index);
extern "C" void EmitImportedVariable(intptr_t module_index, NameRef name, intptr_t type_index, intptr_t& r_index);
extern "C" void EmitImportedHandler(intptr_t module_index, NameRef name, intptr_t type_index, intptr_t& r_index);
extern "C" void EmitImportedSyntax(intptr_t p_module_index, NameRef p_name, intptr_t p_type_index, intptr_t& r_index);
extern "C" void EmitExportedDefinition(intptr_t index);
extern "C" void EmitDefinitionIndex(const char *type, intptr_t& r_index);
extern "C" void EmitTypeDefinition(intptr_t index, PositionRef position, NameRef name, intptr_t type_index);
extern "C" void EmitConstantDefinition(intptr_t p_index, PositionRef p_position, NameRef p_name, intptr_t p_const_index);
extern "C" void EmitVariableDefinition(intptr_t index, PositionRef position, NameRef name, intptr_t type_index);
extern "C" void EmitBeginHandlerDefinition(intptr_t index, PositionRef position, NameRef name, intptr_t type_index);
extern "C" void EmitBeginUnsafeHandlerDefinition(intptr_t index, PositionRef position, NameRef name, intptr_t type_index);
extern "C" void EmitEndHandlerDefinition(void);
extern "C" void EmitForeignHandlerDefinition(intptr_t index, PositionRef position, NameRef name, intptr_t type_index, intptr_t binding);
extern "C" void EmitEventDefinition(intptr_t p_index, PositionRef p_position, NameRef p_name, intptr_t p_type_index);
extern "C" void EmitPropertyDefinition(intptr_t p_index, PositionRef p_position, NameRef p_name, intptr_t setter, intptr_t getter);
extern "C" void EmitBeginSyntaxDefinition(intptr_t p_index, PositionRef p_position, NameRef p_name);
extern "C" void EmitEndSyntaxDefinition(void);
extern "C" void EmitBeginSyntaxMethod(intptr_t p_handler_index);
extern "C" void EmitEndSyntaxMethod(void);
extern "C" void EmitUndefinedSyntaxMethodArgument(void);
extern "C" void EmitTrueSyntaxMethodArgument(void);
extern "C" void EmitFalseSyntaxMethodArgument(void);
extern "C" void EmitInputSyntaxMethodArgument(void);
extern "C" void EmitOutputSyntaxMethodArgument(void);
extern "C" void EmitContextSyntaxMethodArgument(void);
extern "C" void EmitIteratorSyntaxMethodArgument(void);
extern "C" void EmitContainerSyntaxMethodArgument(void);
extern "C" void EmitIntegerSyntaxMethodArgument(intptr_t p_int);
extern "C" void EmitRealSyntaxMethodArgument(intptr_t p_double);
extern "C" void EmitStringSyntaxMethodArgument(intptr_t p_string);
extern "C" void EmitVariableSyntaxMethodArgument(intptr_t p_index);
extern "C" void EmitIndexedVariableSyntaxMethodArgument(intptr_t p_var_index, intptr_t p_element_index);
extern "C" void EmitBeginDefinitionGroup(void);
extern "C" void EmitContinueDefinitionGroup(intptr_t index);
extern "C" void EmitEndDefinitionGroup(intptr_t *r_index);
extern "C" void EmitDefinedType(intptr_t index, intptr_t& r_type_index);
extern "C" void EmitForeignType(intptr_t binding, intptr_t& r_type_index);
extern "C" void EmitNamedType(NameRef module_name, NameRef name, intptr_t& r_new_index);
extern "C" void EmitAliasType(NameRef name, intptr_t typeindex, intptr_t& r_new_index);
extern "C" void EmitOptionalType(intptr_t index, intptr_t& r_new_index);
extern "C" void EmitAnyType(intptr_t& r_new_index);
extern "C" void EmitBooleanType(intptr_t& r_new_index);
extern "C" void EmitIntegerType(intptr_t& r_new_index);
extern "C" void EmitRealType(intptr_t& r_new_index);
extern "C" void EmitNumberType(intptr_t& r_new_index);
extern "C" void EmitStringType(intptr_t& r_new_index);
extern "C" void EmitDataType(intptr_t& r_new_index);
extern "C" void EmitArrayType(intptr_t& r_new_index);
extern "C" void EmitListType(intptr_t& r_new_index);
extern "C" void EmitUndefinedType(intptr_t& r_new_index);
extern "C" void EmitBeginRecordType(void);
extern "C" void EmitRecordTypeField(NameRef name, intptr_t type_index);
extern "C" void EmitEndRecordType(intptr_t& r_type_index);
extern "C" void EmitBeginHandlerType(intptr_t return_type_index);
extern "C" void EmitBeginForeignHandlerType(intptr_t return_type_index);
extern "C" void EmitHandlerTypeInParameter(NameRef name, intptr_t type_index);
extern "C" void EmitHandlerTypeOutParameter(NameRef name, intptr_t type_index);
extern "C" void EmitHandlerTypeInOutParameter(NameRef name, intptr_t type_index);
extern "C" void EmitHandlerTypeVariadicParameter(NameRef name);
extern "C" void EmitEndHandlerType(intptr_t& r_index);
extern "C" void EmitHandlerParameter(NameRef name, intptr_t type_index, intptr_t& r_index);
extern "C" void EmitHandlerVariable(NameRef name, intptr_t type_index, intptr_t& r_index);
extern "C" void EmitDeferLabel(intptr_t& r_label);
extern "C" void EmitResolveLabel(intptr_t label);
extern "C" void EmitCreateRegister(intptr_t& r_regindex);
extern "C" void EmitDestroyRegister(intptr_t regindex);
extern "C" void EmitBeginOpcode(intptr_t opcode);
extern "C" void EmitContinueOpcode(intptr_t argument);
extern "C" void EmitEndOpcode(void);
extern "C" void EmitJump(intptr_t label);
extern "C" void EmitJumpIfTrue(intptr_t reg, intptr_t label);
extern "C" void EmitJumpIfFalse(intptr_t reg, intptr_t label);
extern "C" void EmitPushRepeatLabels(intptr_t next, intptr_t exit);
extern "C" void EmitPopRepeatLabels(void);
extern "C" void EmitCurrentRepeatLabels(intptr_t& r_next, intptr_t& r_exit);
extern "C" void EmitBeginCall(intptr_t index, intptr_t resultreg);
extern "C" void EmitBeginIndirectCall(intptr_t reg, intptr_t resultreg);
extern "C" void EmitContinueCall(intptr_t reg);
extern "C" void EmitEndCall(void);
extern "C" void EmitBeginInvoke(intptr_t index, intptr_t contextreg, intptr_t resultreg);
extern "C" void EmitBeginIndirectInvoke(intptr_t handlerreg, intptr_t contextreg, intptr_t resultreg);
extern "C" void EmitContinueInvoke(intptr_t reg);
extern "C" void EmitEndInvoke(void);
extern "C" void EmitAssign(intptr_t dst, intptr_t src);
extern "C" void EmitAssignConstant(intptr_t dst, intptr_t constidx);
extern "C" void EmitUndefinedConstant(intptr_t *idx);
extern "C" void EmitTrueConstant(intptr_t *idx);
extern "C" void EmitFalseConstant(intptr_t *idx);
extern "C" void EmitIntegerConstant(intptr_t value, intptr_t *idx);
extern "C" void EmitUnsignedIntegerConstant(uintptr_t value, intptr_t *idx);
extern "C" void EmitRealConstant(intptr_t value, intptr_t *idx);
extern "C" void EmitStringConstant(intptr_t value, intptr_t *idx);
extern "C" void EmitBeginListConstant(void);
extern "C" void EmitContinueListConstant(intptr_t idx);
extern "C" void EmitEndListConstant(intptr_t *idx);
extern "C" void EmitBeginArrayConstant(void);
extern "C" void EmitContinueArrayConstant(intptr_t key_idx, intptr_t value_idx);
extern "C" void EmitEndArrayConstant(intptr_t *idx);
extern "C" void EmitBeginAssignList(intptr_t reg);
extern "C" void EmitContinueAssignList(intptr_t reg);
extern "C" void EmitEndAssignList(void);
extern "C" void EmitBeginAssignArray(intptr_t reg);
extern "C" void EmitContinueAssignArray(intptr_t reg);
extern "C" void EmitEndAssignArray(void);
extern "C" void EmitFetch(intptr_t reg, intptr_t var, intptr_t level);
extern "C" void EmitStore(intptr_t reg, intptr_t var, intptr_t level);
extern "C" void EmitReturn(intptr_t reg);
extern "C" void EmitReturnNothing(void);
extern "C" void EmitReset(intptr_t reg);
extern "C" void EmitAttachRegisterToExpression(intptr_t reg, intptr_t expr);
extern "C" void EmitDetachRegisterFromExpression(intptr_t expr);
extern "C" int EmitGetRegisterAttachedToExpression(intptr_t expr, intptr_t *reg);
extern "C" void EmitPosition(PositionRef position);
extern "C" void OutputBeginManifest(void);
extern "C" int IsBootstrapCompile(void);
extern "C" int IsNotBytecodeOutput(void);
extern "C" int ForceCBindingsAsBuiltins(void);
extern "C" void DependStart(void);
extern "C" void DependFinish(void);
extern "C" void DependDefineMapping(NameRef module_name, const char *source_file);
extern "C" void DependDefineDependency(NameRef module_name, NameRef dependency_name);
extern "C" int BytecodeEnumerate(intptr_t index, intptr_t *r_name);
extern "C" int BytecodeLookup(intptr_t name, intptr_t *r_opcode);
extern "C" void BytecodeDescribe(intptr_t opcode, intptr_t *r_name);
extern "C" int BytecodeIsValidArgumentCount(intptr_t opcode, intptr_t count);
extern "C" void BytecodeDescribeParameter(intptr_t opcode, intptr_t index, intptr_t *r_type);
//////////
struct AttachedReg
{
AttachedReg *next;
intptr_t expr;
intptr_t reg;
};
static AttachedReg *s_attached_regs = nil;
void EmitCheckNoRegisters(void);
//////////
//static MCTypeInfoRef *s_typeinfos = nil;
//static uindex_t s_typeinfo_count = 0;
static MCNameRef to_mcnameref(NameRef p_name)
{
const char *t_cstring;
GetStringOfNameLiteral(p_name, &t_cstring);
/* Names _may_ contain non-ASCII characters. Therefore interpret
* them as UTF-8. This is particularly important for properties,
* for example, which generate a name but via a string literal. */
MCAutoStringRef t_string;
MCStringCreateWithBytes(reinterpret_cast<const byte_t *>(t_cstring),
(uindex_t)strlen(t_cstring), kMCStringEncodingUTF8,
false, &t_string);
MCNameRef t_name;
MCNameCreate(*t_string, t_name);
return t_name;
}
static const char *
cstring_from_nameref(NameRef p_name)
{
const char *t_cstring;
GetStringOfNameLiteral(p_name, &t_cstring);
return t_cstring;
}
static NameRef
nameref_from_cstring(const char *p_cstring)
{
NameRef t_name;
MakeNameLiteral(p_cstring, &t_name);
return t_name;
}
static MCStringRef to_mcstringref(intptr_t p_string)
{
MCAutoStringRef t_string;
MCStringCreateWithBytes(reinterpret_cast<const byte_t *>(p_string),
(uindex_t)strlen(reinterpret_cast<const char *>(p_string)),
kMCStringEncodingUTF8, false, &t_string);
MCAutoStringRef t_uniq_string;
MCValueInter(*t_string, &t_uniq_string);
return t_uniq_string.Take();
}
static NameRef nameref_from_mcstringref(MCStringRef p_string)
{
MCAutoPointer<char> t_utf8_string;
MCStringConvertToUTF8String(p_string, &t_utf8_string);
NameRef t_name;
MakeNameLiteral(*t_utf8_string, &t_name);
return t_name;
}
//////////
static MCScriptModuleBuilderRef s_builder;
static NameRef s_module_name;
static NameRef *s_ordered_modules = NULL;
static unsigned int s_ordered_module_count;
static FILE *s_output_code_file = NULL;
static const char *s_output_code_filename = NULL;
//////////
struct CompiledModule
{
CompiledModule *next;
NameRef name;
byte_t *bytecode;
size_t bytecode_len;
};
static CompiledModule *s_compiled_modules = NULL;
//////////
struct EmittedModule
{
EmittedModule *next;
NameRef name;
char *modified_name;
bool has_foreign : 1;
};
static EmittedModule *s_emitted_modules = NULL;
static void EmittedModuleAdd(NameRef p_module_name, char *p_modified_name)
{
EmittedModule *t_mod;
t_mod = (EmittedModule *)Allocate(sizeof(EmittedModule));
t_mod -> next = s_emitted_modules;
t_mod -> name = p_module_name;
t_mod -> modified_name = p_modified_name;
s_emitted_modules = t_mod;
}
static bool EmitEmittedModules(void)
{
if (!OutputFileAsC)
{
return true;
}
FILE *t_file = s_output_code_file;
if (nullptr == t_file)
{
return false;
}
for(EmittedModule *t_module = s_emitted_modules; t_module != nullptr; t_module = t_module->next)
{
const char *t_modified_name = t_module->modified_name;
if (0 > fprintf(t_file,
"static __builtin_module_info __%s_module_info =\n{\n 0,\n 0,\n %s_module_data,\n sizeof(%s_module_data),\n",
t_modified_name,
t_modified_name,
t_modified_name))
return false;
if (!ForceCBindingsAsBuiltins())
{
if (0 > fprintf(t_file,
" %s_Initialize,\n %s_Finalize,\n",
t_modified_name,
t_modified_name))
return false;
}
else
{
if (0 > fprintf(t_file,
" nullptr,\n nullptr,\n"))
return false;
}
if (0 > fprintf(t_file,
" __builtin_ordinal_map\n};\n__builtin_module_loader __%s_loader(&__%s_module_info);\n\n",
t_modified_name,
t_modified_name))
return false;
}
return true;
}
//////////
struct EmittedBuiltin
{
EmittedBuiltin *next;
NameRef name;
uindex_t ordinal;
MCStringRef ordinal_stringref;
MCScriptForeignPrimitiveType return_type;
uindex_t parameter_count;
MCScriptForeignPrimitiveType *parameter_types;
};
static EmittedBuiltin *s_emitted_builtins = nullptr;
static uindex_t s_emitted_builtin_count = 0;
static MCStringRef EmittedBuiltinAdd(NameRef p_symbol_name, uindex_t p_type_index, bool p_force)
{
if (!p_force && (!OutputFileAsC || OutputFileAsAuxC))
{
return MCNameGetString(to_mcnameref(p_symbol_name));
}
/* If this is a parameterized foriegn type, then don't shim it */
if (p_type_index == UINDEX_MAX &&
strchr(cstring_from_nameref(p_symbol_name), ':') != NULL)
{
return MCNameGetString(to_mcnameref(p_symbol_name));
}
for(EmittedBuiltin *t_builtin = s_emitted_builtins; t_builtin != nullptr; t_builtin = t_builtin->next)
{
if (t_builtin->name == p_symbol_name)
{
return t_builtin->ordinal_stringref;
}
}
EmittedBuiltin *t_builtin;
t_builtin = (EmittedBuiltin *)Allocate(sizeof(EmittedBuiltin));
t_builtin -> next = s_emitted_builtins;
t_builtin -> name = p_symbol_name;
t_builtin -> ordinal = s_emitted_builtin_count;
if (p_type_index != UINDEX_MAX)
{
t_builtin->return_type = MCScriptQueryForeignHandlerReturnTypeInModule(s_builder, p_type_index);
t_builtin->parameter_count = MCScriptQueryForeignHandlerParameterCountInModule(s_builder, p_type_index);
t_builtin->parameter_types = new MCScriptForeignPrimitiveType[t_builtin->parameter_count];
for(uindex_t i = 0; i < t_builtin->parameter_count; i++)
{
t_builtin->parameter_types[i] = MCScriptQueryForeignHandlerParameterTypeInModule(s_builder, p_type_index, i);
}
}
else
{
t_builtin->return_type = kMCScriptForeignPrimitiveTypePointer;
t_builtin->parameter_count = 0;
t_builtin->parameter_types = nullptr;
}
char t_ordinal_str[32];
sprintf(t_ordinal_str, "%u", t_builtin->ordinal);
t_builtin->ordinal_stringref = to_mcstringref((intptr_t)t_ordinal_str);
s_emitted_builtins = t_builtin;
s_emitted_builtin_count++;
return t_builtin->ordinal_stringref;
};
#define DEFINE_PRIMITIVE_TYPE_MAPPING(PType, CType) \
{ kMCScriptForeignPrimitiveType##PType, #CType },
static struct { MCScriptForeignPrimitiveType type; const char *ctype; } s_primitive_type_map[] =
{
DEFINE_PRIMITIVE_TYPE_MAPPING(Unknown, void)
DEFINE_PRIMITIVE_TYPE_MAPPING(Void, void)
DEFINE_PRIMITIVE_TYPE_MAPPING(Pointer, void*)
DEFINE_PRIMITIVE_TYPE_MAPPING(SInt8, int8_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(UInt8, uint8_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(SInt16, int16_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(UInt16, uint16_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(SInt32, int32_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(UInt32, uint32_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(SInt64, int64_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(UInt64, uint64_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(SIntSize, ssize_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(UIntSize, size_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(SIntPtr, intptr_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(UIntPtr, uintptr_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(Float32, float)
DEFINE_PRIMITIVE_TYPE_MAPPING(Float64, double)
DEFINE_PRIMITIVE_TYPE_MAPPING(CBool, bool)
DEFINE_PRIMITIVE_TYPE_MAPPING(CChar, char)
DEFINE_PRIMITIVE_TYPE_MAPPING(CSChar, signed char)
DEFINE_PRIMITIVE_TYPE_MAPPING(CUChar, unsigned char)
DEFINE_PRIMITIVE_TYPE_MAPPING(CSShort, signed short)
DEFINE_PRIMITIVE_TYPE_MAPPING(CUShort, unsigned short)
DEFINE_PRIMITIVE_TYPE_MAPPING(CSInt, signed int)
DEFINE_PRIMITIVE_TYPE_MAPPING(CUInt, unsigned int)
DEFINE_PRIMITIVE_TYPE_MAPPING(CSLong, signed long)
DEFINE_PRIMITIVE_TYPE_MAPPING(CULong, unsigned long)
DEFINE_PRIMITIVE_TYPE_MAPPING(CSLongLong, signed long long)
DEFINE_PRIMITIVE_TYPE_MAPPING(CULongLong, unsigned long long)
DEFINE_PRIMITIVE_TYPE_MAPPING(CFloat, float)
DEFINE_PRIMITIVE_TYPE_MAPPING(CDouble, double)
DEFINE_PRIMITIVE_TYPE_MAPPING(SInt, int32_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(UInt, uint32_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(NaturalUInt, natural_uint_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(NaturalSInt, natural_sint_t)
DEFINE_PRIMITIVE_TYPE_MAPPING(NaturalFloat, natural_float_t)
};
#undef DEFINE_PRIMITIVE_TYPE_MAPPING
static const char *CTypeFromPrimitiveType(MCScriptForeignPrimitiveType p_type)
{
if (p_type == kMCScriptForeignPrimitiveTypeUnknown)
{
Fatal_InternalInconsistency("type bound in foreign handler unknown");
return nullptr;
}
if (s_primitive_type_map[p_type].type != p_type)
{
Fatal_InternalInconsistency("s_primitive_type_map out of order");
return nullptr;
}
return s_primitive_type_map[p_type].ctype;
}
static bool EmitEmittedBuiltins(void)
{
if (!OutputFileAsC)
{
return true;
}
FILE *t_file = s_output_code_file;
if (nullptr == t_file)
{
return false;
}
MCAutoArray<EmittedBuiltin*> t_builtins;
if (!t_builtins.Resize(s_emitted_builtin_count))
{
return false;
}
for(EmittedBuiltin *t_builtin = s_emitted_builtins; t_builtin != nullptr; t_builtin = t_builtin->next)
{
t_builtins[t_builtin->ordinal] = t_builtin;
}
// Emit builtin symbol external references
if (0 > fprintf(t_file, "\n"))
{
return false;
}
for(uindex_t i = 0; i < s_emitted_builtin_count; i++)
{
/* Generate extern for original function */
if (0 > fprintf(t_file,
"extern \"C\" %s %s(",
CTypeFromPrimitiveType(t_builtins[i]->return_type),
cstring_from_nameref(t_builtins[i]->name)))
{
return false;
}
for(uindex_t t_arg_index = 0; t_arg_index < t_builtins[i]->parameter_count; t_arg_index++)
{
if (0 > fprintf(t_file,
"%s%s",
t_arg_index > 0 ? ", " : "",
CTypeFromPrimitiveType(t_builtins[i]->parameter_types[t_arg_index])))
{
return false;
}
}
if (0 > fprintf(t_file,
");\n"))
{
return false;
}
/* Generate shim around original function */
if (0 > fprintf(t_file,
"static void shim__%s(void *rv, void **av)\n{\n",
cstring_from_nameref(t_builtins[i]->name)))
{
return false;
}
if (t_builtins[i]->return_type != kMCScriptForeignPrimitiveTypeVoid)
{
if (0 > fprintf(t_file,
"\t*(%s *)rv =",
CTypeFromPrimitiveType(t_builtins[i]->return_type)))
{
return false;
}
}
if (0 > fprintf(t_file,
"%s(",
cstring_from_nameref(t_builtins[i]->name)))
{
return false;
}
for(uindex_t t_arg_index = 0; t_arg_index < t_builtins[i]->parameter_count; t_arg_index++)
{
if (0 > fprintf(t_file,
"%s*(%s *)av[%d]",
t_arg_index > 0 ? ", " : "",
CTypeFromPrimitiveType(t_builtins[i]->parameter_types[t_arg_index]),
t_arg_index))
{
return false;
}
}
if (0 > fprintf(t_file,
");\n}\n\n"))
{
return false;
}
}
// Emit builtin ordinal mapping array
if (0 > fprintf(t_file, "static __builtin_shim_type __builtin_ordinal_map[] =\n{\n"))
{
return false;
}
for(uindex_t i = 0; i < s_emitted_builtin_count; i++)
{
if (0 > fprintf(t_file, "\tshim__%s,\n", cstring_from_nameref(t_builtins[i]->name)))
{
return false;
}
}
if (0 > fprintf(t_file, "\tnullptr\n};\n\n"))
{
return false;
}
return true;
}
//////////
static const char *kOutputCDefinitions =
"#include <stdint.h>\n"
"#include <stddef.h>\n\n"
"#if UINTPTR_MAX == 0xffffffff\n"
"typedef uint32_t natural_uint_t;\n"
"typedef int32_t natural_sint_t;\n"
"typedef float natural_float_t;\n"
"#elif UINTPTR_MAX == 0xffffffffffffffff\n"
"typedef uint64_t natural_uint_t;\n"
"typedef int64_t natural_sint_t;\n"
"typedef double natural_float_t;\n"
"#endif\n\n"
"typedef void (*__builtin_shim_type)(void*, void**);\n"
"struct __builtin_module_info\n"
"{\n"
" void *next;\n"
" void *handle;\n"
" unsigned char *data;\n"
" unsigned long length;\n"
" bool (*initializer)();\n"
" void (*finalizer)();\n"
" __builtin_shim_type *builtins;\n"
"};\n"
"extern \"C\" void MCScriptRegisterBuiltinModule(__builtin_module_info *desc);\n"
"class __builtin_module_loader\n"
"{\n"
"public:\n"
" __builtin_module_loader(__builtin_module_info *p_desc)\n"
" {\n"
" MCScriptRegisterBuiltinModule(p_desc);\n"
" }\n"
"};\n\n";
static void BuildBuiltinModule(void);
void EmitStart(void)
{
MCInitialize();
s_output_code_file = OpenOutputCodeFile(&s_output_code_filename);
s_emitted_modules = NULL;
if (s_output_code_file != NULL)
{
if (fprintf(s_output_code_file, "%s", kOutputCDefinitions) < 0)
goto error_cleanup;
if (OutputFileAsC &&
!OutputFileAsAuxC)
BuildBuiltinModule();
}
return;
error_cleanup:
if (nil != s_output_code_file)
{
fclose (s_output_code_file);
s_output_code_file = NULL;
}
Error_CouldNotWriteOutputFile (s_output_code_filename);
}
static void __EmitModuleOrder(NameRef p_name)
{
for(unsigned int i = 0; i < s_ordered_module_count; i++)
if (IsNameEqualToName(p_name, s_ordered_modules[i]))
return;
s_ordered_modules = (NameRef *)Reallocate(s_ordered_modules, sizeof(NameRef) * (s_ordered_module_count + 1));
s_ordered_modules[s_ordered_module_count++] = p_name;
}
static bool
EmitCompiledModules (void)
{
const char *t_filename = nil;
FILE *t_file = OpenOutputBytecodeFile (&t_filename);
if (nil == t_file)
goto error_cleanup;
while(s_compiled_modules != nullptr)
{
size_t t_written;
t_written = fwrite (s_compiled_modules->bytecode, sizeof(byte_t), s_compiled_modules->bytecode_len, t_file);
if (t_written != s_compiled_modules->bytecode_len)
goto error_cleanup;
s_compiled_modules = s_compiled_modules->next;
}
fflush (t_file);
fclose (t_file);
return true;
error_cleanup:
if (nil != t_file)
fclose (t_file);
Error_CouldNotWriteOutputFile (t_filename);
return false;
}
void EmitFinish(void)
{
if (s_compiled_modules != NULL &&
!EmitCompiledModules())
{
goto error_cleanup;
}
if (!EmitEmittedBuiltins())
{
goto error_cleanup;
}
if (!EmitEmittedModules())
{
goto error_cleanup;
}
if (nil != s_output_code_file)
{
fclose (s_output_code_file);
s_output_code_file = NULL;
}
return;
error_cleanup:
if (nil != s_output_code_file)
{
fclose (s_output_code_file);
s_output_code_file = NULL;
}
Error_CouldNotWriteOutputFile (s_output_code_filename);
}
void EmitBeginModule(NameRef p_name, intptr_t& r_index)
{
MCInitialize();
Debug_Emit("BeginModule(%s) -> 0", cstring_from_nameref(p_name));
s_module_name = p_name;
MCScriptBeginModule(kMCScriptModuleKindNone, to_mcnameref(p_name), s_builder);
r_index = 0;
}
void EmitBeginWidgetModule(NameRef p_name, intptr_t& r_index)
{
MCInitialize();
Debug_Emit("BeginWidgetModule(%s) -> 0", cstring_from_nameref(p_name));
s_module_name = p_name;
MCScriptBeginModule(kMCScriptModuleKindWidget, to_mcnameref(p_name), s_builder);
r_index = 0;
}
void EmitBeginLibraryModule(NameRef p_name, intptr_t& r_index)
{
MCInitialize();
Debug_Emit("BeginLibraryModule(%s) -> 0", cstring_from_nameref(p_name));
s_module_name = p_name;
MCScriptBeginModule(kMCScriptModuleKindLibrary, to_mcnameref(p_name), s_builder);
r_index = 0;
}
static bool
EmitEndModuleGetByteCodeBuffer (byte_t*& r_bytecode, size_t& r_bytecode_len)
{
MCAutoValueRefBase<MCStreamRef> t_stream;
MCMemoryOutputStreamCreate (&t_stream);
if (!MCScriptEndModule (s_builder, *t_stream))
goto error_cleanup;
void *t_bytecode;
size_t t_bytecode_len;
MCMemoryOutputStreamFinish (*t_stream,
t_bytecode,
t_bytecode_len);
MCAssert (t_bytecode_len <= UINDEX_MAX);
r_bytecode = (byte_t*)t_bytecode;
r_bytecode_len = t_bytecode_len;
return true;
error_cleanup:
Error_CouldNotGenerateBytecode();
return false;
}
static bool
EmitEndModuleOutputC (NameRef p_module_name,
const char *p_module_name_string,
const byte_t *p_bytecode,
size_t p_bytecode_len)
{
char *t_modified_name = nil;
FILE *t_file = nil;
t_file = s_output_code_file;
if (nil == t_file)
goto error_cleanup;
t_modified_name = strdup(p_module_name_string);
if (nil == t_modified_name)
goto error_cleanup;
for(int i = 0; t_modified_name[i] != '\0'; i++)
if (t_modified_name[i] == '.')
t_modified_name[i] = '_';
if (!ForceCBindingsAsBuiltins())
{
// Emit the initializer reference.
if (0 > fprintf(s_output_code_file,
"extern \"C\" bool %s_Initialize(void);\n",
t_modified_name))
goto error_cleanup;
// Emit the finalizer reference.
if (0 > fprintf(s_output_code_file,
"extern \"C\" void %s_Finalize(void);\n",
t_modified_name))
goto error_cleanup;
}
if (0 > fprintf(t_file, "static unsigned char %s_module_data[] = {", t_modified_name))
goto error_cleanup;
for(size_t i = 0; i < p_bytecode_len; i++)
{
if ((i % 16) == 0)
if (0 > fprintf(t_file, "\n"))
goto error_cleanup;
if (0 > fprintf(t_file, "0x%02x, ", ((unsigned char *)p_bytecode)[i]))
goto error_cleanup;
}
if (0 > fprintf(t_file, "};\n"))
goto error_cleanup;
EmittedModuleAdd(p_module_name, t_modified_name);
fflush (t_file);
return true;
error_cleanup:
free (t_modified_name);
if (nil != s_output_code_file)
{
fclose (s_output_code_file);
s_output_code_file = NULL;
}
Error_CouldNotWriteOutputFile (s_output_code_filename);
return false;
}
static bool
EmitEndModuleGetInterfaceBuffer (const byte_t *p_bytecode,
const size_t p_bytecode_len,
MCAutoByteArray & r_interface)
{
MCAutoValueRefBase<MCStreamRef> t_stream;
MCAutoScriptModuleRef t_module;
MCAutoValueRefBase<MCStreamRef> t_output_stream;
void *t_interface = nil;
size_t t_interface_len = 0;
if (!MCMemoryInputStreamCreate(p_bytecode, p_bytecode_len, &t_stream))
goto error_cleanup;
if (!MCScriptCreateModuleFromStream(*t_stream, &t_module))
goto error_cleanup;
if (!MCMemoryOutputStreamCreate(&t_output_stream))
goto error_cleanup;
if (!MCScriptWriteInterfaceOfModule(*t_module, *t_output_stream))
goto error_cleanup;
if (!MCMemoryOutputStreamFinish(*t_output_stream,
t_interface, t_interface_len))
goto error_cleanup;
MCAssert (t_interface_len <= UINDEX_MAX);
r_interface.Give ((byte_t *) t_interface, (uindex_t)t_interface_len);
return true;
error_cleanup:
Error_CouldNotGenerateInterface();
return false;
}
static bool
EmitEndModuleOutputInterface (const char *p_module_name,
const byte_t *p_interface,
size_t p_interface_len)
{
char *t_filename = nil;
FILE *t_import = nil;
t_import = OpenImportedModuleFile(p_module_name, &t_filename);
if (nil == t_import)
goto error_cleanup;
size_t t_written;
t_written = fwrite (p_interface, sizeof(byte_t), p_interface_len, t_import);
if (t_written != p_interface_len)
goto error_cleanup;
fflush (t_import);
fclose (t_import);
free (t_filename);
return true;
error_cleanup:
if (nil != t_import)
fclose (t_import);
Error_CouldNotWriteInterfaceFile(t_filename);
free (t_filename);
return false;
}
void
EmitEndModule (void)
{
const char *t_module_string = nil;
byte_t *t_bytecode_buf = nil;
size_t t_bytecode_len = 0;
MCAutoByteArray t_interface;
const byte_t *t_interface_buf = nil;
size_t t_interface_len = 0;
Debug_Emit("EndModule()");
__EmitModuleOrder(s_module_name);
GetStringOfNameLiteral(s_module_name, &t_module_string);
MCAssert (nil != t_module_string);
/* ---------- 1. Get bytecode */
if (!EmitEndModuleGetByteCodeBuffer (t_bytecode_buf, t_bytecode_len))
goto cleanup;
/* ---------- 2. Output module contents */
if (OutputFileAsC)
{
if (!EmitEndModuleOutputC (s_module_name, t_module_string,
t_bytecode_buf, t_bytecode_len))
goto cleanup;
}
else if (OutputFileAsBytecode)
{
CompiledModule *t_cmodule = (CompiledModule*)Allocate(sizeof(CompiledModule));
t_cmodule->next = s_compiled_modules;
t_cmodule->name = s_module_name;
t_cmodule->bytecode = t_bytecode_buf;
t_cmodule->bytecode_len = t_bytecode_len;
s_compiled_modules = t_cmodule;
}
/* ---------- 3. Output module interface */
if (!EmitEndModuleGetInterfaceBuffer (t_bytecode_buf, t_bytecode_len,
t_interface))
goto cleanup;
t_interface_buf = t_interface.Bytes();
t_interface_len = t_interface.ByteCount();
if (!EmitEndModuleOutputInterface (t_module_string,
t_interface_buf, t_interface_len))
goto cleanup;