forked from rochus-keller/Oberon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObLuaGen2.cpp
1720 lines (1556 loc) · 53.8 KB
/
ObLuaGen2.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 2019, 2020 Rochus Keller <mailto:me@rochus-keller.ch>
*
* This file is part of the Oberon parser/code model 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 "ObLuaGen2.h"
#include "ObAst.h"
#include "ObErrors.h"
#include "ObAstEval.h"
#include <QTextStream>
#include <QtDebug>
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
using namespace Ob;
using namespace Ob::Ast;
struct TransformIndexFunctionToStats : public AstVisitor
{
// Rules:
// A function call cannot be the actual arg of a VAR param
// Lua cannot take the address of a slot; thus the slot is passed by value to the param and returned
// as an additional return value of the procedure, which might already have a regular return value or not.
// If the desig is an Index we need two slots as a substitute of the address: the table and the index.
// So if we have A[B] as an actual argument of VAR param, we need to remember both A and B to be able
// to assign the changed value to the right element; otherwise doing something like "A[B] = func(A[B])"
// could go to the wrong element if B renders a different value when applied twice.
// If we have A.B (IdentSel) as an actual argument of VAR param, then "A.B = func(A.B)" hits the same element ever.
// If we have A[B].C, we again have to remember the table referenced by A[B] and the index "C".
// To conclude: whenever the desig includes an index (and only then), we need two slots to remember the table and the index.
// The index can contain other function calls, which by themselves have indexed arguments,
// e.g. "F1( A[ F2( B[C] ) ] )"; here we need to memorize the table referenced by A, the index "F2( B[C] )",
// the table referenced by B and the index C, if both F1 and F2 have VAR params. This call translates to
// "T1 = B; T2 = C; T3, T1[T2] = F2(T1[T2]); T4 = A; T4[T3] = F1( T4[T3] );" T4 can reuse T1 or T2, B and A no
// copy required, so more efficient "T2 = C; T3, B[T2] = F2(B[T2]); A[T3] = F1(A[T3]);"
// Therefore the main goal is to move function calls in VAR param actuals to preceding, isolated assign statements.
// Adding return assignments for VAR params is then simply a local operation of the assignment or call
TransformIndexFunctionToStats():curScope(0){}
Module* curModule;
Scope* curScope;
int allocatedVarTemps;
bool allocatedTemp1;
bool allocatedTemp2;
QList<StatSeq> bodies;
QList<bool> inVar;
void assureTemp1()
{
if( allocatedTemp1 )
return;
Ref<Variable> tmp = new Variable();
tmp->d_scope = curScope;
tmp->d_name = QByteArray("__tmp1");
tmp->d_synthetic = true;
curScope->d_names.insert( tmp->d_name,tmp.data() );
curScope->d_order.append(tmp.data());
allocatedTemp1 = true;
}
void prepareBody( Scope* m )
{
curScope = m;
allocatedVarTemps = 0;
allocatedTemp1 = false;
allocatedTemp2 = false;
}
void iterateBody( StatSeq& body )
{
bodies.push_back( StatSeq() );
for( int i = 0; i < body.size(); i++ )
{
body[i]->accept(this);
bodies.back().append( body[i] );
}
body = bodies.back();
bodies.pop_back();
}
void visit( Procedure* m)
{
for( int i = 0; i < m->d_order.size(); i++ )
m->d_order[i]->accept(this); // subprocs
prepareBody(m);
iterateBody( m->d_body );
curScope = 0;
}
void visit( Module* m )
{
for( int i = 0; i < m->d_order.size(); i++ )
m->d_order[i]->accept(this); // subprocs
prepareBody(m);
iterateBody( m->d_body );
curScope = 0;
}
void handleCall( Ref<Expression>& e )
{
if( e->getTag() != Thing::T_CallExpr )
return;
CallExpr* c = static_cast<CallExpr*>( e.data() );
ProcType* pt = c->getProcType();
if( pt->isBuiltIn() )
return; // RISK
// if this call is part of a designator expression which is passed to a VAR param, it could have a side effect
// and thus must be taken out of the expression
const bool isInVar = !inVar.isEmpty() && inVar.back();
// if this calls a procedure with var params, we need to account for the additional returns
// we therefore need to transform function calls to assign statements; the function assigns its regular value
// to a temporary variable which is then used at the original place of the function
bool hasVar = false;
int numOfIndexVar = 0;
for( int i = 0; i < pt->d_formals.size(); i++ )
{
if( pt->d_formals[i]->d_var )
{
hasVar = true;
if( i < c->d_actuals.size() && getLastIndexOp(c->d_actuals[i].data()).first != 0 )
numOfIndexVar++;
}
}
if( !hasVar && !isInVar )
return;
// The function assigns to a new local variable which then replaces the function call at it's original
// place; the function call is moved to a preceding assignment statement.
// We only take care of the regular function return here which we assign to a temorary. The additional return
// values required - one for each VAR param - are handled in the code generator directly.
// It's no issue to add new temporary variables ad libidum, because the Lua compiler will recognize their scope
// and reuse the slots.
Ref<Variable> tmp = new Variable();
tmp->d_scope = curScope;
tmp->d_name = QByteArray("__c") + QByteArray::number( curScope->d_order.size() );
tmp->d_synthetic = true;
curScope->d_names.insert( tmp->d_name,tmp.data() );
curScope->d_order.append(tmp.data());
tmp->d_type = e->d_type.data();
tmp->d_liveFrom = 1;
if( !bodies.back().isEmpty() )
tmp->d_liveFrom = bodies.back().back()->d_loc.d_row;
tmp->d_liveTo = e->d_loc.d_row;
Ref<Assign> a = new Assign();
Ref<IdentLeaf> id = new IdentLeaf();
id->d_ident = tmp.data();
a->d_lhs = id.data();
a->d_rhs = c;
Q_ASSERT( !bodies.isEmpty() );
bodies.back().append( a.data() );
e = id.data();
const int diff = numOfIndexVar - allocatedVarTemps;
if( diff > 0 )
{
// not all requred vars are allocated yet
for( int i = 0; i < diff; i++ )
{
Ref<Variable> tmp = new Variable();
tmp->d_scope = curScope;
tmp->d_name = QByteArray("__t") + QByteArray::number( allocatedVarTemps );
tmp->d_synthetic = true;
curScope->d_names.insert( tmp->d_name,tmp.data() );
curScope->d_order.append(tmp.data());
// type is left empty here; just a placehoder
tmp = new Variable();
tmp->d_scope = curScope;
tmp->d_name = QByteArray("__i") + QByteArray::number( allocatedVarTemps );
tmp->d_synthetic = true;
curScope->d_names.insert( tmp->d_name,tmp.data() );
curScope->d_order.append(tmp.data());
// type is left empty here; just a placehoder
}
allocatedVarTemps += diff;
}
}
void visit( Call* c )
{
// this is a procedure call, but when VAR params are present it turns to an implicit function call
c->d_what->accept(this);
}
void visit( Return* r )
{
r->d_what->accept(this);
handleCall( r->d_what );
}
void visit( Assign* a )
{
// lhs cannot be a procedure call
a->d_lhs->accept(this);
a->d_rhs->accept(this);
handleCall( a->d_rhs );
}
void visit( IfLoop* l )
{
Q_ASSERT( l->d_if.size() == l->d_then.size() );
for( int i = 0; i < l->d_if.size(); i++ )
{
Q_ASSERT( !bodies.isEmpty() );
const int pre = bodies.back().size();
l->d_if[i]->accept(this);
handleCall(l->d_if[i]);
const StatSeq added = bodies.back().mid(pre);
if( l->d_op == IfLoop::REPEAT )
bodies.back() = bodies.back().mid(0,pre);
iterateBody( l->d_then[i] );
// replicate statements generated from d_if to end of body for WHILE and REPEAT
// in case of REPEAT the added statements only occur in the loop, not before.
if( !added.isEmpty() && ( l->d_op == IfLoop::REPEAT || l->d_op == IfLoop::WHILE ) )
l->d_then[i] += added;
}
iterateBody( l->d_else );
}
void visit( ForLoop* l )
{
l->d_from->accept(this);
handleCall( l->d_from );
Q_ASSERT( !bodies.isEmpty() );
const int pre = bodies.back().size();
l->d_to->accept(this);
handleCall( l->d_to );
const StatSeq added = bodies.back().mid(pre);
l->d_by->accept(this); // const expr cannot contain procedure call
iterateBody( l->d_do );
// replicate statements generated from d_to to end of body
if( !added.isEmpty() )
l->d_do += added;
}
void visit( CaseStmt* c )
{
c->d_exp->accept(this);
handleCall( c->d_exp );
for( int i = 0; i < c->d_cases.size(); i++ )
{
for( int j = 0; j < c->d_cases[i].d_labels.size(); j++ )
{
c->d_cases[i].d_labels[j]->accept(this);
handleCall(c->d_cases[i].d_labels[j]); // can case labels be funcion calls?
}
iterateBody( c->d_cases[i].d_block );
}
}
void visit( SetExpr* s )
{
for( int i = 0; i < s->d_parts.size(); i++ )
{
s->d_parts[i]->accept(this);
handleCall(s->d_parts[i]);
}
}
void visit( UnExpr* e )
{
e->d_sub->accept(this);
handleCall(e->d_sub);
}
void visit( IdentSel* e )
{
e->d_sub->accept(this);
handleCall(e->d_sub);
}
void visit( CallExpr* c )
{
Q_ASSERT( curScope != 0 );
Q_ASSERT( !c->d_sub.isNull() && !c->d_sub->d_type.isNull() && c->d_sub->d_type->derefed()->getTag() == Thing::T_ProcType );
ProcType* pt = static_cast<ProcType*>( c->d_sub->d_type->derefed() );
// CallExpr is always the top Expr in a desig
c->d_sub->accept(this);
if( pt->isBuiltIn() )
{
// built-in procedures which need special treatment or are not supported
BuiltIn* bi = static_cast<BuiltIn*>( pt->d_ident );
switch(bi->d_func)
{
case BuiltIn::INC:
case BuiltIn::DEC:
return; // no VAR
case BuiltIn::NEW:
assureTemp1();
return; // inline anyway
case BuiltIn::GET:
case BuiltIn::PUT:
return; // not supported
}
// else
}
Q_ASSERT( pt->d_formals.size() == c->d_actuals.size() );
for( int i = 0; i < c->d_actuals.size(); i++ )
{
inVar.push_back(pt->d_formals[i]->d_var);
c->d_actuals[i]->accept(this);
inVar.pop_back();
/* unnecessary; moving the calls to a separate statement each is sufficient; the additional
* return assignments to the actuals of VAR params is directly done by the code generator
if( pt->d_formals[i]->d_var )
{
// check wheter actual contains an index
// we already assured that actual is a desig, not an arbitrary expr
Expression* e = getLastIndexOp( c->d_actuals[i].data() );
if( e )
qDebug() << "VAR param with actual index desig" << e->d_loc.d_row << e->d_loc.d_col << curModule->d_file
<< "nest depth" << calls.size();
}
*/
handleCall(c->d_actuals[i]); // actual of a value param may be function call; the latter function might have VAR params.
}
}
void visit( BinExpr* e )
{
e->d_lhs->accept(this);
handleCall(e->d_lhs);
e->d_rhs->accept(this);
handleCall(e->d_rhs);
}
typedef QPair<BinExpr*,Expression*> IndexPred;
static IndexPred getLastIndexOp( Expression* e, Expression* pred = 0 )
{
// TODO: review this concept and printRightPart. Only the case where a
// desig contains [] has to be handled, and then only the last table/index
if( e == 0 )
return IndexPred();
switch( e->getTag() )
{
case Thing::T_BinExpr:
{
BinExpr* bi = static_cast<BinExpr*>(e);
if( bi->d_op == BinExpr::Index )
return qMakePair(bi,pred);
else
return getLastIndexOp(bi->d_lhs.data(),bi); // RISK: only look in lhs
}
break;
case Thing::T_UnExpr:
return getLastIndexOp( static_cast<UnExpr*>(e)->d_sub.data(), e );
case Thing::T_IdentSel:
return getLastIndexOp( static_cast<IdentSel*>(e)->d_sub.data(), e );
case Thing::T_CallExpr:
return getLastIndexOp( static_cast<CallExpr*>(e)->d_sub.data(), e );
}
return IndexPred();
}
};
static QSet<QByteArray> s_lkw;
static bool isLuaKeyword( const QByteArray& str )
{
if( s_lkw.isEmpty() )
s_lkw << "and" << "break" << "do" << "else" << "elseif"
<< "end" << "false" << "for" << "function" << "if"
<< "in" << "local" << "nil" << "not" << "or"
<< "repeat" << "return" << "then" << "true" << "until" << "while"
// built-in LuaJIT libraries
<< "math" << "bit" << "obnlj" << "module";
return s_lkw.contains(str);
}
static bool startsWith2Underscores( const QByteArray& str )
{
if( !str.startsWith("__") )
return false;
if( str.size() == 2 )
return true;
if( str[3] == '_' )
return false;
else
return true;
}
static QByteArray luaStringEscape( QByteArray str )
{
QByteArray out;
out.reserve(str.size()*2);
char buf[10];
for( int i = 0; i < str.size(); i++ )
{
const quint8 c = quint8(str[i]);
if( QChar::fromLatin1(str[i]).isPrint() && c != 255 )
{
switch( quint8(str[i]))
{
case '\\':
out += "\\\\";
break;
case '"':
out += "\\\"";
break;
default:
out += str[i];
break;
}
}else
{
switch( c )
{
case '\n':
out += "\\n";
break;
case '\t':
out += "\\t";
break;
case '\a':
out += "\\a";
break;
case '\b':
out += "\\b";
case '\f':
out += "\\f";
break;
case '\v':
out += "\\v";
break;
case 0:
out += "\\0";
break;
default:
::sprintf(buf,"\\%03d", c );
out += buf;
break;
}
}
}
return out;
}
static QByteArray toName( Named* id)
{
if( id == 0 )
return QByteArray();
if( id->d_synthetic )
return id->d_name;
QByteArray res = id->d_name;
if( isLuaKeyword(res) || startsWith2Underscores(res) )
return res + "_";
else
return res;
}
struct LuaGen2Imp : public AstVisitor
{
QTextStream out;
Errors* err;
Module* mod;
quint16 level;
Scope* curScope;
bool ownsErr;
QString ws() const
{
return QString(level,QChar('\t'));
}
static QualiType::ModItem findClass( Type* t )
{
// 1:1 from LjbcGen
QualiType::ModItem res;
if( t->getTag() == Thing::T_Pointer )
{
Pointer* p = static_cast<Pointer*>(t);
if( p->d_to->getTag() == Thing::T_QualiType )
return findClass( p->d_to.data() );
Q_ASSERT( p->d_to->getTag() == Thing::T_Record &&
p->d_to->d_ident == 0 );
// since QualiType type aliasses are no longer shortcutted, but there is an instance of
// QualiType wherever there is no inplace type declaration after TO. But the latter has
// no d_ident by definition.
}else if( t->getTag() == Thing::T_QualiType )
{
QualiType* q = static_cast<QualiType*>( t );
res = q->getQuali();
if( res.first )
return res; // quali points to an import, that's where we find a class for sure
Q_ASSERT( res.second );
return findClass( res.second->d_type.data() );
}
Q_ASSERT( t->getTag() != Thing::T_QualiType && t == t->derefed() );
res.second = t->d_ident;
if( res.second == 0 )
{
if( t->getTag() == Thing::T_Record )
{
Record* r = static_cast<Record*>( t );
if( r->d_binding )
res.second = r->d_binding->d_ident;
}
}
return res;
}
static QByteArray className( Type* t )
{
Q_ASSERT( t );
QualiType::ModItem mi = findClass( t );
if( mi.first && mi.second )
return toName(mi.first) + "." + toName(mi.second);
else if( mi.second )
return toName(mi.second);
else
return "???";
}
void inline initHelper( Array* a, int curDim, const QByteArray& name, const QByteArray& rec = QByteArray() )
{
// TODO: higher dims via local temporary instead of n-dim index (only relevant for dim > 2)
out << " = obnlj.Arr(" << a->d_len << ")" << endl;
out << ws() << "for __" << curDim << "=1," << a->d_len << " do" << endl;
level++;
if( !rec.isEmpty() )
out << ws() << "local " << rec << " = {}" << endl;
out << ws() << name;
for( int j = 0; j <= curDim; j++ )
out << "[__" << j << "]";
if( !rec.isEmpty())
out << " = " << rec << endl;
level--;
}
void initMatrix( const QList<Array*>& dims, const QByteArray& name, int curDim )
{
// We need to create the arrays for each matrix dimension besides the highest one, unless it is of record value.
// If a matrix has only one dimension (i.e. it is an array), no initialization is required, unless it is of record value
// Each matrix dimension is created in a recursive call of this method.
// Examples:
// ARRAY n OF INTEGER
// -> obnlj.Arr(n)
// ARRAY n OF CHAR
// -> obnlj.Str(n)
// ARRAY n, m OF INTEGER
// -> for i=1,n do A[i] = obnlj.Arr(m) end
// ARRAY n, m OF RECORD END
// -> for i=1,n do A[i] = obnlj.Arr(m)
// for j=1,m do A[i][j] = initRecord() end end
const int oldLevel = level;
level += curDim;
if( curDim == dims.size() - 1 )
{
// we're at the highest dimension
if( isString( dims[curDim] ) )
out << " = obnlj.Str(" << dims[curDim]->d_len << ")";
else if( dims[curDim]->d_type->derefed()->getTag() == Thing::T_Record )
{
const QByteArray rec = "__r" + QByteArray::number(curDim);
initHelper( dims[curDim], curDim, name, rec );
level++;
initRecord( dims[curDim]->d_type.data(), rec );
level--;
out << ws() << "end";
}
else
out << " = obnlj.Arr(" << dims[curDim]->d_len << ")";
}else
{
// we're at a lower dimension
initHelper( dims[curDim], curDim, name );
initMatrix( dims, name, curDim + 1 );
out << ws() << "end";
}
level = oldLevel;
out << endl;
}
static bool isString( Type* t )
{
if( t && t->getTag() == Thing::T_Array )
{
Array* a = static_cast<Array*>(t);
Type* td = a->d_type->derefed();
if( td->getTag() == Thing::T_BaseType &&
static_cast<BaseType*>( td )->d_type == BaseType::CHAR )
return true;
}
return false;
}
void initArray(Array* arr, const QByteArray& name )
{
// out << name << " = "; was already done by the caller
// provide the code right of the '=' with all the necessary initialization
Array* curDim = arr;
QList<Array*> dims;
dims << curDim;
Type* td = curDim->d_type->derefed();
while( td->getTag() == Thing::T_Array )
{
curDim = static_cast<Array*>( td );
dims << curDim;
td = curDim->d_type->derefed();
}
initMatrix( dims, name, 0 );
}
void initRecord( Type* rt, const QByteArray& name )
{
// out << " = {}" << endl; was already done by the caller
Q_ASSERT( rt != 0 );
if( findClass(rt).second != 0 )
out << ws() << "setmetatable(" << name << "," << className( rt ) << ")" << endl;
Record* r = toRecord(rt);
QList<Record*> topDown;
topDown << r;
Record* base = r->getBaseRecord();
while( base )
{
topDown.prepend(base);
base = base->getBaseRecord();
}
for( int j = 0; j < topDown.size(); j++ )
{
// go from top to bottom through inheritance hierarchy and initialize members
Record* rec = topDown[j];
for( int i = 0; i < rec->d_fields.size(); i++ )
{
Type* t = rec->d_fields[i]->d_type.data();
Type* td = t->derefed();
const QByteArray field = name + "." + rec->d_fields[i]->d_name;
level++;
if( td->getTag() == Thing::T_Record )
{
out << ws() << field << " = {}" << endl;
initRecord( t, field );
}else if( td->getTag() == Thing::T_Array )
{
out << ws() << field;
initArray( static_cast<Array*>(td), field);
}
level--;
}
}
}
void emitVariable( Named* v )
{
const QByteArray name = toName(v);
out << ws() << "local ";
// v->d_type can be null here because of the allocatedVarTemps in TransformIndexFunctionToStats
Type* td = v->d_type.isNull() ? 0 : v->d_type->derefed();
if( td && td->getTag() == Thing::T_Record )
{
level++;
out << name << " = {}" << endl;
initRecord( v->d_type.data(), name );
level--;
}else if( td && td->getTag() == Thing::T_Array )
{
level++;
out << name;
initArray( static_cast<Array*>(td), name );
level--;
}else
out << name << endl;
if( v->d_scope == mod && v->d_public )
out << "module" << "." << name << " = function() return " << name << " end" << endl;
}
void visit( Variable* v )
{
emitVariable(v);
}
void visit( LocalVar* v )
{
emitVariable(v);
}
void visit( Parameter* p )
{
out << toName( p );
}
void visit( ProcType* p )
{
out << "(";
for( int i = 0; i < p->d_formals.size(); i++ )
{
if( i != 0 )
out << ",";
out << toName(p->d_formals[i].data());
}
out << ")";
}
static bool inline isNamedTypeWithLocal( Named* nt )
{
// adapted from LjbcGen
if( nt->getTag() != Thing::T_NamedType )
return false;
// we only consider original named type declarations here, i.e. no aliasses.
if( nt->d_type->d_ident != nt )
return false;
const int tag = nt->d_type->getTag();
// In case of type aliasses which point to record types (wheter in this or another module), we at least
// put a copy of the original named type table to the module table of the present module,
// but we don't allocate a new slot.
if( tag == Thing::T_QualiType )
return false;
// We need a table for a named record type so it can be used as metatable for the
// instance of the record and a base for subrecords.
if( tag == Thing::T_Record )
return true;
if( tag == Thing::T_Pointer )
{
Pointer* p = static_cast<Pointer*>(nt->d_type.data());
Q_ASSERT( p->d_to->derefed()->getTag() == Thing::T_Record );
Record* r = static_cast<Record*>(p->d_to->derefed());
// A pointer to an anonymous record declared for the pointer is treatet the
// same way as a named Record declaration
if( r->d_binding == p )
return true;
}
return false;
}
void visit( NamedType* t )
{
if( isNamedTypeWithLocal( t ) )
{
// this is an original (i.e. non-alias) declaration of a recrod
Record* r = toRecord(t->d_type.data());
const QByteArray name = toName(t);
out << ws() << "local " << name << " = ";
out << "{}" << endl;
if( !r->d_base.isNull() )
{
Q_ASSERT( r->d_base->d_quali->getIdent() != 0 );
level++;
out << ws() << "setmetatable(" << name << "," << className(r->d_base.data()) << ")" << endl;
level--;
}
if( t->d_scope == mod && t->d_public )
out << "module" << "." << name << " = " << name << endl;
}else if( t->d_type->getTag() == Thing::T_QualiType && Model::toRecord(t->d_type.data()) != 0 )
{
QualiType* q = static_cast<QualiType*>(t->d_type.data());
const QByteArray name = toName(t);
out << ws() << "local " << name << " = ";
q->d_quali->accept(this);
out << endl;
// << quali( tr->d_quali->d_type->d_ident ) << endl;
if( t->d_scope == mod && t->d_public )
out << "module" << "." << name << " = " << name << endl;
}
}
void print( const QVariant& v )
{
if( v.canConvert<Ast::Set>() )
out << "obnlj.SET(" << QByteArray::number( quint32(v.value<Ast::Set>().to_ulong()) ) << ")";
else if( v.type() == QVariant::ByteArray )
out << "obnlj.Str(\"" << luaStringEscape(v.toByteArray() ) << "\")";
else if( v.isNull() )
out << "null";
else
out << v.toByteArray();
}
void visit( Const* c)
{
out << ws() << "local " + toName(c) << " = ";
print( c->d_val );
out << endl;
if( c->d_scope == mod && c->d_public )
out << "module" << "." << toName(c) << " = " << toName(c) << endl;
}
void visit( Import* i )
{
out << "local " << toName(i) << " = require '" << toName(i->d_mod.data()) << "'" << endl;
}
void visit( Procedure* m)
{
out << ws() << "local function " << toName(m);
m->d_type->accept(this);
out << endl;
level++;
for( int i = 0; i < m->d_order.size(); i++ )
{
if( m->d_order[i]->getTag() != Thing::T_Parameter )
m->d_order[i]->accept(this);
}
if( !m->d_body.isEmpty() )
out << ws() << "-- BEGIN" << endl;
curScope = m;
for( int i = 0; i < m->d_body.size(); i++ )
m->d_body[i]->accept(this);
Type* td = m->d_type->derefed();
Q_ASSERT( td->getTag() == Thing::T_ProcType );
ProcType* p = static_cast<ProcType*>( td );
if( p->d_return.isNull() )
{
int numOfVar = 0;
// add return of VAR params to proper procedure
for( int i = 0; i < p->d_formals.size(); i++ )
{
if( p->d_formals[i]->d_var )
{
numOfVar++;
if( numOfVar == 1 )
out << ws() << "return " << toName(p->d_formals[i].data());
else if( numOfVar > 1 )
out << "," << toName(p->d_formals[i].data());
}
}
out << endl;
}
curScope = 0;
level--;
out << ws() << "end" << endl;
if( m->d_scope == mod && m->d_public )
out << "module" << "." << toName(m) << " = " << toName(m) << endl;
}
void visit( Module* m )
{
curScope = 0;
out << "-- Generated by " << qApp->applicationName() << " " << qApp->applicationVersion() <<
" on " << QDateTime::currentDateTime().toString(Qt::ISODate) << endl << endl;
out << "---------- MODULE " << m->d_name << " ----------" << endl;
out << "local module = {}" << endl << endl;
out << "local obnlj = require 'obnlj'" << endl;
for( int i = 0; i < m->d_order.size(); i++ )
m->d_order[i]->accept(this);
curScope = m;
for( int i = 0; i < m->d_body.size(); i++ )
m->d_body[i]->accept(this);
curScope = 0;
out << "return module" << endl;
out << "---------- END MODULE " << m->d_name << " ----------" << endl;
out.flush();
}
void printRightPart( const TransformIndexFunctionToStats::IndexPred& ip, Expression* e )
{
if( ip.second )
{
Q_ASSERT( ip.second->getTag() == Thing::T_UnExpr || ip.second->getTag() == Thing::T_IdentSel
|| ip.second->getTag() == Thing::T_CallExpr );
UnExpr* u = static_cast<UnExpr*>( ip.second );
Q_ASSERT( u->d_sub.data() == ip.first );
Ref<Expression> holder = u->d_sub; // otherwise first is deleted when splitting
u->d_sub = new IdentLeaf(); // temp value without contents
e->accept(this);
u->d_sub = holder;
}
}
void printVarReturns( Expression* e )
{
if( e->getTag() != Thing::T_CallExpr )
return;
CallExpr* c = static_cast<CallExpr*>(e);
ProcType* pt = c->getProcType();
if( pt->isBuiltIn() )
return;
int count1 = 0, count2 = 0;
for( int i = 0; i < c->d_actuals.size(); i++ )
{
if( pt->d_formals[i]->d_var )
{
TransformIndexFunctionToStats::IndexPred ip = TransformIndexFunctionToStats::getLastIndexOp(
c->d_actuals[i].data() );
if( count1 > 0 || count2 > 0 )
out << ",";
if( ip.first )
{
out << "__t" << count1 << "[__i" << count1 << "+1]";
printRightPart( ip, c->d_actuals[i].data() );
count1++;
}else
{
c->d_actuals[i]->accept(this);
count2++;
}
}
}
}
bool generateIndexVarStatements( Expression* e )
{
if( e->getTag() != Thing::T_CallExpr )
return false;
CallExpr* c = static_cast<CallExpr*>(e);
ProcType* pt = c->getProcType();
if( pt->isBuiltIn() )
return false;
int cur = 0;
bool hasVar = false;
for( int i = 0; i < c->d_actuals.size(); i++ )
{
if( pt->d_formals[i]->d_var )
{
TransformIndexFunctionToStats::IndexPred ip = TransformIndexFunctionToStats::getLastIndexOp(
c->d_actuals[i].data() );
if( ip.first )
{
out << ws() << "__t" << cur << " = ";
Ref<Expression> table = ip.first->d_lhs;
ip.first->d_lhs = 0;
table->accept(this);
ip.first->d_lhs = table;
out << endl;
out << ws() << "__i" << cur << " = ";
ip.first->d_rhs->accept(this);
out << endl;
cur++;
}
hasVar = true;
}
}
return hasVar;
}
void visit( Call* c )
{
CallExpr* ce = c->getCallExpr();
if( ce->getProcType()->isBuiltIn() && renderBuiltIn( ce ) )
return;
const bool hasVar = generateIndexVarStatements(c->d_what.data());
out << ws();
if( hasVar )
{
printVarReturns(c->d_what.data());
out << " = ";