/
escape.d
2637 lines (2374 loc) · 86.1 KB
/
escape.d
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
/**
* Most of the logic to implement scoped pointers and scoped references is here.
*
* Copyright: Copyright (C) 1999-2024 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/escape.d, _escape.d)
* Documentation: https://dlang.org/phobos/dmd_escape.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/escape.d
*/
module dmd.escape;
import core.stdc.stdio : printf;
import core.stdc.stdlib;
import core.stdc.string;
import dmd.root.rmem;
import dmd.aggregate;
import dmd.astenums;
import dmd.declaration;
import dmd.dscope;
import dmd.dsymbol;
import dmd.errors;
import dmd.expression;
import dmd.func;
import dmd.funcsem;
import dmd.globals : FeatureState;
import dmd.id;
import dmd.identifier;
import dmd.init;
import dmd.location;
import dmd.mtype;
import dmd.printast;
import dmd.rootobject;
import dmd.tokens;
import dmd.typesem : hasPointers, parameterStorageClass;
import dmd.visitor;
import dmd.arraytypes;
private:
/// Groups global state for escape checking together
package(dmd) struct EscapeState
{
// Maps `sequenceNumber` of a `VarDeclaration` to an object that contains the
// reason it failed to infer `scope`
// https://issues.dlang.org/show_bug.cgi?id=23295
private __gshared RootObject[int] scopeInferFailure;
/// Called by `initDMD` / `deinitializeDMD` to reset global state
static void reset()
{
scopeInferFailure = null;
}
}
/******************************************************
* Checks memory objects passed to a function.
* Checks that if a memory object is passed by ref or by pointer,
* all of the refs or pointers are const, or there is only one mutable
* ref or pointer to it.
* References:
* DIP 1021
* Params:
* sc = used to determine current function and module
* fd = function being called
* tf = fd's type
* ethis = if not null, the `this` pointer
* arguments = actual arguments to function
* gag = do not print error messages
* Returns:
* `true` if error
*/
public
bool checkMutableArguments(ref Scope sc, FuncDeclaration fd, TypeFunction tf,
Expression ethis, Expressions* arguments, bool gag)
{
enum log = false;
if (log) printf("[%s] checkMutableArguments, fd: `%s`\n", fd.loc.toChars(), fd.toChars());
if (log && ethis) printf("ethis: `%s`\n", ethis.toChars());
bool errors = false;
/* Outer variable references are treated as if they are extra arguments
* passed by ref to the function (which they essentially are via the static link).
*/
VarDeclaration[] outerVars = fd ? fd.outerVars[] : null;
const len = arguments.length + (ethis !is null) + outerVars.length;
if (len <= 1)
return errors;
struct EscapeBy
{
VarDeclarations byref;
VarDeclarations byvalue;
Parameter param; // null if no Parameter for this argument
bool isMutable; // true if reference to mutable
}
auto escapeBy = new EscapeBy[len];
const paramLength = tf.parameterList.length;
// Fill in escapeBy[] with arguments[], ethis, and outerVars[]
foreach (const i, ref eb; escapeBy)
{
bool refs;
Expression arg;
if (i < arguments.length)
{
arg = (*arguments)[i];
if (i < paramLength)
{
eb.param = tf.parameterList[i];
refs = eb.param.isReference();
eb.isMutable = eb.param.isReferenceToMutable(arg.type);
}
else
{
eb.param = null;
refs = false;
eb.isMutable = arg.type.isReferenceToMutable();
}
}
else if (ethis)
{
/* ethis is passed by value if a class reference,
* by ref if a struct value
*/
eb.param = null;
arg = ethis;
auto ad = fd.isThis();
assert(ad);
assert(ethis);
if (ad.isClassDeclaration())
{
refs = false;
eb.isMutable = arg.type.isReferenceToMutable();
}
else
{
assert(ad.isStructDeclaration());
refs = true;
eb.isMutable = arg.type.isMutable();
}
}
else
{
// outer variables are passed by ref
eb.param = null;
refs = true;
auto var = outerVars[i - (len - outerVars.length)];
eb.isMutable = var.type.isMutable();
eb.byref.push(var);
continue;
}
void onRef(VarDeclaration v, bool transition) { eb.byref.push(v); }
void onValue(VarDeclaration v) { eb.byvalue.push(v); }
void onFunc(FuncDeclaration fd, bool called) {}
void onExp(Expression e, bool transition) {}
scope EscapeByResults er = EscapeByResults(&onRef, &onValue, &onFunc, &onExp);
if (refs)
escapeByRef(arg, er);
else
escapeByValue(arg, er);
}
void checkOnePair(size_t i, ref EscapeBy eb, ref EscapeBy eb2,
VarDeclaration v, VarDeclaration v2, bool of)
{
if (log) printf("v2: `%s`\n", v2.toChars());
if (v2 != v)
return;
//printf("v %d v2 %d\n", eb.isMutable, eb2.isMutable);
if (!(eb.isMutable || eb2.isMutable))
return;
if (!tf.islive && !(sc.useDIP1000 == FeatureState.enabled && sc.func && sc.func.setUnsafe()))
return;
if (!gag)
{
// int i; funcThatEscapes(ref int i);
// funcThatEscapes(i); // error escaping reference _to_ `i`
// int* j; funcThatEscapes2(int* j);
// funcThatEscapes2(j); // error escaping reference _of_ `i`
const(char)* referenceVerb = of ? "of" : "to";
const(char)* msg = eb.isMutable && eb2.isMutable
? "more than one mutable reference %s `%s` in arguments to `%s()`"
: "mutable and const references %s `%s` in arguments to `%s()`";
sc.eSink.error((*arguments)[i].loc, msg,
referenceVerb,
v.toChars(),
fd ? fd.toPrettyChars() : "indirectly");
}
errors = true;
}
void escape(size_t i, ref EscapeBy eb, bool byval)
{
foreach (VarDeclaration v; byval ? eb.byvalue : eb.byref)
{
if (log)
{
const(char)* by = byval ? "byval" : "byref";
printf("%s %s\n", by, v.toChars());
}
if (byval && !v.type.hasPointers())
continue;
foreach (ref eb2; escapeBy[i + 1 .. $])
{
foreach (VarDeclaration v2; byval ? eb2.byvalue : eb2.byref)
{
checkOnePair(i, eb, eb2, v, v2, byval);
}
}
}
}
foreach (const i, ref eb; escapeBy[0 .. $ - 1])
{
escape(i, eb, true);
escape(i, eb, false);
}
return errors;
}
/******************************************
* Array literal is going to be allocated on the GC heap.
* Check its elements to see if any would escape by going on the heap.
* Params:
* sc = used to determine current function and module
* ae = array literal expression
* gag = do not print error messages
* Returns:
* `true` if any elements escaped
*/
public
bool checkArrayLiteralEscape(ref Scope sc, ArrayLiteralExp ae, bool gag)
{
bool errors;
if (ae.basis)
errors = checkNewEscape(sc, ae.basis, gag);
foreach (ex; *ae.elements)
{
if (ex)
errors |= checkNewEscape(sc, ex, gag);
}
return errors;
}
/******************************************
* Associative array literal is going to be allocated on the GC heap.
* Check its elements to see if any would escape by going on the heap.
* Params:
* sc = used to determine current function and module
* ae = associative array literal expression
* gag = do not print error messages
* Returns:
* `true` if any elements escaped
*/
public
bool checkAssocArrayLiteralEscape(ref Scope sc, AssocArrayLiteralExp ae, bool gag)
{
bool errors;
foreach (ex; *ae.keys)
{
if (ex)
errors |= checkNewEscape(sc, ex, gag);
}
foreach (ex; *ae.values)
{
if (ex)
errors |= checkNewEscape(sc, ex, gag);
}
return errors;
}
/**
* A `scope` variable was assigned to non-scope parameter `v`.
* If applicable, print why the parameter was not inferred `scope`.
*
* Params:
* printFunc = error/deprecation print function to use
* v = parameter that was not inferred
* recursionLimit = recursion limit for printing the reason
*/
private
void printScopeFailure(E)(E printFunc, VarDeclaration v, int recursionLimit)
{
recursionLimit--;
if (recursionLimit < 0 || !v)
return;
if (RootObject* o = v.sequenceNumber in EscapeState.scopeInferFailure)
{
switch ((*o).dyncast())
{
case DYNCAST.expression:
Expression e = cast(Expression) *o;
printFunc(e.loc, "which is not `scope` because of `%s`", e.toChars());
break;
case DYNCAST.dsymbol:
VarDeclaration v1 = cast(VarDeclaration) *o;
printFunc(v1.loc, "which is assigned to non-scope parameter `%s`", v1.toChars());
printScopeFailure(printFunc, v1, recursionLimit);
break;
default:
assert(0);
}
}
}
/****************************************
* Function parameter `par` is being initialized to `arg`,
* and `par` may escape.
* Detect if scoped values can escape this way.
* Print error messages when these are detected.
* Params:
* sc = used to determine current function and module
* fdc = function being called, `null` if called indirectly
* parId = name of function parameter for error messages
* vPar = `VarDeclaration` corresponding to `par`
* parStc = storage classes of function parameter (may have added `scope` from `pure`)
* arg = initializer for param
* assertmsg = true if the parameter is the msg argument to assert(bool, msg).
* gag = do not print error messages
* Returns:
* `true` if pointers to the stack can escape via assignment
*/
public
bool checkParamArgumentEscape(ref Scope sc, FuncDeclaration fdc, Identifier parId, VarDeclaration vPar, STC parStc, Expression arg, bool assertmsg, bool gag)
{
enum log = false;
if (log) printf("checkParamArgumentEscape(arg: %s par: %s parSTC: %llx)\n",
arg ? arg.toChars() : "null",
parId ? parId.toChars() : "null", parStc);
//printf("type = %s, %d\n", arg.type.toChars(), arg.type.hasPointers());
if (!arg.type.hasPointers())
return false;
bool result = false;
/* 'v' is assigned unsafely to 'par'
*/
void unsafeAssign(string desc)(VarDeclaration v)
{
if (assertmsg)
{
result |= sc.setUnsafeDIP1000(gag, arg.loc,
desc ~ " `%s` assigned to non-scope parameter calling `assert()`", v);
return;
}
bool isThis = fdc && fdc.needThis() && fdc.vthis == vPar; // implicit `this` parameter to member function
const(char)* msg =
(isThis) ? (desc ~ " `%s` calling non-scope member function `%s.%s()`") :
(fdc && parId) ? (desc ~ " `%s` assigned to non-scope parameter `%s` calling `%s`") :
(fdc && !parId) ? (desc ~ " `%s` assigned to non-scope anonymous parameter calling `%s`") :
(!fdc && parId) ? (desc ~ " `%s` assigned to non-scope parameter `%s`") :
(desc ~ " `%s` assigned to non-scope anonymous parameter");
if (isThis ?
sc.setUnsafeDIP1000(gag, arg.loc, msg, arg, fdc.toParent2(), fdc) :
sc.setUnsafeDIP1000(gag, arg.loc, msg, v, parId ? parId : fdc, fdc))
{
result = true;
printScopeFailure(previewSupplementalFunc(sc.isDeprecated(), sc.useDIP1000), vPar, 10);
}
}
void onValue(VarDeclaration v)
{
if (log) printf("byvalue %s\n", v.toChars());
if (parStc & STC.scope_ || v.isDataseg())
return;
Dsymbol p = v.toParent2();
notMaybeScope(v, vPar);
if (v.isScope())
{
unsafeAssign!"scope variable"(v);
}
else if (v.isTypesafeVariadicArray && p == sc.func)
{
unsafeAssign!"variadic variable"(v);
}
}
void onRef(VarDeclaration v, bool retRefTransition)
{
if (log) printf("byref %s\n", v.toChars());
if (v.isDataseg())
return;
Dsymbol p = v.toParent2();
notMaybeScope(v, arg);
if (checkScopeVarAddr(v, arg, sc, gag))
{
result = true;
return;
}
if (p == sc.func && !(parStc & STC.scope_))
{
unsafeAssign!"reference to local variable"(v);
return;
}
}
void onFunc(FuncDeclaration fd, bool called)
{
//printf("fd = %s, %d\n", fd.toChars(), fd.tookAddressOf);
if (parStc & STC.scope_)
return;
VarDeclarations vars;
findAllOuterAccessedVariables(fd, &vars);
foreach (v; vars)
{
//printf("v = %s\n", v.toChars());
assert(!v.isDataseg()); // these are not put in the closureVars[]
Dsymbol p = v.toParent2();
notMaybeScope(v, arg);
if ((v.isReference() || v.isScope()) && p == sc.func)
{
unsafeAssign!"reference to local"(v);
return;
}
}
}
void onExp(Expression ee, bool retRefTransition)
{
if (parStc & STC.scope_)
return;
const(char)* msg = parId ?
"reference to stack allocated value returned by `%s` assigned to non-scope parameter `%s`" :
"reference to stack allocated value returned by `%s` assigned to non-scope anonymous parameter";
result |= sc.setUnsafeDIP1000(gag, ee.loc, msg, ee, parId);
}
scope EscapeByResults er = EscapeByResults(&onRef, &onValue, &onFunc, &onExp);
escapeByValue(arg, er);
return result;
}
/*****************************************************
* Function argument initializes a `return` parameter,
* and that parameter gets assigned to `firstArg`.
* Essentially, treat as `firstArg = arg;`
* Params:
* sc = used to determine current function and module
* firstArg = `ref` argument through which `arg` may be assigned
* arg = initializer for parameter
* param = parameter declaration corresponding to `arg`
* gag = do not print error messages
* Returns:
* `true` if assignment to `firstArg` would cause an error
*/
public
bool checkParamArgumentReturn(ref Scope sc, Expression firstArg, Expression arg, Parameter param, bool gag)
{
enum log = false;
if (log) printf("checkParamArgumentReturn(firstArg: %s arg: %s)\n",
firstArg.toChars(), arg.toChars());
//printf("type = %s, %d\n", arg.type.toChars(), arg.type.hasPointers());
if (!(param.storageClass & STC.return_))
return false;
if (!arg.type.hasPointers() && !param.isReference())
return false;
// `byRef` needed for `assign(ref int* x, ref int i) {x = &i};`
// Note: taking address of scope pointer is not allowed
// `assign(ref int** x, return ref scope int* i) {x = &i};`
// Thus no return ref/return scope ambiguity here
const byRef = param.isReference() && !(param.storageClass & STC.scope_)
&& !(param.storageClass & STC.returnScope); // fixme: it's possible to infer returnScope without scope with vaIsFirstRef
auto e = new AssignExp(arg.loc, firstArg, arg);
return checkAssignEscape(sc, e, gag, byRef);
}
/*****************************************************
* Check struct constructor of the form `s.this(args)`, by
* checking each `return` parameter to see if it gets
* assigned to `s`.
* Params:
* sc = used to determine current function and module
* ce = constructor call of the form `s.this(args)`
* gag = do not print error messages
* Returns:
* `true` if construction would cause an escaping reference error
*/
public
bool checkConstructorEscape(ref Scope sc, CallExp ce, bool gag)
{
enum log = false;
if (log) printf("checkConstructorEscape(%s, %s)\n", ce.toChars(), ce.type.toChars());
Type tthis = ce.type.toBasetype();
assert(tthis.ty == Tstruct);
if (!tthis.hasPointers())
return false;
if (!ce.arguments && ce.arguments.length)
return false;
DotVarExp dve = ce.e1.isDotVarExp();
CtorDeclaration ctor = dve.var.isCtorDeclaration();
TypeFunction tf = ctor.type.isTypeFunction();
const nparams = tf.parameterList.length;
const n = ce.arguments.length;
// j=1 if _arguments[] is first argument
const j = tf.isDstyleVariadic();
/* Attempt to assign each `return` arg to the `this` reference
*/
foreach (const i; 0 .. n)
{
Expression arg = (*ce.arguments)[i];
//printf("\targ[%d]: %s\n", i, arg.toChars());
if (i - j < nparams && i >= j)
{
Parameter p = tf.parameterList[i - j];
if (checkParamArgumentReturn(sc, dve.e1, arg, p, gag))
return true;
}
}
return false;
}
/// How a `return` parameter escapes its pointer value
public
enum ReturnParamDest
{
returnVal, /// through return statement: `return x`
this_, /// assigned to a struct instance: `this.x = x`
firstArg, /// assigned to first argument: `firstArg = x`
}
/****************************************
* Find out if instead of returning a `return` parameter via a return statement,
* it is returned via assignment to either `this` or the first parameter.
*
* This works the same as returning the value via a return statement.
* Although the first argument must be `ref`, it is not regarded as returning by `ref`.
*
* See_Also: https://dlang.org.spec/function.html#return-ref-parameters
*
* Params:
* tf = function type
* tthis = type of `this` parameter, or `null` if none
* Returns: What a `return` parameter should transfer the lifetime of the argument to
*/
public
ReturnParamDest returnParamDest(TypeFunction tf, Type tthis)
{
assert(tf);
if (tf.isctor)
return ReturnParamDest.this_;
if (!tf.nextOf() || (tf.nextOf().ty != Tvoid))
return ReturnParamDest.returnVal;
if (tthis && tthis.toBasetype().ty == Tstruct) // class `this` is passed by value
return ReturnParamDest.this_;
if (tf.parameterList.length > 0 && tf.parameterList[0].isReference)
return ReturnParamDest.firstArg;
return ReturnParamDest.returnVal;
}
/****************************************
* Given an `AssignExp`, determine if the lvalue will cause
* the contents of the rvalue to escape.
* Print error messages when these are detected.
* Infer `scope` attribute for the lvalue where possible, in order
* to eliminate the error.
* Params:
* sc = used to determine current function and module
* e = `AssignExp` or `CatAssignExp` to check for any pointers to the stack
* gag = do not print error messages
* byRef = set to `true` if `e1` of `e` gets assigned a reference to `e2`
* Returns:
* `true` if pointers to the stack can escape via assignment
*/
public
bool checkAssignEscape(ref Scope sc, Expression e, bool gag, bool byRef)
{
enum log = false;
if (log) printf("checkAssignEscape(e: %s, byRef: %d)\n", e.toChars(), byRef);
if (e.op != EXP.assign && e.op != EXP.blit && e.op != EXP.construct &&
e.op != EXP.concatenateAssign && e.op != EXP.concatenateElemAssign && e.op != EXP.concatenateDcharAssign)
return false;
auto ae = cast(BinExp)e;
Expression e1 = ae.e1;
Expression e2 = ae.e2;
//printf("type = %s, %d\n", e1.type.toChars(), e1.type.hasPointers());
if (!e1.type.hasPointers())
return false;
if (e1.isSliceExp())
{
if (VarDeclaration va = expToVariable(e1))
{
if (!va.type.toBasetype().isTypeSArray() || // treat static array slice same as a variable
!va.type.hasPointers())
return false;
}
else
return false;
}
/* The struct literal case can arise from the S(e2) constructor call:
* return S(e2);
* and appears in this function as:
* structLiteral = e2;
* Such an assignment does not necessarily remove scope-ness.
*/
if (e1.isStructLiteralExp())
return false;
VarDeclaration va = expToVariable(e1);
if (va && e.op == EXP.concatenateElemAssign)
{
/* https://issues.dlang.org/show_bug.cgi?id=17842
* Draw an equivalence between:
* *q = p;
* and:
* va ~= e;
* since we are not assigning to va, but are assigning indirectly through va.
*/
va = null;
}
if (va && e1.isDotVarExp() && va.type.toBasetype().isTypeClass())
{
/* https://issues.dlang.org/show_bug.cgi?id=17949
* Draw an equivalence between:
* *q = p;
* and:
* va.field = e2;
* since we are not assigning to va, but are assigning indirectly through class reference va.
*/
va = null;
}
if (log && va) printf("va: %s\n", va.toChars());
FuncDeclaration fd = sc.func;
// Determine if va is a `ref` parameter, so it has a lifetime exceding the function scope
const bool vaIsRef = va && va.isParameter() && va.isReference();
if (log && vaIsRef) printf("va is ref `%s`\n", va.toChars());
// Determine if va is the first parameter, through which other 'return' parameters
// can be assigned.
bool vaIsFirstRef = false;
if (fd && fd.type)
{
final switch (returnParamDest(fd.type.isTypeFunction(), fd.vthis ? fd.vthis.type : null))
{
case ReturnParamDest.this_:
vaIsFirstRef = va == fd.vthis;
break;
case ReturnParamDest.firstArg:
// While you'd expect fd.parameters[0] to exist in this case, the compiler-generated
// expression that initializes an `out int* p = null` is analyzed before fd.parameters
// is created, so we still do a null and length check
vaIsFirstRef = fd.parameters && 0 < fd.parameters.length && (*fd.parameters)[0] == va;
break;
case ReturnParamDest.returnVal:
break;
}
}
if (log && vaIsFirstRef) printf("va is first ref `%s`\n", va.toChars());
bool result = false;
void onValue(VarDeclaration v)
{
if (log) printf("byvalue: %s\n", v.toChars());
if (v.isDataseg())
return;
if (v == va)
return;
Dsymbol p = v.toParent2();
if (va && !vaIsRef && !va.isScope() && !v.isScope() &&
!v.isTypesafeVariadicArray && !va.isTypesafeVariadicArray &&
(va.isParameter() && va.maybeScope && v.isParameter() && v.maybeScope) &&
p == fd)
{
/* Add v to va's list of dependencies
*/
va.addMaybe(v);
return;
}
if (vaIsFirstRef && p == fd)
{
inferReturn(fd, v, /*returnScope:*/ true);
}
if (!(va && va.isScope()) || vaIsRef)
notMaybeScope(v, e);
if (v.isScope())
{
if (vaIsFirstRef && v.isParameter() && v.isReturn())
{
// va=v, where v is `return scope`
if (inferScope(va))
return;
}
// If va's lifetime encloses v's, then error
if (EnclosedBy eb = va.enclosesLifetimeOf(v))
{
const(char)* msg;
final switch (eb)
{
case EnclosedBy.none: assert(0);
case EnclosedBy.returnScope:
msg = "scope variable `%s` assigned to return scope `%s`";
break;
case EnclosedBy.longerScope:
if (v.storage_class & STC.temp)
return;
msg = "scope variable `%s` assigned to `%s` with longer lifetime";
break;
case EnclosedBy.refVar:
msg = "scope variable `%s` assigned to `ref` variable `%s` with longer lifetime";
break;
case EnclosedBy.global:
msg = "scope variable `%s` assigned to global variable `%s`";
break;
}
if (sc.setUnsafeDIP1000(gag, ae.loc, msg, v, va))
{
result = true;
return;
}
}
// v = scope, va should be scope as well
const vaWasScope = va && va.isScope();
if (inferScope(va))
{
// In case of `scope local = returnScopeParam`, do not infer return scope for `x`
if (!vaWasScope && v.isReturn() && !va.isReturn())
{
if (log) printf("infer return for %s\n", va.toChars());
va.storage_class |= STC.return_ | STC.returninferred;
// Added "return scope" so don't confuse it with "return ref"
if (isRefReturnScope(va.storage_class))
va.storage_class |= STC.returnScope;
}
return;
}
result |= sc.setUnsafeDIP1000(gag, ae.loc, "scope variable `%s` assigned to non-scope `%s`", v, e1);
}
else if (v.isTypesafeVariadicArray && p == fd)
{
if (inferScope(va))
return;
result |= sc.setUnsafeDIP1000(gag, ae.loc, "variadic variable `%s` assigned to non-scope `%s`", v, e1);
}
else
{
/* v is not 'scope', and we didn't check the scope of where we assigned it to.
* It may escape via that assignment, therefore, v can never be 'scope'.
*/
//printf("no infer for %s in %s, %d\n", v.toChars(), fd.ident.toChars(), __LINE__);
doNotInferScope(v, e);
}
}
void onRef(VarDeclaration v, bool retRefTransition)
{
if (log) printf("byref: %s\n", v.toChars());
if (v.isDataseg())
return;
if (checkScopeVarAddr(v, ae, sc, gag))
{
result = true;
return;
}
if (va && va.isScope() && !v.isReference())
{
if (!va.isReturn())
{
va.doNotInferReturn = true;
}
else
{
result |= sc.setUnsafeDIP1000(gag, ae.loc,
"address of local variable `%s` assigned to return scope `%s`", v, va);
}
}
Dsymbol p = v.toParent2();
if (vaIsFirstRef && p == fd)
{
//if (log) printf("inferring 'return' for parameter %s in function %s\n", v.toChars(), fd.toChars());
inferReturn(fd, v, /*returnScope:*/ false);
}
// If va's lifetime encloses v's, then error
if (va && !(vaIsFirstRef && v.isReturn()) && va.enclosesLifetimeOf(v))
{
if (sc.setUnsafeDIP1000(gag, ae.loc, "address of variable `%s` assigned to `%s` with longer lifetime", v, va))
{
result = true;
return;
}
}
if (!(va && va.isScope()))
notMaybeScope(v, e);
if (p != sc.func)
return;
if (inferScope(va))
{
if (v.isReturn() && !va.isReturn())
va.storage_class |= STC.return_ | STC.returninferred;
return;
}
if (e1.op == EXP.structLiteral)
return;
result |= sc.setUnsafeDIP1000(gag, ae.loc, "reference to local variable `%s` assigned to non-scope `%s`", v, e1);
}
void onFunc(FuncDeclaration func, bool called)
{
if (log) printf("byfunc: %s, %d\n", func.toChars(), func.tookAddressOf);
VarDeclarations vars;
findAllOuterAccessedVariables(func, &vars);
/* https://issues.dlang.org/show_bug.cgi?id=16037
* If assigning the address of a delegate to a scope variable,
* then uncount that address of. This is so it won't cause a
* closure to be allocated.
*/
if (va && va.isScope() && !va.isReturn() && func.tookAddressOf)
--func.tookAddressOf;
foreach (v; vars)
{
//printf("v = %s\n", v.toChars());
assert(!v.isDataseg()); // these are not put in the closureVars[]
Dsymbol p = v.toParent2();
if (!(va && va.isScope()))
notMaybeScope(v, e);
if (!(v.isReference() || v.isScope()) || p != fd)
return;
if (va && !va.isDataseg() && (va.isScope() || va.maybeScope))
{
/* Don't infer STC.scope_ for va, because then a closure
* won't be generated for fd.
*/
//if (!va.isScope())
//va.storage_class |= STC.scope_ | STC.scopeinferred;
return;
}
result |= sc.setUnsafeDIP1000(gag, ae.loc,
"reference to local `%s` assigned to non-scope `%s` in @safe code", v, e1);
}
}
void onExp(Expression ee, bool retRefTransition)
{
if (log) printf("byexp: %s\n", ee.toChars());
/* Do not allow slicing of a static array returned by a function
*/
if (ee.op == EXP.call && ee.type.toBasetype().isTypeSArray() && e1.type.toBasetype().isTypeDArray() &&
!(va && va.storage_class & STC.temp))
{
if (!gag)
sc.eSink.deprecation(ee.loc, "slice of static array temporary returned by `%s` assigned to longer lived variable `%s`",
ee.toChars(), e1.toChars());
//result = true;
return;
}
if (ee.op == EXP.call && ee.type.toBasetype().isTypeStruct() &&
(!va || !(va.storage_class & STC.temp) && !va.isScope()))
{
if (sc.setUnsafeDIP1000(gag, ee.loc, "address of struct temporary returned by `%s` assigned to longer lived variable `%s`", ee, e1))
{
result = true;
return;
}
}
if (ee.op == EXP.structLiteral &&
(!va || !(va.storage_class & STC.temp)))
{
if (sc.setUnsafeDIP1000(gag, ee.loc, "address of struct literal `%s` assigned to longer lived variable `%s`", ee, e1))
{
result = true;
return;
}
}
if (inferScope(va))
return;
result |= sc.setUnsafeDIP1000(gag, ee.loc,
"reference to stack allocated value returned by `%s` assigned to non-scope `%s`", ee, e1);
}
scope EscapeByResults er = EscapeByResults(&onRef, &onValue, &onFunc, &onExp);
if (byRef)
escapeByRef(e2, er);
else
escapeByValue(e2, er);
return result;
}
/************************************
* Detect cases where pointers to the stack can escape the
* lifetime of the stack frame when throwing `e`.
* Print error messages when these are detected.
* Params:
* sc = used to determine current function and module
* e = expression to check for any pointers to the stack
* gag = do not print error messages
* Returns:
* `true` if pointers to the stack can escape
*/
public
bool checkThrowEscape(ref Scope sc, Expression e, bool gag)
{
//printf("[%s] checkThrowEscape, e = %s\n", e.loc.toChars(), e.toChars());
bool result = false;
void onRef(VarDeclaration v, bool retRefTransition) {}
void onValue(VarDeclaration v)
{
//printf("byvalue %s\n", v.toChars());
if (v.isDataseg())
return;
if (v.isScope() && !v.iscatchvar) // special case: allow catch var to be rethrown
// despite being `scope`
{
// https://issues.dlang.org/show_bug.cgi?id=17029
result |= sc.setUnsafeDIP1000(gag, e.loc, "scope variable `%s` may not be thrown", v);
return;
}
else
{
notMaybeScope(v, new ThrowExp(e.loc, e));
}
}
void onFunc(FuncDeclaration fd, bool called) {}
void onExp(Expression exp, bool retRefTransition) {}
scope EscapeByResults er = EscapeByResults(&onRef, &onValue, &onFunc, &onExp);
escapeByValue(e, er);
return result;