-
Notifications
You must be signed in to change notification settings - Fork 30
/
ObxCGen2.cpp
4167 lines (3927 loc) · 148 KB
/
ObxCGen2.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
/*
* Copyright 2021 Rochus Keller <mailto:me@rochus-keller.ch>
*
* This file is part of the Oberon+ parser/compiler library.
*
* The following is the license that applies to this copy of the
* library. For a license to use the library under conditions
* other than those described here, please email to me@rochus-keller.ch.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General Public
* License (GPL) versions 2.0 or 3.0 as published by the Free Software
* Foundation and appearing in the file LICENSE.GPL included in
* the packaging of this file. Please review the following information
* to ensure GNU General Public Licensing requirements will be met:
* http://www.fsf.org/licensing/licenses/info/GPLv2.html and
* http://www.gnu.org/copyleft/gpl.html.
*/
#include "ObxCGen2.h"
#include "ObxAst.h"
#include "ObErrors.h"
#include "ObxProject.h"
#include <QtDebug>
#include <QFile>
#include <QDir>
#include <QCryptographicHash>
#include <QCoreApplication>
#include <QDateTime>
#include <QBuffer>
using namespace Obx;
using namespace Ob;
#ifndef OBX_AST_DECLARE_SET_METATYPE_IN_HEADER
Q_DECLARE_METATYPE( Obx::Literal::SET )
#endif
#define _OBX_FUNC_SEQ_POINT_
/* The concept ($t1 = object)->func($t1) correctly works on all compilers and platforms tested so far,
* also interleaved applications of the concept like ($t1 = object)->func($t1, ($t2 = object2)->func2($t2) )
* properly work. I neither came across a situation since I wrote my first C program in the eighties where
* this was suspected not to work. Unfortunately the unspecified evaluation order in the C99 standard includes the
* function designator (not only the order of arguments). So theoretically the function argument $t1 could
* be evaluated before the assignment $t1 = object. This define enables a version with an additional indirection
* and comma expression like ($t2 = ($t1 = object)->func, $t2($t1)) so that there is an explicit sequence point
* between the evaluation of the function designator and the evaluation of the arguments. The additional performance
* cost is neglible, so we can just leave it enabled.
*/
/* NOTE: unsafe arrays are treated the same way as regular arrays
* only parameters and return values are normal C types
*/
struct ObxCGenCollector : public AstVisitor
{
QList<Procedure*> allProcs;
QList<Record*> allRecords;
Module* thisMod;
void collect(Type* t)
{
switch( t->getTag() )
{
case Thing::T_Array:
collect(cast<Array*>(t)->d_type.data());
break;
case Thing::T_Record:
{
Record* r = cast<Record*>(t);
allRecords.append( r );
foreach( const Ref<Field>& f, r->d_fields )
{
collect(f->d_type.data());
}
if( r->d_base )
collect(r->d_base.data());
}
break;
case Thing::T_Pointer:
collect(cast<Pointer*>(t)->d_to.data());
break;
case Thing::T_ProcType:
{
ProcType* pt = cast<ProcType*>(t);
foreach( const Ref<Parameter>& p, pt->d_formals )
collect(p->d_type.data());
if( pt->d_return )
collect(pt->d_return.data());
}
break;
case Thing::T_QualiType:
break;
}
}
void collect( Named* n )
{
switch( n->getTag() )
{
case Thing::T_Procedure:
{
Procedure* p = cast<Procedure*>(n);
allProcs.append(cast<Procedure*>(n));
p->accept(this);
}
break;
case Thing::T_NamedType:
collect(n->d_type.data());
break;
case Thing::T_Variable:
case Thing::T_Parameter:
case Thing::T_LocalVar:
collect(n->d_type.data());
break;
}
}
void visit( Module* me )
{
thisMod = me;
foreach( const Ref<Named>& n, me->d_order )
collect(n.data());
}
void visit( Procedure* me)
{
foreach( const Ref<Named>& n, me->d_order )
collect(n.data());
}
};
struct ObxCGenImp : public AstVisitor
{
Errors* err;
Module* thisMod;
QByteArray modName;
int level;
QTextStream h,b;
QList<QPair<QString,QIODevice*> > overlay;
bool ownsErr;
bool debug; // generate line pragmas
quint32 anonymousDeclNr; // starts with one, zero is an invalid slot
Procedure* curProc;
Named* curVarDecl;
QSet<Record*> declToInline;
#ifdef _OBX_FUNC_SEQ_POINT_
struct Temp
{
QByteArray d_type;
ProcType* d_pt;
bool d_inUse;
Temp(const QByteArray& name = QByteArray(), ProcType* pt = 0, bool inUse = false ):d_type(name),d_pt(pt),d_inUse(inUse){}
};
QList<Temp> temps;
#else
QList<QPair<QByteArray,bool> > temps;
#endif
QList<int> sellLater;
ObxCGenImp():err(0),thisMod(0),ownsErr(false),level(0),debug(false),anonymousDeclNr(1),
curProc(0),curVarDecl(0){}
inline QByteArray ws() { return QByteArray(level*4,' '); }
#ifdef _OBX_FUNC_SEQ_POINT_
int buyTemp( const QByteArray& type, ProcType* pt = 0 )
{
for( int i = 0; i < temps.size(); i++ )
{
if( temps[i].d_type == type && !temps[i].d_inUse )
{
temps[i].d_inUse = true;
return i;
}
}
temps.append(Temp(type,pt,true));
return temps.size() - 1;
}
void sellTemp(int i, bool later = true) // if default false then crash with GCC 4.8 -O2
{
Q_ASSERT( i >= 0 && i < temps.size() );
if( later )
sellLater.append(i);
else
temps[i].d_inUse = false;
}
#else
int buyTemp( const QByteArray& type )
{
for( int i = 0; i < temps.size(); i++ )
{
if( temps[i].first == type && !temps[i].second )
{
temps[i].second = true;
return i;
}
}
temps.append(qMakePair(type,true));
return temps.size() - 1;
}
void sellTemp(int i, bool later = true )
{
Q_ASSERT( i >= 0 && i < temps.size() );
if( later )
sellLater.append(i);
else
temps[i].second = false;
}
#endif
void pushStream()
{
Q_ASSERT( b.device() );
overlay.push_back(qMakePair(QString(),b.device()));
b.setDevice(0);
b.setString(&overlay.back().first);
}
void popStream(bool write = false)
{
Q_ASSERT( !overlay.isEmpty() );
b.flush();
overlay.back().second->write(overlay.back().first.toUtf8());
b.setDevice(overlay.back().second);
overlay.pop_back();
}
void beginBody()
{
pushStream();
temps.clear();
}
void endBody()
{
Q_ASSERT( !overlay.isEmpty() );
b.flush();
QIODevice* park = overlay.back().second;
for(int i = 0; i < temps.size(); i++ )
{
#ifdef _OBX_FUNC_SEQ_POINT_
if( temps[i].d_pt )
park->write(ws() + formatProcType(temps[i].d_pt," $t" + QByteArray::number(i)) + ";\n" );
else
park->write(ws() + temps[i].d_type + " $t" + QByteArray::number(i) + ";\n" );
#else
park->write(ws() + temps[i].first + " $t" + QByteArray::number(i) + ";\n" );
#endif
}
popStream(true);
}
static QByteArray escape(const QByteArray& str)
{
static QSet<QByteArray> keywords;
if( keywords.isEmpty() )
{
keywords << "auto" << "break" << "case" << "char" << "const" << "continue" << "default"
<< "do" << "double" << "else" << "enum" << "extern" << "float" << "for" << "goto"
<< "if" << "inline" << "int" << "long" << "register" << "restrict" << "return" << "short"
<< "signed" << "sizeof" << "static" << "struct" << "switch" << "typedef" << "union"
<< "unsigned" << "void" << "volatile" << "while" << "_Bool" << "_Complex" << "_Imaginary"
<< "assert" << "main" << "fabs" << "fabsf" << "llabs" << "abs" << "floor" << "floorf"
<< "exit";
}
if( keywords.contains(str) )
return str + "_"; // avoid collision with C keywords
else
return str;
}
static void dedication(QTextStream& out)
{
out << "// Generated by " << qApp->applicationName() << " " << qApp->applicationVersion() << " on "
<< QDateTime::currentDateTime().toString(Qt::ISODate) << endl << endl;
}
static inline Type* derefed( Type* t )
{
if( t )
return t->derefed();
else
return 0;
}
QByteArray dottedName( Named* n, bool withModule = true )
{
// concatenate names up to but not including module
if( n->getTag() == Thing::T_Const )
{
Const* c = cast<Const*>(n);
Procedure* p = c->findProc();
if( p )
n = p;
}
QByteArray name = n->d_name; // TODO: check escape is done by callers
Named* scope = n->d_scope;
if( n->getTag() == Thing::T_Procedure )
{
Procedure* proc = cast<Procedure*>(n);
if( proc->d_receiverRec )
{
// if the scope is a bound proc follow its receiver, but first use the proc name.
// this is necessary because procs bound to different recs can have the same name and
// even have the same name as ordinary procs, so there is a risk of duplicate names when
// just following the normal scope
scope = proc->d_receiverRec->findDecl();
Q_ASSERT( scope );
}
}
if( scope )
{
const int tag = scope->getTag();
if( tag != Thing::T_Module )
{
return dottedName(scope) + "$" + name;
}else if( withModule )
return moduleRef(cast<Module*>(scope)) + "$" + name;
}
return name;
}
static QByteArray moduleRef(Module* m, char separator = '$')
{
QByteArray name = m->d_fullName.join(separator);
if( name.isEmpty() )
name = m->d_name; // happens with built-in modules like Out
if( !m->d_metaActuals.isEmpty() )
{
QCryptographicHash hash(QCryptographicHash::Md5);
hash.addData(m->formatMetaActuals());
name += separator + hash.result().toHex().left(10); // TODO
}
return escape(name);
}
static QByteArray fileName(Module* m)
{
return moduleRef(m,'.');
}
QByteArray classRef( Named* className )
{
Q_ASSERT( className && className->getTag() == Thing::T_NamedType );
Module* m = className->getModule();
return dottedName(className); // dotted because also records nested in procs are lifted to module level
}
QByteArray classRef( Type* rec )
{
return classRef(rec->toRecord());
}
QByteArray classRef( Record* r )
{
if( r->getBaseType() == Type::ANYREC )
return "OBX$Anyrec";
Named* n = r->findDecl();
if( n && n->getTag() == Thing::T_NamedType )
return classRef(n);
else
{
#ifdef _DEBUG
Q_ASSERT( r->d_slotValid );
#endif
if( n == 0 )
n = r->findDecl(true);
Module* m = n ? n->getModule() : 0;
if( m == 0 )
m = thisMod;
return moduleRef(m) + "$" + QByteArray::number(r->d_slot);
}
}
static inline bool passByRef( Parameter* p )
{
return p->d_var;
}
QByteArray formatFormals( ProcType* pt, bool withName = true, Parameter* receiver = 0 )
{
QByteArray res = "(";
if( pt->d_typeBound )
{
res += "void*" + ( withName && receiver ? " " + escape(receiver->d_name) : "" );
}
for( int i = 0; i < pt->d_formals.size(); i++ )
{
if( i != 0 || pt->d_typeBound )
res += ", ";
Type* t = pt->d_formals[i]->d_type.data();
Type* td = derefed(t);
Pointer p;
if( passByRef(pt->d_formals[i].data()) || td->getTag() == Thing::T_Array )
{
// TODO: avoid passing by ref when IN with non-structured types
t = &p;
p.d_to = pt->d_formals[i]->d_type.data();
p.d_decl = pt->d_formals[i].data();
p.d_loc = pt->d_formals[i]->d_loc;
}
res += formatType( t, withName ? escape(pt->d_formals[i]->d_name) : "" );
}
if( pt->d_varargs )
{
if( !pt->d_formals.isEmpty() )
res += ", ";
res += "...";
}
if( !pt->d_nonLocals.isEmpty() )
{
if( !pt->d_formals.isEmpty() )
res += ", ";
for( int i = 0; i < pt->d_nonLocals.size(); i++ )
{
if( i != 0 )
res += ", ";
Named* n = pt->d_nonLocals[i];
Type* t = n->d_type.data();
Type* td = derefed(t);
const int tag = td->getTag();
Pointer p;
if( tag == Thing::T_Array )
{
t = &p;
p.d_to = n->d_type.data();
p.d_decl = n;
p.d_loc = n->d_loc;
}
#if 0
res += formatType( t );
if( tag != Thing::T_Array )
res += "*";
if( withName )
res += " " + escape(n->d_name); // doesn't work with function pointers
#else
// this also works with function pointers
QByteArray name;
if( tag != Thing::T_Array )
name += "*";
if( withName )
name += " " + escape(n->d_name);
res += formatType( t, name );
#endif
}
}
res += ")";
return res;
}
QByteArray formatReturn( ProcType* pt, const QByteArray& residue )
{
QByteArray res;
if( pt->d_return.isNull() )
res = formatType(0,residue);
else
{
Type* t = pt->d_return.data();
Type* td = derefed(t);
Pointer p;
if( td->getTag() == Thing::T_Array )
{
t = &p;
p.d_to = pt->d_return.data();
p.d_decl = pt->d_decl;
p.d_loc = pt->d_return->d_loc;
}
res += formatType( t, residue );
}
return res;
}
inline static QByteArray formatBaseType(int t)
{
switch( t )
{
case Type::BYTE:
case Type::BOOLEAN:
return "uint8_t";
case Type::CHAR:
return "char";
case Type::WCHAR:
return "wchar_t";
case Type::INT8:
return "int8_t";
case Type::INT16:
return "int16_t";
case Type::INT32:
return "int32_t";
case Type::INT64:
return "int64_t";
case Type::REAL:
return "float";
case Type::LONGREAL:
return "double";
case Type::SET:
return "uint32_t";
case Type::CVOID:
return "void";
default:
return "?basetype?";
}
}
QByteArray arrayType(int dims, const RowCol& loc)
{
switch( dims )
{
case 1:
return "struct OBX$Array$1";
case 2:
return "struct OBX$Array$2";
case 3:
return "struct OBX$Array$3";
case 4:
return "struct OBX$Array$4";
case 5:
return "struct OBX$Array$5";
default:
err->error(Errors::Generator, Loc(loc,thisMod->d_file),
"C code generator cannot handle array dimensions > 5");
return "???";
}
}
QByteArray formatProcType( ProcType* pt, const QByteArray& name = QByteArray() )
{
return formatReturn(pt, "(*" + name + ")" + formatFormals(pt, false));
}
QByteArray formatType( Type* t, const QByteArray& name = QByteArray(),
bool comingFromPointer = false, bool forceUnsafe = false )
{
if( t == 0 )
return "void" + ( !name.isEmpty() ? " " + name : "" );
switch(t->getTag())
{
case Thing::T_BaseType:
return formatBaseType(t->getBaseType()) + ( !name.isEmpty() ? " " + name : "" );
case Thing::T_Enumeration:
return "int" + ( !name.isEmpty() ? " " + name : "" );
case Thing::T_Array:
/*
arrays or pointer to arrays can be the types of fields, variables, locals and parameters.
in general taking the address of an array is not supported, but with VAR/IN params an implicit
address is handed into the procedure; it still cannot be converted to a pointer though.
in contrast arrays can be dynamically created, even with a length not known at compile time.
we need a way to transport the dim/size of an array with the pointer. it's inefficient to explicitly
store these data with value arrays where it is known at compile time and invariant. with open
arrays (or VAR/IN parameter) it is unavoidable though. If we add this information to the array object
we obviously need two types of array objects, one with and one without dim/size information.
A possible solution is to add dim/size information to the pointer/var param value. the dim number
and type doens't change and is always known at compile time; so the pointer/var param could look
e.g. like struct { uint32_t $0; void* $a; } or struct { uint32_t $0,$1; void* $a; } etc.
if this information is in the array object instead we get a problem when passing either a value array
(which has no size info) or a dereferenced array pointer (whose object has size info) is passed
to a var parameter (the body of the proc has no clue which kind was passed).
NOTE this approach has some disadvantages: a) a lot of anonymous objects on stack which might be
difficult to follow by a M&S GC; b) parallel existence of structured (safe) array pointers and
plain unsafe array pointers, c) complexity because of size transfer etc. requiring e.g. the $ trick.
*/
{
Array* a = cast<Array*>(t);
if( a->d_type.isNull() )
return QByteArray(); // already reported
QByteArray res;
if( a->d_lenExpr.isNull() || name.isEmpty() )
res = "*" + ( !name.isEmpty() ? " " + name : "" );
else
{
res = name;
res += "[";
if( a->d_vla )
{
#if 0
pushStream();
a->d_lenExpr->accept(this);
const QByteArray tmp = overlay.back().first.toUtf8();
popStream();
res += tmp;
#else
QList<Array*> dims = a->getDims();
for( int i = 0; i < dims.size(); i++ )
{
if( i != 0 )
res += "][";
res += name + "$len[" + QByteArray::number(i) + "]";
}
res += "]";
return formatType( dims.last()->d_type.data(), res, false, forceUnsafe );
#endif
}else
res += QByteArray::number(a->d_len);
res += "]";
}
return formatType( a->d_type.data(), res, false, forceUnsafe );
}
break;
case Thing::T_Pointer:
{
Pointer* me = cast<Pointer*>(t);
if( me->d_to.isNull() )
break;
QByteArray res = "*" + ( !name.isEmpty() ? " " + name : "" );
Type* td = derefed(me->d_to.data());
if( td && td->getTag() == Thing::T_Array )
{
if( ( td->d_unsafe && thisMod->d_externC ) || forceUnsafe )
res = name; // pointer to array is equal to array in c
else
{
Array* a = cast<Array*>(td);
int dims = 0;
a->getTypeDim(dims);
res = arrayType(dims, t->d_loc);
res += ( !name.isEmpty() ? " " + name : "" );
return res;
}
}else if( td && td->getBaseType() == Type::ANYREC )
return "struct OBX$Anyrec*" + ( !name.isEmpty() ? " " + name : "");
// else
return formatType( me->d_to.data(), res, true, forceUnsafe );
}
break;
case Thing::T_ProcType:
{
ProcType* pt = cast<ProcType*>(t);
if( pt->d_typeBound )
return "struct OBX$Deleg" + ( !name.isEmpty() ? " " + name : "" );
return formatProcType(pt,name);
//return formatReturn(pt, "(*" + name + ")" + formatFormals(pt)); // fix for proc type returns
//const QByteArray returnType = formatType(pt->d_return.data());
//return returnType + " (*" + name + ")" + formatFormals(pt); // name can legally be empty
}
break;
case Thing::T_QualiType:
{
QualiType* me = cast<QualiType*>(t);
#if 0
Named* n = me->d_quali->getIdent();
if( n )
{
Module* m = n->getModule();
if( m )
return moduleRef(m) + "$" + dottedName(n);
else
return formatType(n->d_type.data());
}else
return "???";
#else
return formatType(me->d_quali->d_type.data(),name,comingFromPointer,forceUnsafe);
#endif
}
break;
case Thing::T_Record:
{
// create a local dummy struct with the same memory layout as the original struct, but avoiding
// the declaration order deadlock caused by mutual dependency of generic modules with the ones
// where the instantiated types are declared
Record* r = cast<Record*>(t);
if( !thisMod->d_metaActuals.isEmpty() && curVarDecl && declToInline.contains(r) && !comingFromPointer )
{
QByteArray res = (r->d_union ? "union /*" : "struct /*" ) + classRef(r) + "*/ { ";
if( !r->d_unsafe )
res += "void* class$; ";
QList<Field*> fields = r->getOrderedFields();
foreach( Field* f, fields )
res += formatType(f->d_type.data(), escape(f->d_name),false,forceUnsafe ) + "; ";
res += "}";
return res + ( !name.isEmpty() ? " " + name : "" );
}else
return ( t->d_union ? "union " : "struct " ) +
classRef(r) + ( !name.isEmpty() ? " " + name : "" );
}
break;
default:
Q_ASSERT(false);
}
return "?type?" + ( !name.isEmpty() ? " " + name : "" );
}
void allocRecordDecl(Record* r)
{
if( r->d_slotValid )
return; // can happen e.g. with VAR foo, bar: RECORD ch: CHAR; i: INTEGER END;
Named* n = r->findDecl();
if( n == 0 || n->getTag() != Thing::T_NamedType )
{
r->d_slot = anonymousDeclNr++;
r->d_slotValid = true;
}
}
void emitArrayInit( Array* a, const QByteArray& variable )
{
QList<Array*> dims = cast<Array*>(a)->getDims();
Type* td = derefed(dims.last()->d_type.data());
if( td->getTag() == Thing::T_Record && !td->d_unsafe )
{
// array of records by value; call init on each
b << ws() << "for(int $i = 0; $i < (";
for( int i = 0; i < dims.size(); i++ )
{
if( i != 0 )
b << "*";
Q_ASSERT(!dims[i]->d_lenExpr.isNull() );
if( a->d_vla )
b << variable << "$len[" << i << "]";
else
b << dims[i]->d_len;
}
b << "); $i++) ";
b << classRef(td) << "$init$(&((" << formatType(td,"*") << ")"
<< variable << ")[$i]);" << endl;
}
}
void emitRecordDecl(Record* r)
{
if( r->d_slotAllocated )
return;
r->d_slotAllocated = true;
QList<Field*> fields = r->getOrderedFields();
if( r->d_unsafe && fields.isEmpty() )
return; // aparently it's just a pointer type, done with forward decl;
const QByteArray className = classRef(r);
h << ws() << (r->d_union ? "union " : "struct " ) << className << " {" << endl;
level++;
if( !r->d_unsafe )
h << ws() << "struct " << className << "$Class$* class$;" << endl;
foreach( Field* f, fields )
f->accept(this);
level--;
h << "};" << endl << endl;
if( !r->d_unsafe )
{
h << ws() << "extern void " << className << "$init$(struct " << className << "*);" << endl;
b << ws() << "void " << className << "$init$(struct " << className << "* inst){" << endl;
level++;
b << ws() << "inst->class$ = &" << className << "$class$;" << endl;
foreach( Field* f, fields )
{
Type* td = derefed(f->d_type.data());
switch( td->getTag() )
{
case Thing::T_Record:
if( !td->d_unsafe )
{
b << ws() << classRef(td) << "$init$(";
if( declToInline.contains(cast<Record*>(td) ) )
b << "(struct " << classRef(td) << "*)";
b << "&inst->" << escape(f->d_name) << ");" << endl;
}
break;
case Thing::T_Array:
emitArrayInit( cast<Array*>(td), "inst->" + escape(f->d_name));
break;
}
}
level--;
b << ws() << "}" << endl;
}
}
void emitClassDecl(Record* r)
{
if( r->d_unsafe )
return;
const QByteArray className = classRef(r);
h << ws() << "struct " << className << "$Class$ {" << endl;
b << ws() << "struct " << className << "$Class$ " << className << "$class$ = { " << endl;
level++;
// we need a valid type in any case, thus use this type if no base rec
h << ws() << "struct " << classRef(
r->d_baseRec && r->d_baseRec->getBaseType() != Type::ANYREC ?
r->d_baseRec : r ) << "$Class$* super$;" << endl;
if( r->d_baseRec && r->d_baseRec->getBaseType() != Type::ANYREC )
b << ws() << "&" << classRef(r->d_baseRec) << "$class$," << endl;
else
b << ws() << "0," << endl;
QList<Procedure*> mm = r->getOrderedMethods();
foreach( Procedure* m, mm )
{
ProcType* pt = m->getProcType();
QByteArray name = escape(m->d_name);
name = "(*" + name + ")";
name += formatFormals(pt,true,m->d_receiver.data());
name = formatReturn(pt, name);
h << ws() << name << ";" << endl;
name = dottedName(m);
b << ws() << name << "," << endl;
}
level--;
b << "};" << endl << endl;
h << "};" << endl;
h << "extern struct " << className << "$Class$ " << className << "$class$;" << endl << endl;
}
void visit( Module* me)
{
const QByteArray moduleName = moduleRef(me);
h << "#ifndef _" << moduleName.toUpper() << "_" << endl;
h << "#define _" << moduleName.toUpper() << "_" << endl << endl;
modName = moduleName;
dedication(h);
h << "#include \"OBX.Runtime.h\"" << endl;
dedication(b);
b << "#include \"" << fileName(thisMod) << ".h\"" << endl;
ObxCGenCollector co;
me->accept(&co);
foreach( Import* imp, me->d_imports )
{
if(imp->d_mod->d_synthetic )
continue; // ignore SYSTEM
h << "#include \"" << fileName(imp->d_mod.data()) << ".h\"" << endl;
if( !imp->d_mod.isNull() && !imp->d_mod->d_metaActuals.isEmpty() )
{
for( int i = 0; i < imp->d_mod->d_metaActuals.size(); i++ )
{
Type* at = imp->d_mod->d_metaActuals[i].d_type.data();
//Q_ASSERT( !at->d_slotValid );
at->d_slot = i;
at->d_slotValid = true;
at->d_metaActual = true;
}
}
}
h << endl;
h << "// Declaration of module " << me->getName() << endl << endl;
if( !me->d_metaActuals.isEmpty() )
{
QSet<Module*> imports;
for( int i = 0; i < me->d_metaActuals.size(); i++ )
{
Named* n = me->d_metaActuals[i].d_constExpr->getIdent();
if(n)
{
Module* m = n->getModule();
if( m ) // 0 in case of e.g. INTEGER
imports.insert(m);
Type* td = n->d_type->derefed();
if( td->getTag() == Thing::T_Record )
{
h << formatType(n->d_type.data()) << ";" << endl;
declToInline.insert(cast<Record*>(td));
}
}
}
foreach(Module* m, imports)
b << "#include \"" << fileName(m) << ".h\"" << endl;
}
b << endl;
if( !Record::calcDependencyOrder(co.allRecords).isEmpty() )
err->error(Errors::Generator, thisMod->d_file, 1,1, // shouldn't acutally happen since caught by validator
"circular record by value dependencies are not supported by C");
foreach( Record* r, co.allRecords )
allocRecordDecl(r);
for( int i = 0; i < me->d_metaActuals.size(); i++ )
{
Type* td = derefed(me->d_metaActuals[i].d_type.data());
Q_ASSERT(td);
if( Record* r = td->toRecord() )
h << ws() << (r->d_union ? "union " : "struct " ) << classRef(r) << "; // meta actual" << endl;
}
foreach( Record* r, co.allRecords )
{
// forward decls
const QByteArray className = classRef(r);
if( !r->d_unsafe )
h << ws() << "struct " << className << "$Class$;" << endl;
h << ws() << (r->d_union ? "union " : "struct " ) << className << ";" << endl;
}
foreach( Record* r, co.allRecords )
emitRecordDecl(r);
foreach( const Ref<Named>& n, me->d_order )
{
if( n->getTag() == Thing::T_Variable )
n->accept(this);
}
foreach( Procedure* p, co.allProcs )
p->accept(this);
foreach( Record* r, co.allRecords )
emitClassDecl(r);
h << "extern void " << moduleName << "$init$(void);" << endl;
b << "static int initDone$ = 0;" << endl;
b << "void " << moduleName << "$init$(void) {" << endl;
level++;
beginBody();
b << ws() << "if(initDone$) return; else initDone$ = 1;" << endl;
foreach( Import* imp, me->d_imports )
{
if(imp->d_mod->d_synthetic )
continue; // ignore SYSTEM
b << ws() << moduleRef(imp->d_mod.data()) + "$init$();" << endl;
}
foreach( const Ref<Named>& n, me->d_order )
{
if( n->getTag() == Thing::T_Variable )
{
int f = isStructuredOrArrayPointer(n->d_type.data() );
if( f )
{
Type* td = derefed(n->d_type.data());
const QByteArray name = moduleRef(thisMod)+"$"+n->d_name;
b << ws() << "memset(&" << name << ",0,sizeof(" << name << "));" << endl;
if( f == IsRecord && td && !td->d_unsafe )
b << ws() << classRef(n->d_type.data()) << "$init$(&" << name << ");" << endl;
else if( f == IsArray && td && !td->d_unsafe )
emitArrayInit( cast<Array*>(n->d_type->derefed()), name );
}
}
}
foreach( const Ref<Statement>& s, me->d_body )
{
emitStatement(s.data());
}
if( me->d_externC )
{
QByteArray modDll;
SysAttr* a = me->d_sysAttrs.value("dll").data();
if( a && a->d_values.size() == 1 )
modDll = a->d_values.first().toByteArray();
else
modDll = me->d_name;
b << ws() << "void* $l = 0;" << endl;
QMap<QByteArray,QList<QPair<Procedure*,QByteArray> > > procs; // dll -> proc, name
foreach( Procedure* p, co.allProcs )
{
QByteArray procDll, prefix, alias;
a = me->d_sysAttrs.value("prefix").data(); // meule attr
if( a && a->d_values.size() == 1 )
prefix = a->d_values.first().toByteArray();
a = p->d_sysAttrs.value("dll").data(); // proc attr
if( a && a->d_values.size() == 1 )
procDll = a->d_values.first().toByteArray();
else
procDll = modDll;
a = p->d_sysAttrs.value("prefix").data(); // proc attr
if( a && a->d_values.size() == 1 )
prefix = a->d_values.first().toByteArray();
a = p->d_sysAttrs.value("alias").data(); // proc attr
if( a && a->d_values.size() == 1 )
alias = a->d_values.first().toByteArray();
QByteArray useName = p->d_name;
if( !alias.isEmpty() )
useName = alias;
else if( !prefix.isEmpty() )
useName = prefix + p->d_name;
procs[procDll].append(qMakePair(p,useName));
// b << ws() << dottedName(p) << " = 0;" << endl;
}
QMap<QByteArray,QList<QPair<Procedure*,QByteArray> > >::const_iterator i;
for( i = procs.begin(); i != procs.end(); ++i )
{
b << ws() << "$l = OBX$LoadDynLib(\"" << i.key() << "\");" << endl;