| 1 |
/** |
| 2 |
* Most of the logic to implement scoped pointers and scoped references is here. |
| 3 |
* |
| 4 |
* Copyright: Copyright (C) 1999-2025 by The D Language Foundation, All Rights Reserved |
| 5 |
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright) |
| 6 |
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0) |
| 7 |
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/compiler/src/dmd/escape.d, _escape.d) |
| 8 |
* Documentation: https://dlang.org/phobos/dmd_escape.html |
| 9 |
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/compiler/src/dmd/escape.d |
| 10 |
*/ |
| 11 |
|
| 12 |
module dmd.escape; |
| 13 |
|
| 14 |
import core.stdc.stdio : printf; |
| 15 |
import core.stdc.stdlib; |
| 16 |
import core.stdc.string; |
| 17 |
|
| 18 |
import dmd.root.rmem; |
| 19 |
|
| 20 |
import dmd.aggregate; |
| 21 |
import dmd.astenums; |
| 22 |
import dmd.declaration; |
| 23 |
import dmd.dscope; |
| 24 |
import dmd.dsymbol; |
| 25 |
import dmd.errors; |
| 26 |
import dmd.expression; |
| 27 |
import dmd.func; |
| 28 |
import dmd.funcsem; |
| 29 |
import dmd.globals : FeatureState; |
| 30 |
import dmd.id; |
| 31 |
import dmd.identifier; |
| 32 |
import dmd.init; |
| 33 |
import dmd.location; |
| 34 |
import dmd.mtype; |
| 35 |
import dmd.printast; |
| 36 |
import dmd.rootobject; |
| 37 |
import dmd.safe; |
| 38 |
import dmd.tokens; |
| 39 |
import dmd.typesem : hasPointers, parameterStorageClass; |
| 40 |
import dmd.visitor; |
| 41 |
import dmd.arraytypes; |
| 42 |
|
| 43 |
private: |
| 44 |
|
| 45 |
/// Groups global state for escape checking together |
| 46 |
package(dmd) struct EscapeState |
| 47 |
{ |
| 48 |
// Maps `sequenceNumber` of a `VarDeclaration` to an object that contains the |
| 49 |
// reason it failed to infer `scope` |
| 50 |
// https://issues.dlang.org/show_bug.cgi?id=23295 |
| 51 |
private __gshared RootObject[int] scopeInferFailure; |
| 52 |
|
| 53 |
/// Called by `initDMD` / `deinitializeDMD` to reset global state |
| 54 |
static void reset() |
| 55 |
{ |
| 56 |
scopeInferFailure = null; |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
/****************************************************** |
| 61 |
* Checks memory objects passed to a function. |
| 62 |
* Checks that if a memory object is passed by ref or by pointer, |
| 63 |
* all of the refs or pointers are const, or there is only one mutable |
| 64 |
* ref or pointer to it. |
| 65 |
* References: |
| 66 |
* DIP 1021 |
| 67 |
* Params: |
| 68 |
* sc = used to determine current function and module |
| 69 |
* fd = function being called |
| 70 |
* tf = fd's type |
| 71 |
* ethis = if not null, the `this` pointer |
| 72 |
* arguments = actual arguments to function |
| 73 |
* gag = do not print error messages |
| 74 |
* Returns: |
| 75 |
* `true` if error |
| 76 |
*/ |
| 77 |
public |
| 78 |
bool checkMutableArguments(ref Scope sc, FuncDeclaration fd, TypeFunction tf, |
| 79 |
Expression ethis, Expressions* arguments, bool gag) |
| 80 |
{ |
| 81 |
enum log = false; |
| 82 |
if (log) printf("[%s] checkMutableArguments, fd: `%s`\n", fd.loc.toChars(), fd.toChars()); |
| 83 |
if (log && ethis) printf("ethis: `%s`\n", ethis.toChars()); |
| 84 |
bool errors = false; |
| 85 |
|
| 86 |
/* Outer variable references are treated as if they are extra arguments |
| 87 |
* passed by ref to the function (which they essentially are via the static link). |
| 88 |
*/ |
| 89 |
VarDeclaration[] outerVars = fd ? fd.outerVars[] : null; |
| 90 |
|
| 91 |
const len = arguments.length + (ethis !is null) + outerVars.length; |
| 92 |
if (len <= 1) |
| 93 |
return errors; |
| 94 |
|
| 95 |
struct EscapeBy |
| 96 |
{ |
| 97 |
VarDeclarations byref; |
| 98 |
VarDeclarations byvalue; |
| 99 |
Parameter param; // null if no Parameter for this argument |
| 100 |
bool isMutable; // true if reference to mutable |
| 101 |
} |
| 102 |
|
| 103 |
auto escapeBy = new EscapeBy[len]; |
| 104 |
const paramLength = tf.parameterList.length; |
| 105 |
|
| 106 |
// Fill in escapeBy[] with arguments[], ethis, and outerVars[] |
| 107 |
foreach (const i, ref eb; escapeBy) |
| 108 |
{ |
| 109 |
bool refs; |
| 110 |
Expression arg; |
| 111 |
if (i < arguments.length) |
| 112 |
{ |
| 113 |
arg = (*arguments)[i]; |
| 114 |
if (i < paramLength) |
| 115 |
{ |
| 116 |
eb.param = tf.parameterList[i]; |
| 117 |
refs = eb.param.isReference(); |
| 118 |
eb.isMutable = eb.param.isReferenceToMutable(arg.type); |
| 119 |
} |
| 120 |
else |
| 121 |
{ |
| 122 |
eb.param = null; |
| 123 |
refs = false; |
| 124 |
eb.isMutable = arg.type.isReferenceToMutable(); |
| 125 |
} |
| 126 |
} |
| 127 |
else if (ethis) |
| 128 |
{ |
| 129 |
/* ethis is passed by value if a class reference, |
| 130 |
* by ref if a struct value |
| 131 |
*/ |
| 132 |
eb.param = null; |
| 133 |
arg = ethis; |
| 134 |
auto ad = fd.isThis(); |
| 135 |
assert(ad); |
| 136 |
assert(ethis); |
| 137 |
if (ad.isClassDeclaration()) |
| 138 |
{ |
| 139 |
refs = false; |
| 140 |
eb.isMutable = arg.type.isReferenceToMutable(); |
| 141 |
} |
| 142 |
else |
| 143 |
{ |
| 144 |
assert(ad.isStructDeclaration()); |
| 145 |
refs = true; |
| 146 |
eb.isMutable = arg.type.isMutable(); |
| 147 |
} |
| 148 |
} |
| 149 |
else |
| 150 |
{ |
| 151 |
// outer variables are passed by ref |
| 152 |
eb.param = null; |
| 153 |
refs = true; |
| 154 |
auto var = outerVars[i - (len - outerVars.length)]; |
| 155 |
eb.isMutable = var.type.isMutable(); |
| 156 |
eb.byref.push(var); |
| 157 |
continue; |
| 158 |
} |
| 159 |
|
| 160 |
void onRef(VarDeclaration v, bool transition) { eb.byref.push(v); } |
| 161 |
void onValue(VarDeclaration v) { eb.byvalue.push(v); } |
| 162 |
void onFunc(FuncDeclaration fd, bool called) {} |
| 163 |
void onExp(Expression e, bool transition) {} |
| 164 |
|
| 165 |
scope EscapeByResults er = EscapeByResults(&onRef, &onValue, &onFunc, &onExp); |
| 166 |
|
| 167 |
if (refs) |
| 168 |
escapeByRef(arg, er); |
| 169 |
else |
| 170 |
escapeByValue(arg, er); |
| 171 |
} |
| 172 |
|
| 173 |
void checkOnePair(size_t i, ref EscapeBy eb, ref EscapeBy eb2, |
| 174 |
VarDeclaration v, VarDeclaration v2, bool of) |
| 175 |
{ |
| 176 |
if (log) printf("v2: `%s`\n", v2.toChars()); |
| 177 |
if (v2 != v) |
| 178 |
return; |
| 179 |
//printf("v %d v2 %d\n", eb.isMutable, eb2.isMutable); |
| 180 |
if (!(eb.isMutable || eb2.isMutable)) |
| 181 |
return; |
| 182 |
|
| 183 |
if (!tf.isLive && !(sc.useDIP1000 == FeatureState.enabled && sc.func && setFunctionToUnsafe(sc.func))) |
| 184 |
return; |
| 185 |
|
| 186 |
if (!gag) |
| 187 |
{ |
| 188 |
// int i; funcThatEscapes(ref int i); |
| 189 |
// funcThatEscapes(i); // error escaping reference _to_ `i` |
| 190 |
// int* j; funcThatEscapes2(int* j); |
| 191 |
// funcThatEscapes2(j); // error escaping reference _of_ `i` |
| 192 |
const(char)* referenceVerb = of ? "of" : "to"; |
| 193 |
const(char)* msg = eb.isMutable && eb2.isMutable |
| 194 |
? "more than one mutable reference %s `%s` in arguments to `%s()`" |
| 195 |
: "mutable and const references %s `%s` in arguments to `%s()`"; |
| 196 |
sc.eSink.error((*arguments)[i].loc, msg, |
| 197 |
referenceVerb, |
| 198 |
v.toChars(), |
| 199 |
fd ? fd.toPrettyChars() : "indirectly"); |
| 200 |
} |
| 201 |
errors = true; |
| 202 |
} |
| 203 |
|
| 204 |
void escape(size_t i, ref EscapeBy eb, bool byval) |
| 205 |
{ |
| 206 |
foreach (VarDeclaration v; byval ? eb.byvalue : eb.byref) |
| 207 |
{ |
| 208 |
if (log) |
| 209 |
{ |
| 210 |
const(char)* by = byval ? "byval" : "byref"; |
| 211 |
printf("%s %s\n", by, v.toChars()); |
| 212 |
} |
| 213 |
if (byval && !v.type.hasPointers()) |
| 214 |
continue; |
| 215 |
foreach (ref eb2; escapeBy[i + 1 .. $]) |
| 216 |
{ |
| 217 |
foreach (VarDeclaration v2; byval ? eb2.byvalue : eb2.byref) |
| 218 |
{ |
| 219 |
checkOnePair(i, eb, eb2, v, v2, byval); |
| 220 |
} |
| 221 |
} |
| 222 |
} |
| 223 |
} |
| 224 |
foreach (const i, ref eb; escapeBy[0 .. $ - 1]) |
| 225 |
{ |
| 226 |
escape(i, eb, true); |
| 227 |
escape(i, eb, false); |
| 228 |
} |
| 229 |
|
| 230 |
return errors; |
| 231 |
} |
| 232 |
|
| 233 |
/****************************************** |
| 234 |
* Array literal is going to be allocated on the GC heap. |
| 235 |
* Check its elements to see if any would escape by going on the heap. |
| 236 |
* Params: |
| 237 |
* sc = used to determine current function and module |
| 238 |
* ae = array literal expression |
| 239 |
* gag = do not print error messages |
| 240 |
* Returns: |
| 241 |
* `true` if any elements escaped |
| 242 |
*/ |
| 243 |
public |
| 244 |
bool checkArrayLiteralEscape(ref Scope sc, ArrayLiteralExp ae, bool gag) |
| 245 |
{ |
| 246 |
bool errors; |
| 247 |
if (ae.basis) |
| 248 |
errors = checkNewEscape(sc, ae.basis, gag); |
| 249 |
foreach (ex; *ae.elements) |
| 250 |
{ |
| 251 |
if (ex) |
| 252 |
errors |= checkNewEscape(sc, ex, gag); |
| 253 |
} |
| 254 |
return errors; |
| 255 |
} |
| 256 |
|
| 257 |
/****************************************** |
| 258 |
* Associative array literal is going to be allocated on the GC heap. |
| 259 |
* Check its elements to see if any would escape by going on the heap. |
| 260 |
* Params: |
| 261 |
* sc = used to determine current function and module |
| 262 |
* ae = associative array literal expression |
| 263 |
* gag = do not print error messages |
| 264 |
* Returns: |
| 265 |
* `true` if any elements escaped |
| 266 |
*/ |
| 267 |
public |
| 268 |
bool checkAssocArrayLiteralEscape(ref Scope sc, AssocArrayLiteralExp ae, bool gag) |
| 269 |
{ |
| 270 |
bool errors; |
| 271 |
foreach (ex; *ae.keys) |
| 272 |
{ |
| 273 |
if (ex) |
| 274 |
errors |= checkNewEscape(sc, ex, gag); |
| 275 |
} |
| 276 |
foreach (ex; *ae.values) |
| 277 |
{ |
| 278 |
if (ex) |
| 279 |
errors |= checkNewEscape(sc, ex, gag); |
| 280 |
} |
| 281 |
return errors; |
| 282 |
} |
| 283 |
|
| 284 |
/** |
| 285 |
* A `scope` variable was assigned to non-scope parameter `v`. |
| 286 |
* If applicable, print why the parameter was not inferred `scope`. |
| 287 |
* |
| 288 |
* Params: |
| 289 |
* printFunc = error/deprecation print function to use |
| 290 |
* v = parameter that was not inferred |
| 291 |
* recursionLimit = recursion limit for printing the reason |
| 292 |
*/ |
| 293 |
private |
| 294 |
void printScopeFailure(E)(E printFunc, VarDeclaration v, int recursionLimit) |
| 295 |
{ |
| 296 |
recursionLimit--; |
| 297 |
if (recursionLimit < 0 || !v) |
| 298 |
return; |
| 299 |
|
| 300 |
if (RootObject* o = v.sequenceNumber in EscapeState.scopeInferFailure) |
| 301 |
{ |
| 302 |
switch ((*o).dyncast()) |
| 303 |
{ |
| 304 |
case DYNCAST.expression: |
| 305 |
Expression e = cast(Expression) *o; |
| 306 |
printFunc(e.loc, "which is not `scope` because of `%s`", e.toChars()); |
| 307 |
break; |
| 308 |
case DYNCAST.dsymbol: |
| 309 |
VarDeclaration v1 = cast(VarDeclaration) *o; |
| 310 |
printFunc(v1.loc, "which is assigned to non-scope parameter `%s`", v1.toChars()); |
| 311 |
printScopeFailure(printFunc, v1, recursionLimit); |
| 312 |
break; |
| 313 |
default: |
| 314 |
assert(0); |
| 315 |
} |
| 316 |
} |
| 317 |
} |
| 318 |
|
| 319 |
/**************************************** |
| 320 |
* Function parameter `par` is being initialized to `arg`, |
| 321 |
* and `par` may escape. |
| 322 |
* Detect if scoped values can escape this way. |
| 323 |
* Print error messages when these are detected. |
| 324 |
* Params: |
| 325 |
* sc = used to determine current function and module |
| 326 |
* fdc = function being called, `null` if called indirectly |
| 327 |
* parId = name of function parameter for error messages |
| 328 |
* vPar = `VarDeclaration` corresponding to `par` |
| 329 |
* parStc = storage classes of function parameter (may have added `scope` from `pure`) |
| 330 |
* arg = initializer for param |
| 331 |
* assertmsg = true if the parameter is the msg argument to assert(bool, msg). |
| 332 |
* gag = do not print error messages |
| 333 |
* Returns: |
| 334 |
* `true` if pointers to the stack can escape via assignment |
| 335 |
*/ |
| 336 |
public |
| 337 |
bool checkParamArgumentEscape(ref Scope sc, FuncDeclaration fdc, Identifier parId, VarDeclaration vPar, STC parStc, Expression arg, bool assertmsg, bool gag) |
| 338 |
{ |
| 339 |
enum log = false; |
| 340 |
if (log) printf("checkParamArgumentEscape(arg: %s par: %s parSTC: %llx)\n", |
| 341 |
arg ? arg.toChars() : "null", |
| 342 |
parId ? parId.toChars() : "null", parStc); |
| 343 |
//printf("type = %s, %d\n", arg.type.toChars(), arg.type.hasPointers()); |
| 344 |
|
| 345 |
if (!arg.type.hasPointers()) |
| 346 |
return false; |
| 347 |
|
| 348 |
bool result = false; |
| 349 |
|
| 350 |
/* 'v' is assigned unsafely to 'par' |
| 351 |
*/ |
| 352 |
void unsafeAssign(string desc)(VarDeclaration v) |
| 353 |
{ |
| 354 |
if (assertmsg) |
| 355 |
{ |
| 356 |
result |= sc.setUnsafeDIP1000(gag, arg.loc, |
| 357 |
"assigning" ~ desc ~ " `%s` to non-scope parameter calling `assert()`", v); |
| 358 |
return; |
| 359 |
} |
| 360 |
|
| 361 |
bool isThis = fdc && fdc.needThis() && fdc.vthis == vPar; // implicit `this` parameter to member function |
| 362 |
|
| 363 |
const(char)* msg = |
| 364 |
(isThis) ? (desc ~ " `%s` calling non-scope member function `%s.%s()`") : |
| 365 |
(fdc && parId) ? ("assigning " ~ desc ~ " `%s` to non-scope parameter `%s` calling `%s`") : |
| 366 |
(fdc && !parId) ? ("assigning " ~ desc ~ " `%s` to non-scope anonymous parameter calling `%s`") : |
| 367 |
(!fdc && parId) ? ("assigning " ~ desc ~ " `%s` to non-scope parameter `%s`") : |
| 368 |
(desc ~ " `%s` assigned to non-scope anonymous parameter"); |
| 369 |
|
| 370 |
if (isThis ? |
| 371 |
sc.setUnsafeDIP1000(gag, arg.loc, msg, arg, fdc.toParent2(), fdc) : |
| 372 |
sc.setUnsafeDIP1000(gag, arg.loc, msg, v, parId ? parId : fdc, fdc)) |
| 373 |
{ |
| 374 |
result = true; |
| 375 |
printScopeFailure(previewSupplementalFunc(sc.isDeprecated(), sc.useDIP1000), vPar, 10); |
| 376 |
} |
| 377 |
} |
| 378 |
|
| 379 |
void onValue(VarDeclaration v) |
| 380 |
{ |
| 381 |
if (log) printf("byvalue %s\n", v.toChars()); |
| 382 |
if (parStc & STC.scope_) |
| 383 |
return; |
| 384 |
|
| 385 |
doNotInferScope(v, vPar); |
| 386 |
|
| 387 |
if (v.isScope()) |
| 388 |
{ |
| 389 |
unsafeAssign!"scope variable"(v); |
| 390 |
} |
| 391 |
} |
| 392 |
|
| 393 |
void onRef(VarDeclaration v, bool retRefTransition) |
| 394 |
{ |
| 395 |
if (log) printf("byref %s\n", v.toChars()); |
| 396 |
|
| 397 |
Dsymbol p = v.toParent2(); |
| 398 |
|
| 399 |
doNotInferScope(v, arg); |
| 400 |
if (checkScopeVarAddr(v, arg, sc, gag)) |
| 401 |
{ |
| 402 |
result = true; |
| 403 |
return; |
| 404 |
} |
| 405 |
|
| 406 |
if (p == sc.func && !(parStc & STC.scope_)) |
| 407 |
{ |
| 408 |
unsafeAssign!"reference to local variable"(v); |
| 409 |
return; |
| 410 |
} |
| 411 |
} |
| 412 |
|
| 413 |
void onFunc(FuncDeclaration fd, bool called) |
| 414 |
{ |
| 415 |
//printf("fd = %s, %d\n", fd.toChars(), fd.tookAddressOf); |
| 416 |
if (parStc & STC.scope_) |
| 417 |
return; |
| 418 |
VarDeclarations vars; |
| 419 |
findAllOuterAccessedVariables(fd, &vars); |
| 420 |
|
| 421 |
foreach (v; vars) |
| 422 |
{ |
| 423 |
//printf("v = %s\n", v.toChars()); |
| 424 |
assert(!v.isDataseg()); // these are not put in the closureVars[] |
| 425 |
|
| 426 |
Dsymbol p = v.toParent2(); |
| 427 |
|
| 428 |
doNotInferScope(v, arg); |
| 429 |
|
| 430 |
if ((v.isReference() || v.isScope()) && p == sc.func) |
| 431 |
{ |
| 432 |
unsafeAssign!"reference to local"(v); |
| 433 |
return; |
| 434 |
} |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
void onExp(Expression ee, bool retRefTransition) |
| 439 |
{ |
| 440 |
if (parStc & STC.scope_) |
| 441 |
return; |
| 442 |
const(char)* msg = parId ? |
| 443 |
"assigning reference to stack allocated value returned by `%s` to non-scope parameter `%s`" : |
| 444 |
"assigning reference to stack allocated value returned by `%s` to non-scope anonymous parameter"; |
| 445 |
|
| 446 |
result |= sc.setUnsafeDIP1000(gag, ee.loc, msg, ee, parId); |
| 447 |
} |
| 448 |
|
| 449 |
scope EscapeByResults er = EscapeByResults(&onRef, &onValue, &onFunc, &onExp); |
| 450 |
escapeByValue(arg, er); |
| 451 |
return result; |
| 452 |
} |
| 453 |
|
| 454 |
/***************************************************** |
| 455 |
* Function argument initializes a `return` parameter, |
| 456 |
* and that parameter gets assigned to `firstArg`. |
| 457 |
* Essentially, treat as `firstArg = arg;` |
| 458 |
* Params: |
| 459 |
* sc = used to determine current function and module |
| 460 |
* firstArg = `ref` argument through which `arg` may be assigned |
| 461 |
* arg = initializer for parameter |
| 462 |
* param = parameter declaration corresponding to `arg` |
| 463 |
* gag = do not print error messages |
| 464 |
* Returns: |
| 465 |
* `true` if assignment to `firstArg` would cause an error |
| 466 |
*/ |
| 467 |
public |
| 468 |
bool checkParamArgumentReturn(ref Scope sc, Expression firstArg, Expression arg, Parameter param, bool gag) |
| 469 |
{ |
| 470 |
enum log = false; |
| 471 |
if (log) printf("checkParamArgumentReturn(firstArg: %s arg: %s)\n", |
| 472 |
firstArg.toChars(), arg.toChars()); |
| 473 |
//printf("type = %s, %d\n", arg.type.toChars(), arg.type.hasPointers()); |
| 474 |
|
| 475 |
if (!(param.storageClass & STC.return_)) |
| 476 |
return false; |
| 477 |
|
| 478 |
if (!arg.type.hasPointers() && !param.isReference()) |
| 479 |
return false; |
| 480 |
|
| 481 |
// `byRef` needed for `assign(ref int* x, ref int i) {x = &i};` |
| 482 |
// Note: taking address of scope pointer is not allowed |
| 483 |
// `assign(ref int** x, return ref scope int* i) {x = &i};` |
| 484 |
// Thus no return ref/return scope ambiguity here |
| 485 |
const byRef = param.isReference() && !(param.storageClass & STC.scope_) |
| 486 |
&& !(param.storageClass & STC.returnScope); // fixme: it's possible to infer returnScope without scope with vaIsFirstRef |
| 487 |
|
| 488 |
auto e = new AssignExp(arg.loc, firstArg, arg); |
| 489 |
return checkAssignEscape(sc, e, gag, byRef); |
| 490 |
} |
| 491 |
|
| 492 |
/***************************************************** |
| 493 |
* Check struct constructor of the form `s.this(args)`, by |
| 494 |
* checking each `return` parameter to see if it gets |
| 495 |
* assigned to `s`. |
| 496 |
* Params: |
| 497 |
* sc = used to determine current function and module |
| 498 |
* ce = constructor call of the form `s.this(args)` |
| 499 |
* gag = do not print error messages |
| 500 |
* Returns: |
| 501 |
* `true` if construction would cause an escaping reference error |
| 502 |
*/ |
| 503 |
public |
| 504 |
bool checkConstructorEscape(ref Scope sc, CallExp ce, bool gag) |
| 505 |
{ |
| 506 |
enum log = false; |
| 507 |
if (log) printf("checkConstructorEscape(%s, %s)\n", ce.toChars(), ce.type.toChars()); |
| 508 |
Type tthis = ce.type.toBasetype(); |
| 509 |
assert(tthis.ty == Tstruct); |
| 510 |
if (!tthis.hasPointers()) |
| 511 |
return false; |
| 512 |
|
| 513 |
if (!ce.arguments && ce.arguments.length) |
| 514 |
return false; |
| 515 |
|
| 516 |
DotVarExp dve = ce.e1.isDotVarExp(); |
| 517 |
CtorDeclaration ctor = dve.var.isCtorDeclaration(); |
| 518 |
TypeFunction tf = ctor.type.isTypeFunction(); |
| 519 |
|
| 520 |
const nparams = tf.parameterList.length; |
| 521 |
const n = ce.arguments.length; |
| 522 |
|
| 523 |
// j=1 if _arguments[] is first argument |
| 524 |
const j = tf.isDstyleVariadic(); |
| 525 |
|
| 526 |
/* Attempt to assign each `return` arg to the `this` reference |
| 527 |
*/ |
| 528 |
foreach (const i; 0 .. n) |
| 529 |
{ |
| 530 |
Expression arg = (*ce.arguments)[i]; |
| 531 |
//printf("\targ[%d]: %s\n", i, arg.toChars()); |
| 532 |
|
| 533 |
if (i - j < nparams && i >= j) |
| 534 |
{ |
| 535 |
Parameter p = tf.parameterList[i - j]; |
| 536 |
if (checkParamArgumentReturn(sc, dve.e1, arg, p, gag)) |
| 537 |
return true; |
| 538 |
} |
| 539 |
} |
| 540 |
|
| 541 |
return false; |
| 542 |
} |
| 543 |
|
| 544 |
/// How a `return` parameter escapes its pointer value |
| 545 |
public |
| 546 |
enum ReturnParamDest |
| 547 |
{ |
| 548 |
returnVal, /// through return statement: `return x` |
| 549 |
this_, /// assigned to a struct instance: `this.x = x` |
| 550 |
firstArg, /// assigned to first argument: `firstArg = x` |
| 551 |
} |
| 552 |
|
| 553 |
/**************************************** |
| 554 |
* Find out if instead of returning a `return` parameter via a return statement, |
| 555 |
* it is returned via assignment to either `this` or the first parameter. |
| 556 |
* |
| 557 |
* This works the same as returning the value via a return statement. |
| 558 |
* Although the first argument must be `ref`, it is not regarded as returning by `ref`. |
| 559 |
* |
| 560 |
* See_Also: https://dlang.org.spec/function.html#return-ref-parameters |
| 561 |
* |
| 562 |
* Params: |
| 563 |
* tf = function type |
| 564 |
* tthis = type of `this` parameter, or `null` if none |
| 565 |
* Returns: What a `return` parameter should transfer the lifetime of the argument to |
| 566 |
*/ |
| 567 |
public |
| 568 |
ReturnParamDest returnParamDest(TypeFunction tf, Type tthis) |
| 569 |
{ |
| 570 |
assert(tf); |
| 571 |
if (tf.isCtor) |
| 572 |
return ReturnParamDest.this_; |
| 573 |
|
| 574 |
if (!tf.nextOf() || (tf.nextOf().ty != Tvoid)) |
| 575 |
return ReturnParamDest.returnVal; |
| 576 |
|
| 577 |
if (tthis && tthis.toBasetype().ty == Tstruct) // class `this` is passed by value |
| 578 |
return ReturnParamDest.this_; |
| 579 |
|
| 580 |
if (tf.parameterList.length > 0 && tf.parameterList[0].isReference) |
| 581 |
return ReturnParamDest.firstArg; |
| 582 |
|
| 583 |
return ReturnParamDest.returnVal; |
| 584 |
} |
| 585 |
|
| 586 |
/**************************************** |
| 587 |
* Given an `AssignExp`, determine if the lvalue will cause |
| 588 |
* the contents of the rvalue to escape. |
| 589 |
* Print error messages when these are detected. |
| 590 |
* Infer `scope` attribute for the lvalue where possible, in order |
| 591 |
* to eliminate the error. |
| 592 |
* Params: |
| 593 |
* sc = used to determine current function and module |
| 594 |
* e = `AssignExp` or `CatAssignExp` to check for any pointers to the stack |
| 595 |
* gag = do not print error messages |
| 596 |
* byRef = set to `true` if `e1` of `e` gets assigned a reference to `e2` |
| 597 |
* Returns: |
| 598 |
* `true` if pointers to the stack can escape via assignment |
| 599 |
*/ |
| 600 |
public |
| 601 |
bool checkAssignEscape(ref Scope sc, Expression e, bool gag, bool byRef) |
| 602 |
{ |
| 603 |
enum log = false; |
| 604 |
if (log) printf("checkAssignEscape(e: %s, byRef: %d)\n", e.toChars(), byRef); |
| 605 |
if (e.op != EXP.assign && e.op != EXP.blit && e.op != EXP.construct && |
| 606 |
e.op != EXP.concatenateAssign && e.op != EXP.concatenateElemAssign && e.op != EXP.concatenateDcharAssign) |
| 607 |
return false; |
| 608 |
auto ae = cast(BinExp)e; |
| 609 |
Expression e1 = ae.e1; |
| 610 |
Expression e2 = ae.e2; |
| 611 |
//printf("type = %s, %d\n", e1.type.toChars(), e1.type.hasPointers()); |
| 612 |
|
| 613 |
if (!e1.type.hasPointers()) |
| 614 |
return false; |
| 615 |
|
| 616 |
|
| 617 |
/* The struct literal case can arise from the S(e2) constructor call: |
| 618 |
* return S(e2); |
| 619 |
* and appears in this function as: |
| 620 |
* structLiteral = e2; |
| 621 |
* Such an assignment does not necessarily remove scope-ness. |
| 622 |
*/ |
| 623 |
if (e1.isStructLiteralExp()) |
| 624 |
return false; |
| 625 |
|
| 626 |
int deref; |
| 627 |
VarDeclaration va = expToVariable(e1, deref); |
| 628 |
// transitive scope not implemented, so can't assign scope pointers to a dereferenced variable |
| 629 |
if (deref > 0) |
| 630 |
va = null; |
| 631 |
|
| 632 |
if (e1.isSliceExp()) |
| 633 |
{ |
| 634 |
// slice-copy is not assigning a pointer, but copying array content |
| 635 |
if (va) |
| 636 |
{ |
| 637 |
if (!va.type.toBasetype().isTypeSArray() || // treat static array slice same as a variable |
| 638 |
!va.type.hasPointers()) |
| 639 |
return false; |
| 640 |
} |
| 641 |
else |
| 642 |
return false; |
| 643 |
} |
| 644 |
|
| 645 |
if (va && e.op == EXP.concatenateElemAssign) |
| 646 |
{ |
| 647 |
/* https://issues.dlang.org/show_bug.cgi?id=17842 |
| 648 |
* Draw an equivalence between: |
| 649 |
* *q = p; |
| 650 |
* and: |
| 651 |
* va ~= e; |
| 652 |
* since we are not assigning to va, but are assigning indirectly through va. |
| 653 |
*/ |
| 654 |
va = null; |
| 655 |
} |
| 656 |
|
| 657 |
if (e.op == EXP.construct && va && (va.storage_class & STC.temp) && va._init) |
| 658 |
{ |
| 659 |
// Initializing a temporary is safe, `escapeExp` will forward such vars |
| 660 |
// to their `va._init` if needed. |
| 661 |
return false; |
| 662 |
} |
| 663 |
|
| 664 |
if (log && va) printf("va: %s\n", va.toChars()); |
| 665 |
|
| 666 |
FuncDeclaration fd = sc.func; |
| 667 |
|
| 668 |
// Determine if va is a `ref` parameter, so it has a lifetime exceding the function scope |
| 669 |
const bool vaIsRef = va && va.isParameter() && va.isReference(); |
| 670 |
if (log && vaIsRef) printf("va is ref `%s`\n", va.toChars()); |
| 671 |
|
| 672 |
// Determine if va is the first parameter, through which other 'return' parameters |
| 673 |
// can be assigned. |
| 674 |
bool vaIsFirstRef = false; |
| 675 |
if (fd && fd.type) |
| 676 |
{ |
| 677 |
final switch (returnParamDest(fd.type.isTypeFunction(), fd.vthis ? fd.vthis.type : null)) |
| 678 |
{ |
| 679 |
case ReturnParamDest.this_: |
| 680 |
vaIsFirstRef = va == fd.vthis; |
| 681 |
break; |
| 682 |
case ReturnParamDest.firstArg: |
| 683 |
// While you'd expect fd.parameters[0] to exist in this case, the compiler-generated |
| 684 |
// expression that initializes an `out int* p = null` is analyzed before fd.parameters |
| 685 |
// is created, so we still do a null and length check |
| 686 |
vaIsFirstRef = fd.parameters && 0 < fd.parameters.length && (*fd.parameters)[0] == va; |
| 687 |
break; |
| 688 |
case ReturnParamDest.returnVal: |
| 689 |
break; |
| 690 |
} |
| 691 |
} |
| 692 |
if (log && vaIsFirstRef) printf("va is first ref `%s`\n", va.toChars()); |
| 693 |
|
| 694 |
bool result = false; |
| 695 |
void onValue(VarDeclaration v) |
| 696 |
{ |
| 697 |
if (log) printf("byvalue: %s\n", v.toChars()); |
| 698 |
|
| 699 |
if (v == va) |
| 700 |
return; |
| 701 |
|
| 702 |
Dsymbol p = v.toParent2(); |
| 703 |
|
| 704 |
if (vaIsFirstRef && p == fd) |
| 705 |
{ |
| 706 |
inferReturn(fd, v, /*returnScope:*/ true); |
| 707 |
} |
| 708 |
|
| 709 |
if (!(va && va.isScope()) || vaIsRef) |
| 710 |
doNotInferScope(v, e); |
| 711 |
|
| 712 |
if (v.isScope()) |
| 713 |
{ |
| 714 |
if (vaIsFirstRef && v.isParameter() && v.isReturn()) |
| 715 |
{ |
| 716 |
// va=v, where v is `return scope` |
| 717 |
if (inferScope(va)) |
| 718 |
return; |
| 719 |
} |
| 720 |
|
| 721 |
// If va's lifetime encloses v's, then error |
| 722 |
if (EnclosedBy eb = va.enclosesLifetimeOf(v)) |
| 723 |
{ |
| 724 |
const(char)* msg; |
| 725 |
final switch (eb) |
| 726 |
{ |
| 727 |
case EnclosedBy.none: assert(0); |
| 728 |
case EnclosedBy.returnScope: |
| 729 |
msg = "assigning scope variable `%s` to return scope `%s`"; |
| 730 |
break; |
| 731 |
case EnclosedBy.longerScope: |
| 732 |
msg = "assigning scope variable `%s` to `%s` with longer lifetime"; |
| 733 |
break; |
| 734 |
case EnclosedBy.refVar: |
| 735 |
msg = "assigning scope variable `%s` to `ref` variable `%s` with longer lifetime"; |
| 736 |
break; |
| 737 |
case EnclosedBy.global: |
| 738 |
msg = "assigning scope variable `%s` to global variable `%s`"; |
| 739 |
break; |
| 740 |
} |
| 741 |
|
| 742 |
if (sc.setUnsafeDIP1000(gag, ae.loc, msg, v, va)) |
| 743 |
{ |
| 744 |
result = true; |
| 745 |
return; |
| 746 |
} |
| 747 |
} |
| 748 |
|
| 749 |
// v = scope, va should be scope as well |
| 750 |
const vaWasScope = va && va.isScope(); |
| 751 |
if (inferScope(va)) |
| 752 |
{ |
| 753 |
// In case of `scope local = returnScopeParam`, do not infer return scope for `x` |
| 754 |
if (!vaWasScope && v.isReturn() && !va.isReturn()) |
| 755 |
{ |
| 756 |
if (log) printf("infer return for %s\n", va.toChars()); |
| 757 |
va.storage_class |= STC.return_ | STC.returninferred; |
| 758 |
|
| 759 |
// Added "return scope" so don't confuse it with "return ref" |
| 760 |
if (isRefReturnScope(va.storage_class)) |
| 761 |
va.storage_class |= STC.returnScope; |
| 762 |
} |
| 763 |
return; |
| 764 |
} |
| 765 |
result |= sc.setUnsafeDIP1000(gag, ae.loc, "assigning scope variable `%s` to non-scope `%s`", v, e1); |
| 766 |
} |
| 767 |
else |
| 768 |
{ |
| 769 |
/* v is not 'scope', and we didn't check the scope of where we assigned it to. |
| 770 |
* It may escape via that assignment, therefore, v can never be 'scope'. |
| 771 |
*/ |
| 772 |
//printf("no infer for %s in %s, %d\n", v.toChars(), fd.ident.toChars(), __LINE__); |
| 773 |
if (!v.isParameter) |
| 774 |
doNotInferScope(v, e); |
| 775 |
} |
| 776 |
} |
| 777 |
|
| 778 |
void onRef(VarDeclaration v, bool retRefTransition) |
| 779 |
{ |
| 780 |
if (log) printf("byref: %s\n", v.toChars()); |
| 781 |
|
| 782 |
if (checkScopeVarAddr(v, ae, sc, gag)) |
| 783 |
{ |
| 784 |
result = true; |
| 785 |
return; |
| 786 |
} |
| 787 |
|
| 788 |
if (va && va.isScope() && !v.isReference()) |
| 789 |
{ |
| 790 |
if (!va.isReturn()) |
| 791 |
{ |
| 792 |
va.doNotInferReturn = true; |
| 793 |
} |
| 794 |
else |
| 795 |
{ |
| 796 |
result |= sc.setUnsafeDIP1000(gag, ae.loc, |
| 797 |
"assigning address of local variable `%s` to return scope `%s`", v, va); |
| 798 |
} |
| 799 |
} |
| 800 |
|
| 801 |
Dsymbol p = v.toParent2(); |
| 802 |
|
| 803 |
if (vaIsFirstRef && p == fd) |
| 804 |
{ |
| 805 |
//if (log) printf("inferring 'return' for parameter %s in function %s\n", v.toChars(), fd.toChars()); |
| 806 |
inferReturn(fd, v, /*returnScope:*/ false); |
| 807 |
} |
| 808 |
|
| 809 |
// If va's lifetime encloses v's, then error |
| 810 |
if (va && !(vaIsFirstRef && v.isReturn()) && va.enclosesLifetimeOf(v)) |
| 811 |
{ |
| 812 |
if (sc.setUnsafeDIP1000(gag, ae.loc, "assigning address of variable `%s` to `%s` with longer lifetime", v, va)) |
| 813 |
{ |
| 814 |
result = true; |
| 815 |
return; |
| 816 |
} |
| 817 |
} |
| 818 |
|
| 819 |
if (!(va && va.isScope())) |
| 820 |
doNotInferScope(v, e); |
| 821 |
|
| 822 |
if (p != sc.func) |
| 823 |
return; |
| 824 |
|
| 825 |
if (inferScope(va)) |
| 826 |
{ |
| 827 |
if (v.isReturn() && !va.isReturn()) |
| 828 |
va.storage_class |= STC.return_ | STC.returninferred; |
| 829 |
return; |
| 830 |
} |
| 831 |
|
| 832 |
result |= sc.setUnsafeDIP1000(gag, ae.loc, "assigning reference to local variable `%s` to non-scope `%s`", v, e1); |
| 833 |
} |
| 834 |
|
| 835 |
void onFunc(FuncDeclaration func, bool called) |
| 836 |
{ |
| 837 |
if (log) printf("byfunc: %s, %d\n", func.toChars(), func.tookAddressOf); |
| 838 |
VarDeclarations vars; |
| 839 |
findAllOuterAccessedVariables(func, &vars); |
| 840 |
|
| 841 |
/* https://issues.dlang.org/show_bug.cgi?id=16037 |
| 842 |
* If assigning the address of a delegate to a scope variable, |
| 843 |
* then uncount that address of. This is so it won't cause a |
| 844 |
* closure to be allocated. |
| 845 |
*/ |
| 846 |
if (va && va.isScope() && !va.isReturn() && func.tookAddressOf) |
| 847 |
--func.tookAddressOf; |
| 848 |
|
| 849 |
foreach (v; vars) |
| 850 |
{ |
| 851 |
//printf("v = %s\n", v.toChars()); |
| 852 |
assert(!v.isDataseg()); // these are not put in the closureVars[] |
| 853 |
|
| 854 |
Dsymbol p = v.toParent2(); |
| 855 |
|
| 856 |
if (!(va && va.isScope())) |
| 857 |
doNotInferScope(v, e); |
| 858 |
|
| 859 |
if (!(v.isReference() || v.isScope()) || p != fd) |
| 860 |
return; |
| 861 |
|
| 862 |
if (va && !va.isDataseg() && (va.isScope() || va.maybeScope)) |
| 863 |
{ |
| 864 |
/* Don't infer STC.scope_ for va, because then a closure |
| 865 |
* won't be generated for fd. |
| 866 |
*/ |
| 867 |
//if (!va.isScope()) |
| 868 |
//va.storage_class |= STC.scope_ | STC.scopeinferred; |
| 869 |
return; |
| 870 |
} |
| 871 |
result |= sc.setUnsafeDIP1000(gag, ae.loc, |
| 872 |
"assigning reference to local `%s` to non-scope `%s`", v, e1); |
| 873 |
} |
| 874 |
} |
| 875 |
|
| 876 |
void onExp(Expression ee, bool retRefTransition) |
| 877 |
{ |
| 878 |
if (log) printf("byexp: %s\n", ee.toChars()); |
| 879 |
|
| 880 |
/* Do not allow slicing of a static array returned by a function |
| 881 |
*/ |
| 882 |
if (ee.op == EXP.call && ee.type.toBasetype().isTypeSArray() && e1.type.toBasetype().isTypeDArray()) |
| 883 |
{ |
| 884 |
if (!gag) |
| 885 |
sc.eSink.deprecation(ee.loc, "slice of static array temporary returned by `%s` assigned to longer lived variable `%s`", |
| 886 |
ee.toChars(), e1.toChars()); |
| 887 |
//result = true; |
| 888 |
return; |
| 889 |
} |
| 890 |
|
| 891 |
const(char)* msg = (ee.op == EXP.structLiteral) ? |
| 892 |
"assigning address of struct literal `%s` to `%s` with longer lifetime" : |
| 893 |
"assigning address of expression temporary returned by `%s` to `%s` with longer lifetime"; |
| 894 |
|
| 895 |
result |= sc.setUnsafeDIP1000(gag, ee.loc, msg, ee, e1); |
| 896 |
} |
| 897 |
|
| 898 |
scope EscapeByResults er = EscapeByResults(&onRef, &onValue, &onFunc, &onExp); |
| 899 |
|
| 900 |
if (byRef) |
| 901 |
escapeByRef(e2, er); |
| 902 |
else |
| 903 |
escapeByValue(e2, er); |
| 904 |
|
| 905 |
return result; |
| 906 |
} |
| 907 |
|
| 908 |
/************************************ |
| 909 |
* Detect cases where pointers to the stack can escape the |
| 910 |
* lifetime of the stack frame when throwing `e`. |
| 911 |
* Print error messages when these are detected. |
| 912 |
* Params: |
| 913 |
* sc = used to determine current function and module |
| 914 |
* e = expression to check for any pointers to the stack |
| 915 |
* gag = do not print error messages |
| 916 |
* Returns: |
| 917 |
* `true` if pointers to the stack can escape |
| 918 |
*/ |
| 919 |
public |
| 920 |
bool checkThrowEscape(ref Scope sc, Expression e, bool gag) |
| 921 |
{ |
| 922 |
//printf("[%s] checkThrowEscape, e = %s\n", e.loc.toChars(), e.toChars()); |
| 923 |
|
| 924 |
bool result = false; |
| 925 |
void onRef(VarDeclaration v, bool retRefTransition) {} |
| 926 |
void onValue(VarDeclaration v) |
| 927 |
{ |
| 928 |
//printf("byvalue %s\n", v.toChars()); |
| 929 |
if (v.isScope() && !v.iscatchvar) // special case: allow catch var to be rethrown |
| 930 |
// despite being `scope` |
| 931 |
{ |
| 932 |
// https://issues.dlang.org/show_bug.cgi?id=17029 |
| 933 |
result |= sc.setUnsafeDIP1000(gag, e.loc, "throwing scope variable `%s`", v); |
| 934 |
return; |
| 935 |
} |
| 936 |
else |
| 937 |
{ |
| 938 |
doNotInferScope(v, new ThrowExp(e.loc, e)); |
| 939 |
} |
| 940 |
} |
| 941 |
void onFunc(FuncDeclaration fd, bool called) {} |
| 942 |
void onExp(Expression exp, bool retRefTransition) {} |
| 943 |
|
| 944 |
scope EscapeByResults er = EscapeByResults(&onRef, &onValue, &onFunc, &onExp); |
| 945 |
escapeByValue(e, er); |
| 946 |
return result; |
| 947 |
} |
| 948 |
|
| 949 |
/************************************ |
| 950 |
* Detect cases where pointers to the stack can escape the |
| 951 |
* lifetime of the stack frame by being placed into a GC allocated object. |
| 952 |
* Print error messages when these are detected. |
| 953 |
* Params: |
| 954 |
* sc = used to determine current function and module |
| 955 |
* e = expression to check for any pointers to the stack |
| 956 |
* gag = do not print error messages |
| 957 |
* Returns: |
| 958 |
* `true` if pointers to the stack can escape |
| 959 |
*/ |
| 960 |
public |
| 961 |
bool checkNewEscape(ref Scope sc, Expression e, bool gag) |
| 962 |
{ |
| 963 |
import dmd.globals: FeatureState; |
| 964 |
import dmd.errors: previewErrorFunc; |
| 965 |
|
| 966 |
//printf("[%s] checkNewEscape, e = %s\n", e.loc.toChars(), e.toChars()); |
| 967 |
enum log = false; |
| 968 |
if (log) printf("[%s] checkNewEscape, e: `%s`\n", e.loc.toChars(), e.toChars()); |
| 969 |
|
| 970 |
bool result = false; |
| 971 |
void onValue(VarDeclaration v) |
| 972 |
{ |
| 973 |
if (log) printf("byvalue `%s`\n", v.toChars()); |
| 974 |
|
| 975 |
Dsymbol p = v.toParent2(); |
| 976 |
|
| 977 |
if (v.isScope()) |
| 978 |
{ |
| 979 |
if ( |
| 980 |
/* This case comes up when the ReturnStatement of a __foreachbody is |
| 981 |
* checked for escapes by the caller of __foreachbody. Skip it. |
| 982 |
* |
| 983 |
* struct S { static int opApply(int delegate(S*) dg); } |
| 984 |
* S* foo() { |
| 985 |
* foreach (S* s; S) // create __foreachbody for body of foreach |
| 986 |
* return s; // s is inferred as 'scope' but incorrectly tested in foo() |
| 987 |
* return null; } |
| 988 |
*/ |
| 989 |
!(p.parent == sc.func)) |
| 990 |
{ |
| 991 |
// https://issues.dlang.org/show_bug.cgi?id=20868 |
| 992 |
result |= sc.setUnsafeDIP1000(gag, e.loc, "copying scope variable `%s` into allocated memory", v); |
| 993 |
return; |
| 994 |
} |
| 995 |
} |
| 996 |
else |
| 997 |
{ |
| 998 |
//printf("no infer for %s in %s, %d\n", v.toChars(), sc.func.ident.toChars(), __LINE__); |
| 999 |
doNotInferScope(v, e); |
| 1000 |
} |
| 1001 |
} |
| 1002 |
|
| 1003 |
void onRef(VarDeclaration v, bool retRefTransition) |
| 1004 |
{ |
| 1005 |
if (log) printf("byref `%s`\n", v.toChars()); |
| 1006 |
|
| 1007 |
// 'featureState' tells us whether to emit an error or a deprecation, |
| 1008 |
// depending on the flag passed to the CLI for DIP25 / DIP1000 |
| 1009 |
bool escapingRef(VarDeclaration v, FeatureState fs) |
| 1010 |
{ |
| 1011 |
const(char)* msg = v.isParameter() ? |
| 1012 |
"escaping a reference to parameter `%s` by copying `%s` into allocated memory" : |
| 1013 |
"escaping a reference to local variable `%s` by copying `%s` into allocated memory"; |
| 1014 |
return setUnsafePreview(&sc, fs, gag, e.loc, msg, v, e); |
| 1015 |
} |
| 1016 |
|
| 1017 |
Dsymbol p = v.toParent2(); |
| 1018 |
|
| 1019 |
if (!v.isReference()) |
| 1020 |
{ |
| 1021 |
if (p == sc.func) |
| 1022 |
{ |
| 1023 |
result |= escapingRef(v, sc.useDIP1000); |
| 1024 |
return; |
| 1025 |
} |
| 1026 |
} |
| 1027 |
|
| 1028 |
/* Check for returning a ref variable by 'ref', but should be 'return ref' |
| 1029 |
* Infer the addition of 'return', or set result to be the offending expression. |
| 1030 |
*/ |
| 1031 |
if (!v.isReference()) |
| 1032 |
return; |
| 1033 |
|
| 1034 |
// https://dlang.org/spec/function.html#return-ref-parameters |
| 1035 |
if (p == sc.func) |
| 1036 |
{ |
| 1037 |
//printf("escaping reference to local ref variable %s\n", v.toChars()); |
| 1038 |
//printf("storage class = x%llx\n", v.storage_class); |
| 1039 |
result |= escapingRef(v, sc.useDIP25); |
| 1040 |
return; |
| 1041 |
} |
| 1042 |
// Don't need to be concerned if v's parent does not return a ref |
| 1043 |
FuncDeclaration func = p.isFuncDeclaration(); |
| 1044 |
if (!func || !func.type) |
| 1045 |
return; |
| 1046 |
if (auto tf = func.type.isTypeFunction()) |
| 1047 |
{ |
| 1048 |
if (!tf.isRef) |
| 1049 |
return; |
| 1050 |
|
| 1051 |
const(char)* msg = "storing reference to outer local variable `%s` into allocated memory causes it to escape"; |
| 1052 |
if (!gag) |
| 1053 |
{ |
| 1054 |
previewErrorFunc(sc.isDeprecated(), sc.useDIP25)(e.loc, msg, v.toChars()); |
| 1055 |
} |
| 1056 |
|
| 1057 |
// If -preview=dip25 is used, the user wants an error |
| 1058 |
// Otherwise, issue a deprecation |
| 1059 |
result |= (sc.useDIP25 == FeatureState.enabled); |
| 1060 |
} |
| 1061 |
} |
| 1062 |
|
| 1063 |
void onFunc(FuncDeclaration fd, bool called) |
| 1064 |
{ |
| 1065 |
if (called) |
| 1066 |
result |= sc.setUnsafeDIP1000(gag, e.loc, |
| 1067 |
"escaping a `scope` value returned from nested function `%s` into allocated memory", fd); |
| 1068 |
} |
| 1069 |
|
| 1070 |
void onExp(Expression ee, bool retRefTransition) |
| 1071 |
{ |
| 1072 |
if (log) printf("byexp %s\n", ee.toChars()); |
| 1073 |
if (!gag) |
| 1074 |
sc.eSink.error(ee.loc, "escaping reference to stack allocated value returned by `%s` into allocated memory", |
| 1075 |
ee.toChars()); |
| 1076 |
result = true; |
| 1077 |
} |
| 1078 |
|
| 1079 |
scope EscapeByResults er = EscapeByResults(&onRef, &onValue, &onFunc, &onExp); |
| 1080 |
escapeByValue(e, er); |
| 1081 |
|
| 1082 |
return result; |
| 1083 |
} |
| 1084 |
|
| 1085 |
|
| 1086 |
/************************************ |
| 1087 |
* Detect cases where pointers to the stack can escape the |
| 1088 |
* lifetime of the stack frame by returning `e` by value. |
| 1089 |
* Print error messages when these are detected. |
| 1090 |
* Params: |
| 1091 |
* sc = used to determine current function and module |
| 1092 |
* e = expression to check for any pointers to the stack |
| 1093 |
* gag = do not print error messages |
| 1094 |
* Returns: |
| 1095 |
* `true` if pointers to the stack can escape |
| 1096 |
*/ |
| 1097 |
public |
| 1098 |
bool checkReturnEscape(ref Scope sc, Expression e, bool gag) |
| 1099 |
{ |
| 1100 |
//printf("[%s] checkReturnEscape, e: %s\n", e.loc.toChars(), e.toChars()); |
| 1101 |
return checkReturnEscapeImpl(sc, e, false, gag); |
| 1102 |
} |
| 1103 |
|
| 1104 |
/************************************ |
| 1105 |
* Detect cases where returning `e` by `ref` can result in a reference to the stack |
| 1106 |
* being returned. |
| 1107 |
* Print error messages when these are detected. |
| 1108 |
* Params: |
| 1109 |
* sc = used to determine current function and module |
| 1110 |
* e = expression to check |
| 1111 |
* gag = do not print error messages |
| 1112 |
* Returns: |
| 1113 |
* `true` if references to the stack can escape |
| 1114 |
*/ |
| 1115 |
public |
| 1116 |
bool checkReturnEscapeRef(ref Scope sc, Expression e, bool gag) |
| 1117 |
{ |
| 1118 |
version (none) |
| 1119 |
{ |
| 1120 |
printf("[%s] checkReturnEscapeRef, e = %s\n", e.loc.toChars(), e.toChars()); |
| 1121 |
printf("current function %s\n", sc.func.toChars()); |
| 1122 |
printf("parent2 function %s\n", sc.func.toParent2().toChars()); |
| 1123 |
} |
| 1124 |
|
| 1125 |
return checkReturnEscapeImpl(sc, e, true, gag); |
| 1126 |
} |
| 1127 |
|
| 1128 |
/*************************************** |
| 1129 |
* Implementation of checking for escapes in return expressions. |
| 1130 |
* Params: |
| 1131 |
* sc = used to determine current function and module |
| 1132 |
* e = expression to check |
| 1133 |
* refs = `true`: escape by value, `false`: escape by `ref` |
| 1134 |
* gag = do not print error messages |
| 1135 |
* Returns: |
| 1136 |
* `true` if references to the stack can escape |
| 1137 |
*/ |
| 1138 |
private bool checkReturnEscapeImpl(ref Scope sc, Expression e, bool refs, bool gag) |
| 1139 |
{ |
| 1140 |
enum log = false; |
| 1141 |
if (log) printf("[%s] checkReturnEscapeImpl, refs: %d e: `%s`\n", e.loc.toChars(), refs, e.toChars()); |
| 1142 |
|
| 1143 |
bool result = false; |
| 1144 |
void onValue(VarDeclaration v) |
| 1145 |
{ |
| 1146 |
if (log) printf("byvalue `%s`\n", v.toChars()); |
| 1147 |
|
| 1148 |
const vsr = buildScopeRef(v.storage_class); |
| 1149 |
|
| 1150 |
Dsymbol p = v.toParent2(); |
| 1151 |
|
| 1152 |
if (p == sc.func && inferReturn(sc.func, v, /*returnScope:*/ true)) |
| 1153 |
{ |
| 1154 |
return; |
| 1155 |
} |
| 1156 |
|
| 1157 |
if (v.isTypesafeVariadicArray && p == sc.func) |
| 1158 |
{ |
| 1159 |
if (!gag) |
| 1160 |
sc.eSink.error(e.loc, "returning `%s` escapes a reference to variadic parameter `%s`", e.toChars(), v.toChars()); |
| 1161 |
result = false; |
| 1162 |
} |
| 1163 |
else if (v.isScope()) |
| 1164 |
{ |
| 1165 |
/* If `return scope` applies to v. |
| 1166 |
*/ |
| 1167 |
if (vsr == ScopeRef.ReturnScope || |
| 1168 |
vsr == ScopeRef.Ref_ReturnScope) |
| 1169 |
{ |
| 1170 |
return; |
| 1171 |
} |
| 1172 |
|
| 1173 |
auto pfunc = p.isFuncDeclaration(); |
| 1174 |
if (pfunc && |
| 1175 |
/* This case comes up when the ReturnStatement of a __foreachbody is |
| 1176 |
* checked for escapes by the caller of __foreachbody. Skip it. |
| 1177 |
* |
| 1178 |
* struct S { static int opApply(int delegate(S*) dg); } |
| 1179 |
* S* foo() { |
| 1180 |
* foreach (S* s; S) // create __foreachbody for body of foreach |
| 1181 |
* return s; // s is inferred as 'scope' but incorrectly tested in foo() |
| 1182 |
* return null; } |
| 1183 |
*/ |
| 1184 |
!(!refs && p.parent == sc.func && pfunc.fes) |
| 1185 |
) |
| 1186 |
{ |
| 1187 |
/* |
| 1188 |
* auto p(scope string s) { |
| 1189 |
* string scfunc() { return s; } |
| 1190 |
* } |
| 1191 |
*/ |
| 1192 |
if (sc.func.isFuncDeclaration().getLevel(pfunc, sc.intypeof) > 0 && |
| 1193 |
inferReturn(sc.func, sc.func.vthis, /*returnScope*/ !refs)) |
| 1194 |
{ |
| 1195 |
return; |
| 1196 |
} |
| 1197 |
|
| 1198 |
if (v.isParameter() && !v.isReturn()) |
| 1199 |
{ |
| 1200 |
// https://issues.dlang.org/show_bug.cgi?id=23191 |
| 1201 |
if (!gag) |
| 1202 |
{ |
| 1203 |
previewErrorFunc(sc.isDeprecated(), sc.useDIP1000)(e.loc, |
| 1204 |
"scope parameter `%s` may not be returned", v.toChars() |
| 1205 |
); |
| 1206 |
result = true; |
| 1207 |
return; |
| 1208 |
} |
| 1209 |
} |
| 1210 |
else |
| 1211 |
{ |
| 1212 |
// https://issues.dlang.org/show_bug.cgi?id=17029 |
| 1213 |
result |= sc.setUnsafeDIP1000(gag, e.loc, "returning scope variable `%s`", v); |
| 1214 |
return; |
| 1215 |
} |
| 1216 |
} |
| 1217 |
} |
| 1218 |
else if (p == sc.func || !v.isParameter()) |
| 1219 |
{ |
| 1220 |
//printf("no infer for %s in %s, %d\n", v.toChars(), sc.func.ident.toChars(), __LINE__); |
| 1221 |
doNotInferScope(v, e); |
| 1222 |
} |
| 1223 |
} |
| 1224 |
|
| 1225 |
void onRef(VarDeclaration v, bool retRefTransition) |
| 1226 |
{ |
| 1227 |
if (log) |
| 1228 |
{ |
| 1229 |
printf("byref `%s` %s\n", v.toChars(), ScopeRefToChars(buildScopeRef(v.storage_class))); |
| 1230 |
} |
| 1231 |
|
| 1232 |
// 'featureState' tells us whether to emit an error or a deprecation, |
| 1233 |
// depending on the flag passed to the CLI for DIP25 |
| 1234 |
void escapingRef(VarDeclaration v, FeatureState featureState) |
| 1235 |
{ |
| 1236 |
const(char)* safeMsg = v.isParameter() ? |
| 1237 |
"escaping a reference to parameter `%s` by returning `%s`" : |
| 1238 |
"escaping a reference to local variable `%s` by returning `%s` "; |
| 1239 |
if (v.isParameter() && v.isReference()) |
| 1240 |
{ |
| 1241 |
if (setUnsafePreview(&sc, featureState, gag, e.loc, safeMsg, v, e) || |
| 1242 |
sc.func.isSafeBypassingInference()) |
| 1243 |
{ |
| 1244 |
result = true; |
| 1245 |
if (v.storage_class & STC.returnScope) |
| 1246 |
{ |
| 1247 |
previewSupplementalFunc(sc.isDeprecated(), featureState)(v.loc, |
| 1248 |
"perhaps change the `return scope` into `scope return`"); |
| 1249 |
} |
| 1250 |
else |
| 1251 |
{ |
| 1252 |
const(char)* annotateKind = (v.ident is Id.This) ? "function" : "parameter"; |
| 1253 |
previewSupplementalFunc(sc.isDeprecated(), featureState)(v.loc, |
| 1254 |
"perhaps annotate the %s with `return`", annotateKind); |
| 1255 |
} |
| 1256 |
} |
| 1257 |
} |
| 1258 |
else |
| 1259 |
{ |
| 1260 |
if (retRefTransition) |
| 1261 |
{ |
| 1262 |
result |= sc.setUnsafeDIP1000(gag, e.loc, safeMsg, v, e); |
| 1263 |
} |
| 1264 |
else |
| 1265 |
{ |
| 1266 |
const(char)* msg = v.isParameter() ? |
| 1267 |
"returning `%s` escapes a reference to parameter `%s`" : |
| 1268 |
"returning `%s` escapes a reference to local variable `%s`"; |
| 1269 |
if (!gag) |
| 1270 |
previewErrorFunc(sc.isDeprecated(), featureState)(e.loc, msg, e.toChars(), v.toChars()); |
| 1271 |
result = true; |
| 1272 |
} |
| 1273 |
} |
| 1274 |
} |
| 1275 |
|
| 1276 |
const vsr = buildScopeRef(v.storage_class); |
| 1277 |
|
| 1278 |
Dsymbol p = v.toParent2(); |
| 1279 |
|
| 1280 |
// https://issues.dlang.org/show_bug.cgi?id=19965 |
| 1281 |
if (!refs && checkScopeVarAddr(v, e, sc, gag)) |
| 1282 |
{ |
| 1283 |
result = true; |
| 1284 |
return; |
| 1285 |
} |
| 1286 |
|
| 1287 |
if (!v.isReference()) |
| 1288 |
{ |
| 1289 |
if (p == sc.func) |
| 1290 |
{ |
| 1291 |
escapingRef(v, FeatureState.enabled); |
| 1292 |
return; |
| 1293 |
} |
| 1294 |
FuncDeclaration fd = p.isFuncDeclaration(); |
| 1295 |
if (fd && sc.func.scopeInprocess) |
| 1296 |
{ |
| 1297 |
/* Code like: |
| 1298 |
* int x; |
| 1299 |
* auto dg = () { return &x; } |
| 1300 |
* Making it: |
| 1301 |
* auto dg = () return { return &x; } |
| 1302 |
* Because dg.ptr points to x, this is returning dt.ptr+offset |
| 1303 |
*/ |
| 1304 |
sc.func.storage_class |= STC.return_ | STC.returninferred; |
| 1305 |
} |
| 1306 |
} |
| 1307 |
|
| 1308 |
/* Check for returning a ref variable by 'ref', but should be 'return ref' |
| 1309 |
* Infer the addition of 'return', or set result to be the offending expression. |
| 1310 |
*/ |
| 1311 |
if (vsr == ScopeRef.Ref || |
| 1312 |
vsr == ScopeRef.RefScope || |
| 1313 |
vsr == ScopeRef.Ref_ReturnScope) |
| 1314 |
{ |
| 1315 |
if (p == sc.func && (vsr == ScopeRef.Ref || vsr == ScopeRef.RefScope) && |
| 1316 |
inferReturn(sc.func, v, /*returnScope:*/ false)) |
| 1317 |
{ |
| 1318 |
return; |
| 1319 |
} |
| 1320 |
else |
| 1321 |
{ |
| 1322 |
// https://dlang.org/spec/function.html#return-ref-parameters |
| 1323 |
// Only look for errors if in module listed on command line |
| 1324 |
if (p == sc.func) |
| 1325 |
{ |
| 1326 |
//printf("escaping reference to local ref variable %s\n", v.toChars()); |
| 1327 |
//printf("storage class = x%llx\n", v.storage_class); |
| 1328 |
escapingRef(v, sc.useDIP25); |
| 1329 |
return; |
| 1330 |
} |
| 1331 |
// Don't need to be concerned if v's parent does not return a ref |
| 1332 |
FuncDeclaration fd = p.isFuncDeclaration(); |
| 1333 |
if (fd && fd.type && fd.type.ty == Tfunction) |
| 1334 |
{ |
| 1335 |
TypeFunction tf = fd.type.isTypeFunction(); |
| 1336 |
if (tf.isRef) |
| 1337 |
{ |
| 1338 |
const(char)* msg = "escaping reference to outer local variable `%s`"; |
| 1339 |
if (!gag) |
| 1340 |
previewErrorFunc(sc.isDeprecated(), sc.useDIP25)(e.loc, msg, v.toChars()); |
| 1341 |
result = true; |
| 1342 |
return; |
| 1343 |
} |
| 1344 |
} |
| 1345 |
|
| 1346 |
} |
| 1347 |
} |
| 1348 |
} |
| 1349 |
|
| 1350 |
void onFunc(FuncDeclaration fd, bool called) |
| 1351 |
{ |
| 1352 |
if (called && fd.isNested()) |
| 1353 |
result |= sc.setUnsafeDIP1000(gag, e.loc, "escaping local variable through nested function `%s`", fd); |
| 1354 |
} |
| 1355 |
|
| 1356 |
void onExp(Expression ee, bool retRefTransition) |
| 1357 |
{ |
| 1358 |
if (log) printf("byexp %s\n", ee.toChars()); |
| 1359 |
if (retRefTransition) |
| 1360 |
{ |
| 1361 |
result |= sc.setUnsafeDIP1000(gag, ee.loc, |
| 1362 |
"escaping reference to stack allocated value returned by `%s`", ee); |
| 1363 |
} |
| 1364 |
else |
| 1365 |
{ |
| 1366 |
if (!gag) |
| 1367 |
sc.eSink.error(ee.loc, "escaping reference to stack allocated value returned by `%s`", ee.toChars()); |
| 1368 |
result = true; |
| 1369 |
} |
| 1370 |
} |
| 1371 |
|
| 1372 |
|
| 1373 |
scope EscapeByResults er = EscapeByResults(&onRef, &onValue, &onFunc, &onExp); |
| 1374 |
|
| 1375 |
if (refs) |
| 1376 |
escapeByRef(e, er); |
| 1377 |
else |
| 1378 |
escapeByValue(e, er); |
| 1379 |
|
| 1380 |
return result; |
| 1381 |
} |
| 1382 |
|
| 1383 |
/*********************************** |
| 1384 |
* Infer `scope` for a variable |
| 1385 |
* |
| 1386 |
* Params: |
| 1387 |
* va = variable to infer scope for |
| 1388 |
* Returns: `true` if succesful or already `scope` |
| 1389 |
*/ |
| 1390 |
private |
| 1391 |
bool inferScope(VarDeclaration va) |
| 1392 |
{ |
| 1393 |
if (!va) |
| 1394 |
return false; |
| 1395 |
if (!va.isDataseg() && va.maybeScope && !va.isScope()) |
| 1396 |
{ |
| 1397 |
//printf("inferring scope for %s\n", va.toChars()); |
| 1398 |
va.maybeScope = false; |
| 1399 |
va.storage_class |= STC.scope_ | STC.scopeinferred; |
| 1400 |
return true; |
| 1401 |
} |
| 1402 |
return va.isScope(); |
| 1403 |
} |
| 1404 |
|
| 1405 |
/************************************* |
| 1406 |
* Variable v needs to have 'return' inferred for it. |
| 1407 |
* Params: |
| 1408 |
* fd = function that v is a parameter to |
| 1409 |
* v = parameter that needs to be STC.return_ |
| 1410 |
* returnScope = infer `return scope` instead of `return ref` |
| 1411 |
* |
| 1412 |
* Returns: whether the inference on `v` was successful or `v` already was `return` |
| 1413 |
*/ |
| 1414 |
private bool inferReturn(FuncDeclaration fd, VarDeclaration v, bool returnScope) |
| 1415 |
{ |
| 1416 |
if (v.isReturn()) |
| 1417 |
return !!(v.storage_class & STC.returnScope) == returnScope; |
| 1418 |
|
| 1419 |
if (!v.isParameter() || v.isTypesafeVariadicArray || (returnScope && v.doNotInferReturn)) |
| 1420 |
return false; |
| 1421 |
|
| 1422 |
if (!fd.scopeInprocess) |
| 1423 |
return false; |
| 1424 |
|
| 1425 |
if (returnScope && !(v.isScope() || v.maybeScope)) |
| 1426 |
return false; |
| 1427 |
|
| 1428 |
//printf("for function '%s' inferring 'return' for variable '%s', returnScope: %d\n", fd.toChars(), v.toChars(), returnScope); |
| 1429 |
auto newStcs = STC.return_ | STC.returninferred | (returnScope ? STC.returnScope : 0); |
| 1430 |
v.storage_class |= newStcs; |
| 1431 |
|
| 1432 |
if (v == fd.vthis) |
| 1433 |
{ |
| 1434 |
/* v is the 'this' reference, so mark the function |
| 1435 |
*/ |
| 1436 |
fd.storage_class |= newStcs; |
| 1437 |
if (auto tf = fd.type.isTypeFunction()) |
| 1438 |
{ |
| 1439 |
//printf("'this' too %p %s\n", tf, sc.func.toChars()); |
| 1440 |
tf.isReturnScope = returnScope; |
| 1441 |
tf.isReturn = true; |
| 1442 |
tf.isReturnInferred = true; |
| 1443 |
} |
| 1444 |
} |
| 1445 |
else |
| 1446 |
{ |
| 1447 |
// Perform 'return' inference on parameter |
| 1448 |
if (auto tf = fd.type.isTypeFunction()) |
| 1449 |
{ |
| 1450 |
foreach (i, p; tf.parameterList) |
| 1451 |
{ |
| 1452 |
if (p.ident == v.ident) |
| 1453 |
{ |
| 1454 |
p.storageClass |= newStcs; |
| 1455 |
break; // there can be only one |
| 1456 |
} |
| 1457 |
} |
| 1458 |
} |
| 1459 |
} |
| 1460 |
return true; |
| 1461 |
} |
| 1462 |
|
| 1463 |
|
| 1464 |
/**************************************** |
| 1465 |
* e is an expression to be returned by value, and that value contains pointers. |
| 1466 |
* Walk e to determine which variables are possibly being |
| 1467 |
* returned by value, such as: |
| 1468 |
* int* function(int* p) { return p; } |
| 1469 |
* If e is a form of &p, determine which variables have content |
| 1470 |
* which is being returned as ref, such as: |
| 1471 |
* int* function(int i) { return &i; } |
| 1472 |
* Multiple variables can be inserted, because of expressions like this: |
| 1473 |
* int function(bool b, int i, int* p) { return b ? &i : p; } |
| 1474 |
* |
| 1475 |
* No side effects. |
| 1476 |
* |
| 1477 |
* Params: |
| 1478 |
* e = expression to be returned by value |
| 1479 |
* er = where to place collected data |
| 1480 |
*/ |
| 1481 |
public |
| 1482 |
void escapeByValue(Expression e, ref scope EscapeByResults er) |
| 1483 |
{ |
| 1484 |
escapeExp(e, er, 0); |
| 1485 |
} |
| 1486 |
|
| 1487 |
// Unified implementation of `escapeByValue` and `escapeByRef` |
| 1488 |
// deref = derference level, if `p` has deref 0, then `*p` has deref 1, `&p` has -1, and `**p` has 2 etc. |
| 1489 |
// For escapeByValue, deref = 0 |
| 1490 |
// For escapeByRef, deref = -1 |
| 1491 |
// Currently, `scope` is not transitive, so deref > 0 means no escaping, but `@live` does do transitive checking, |
| 1492 |
// and future enhancements might add some form of transitive scope. |
| 1493 |
void escapeExp(Expression e, ref scope EscapeByResults er, int deref) |
| 1494 |
{ |
| 1495 |
//printf("[%s] escapeByValue, e: %s\n", e.loc.toChars(), e.toChars()); |
| 1496 |
|
| 1497 |
void visit(Expression e) |
| 1498 |
{ |
| 1499 |
} |
| 1500 |
|
| 1501 |
void visitAddr(AddrExp e) |
| 1502 |
{ |
| 1503 |
/* Taking the address of struct literal is normally not |
| 1504 |
* allowed, but CTFE can generate one out of a new expression, |
| 1505 |
* but it'll be placed in static data so no need to check it. |
| 1506 |
*/ |
| 1507 |
if (deref == 0 && e.e1.op != EXP.structLiteral) |
| 1508 |
escapeExp(e.e1, er, deref - 1); |
| 1509 |
} |
| 1510 |
|
| 1511 |
void visitSymOff(SymOffExp e) |
| 1512 |
{ |
| 1513 |
if (VarDeclaration v = e.var.isVarDeclaration()) |
| 1514 |
er.varDeref(v, deref - 1); |
| 1515 |
} |
| 1516 |
|
| 1517 |
void visitVar(VarExp e) |
| 1518 |
{ |
| 1519 |
if (auto v = e.var.isVarDeclaration()) |
| 1520 |
{ |
| 1521 |
const refAddr = deref < 0 && v.storage_class & STC.ref_ ; |
| 1522 |
const tempVar = deref == 0 && v.storage_class & STC.temp; |
| 1523 |
if ((refAddr || tempVar) && v._init && v != er.lastTemp) |
| 1524 |
{ |
| 1525 |
// If compiler generated ref temporary |
| 1526 |
// (ref v = ex; ex) |
| 1527 |
// e.g. to extract side effects of `Tuple!(int, int).modify().expand[0]` |
| 1528 |
// look at the initializer instead |
| 1529 |
if (ExpInitializer ez = v._init.isExpInitializer()) |
| 1530 |
{ |
| 1531 |
// Prevent endless loops. Consider: |
| 1532 |
// `__field0 = (S __tup1 = S(x, y);) , __field0 = __tup1.__fields_field_0` |
| 1533 |
// escapeExp would recurse on the lhs of the last assignment, which is __field0 |
| 1534 |
// again. In this case, we want the rhs. |
| 1535 |
// Also consider appending a struct with a `return scope` constructor: |
| 1536 |
// __appendtmp34 = __appendtmp34.this(null) |
| 1537 |
// In that case we just break the cycle using `lastTemp`. |
| 1538 |
auto lc = ez.exp.lastComma(); |
| 1539 |
auto restoreLastTemp = er.lastTemp; |
| 1540 |
er.lastTemp = v; |
| 1541 |
// printf("%s %s TO %s\n", e.loc.toChars, e.toChars, lc.toChars); |
| 1542 |
if (lc.isAssignExp || lc.isConstructExp || lc.isBlitExp) |
| 1543 |
escapeExp(lc.isBinExp().e2, er, deref); |
| 1544 |
else |
| 1545 |
escapeExp(ez.exp, er, deref); |
| 1546 |
|
| 1547 |
er.lastTemp = restoreLastTemp; |
| 1548 |
return; |
| 1549 |
} |
| 1550 |
} |
| 1551 |
|
| 1552 |
if (deref < 0 || e.type.hasPointers()) |
| 1553 |
er.varDeref(v, deref); |
| 1554 |
} |
| 1555 |
} |
| 1556 |
|
| 1557 |
void visitThis(ThisExp e) |
| 1558 |
{ |
| 1559 |
// Special case because `__this2` isn't `ref` internally |
| 1560 |
if (deref == -1 && e.var && e.var.toParent2().isFuncDeclaration().hasDualContext()) |
| 1561 |
{ |
| 1562 |
escapeByValue(e, er); |
| 1563 |
return; |
| 1564 |
} |
| 1565 |
|
| 1566 |
if (e.var) |
| 1567 |
er.varDeref(e.var, deref); |
| 1568 |
} |
| 1569 |
|
| 1570 |
void visitPtr(PtrExp e) |
| 1571 |
{ |
| 1572 |
if (deref < 0 || (er.live && e.type.hasPointers())) |
| 1573 |
escapeExp(e.e1, er, deref + 1); |
| 1574 |
} |
| 1575 |
|
| 1576 |
void visitDotVar(DotVarExp e) |
| 1577 |
{ |
| 1578 |
auto t1b = e.e1.type.toBasetype(); |
| 1579 |
// Accessing a class field dereferences the `this` pointer |
| 1580 |
if (t1b.isTypeClass()) |
| 1581 |
escapeExp(e.e1, er, deref + 1); |
| 1582 |
else if (deref < 0 || e.type.hasPointers()) |
| 1583 |
escapeExp(e.e1, er, deref); |
| 1584 |
} |
| 1585 |
|
| 1586 |
void visitDelegate(DelegateExp e) |
| 1587 |
{ |
| 1588 |
Type t = e.e1.type.toBasetype(); |
| 1589 |
if (t.isTypeClass() || t.isTypePointer()) |
| 1590 |
escapeByValue(e.e1, er); |
| 1591 |
else |
| 1592 |
escapeByRef(e.e1, er); |
| 1593 |
er.byFunc(e.func, false); |
| 1594 |
} |
| 1595 |
|
| 1596 |
void visitFunc(FuncExp e) |
| 1597 |
{ |
| 1598 |
if (e.fd.tok == TOK.delegate_) |
| 1599 |
er.byFunc(e.fd, false); |
| 1600 |
} |
| 1601 |
|
| 1602 |
void visitTuple(TupleExp e) |
| 1603 |
{ |
| 1604 |
assert(0); // should have been lowered by now |
| 1605 |
} |
| 1606 |
|
| 1607 |
void visitArrayLiteral(ArrayLiteralExp e) |
| 1608 |
{ |
| 1609 |
Type tb = e.type.toBasetype(); |
| 1610 |
if (tb.isStaticOrDynamicArray()) |
| 1611 |
{ |
| 1612 |
if (e.basis) |
| 1613 |
escapeExp(e.basis, er, deref); |
| 1614 |
foreach (el; *e.elements) |
| 1615 |
{ |
| 1616 |
if (el) |
| 1617 |
escapeExp(el, er, deref); |
| 1618 |
} |
| 1619 |
} |
| 1620 |
} |
| 1621 |
|
| 1622 |
void visitStructLiteral(StructLiteralExp e) |
| 1623 |
{ |
| 1624 |
if (e.elements) |
| 1625 |
{ |
| 1626 |
foreach (ex; *e.elements) |
| 1627 |
{ |
| 1628 |
if (ex) |
| 1629 |
escapeExp(ex, er, deref); |
| 1630 |
} |
| 1631 |
} |
| 1632 |
if (deref == -1) |
| 1633 |
{ |
| 1634 |
er.byExp(e, er.inRetRefTransition > 0); // |
| 1635 |
} |
| 1636 |
} |
| 1637 |
|
| 1638 |
void visitNew(NewExp e) |
| 1639 |
{ |
| 1640 |
if (e.placement) |
| 1641 |
escapeExp(e.placement, er, deref); |
| 1642 |
|
| 1643 |
Type tb = e.newtype.toBasetype(); |
| 1644 |
if (tb.isTypeStruct() && !e.member && e.arguments) |
| 1645 |
{ |
| 1646 |
foreach (ex; *e.arguments) |
| 1647 |
{ |
| 1648 |
if (ex) |
| 1649 |
escapeExp(ex, er, deref); |
| 1650 |
} |
| 1651 |
} |
| 1652 |
} |
| 1653 |
|
| 1654 |
void visitCast(CastExp e) |
| 1655 |
{ |
| 1656 |
if (deref < 0 || !e.type.hasPointers()) |
| 1657 |
return; |
| 1658 |
Type tb = e.type.toBasetype(); |
| 1659 |
if (tb.isTypeDArray() && e.e1.type.toBasetype().isTypeSArray()) |
| 1660 |
escapeExp(e.e1, er, deref - 1); |
| 1661 |
else |
| 1662 |
escapeExp(e.e1, er, deref); |
| 1663 |
} |
| 1664 |
|
| 1665 |
void visitSlice(SliceExp e) |
| 1666 |
{ |
| 1667 |
// Usually: slicing a static array escapes by ref, slicing a dynamic array escapes by value. |
| 1668 |
// However, slices with compile-time known length can implicitly converted to static arrays: |
| 1669 |
// int*[3] b = sa[0 .. 3]; |
| 1670 |
// So we need to compare the type before slicing and after slicing |
| 1671 |
const bool staticBefore = e.e1.type.toBasetype().isTypeSArray() !is null; |
| 1672 |
const bool staticAfter = e.type.toBasetype().isTypeSArray() !is null; |
| 1673 |
escapeExp(e.e1, er, deref + staticAfter - staticBefore); |
| 1674 |
} |
| 1675 |
|
| 1676 |
void visitIndex(IndexExp e) |
| 1677 |
{ |
| 1678 |
Type tb = e.e1.type.toBasetype(); |
| 1679 |
|
| 1680 |
if (tb.isTypeSArray()) |
| 1681 |
{ |
| 1682 |
escapeExp(e.e1, er, deref); |
| 1683 |
} |
| 1684 |
else if (tb.isTypeDArray()) |
| 1685 |
{ |
| 1686 |
escapeExp(e.e1, er, deref + 1); |
| 1687 |
} |
| 1688 |
} |
| 1689 |
|
| 1690 |
void visitBin(BinExp e) |
| 1691 |
{ |
| 1692 |
if (e.type.toBasetype().isTypePointer()) |
| 1693 |
{ |
| 1694 |
// The expression must be pointer arithmetic, e.g. `p + 1` or `1 + p` |
| 1695 |
escapeExp(e.e1, er, deref); |
| 1696 |
escapeExp(e.e2, er, deref); |
| 1697 |
} |
| 1698 |
} |
| 1699 |
|
| 1700 |
void visitBinAssign(BinAssignExp e) |
| 1701 |
{ |
| 1702 |
escapeExp(e.e1, er, deref); |
| 1703 |
} |
| 1704 |
|
| 1705 |
void visitAssign(AssignExp e) |
| 1706 |
{ |
| 1707 |
escapeExp(e.e1, er, deref); |
| 1708 |
} |
| 1709 |
|
| 1710 |
void visitComma(CommaExp e) |
| 1711 |
{ |
| 1712 |
escapeExp(e.e2, er, deref); |
| 1713 |
} |
| 1714 |
|
| 1715 |
void visitCond(CondExp e) |
| 1716 |
{ |
| 1717 |
escapeExp(e.e1, er, deref); |
| 1718 |
escapeExp(e.e2, er, deref); |
| 1719 |
} |
| 1720 |
|
| 1721 |
void visitCall(CallExp e) |
| 1722 |
{ |
| 1723 |
//printf("CallExp(): %s\n", e.toChars()); |
| 1724 |
// Check each argument that is passed as 'return scope'. |
| 1725 |
TypeFunction tf = e.calledFunctionType(); |
| 1726 |
if (!tf) |
| 1727 |
return; |
| 1728 |
|
| 1729 |
if (deref < 0 && !tf.isRef) |
| 1730 |
{ |
| 1731 |
er.byExp(e, er.inRetRefTransition > 0); |
| 1732 |
return; |
| 1733 |
} |
| 1734 |
|
| 1735 |
// A function may have a return scope struct parameter, but only return an `int` field of that struct |
| 1736 |
if (deref >= 0 && !e.type.hasPointers()) |
| 1737 |
return; |
| 1738 |
|
| 1739 |
/// Given a `scope` / `return scope` / `return ref` annotation, |
| 1740 |
/// get the corresponding pointer dereference level |
| 1741 |
static int paramDeref(ScopeRef psr) |
| 1742 |
{ |
| 1743 |
return |
| 1744 |
(psr == ScopeRef.ReturnRef || psr == ScopeRef.ReturnRef_Scope) ? -1 : |
| 1745 |
(psr == ScopeRef.ReturnScope || psr == ScopeRef.Ref_ReturnScope) ? 0 : |
| 1746 |
+1; |
| 1747 |
} |
| 1748 |
|
| 1749 |
if (e.arguments && e.arguments.length) |
| 1750 |
{ |
| 1751 |
// j=1 if _arguments[] is first argument, |
| 1752 |
// skip it because it is not passed by ref |
| 1753 |
int j = tf.isDstyleVariadic(); |
| 1754 |
for (size_t i = j; i < e.arguments.length; ++i) |
| 1755 |
{ |
| 1756 |
Expression arg = (*e.arguments)[i]; |
| 1757 |
size_t nparams = tf.parameterList.length; |
| 1758 |
if (i - j < nparams && i >= j) |
| 1759 |
{ |
| 1760 |
Parameter p = tf.parameterList[i - j]; |
| 1761 |
const stc = tf.parameterStorageClass(null, p); |
| 1762 |
ScopeRef psr = buildScopeRef(stc); |
| 1763 |
|
| 1764 |
// For struct constructors, `tf.isRef` is true, but for escape analysis, |
| 1765 |
// it's as if they return `void` and escape through the first (`this`) parameter: |
| 1766 |
// void assign(ref S this, return scope constructorArgs...) |
| 1767 |
// If you then return the constructed result by value, it doesn't count |
| 1768 |
// as dereferencing the scope arguments, they're still escaped. |
| 1769 |
const isRef = tf.isRef && !(tf.isCtor && paramDeref(psr) == 0); |
| 1770 |
const maybeInaccurate = deref == 0 && paramDeref(psr) == 0; |
| 1771 |
er.inRetRefTransition += maybeInaccurate; |
| 1772 |
if (paramDeref(psr) <= 0) |
| 1773 |
escapeExp(arg, er, deref + paramDeref(psr) + isRef); |
| 1774 |
er.inRetRefTransition -= maybeInaccurate; |
| 1775 |
} |
| 1776 |
} |
| 1777 |
} |
| 1778 |
|
| 1779 |
// If 'this' is returned, check it too |
| 1780 |
Type t1 = e.e1.type.toBasetype(); |
| 1781 |
DotVarExp dve = e.e1.isDotVarExp(); |
| 1782 |
if (dve && t1.ty == Tfunction) |
| 1783 |
{ |
| 1784 |
FuncDeclaration fd = dve.var.isFuncDeclaration(); |
| 1785 |
if (!fd) |
| 1786 |
return; |
| 1787 |
|
| 1788 |
// https://issues.dlang.org/show_bug.cgi?id=20149#c10 |
| 1789 |
if (deref < 0 && dve.var.isCtorDeclaration()) |
| 1790 |
{ |
| 1791 |
er.byExp(e, false); |
| 1792 |
return; |
| 1793 |
} |
| 1794 |
|
| 1795 |
// Calling a non-static member function dve.var, which is returning `this`, and with dve.e1 representing `this` |
| 1796 |
const psr = buildScopeRef(getThisStorageClass(fd)); |
| 1797 |
er.inRetRefTransition += (psr == ScopeRef.ReturnRef_Scope); |
| 1798 |
if (paramDeref(psr) <= 0) |
| 1799 |
escapeExp(dve.e1, er, deref + paramDeref(psr) + (tf.isRef && !tf.isCtor)); |
| 1800 |
er.inRetRefTransition -= (psr == ScopeRef.ReturnRef_Scope); |
| 1801 |
} |
| 1802 |
|
| 1803 |
// The return value of a delegate call with return (scope) may point to a closure variable, |
| 1804 |
// so escape the delegate in case it's `scope` / stack allocated. |
| 1805 |
if (t1.isTypeDelegate() && tf.isReturn) |
| 1806 |
{ |
| 1807 |
escapeExp(e.e1, er, deref + tf.isRef); |
| 1808 |
} |
| 1809 |
|
| 1810 |
// If `fd` is a nested function that's return ref / return scope, check that |
| 1811 |
// it doesn't escape closure vars |
| 1812 |
if (auto ve = e.e1.isVarExp()) |
| 1813 |
{ |
| 1814 |
if (FuncDeclaration fd = ve.var.isFuncDeclaration()) |
| 1815 |
{ |
| 1816 |
if (fd.isNested() && tf.isReturn) |
| 1817 |
{ |
| 1818 |
er.byFunc(fd, true); |
| 1819 |
} |
| 1820 |
} |
| 1821 |
} |
| 1822 |
} |
| 1823 |
|
| 1824 |
if (deref > 0 && !er.live) |
| 1825 |
return; // scope is not transitive currently, so dereferencing expressions don't escape |
| 1826 |
|
| 1827 |
if (deref >= 0 && er.live && !e.type.hasPointers()) |
| 1828 |
return; // can't escape non-pointer values by value |
| 1829 |
|
| 1830 |
switch (e.op) |
| 1831 |
{ |
| 1832 |
case EXP.address: return visitAddr(e.isAddrExp()); |
| 1833 |
case EXP.symbolOffset: return visitSymOff(e.isSymOffExp()); |
| 1834 |
case EXP.variable: return visitVar(e.isVarExp()); |
| 1835 |
case EXP.this_: return visitThis(e.isThisExp()); |
| 1836 |
case EXP.star: return visitPtr(e.isPtrExp()); |
| 1837 |
case EXP.dotVariable: return visitDotVar(e.isDotVarExp()); |
| 1838 |
case EXP.delegate_: return visitDelegate(e.isDelegateExp()); |
| 1839 |
case EXP.function_: return visitFunc(e.isFuncExp()); |
| 1840 |
case EXP.tuple: return visitTuple(e.isTupleExp()); |
| 1841 |
case EXP.arrayLiteral: return visitArrayLiteral(e.isArrayLiteralExp()); |
| 1842 |
case EXP.structLiteral: return visitStructLiteral(e.isStructLiteralExp()); |
| 1843 |
case EXP.new_: return visitNew(e.isNewExp()); |
| 1844 |
case EXP.cast_: return visitCast(e.isCastExp()); |
| 1845 |
case EXP.slice: return visitSlice(e.isSliceExp()); |
| 1846 |
case EXP.index: return visitIndex(e.isIndexExp()); |
| 1847 |
case EXP.blit: return visitAssign(e.isBlitExp()); |
| 1848 |
case EXP.construct: return visitAssign(e.isConstructExp()); |
| 1849 |
case EXP.assign: return visitAssign(e.isAssignExp()); |
| 1850 |
case EXP.comma: return visitComma(e.isCommaExp()); |
| 1851 |
case EXP.question: return visitCond(e.isCondExp()); |
| 1852 |
case EXP.call: return visitCall(e.isCallExp()); |
| 1853 |
default: |
| 1854 |
if (auto ba = e.isBinAssignExp()) |
| 1855 |
return visitBinAssign(ba); |
| 1856 |
if (auto b = e.isBinExp()) |
| 1857 |
return visitBin(b); |
| 1858 |
return visit(e); |
| 1859 |
} |
| 1860 |
} |
| 1861 |
|
| 1862 |
/***************************** |
| 1863 |
* Concoct storage class for member function's implicit `this` parameter. |
| 1864 |
* Params: |
| 1865 |
* fd = member function |
| 1866 |
* Returns: |
| 1867 |
* storage class for fd's `this` |
| 1868 |
*/ |
| 1869 |
STC getThisStorageClass(FuncDeclaration fd) |
| 1870 |
{ |
| 1871 |
STC stc; |
| 1872 |
auto tf = fd.type.toBasetype().isTypeFunction(); |
| 1873 |
if (tf.isReturn) |
| 1874 |
stc |= STC.return_; |
| 1875 |
if (tf.isReturnScope) |
| 1876 |
stc |= STC.returnScope | STC.scope_; |
| 1877 |
auto ad = fd.isThis(); |
| 1878 |
if ((ad && ad.isClassDeclaration()) || tf.isScopeQual) |
| 1879 |
stc |= STC.scope_; |
| 1880 |
if (ad && ad.isStructDeclaration()) |
| 1881 |
stc |= STC.ref_; // `this` for a struct member function is passed by `ref` |
| 1882 |
return stc; |
| 1883 |
} |
| 1884 |
|
| 1885 |
/**************************************** |
| 1886 |
* e is an expression to be returned by 'ref'. |
| 1887 |
* Walk e to determine which variables are possibly being |
| 1888 |
* returned by ref, such as: |
| 1889 |
* ref int function(int i) { return i; } |
| 1890 |
* If e is a form of *p, determine which variables have content |
| 1891 |
* which is being returned as ref, such as: |
| 1892 |
* ref int function(int* p) { return *p; } |
| 1893 |
* Multiple variables can be inserted, because of expressions like this: |
| 1894 |
* ref int function(bool b, int i, int* p) { return b ? i : *p; } |
| 1895 |
* |
| 1896 |
* No side effects. |
| 1897 |
* |
| 1898 |
* Params: |
| 1899 |
* e = expression to be returned by 'ref' |
| 1900 |
* er = where to place collected data |
| 1901 |
*/ |
| 1902 |
void escapeByRef(Expression e, ref scope EscapeByResults er) |
| 1903 |
{ |
| 1904 |
escapeExp(e, er, -1); |
| 1905 |
} |
| 1906 |
|
| 1907 |
/************************************ |
| 1908 |
* Aggregate the data collected by the escapeBy??() functions. |
| 1909 |
*/ |
| 1910 |
public |
| 1911 |
struct EscapeByResults |
| 1912 |
{ |
| 1913 |
/* |
| 1914 |
* retRefTransition = Whether the variable / expression went through a `return (ref) scope` function call |
| 1915 |
* |
| 1916 |
* This is needed for the dip1000 by default transition, since the rules for |
| 1917 |
* disambiguating `return scope ref` have changed. Therefore, functions in legacy code |
| 1918 |
* can be mistakenly treated as `return ref` making the compiler believe stack variables |
| 1919 |
* are being escaped, which is an error even in `@system` code. By keeping track of this |
| 1920 |
* information, variables escaped through `return ref` can be treated as a deprecation instead |
| 1921 |
* of error, see test/fail_compilation/dip1000_deprecation.d |
| 1922 |
* |
| 1923 |
* Additionally, return scope can be inferred wrongly instead of scope, in which |
| 1924 |
* case the code could give false positives even without @safe or dip1000: |
| 1925 |
* https://issues.dlang.org/show_bug.cgi?id=23657 |
| 1926 |
*/ |
| 1927 |
|
| 1928 |
/// called on variables being returned by ref / address |
| 1929 |
void delegate(VarDeclaration, bool retRefTransition) byRef; |
| 1930 |
/// called on variables with values containing pointers |
| 1931 |
void delegate(VarDeclaration) byValue; |
| 1932 |
|
| 1933 |
/// Switch over `byValue` and `byRef` based on `deref` level (-1 = by ref, 0 = by value, 1 = only for live currently) |
| 1934 |
private void varDeref(VarDeclaration var, int deref) |
| 1935 |
{ |
| 1936 |
if (var.isDataseg()) |
| 1937 |
return; |
| 1938 |
if (deref == -1) |
| 1939 |
byRef(var, inRetRefTransition > 0); |
| 1940 |
else if (deref == 0) |
| 1941 |
byValue(var); |
| 1942 |
else if (deref > 0 && live) |
| 1943 |
byValue(var); |
| 1944 |
} |
| 1945 |
|
| 1946 |
/// called on nested functions that are turned into delegates |
| 1947 |
/// When `called` is true, it means the delegate escapes variables |
| 1948 |
/// from the closure through a call to it, while `false` means the |
| 1949 |
/// delegate itself escapes. |
| 1950 |
void delegate(FuncDeclaration, bool called) byFunc; |
| 1951 |
/// called when expression temporaries are being returned by ref / address |
| 1952 |
void delegate(Expression, bool retRefTransition) byExp; |
| 1953 |
|
| 1954 |
/// if @live semantics apply, i.e. expressions `p`, `*p`, `**p`, etc., all return `p`. |
| 1955 |
bool live = false; |
| 1956 |
|
| 1957 |
/// Incremented / decremented every time an ambiguous return ref/scope parameter is checked. |
| 1958 |
/// See retRefTransition above. |
| 1959 |
private int inRetRefTransition = 0; |
| 1960 |
|
| 1961 |
/// When forwarding a temp var to its initializer, |
| 1962 |
/// keep track of the temp var to break endless loops |
| 1963 |
private VarDeclaration lastTemp = null; |
| 1964 |
} |
| 1965 |
|
| 1966 |
/************************* |
| 1967 |
* Find all variables accessed by this delegate that are |
| 1968 |
* in functions enclosing it. |
| 1969 |
* Params: |
| 1970 |
* fd = function |
| 1971 |
* vars = array to append found variables to |
| 1972 |
*/ |
| 1973 |
public void findAllOuterAccessedVariables(FuncDeclaration fd, VarDeclarations* vars) |
| 1974 |
{ |
| 1975 |
//printf("findAllOuterAccessedVariables(fd: %s)\n", fd.toChars()); |
| 1976 |
for (auto p = fd.parent; p; p = p.parent) |
| 1977 |
{ |
| 1978 |
auto fdp = p.isFuncDeclaration(); |
| 1979 |
if (!fdp) |
| 1980 |
continue; |
| 1981 |
|
| 1982 |
foreach (v; fdp.closureVars) |
| 1983 |
{ |
| 1984 |
foreach (const fdv; v.nestedrefs) |
| 1985 |
{ |
| 1986 |
if (fdv == fd) |
| 1987 |
{ |
| 1988 |
//printf("accessed: %s, type %s\n", v.toChars(), v.type.toChars()); |
| 1989 |
vars.push(v); |
| 1990 |
} |
| 1991 |
} |
| 1992 |
} |
| 1993 |
} |
| 1994 |
} |
| 1995 |
|
| 1996 |
/*********************************** |
| 1997 |
* Turn off `maybeScope` for variable `v`. |
| 1998 |
* |
| 1999 |
* This exists in order to find where `maybeScope` is getting turned off. |
| 2000 |
* Params: |
| 2001 |
* v = variable |
| 2002 |
* o = reason for it being turned off: |
| 2003 |
* - `Expression` such as `throw e` or `&e` |
| 2004 |
* - `VarDeclaration` of a non-scope parameter it was assigned to |
| 2005 |
* - `null` for no reason |
| 2006 |
*/ |
| 2007 |
private void doNotInferScope(VarDeclaration v, RootObject o) |
| 2008 |
{ |
| 2009 |
if (v.maybeScope) |
| 2010 |
{ |
| 2011 |
v.maybeScope = false; |
| 2012 |
if (o && v.isParameter()) |
| 2013 |
EscapeState.scopeInferFailure[v.sequenceNumber] = o; |
| 2014 |
} |
| 2015 |
} |
| 2016 |
|
| 2017 |
/*********************************** |
| 2018 |
* After semantic analysis of the function body, |
| 2019 |
* try to infer `scope` / `return` on the parameters |
| 2020 |
* |
| 2021 |
* Params: |
| 2022 |
* funcdecl = function declaration that was analyzed |
| 2023 |
* f = final function type. `funcdecl.type` started as the 'premature type' before attribute |
| 2024 |
* inference, then its inferred attributes are copied over to final type `f` |
| 2025 |
*/ |
| 2026 |
public |
| 2027 |
void finishScopeParamInference(FuncDeclaration funcdecl, ref TypeFunction f) |
| 2028 |
{ |
| 2029 |
if (!funcdecl.scopeInprocess) |
| 2030 |
return; |
| 2031 |
funcdecl.scopeInprocess = false; |
| 2032 |
|
| 2033 |
if (funcdecl.storage_class & STC.return_) |
| 2034 |
{ |
| 2035 |
if (funcdecl.type == f) |
| 2036 |
f = cast(TypeFunction)f.copy(); |
| 2037 |
f.isReturn = true; |
| 2038 |
f.isReturnScope = cast(bool) (funcdecl.storage_class & STC.returnScope); |
| 2039 |
if (funcdecl.storage_class & STC.returninferred) |
| 2040 |
f.isReturnInferred = true; |
| 2041 |
} |
| 2042 |
|
| 2043 |
|
| 2044 |
// Infer STC.scope_ |
| 2045 |
if (funcdecl.parameters && !funcdecl.errors) |
| 2046 |
{ |
| 2047 |
assert(f.parameterList.length == funcdecl.parameters.length); |
| 2048 |
foreach (u, p; f.parameterList) |
| 2049 |
{ |
| 2050 |
auto v = (*funcdecl.parameters)[u]; |
| 2051 |
if (!v.isScope() && v.type.hasPointers() && inferScope(v)) |
| 2052 |
{ |
| 2053 |
//printf("Inferring scope for %s\n", v.toChars()); |
| 2054 |
p.storageClass |= STC.scope_ | STC.scopeinferred; |
| 2055 |
} |
| 2056 |
} |
| 2057 |
} |
| 2058 |
|
| 2059 |
if (funcdecl.vthis) |
| 2060 |
{ |
| 2061 |
inferScope(funcdecl.vthis); |
| 2062 |
f.isScopeQual = funcdecl.vthis.isScope(); |
| 2063 |
f.isScopeInferred = !!(funcdecl.vthis.storage_class & STC.scopeinferred); |
| 2064 |
} |
| 2065 |
} |
| 2066 |
|
| 2067 |
/************************************************ |
| 2068 |
* Is type a reference to a mutable value? |
| 2069 |
* |
| 2070 |
* This is used to determine if an argument that does not have a corresponding |
| 2071 |
* Parameter, i.e. a variadic argument, is a pointer to mutable data. |
| 2072 |
* Params: |
| 2073 |
* t = type of the argument |
| 2074 |
* Returns: |
| 2075 |
* true if it's a pointer (or reference) to mutable data |
| 2076 |
*/ |
| 2077 |
private |
| 2078 |
bool isReferenceToMutable(Type t) |
| 2079 |
{ |
| 2080 |
t = t.baseElemOf(); |
| 2081 |
|
| 2082 |
if (!t.isMutable() || |
| 2083 |
!t.hasPointers()) |
| 2084 |
return false; |
| 2085 |
|
| 2086 |
switch (t.ty) |
| 2087 |
{ |
| 2088 |
case Tpointer: |
| 2089 |
if (t.nextOf().isTypeFunction()) |
| 2090 |
break; |
| 2091 |
goto case; |
| 2092 |
|
| 2093 |
case Tarray: |
| 2094 |
case Taarray: |
| 2095 |
case Tdelegate: |
| 2096 |
if (t.nextOf().isMutable()) |
| 2097 |
return true; |
| 2098 |
break; |
| 2099 |
|
| 2100 |
case Tclass: |
| 2101 |
return true; // even if the class fields are not mutable |
| 2102 |
|
| 2103 |
case Tstruct: |
| 2104 |
// Have to look at each field |
| 2105 |
foreach (VarDeclaration v; t.isTypeStruct().sym.fields) |
| 2106 |
{ |
| 2107 |
if (v.storage_class & STC.ref_) |
| 2108 |
{ |
| 2109 |
if (v.type.isMutable()) |
| 2110 |
return true; |
| 2111 |
} |
| 2112 |
else if (v.type.isReferenceToMutable()) |
| 2113 |
return true; |
| 2114 |
} |
| 2115 |
break; |
| 2116 |
|
| 2117 |
case Tnull: |
| 2118 |
return false; |
| 2119 |
|
| 2120 |
default: |
| 2121 |
assert(0); |
| 2122 |
} |
| 2123 |
return false; |
| 2124 |
} |
| 2125 |
|
| 2126 |
/**************************************** |
| 2127 |
* Is parameter a reference to a mutable value? |
| 2128 |
* |
| 2129 |
* This is used if an argument has a corresponding Parameter. |
| 2130 |
* The argument type is necessary if the Parameter is inout. |
| 2131 |
* Params: |
| 2132 |
* p = Parameter to check |
| 2133 |
* t = type of corresponding argument |
| 2134 |
* Returns: |
| 2135 |
* true if it's a pointer (or reference) to mutable data |
| 2136 |
*/ |
| 2137 |
private |
| 2138 |
bool isReferenceToMutable(Parameter p, Type t) |
| 2139 |
{ |
| 2140 |
if (p.isReference()) |
| 2141 |
{ |
| 2142 |
if (p.type.isConst() || p.type.isImmutable()) |
| 2143 |
return false; |
| 2144 |
if (p.type.isWild()) |
| 2145 |
{ |
| 2146 |
return t.isMutable(); |
| 2147 |
} |
| 2148 |
return p.type.isMutable(); |
| 2149 |
} |
| 2150 |
return isReferenceToMutable(p.type); |
| 2151 |
} |
| 2152 |
|
| 2153 |
/// When checking lifetime for assignment `va=v`, the way `va` encloses `v` |
| 2154 |
private enum EnclosedBy |
| 2155 |
{ |
| 2156 |
none = 0, |
| 2157 |
refVar, // `va` is a `ref` variable, which may link to a global variable |
| 2158 |
global, // `va` is a global variable |
| 2159 |
returnScope, // `va` is a scope variable that may be returned |
| 2160 |
longerScope, // `va` is another scope variable declared earlier than `v` |
| 2161 |
} |
| 2162 |
|
| 2163 |
/********************************** |
| 2164 |
* Determine if `va` has a lifetime that lasts past |
| 2165 |
* the destruction of `v` |
| 2166 |
* Params: |
| 2167 |
* va = variable assigned to |
| 2168 |
* v = variable being assigned |
| 2169 |
* Returns: |
| 2170 |
* The way `va` encloses `v` (if any) |
| 2171 |
*/ |
| 2172 |
private EnclosedBy enclosesLifetimeOf(VarDeclaration va, VarDeclaration v) |
| 2173 |
{ |
| 2174 |
if (!va) |
| 2175 |
return EnclosedBy.none; |
| 2176 |
|
| 2177 |
if (va.isDataseg()) |
| 2178 |
return EnclosedBy.global; |
| 2179 |
|
| 2180 |
if (va.isScope() && va.isReturn() && !v.isReturn()) |
| 2181 |
return EnclosedBy.returnScope; |
| 2182 |
|
| 2183 |
if (va.isReference() && va.isParameter()) |
| 2184 |
return EnclosedBy.refVar; |
| 2185 |
|
| 2186 |
assert(va.sequenceNumber != va.sequenceNumber.init); |
| 2187 |
assert(v.sequenceNumber != v.sequenceNumber.init); |
| 2188 |
if (va.sequenceNumber < v.sequenceNumber) |
| 2189 |
return EnclosedBy.longerScope; |
| 2190 |
|
| 2191 |
return EnclosedBy.none; |
| 2192 |
} |
| 2193 |
|
| 2194 |
// `setUnsafePreview` partially evaluated for dip1000 |
| 2195 |
public |
| 2196 |
bool setUnsafeDIP1000(ref Scope sc, bool gag, Loc loc, const(char)* msg, |
| 2197 |
RootObject[] args...) |
| 2198 |
{ |
| 2199 |
return setUnsafePreview(&sc, sc.useDIP1000, gag, loc, msg, args); |
| 2200 |
} |
| 2201 |
|
| 2202 |
/*************************************** |
| 2203 |
* Check that taking the address of `v` is `@safe` |
| 2204 |
* |
| 2205 |
* It's not possible to take the address of a scope variable, because `scope` only applies |
| 2206 |
* to the top level indirection. |
| 2207 |
* |
| 2208 |
* Params: |
| 2209 |
* v = variable that a reference is created |
| 2210 |
* e = expression that takes the referene |
| 2211 |
* sc = used to obtain function / deprecated status |
| 2212 |
* gag = don't print errors |
| 2213 |
* Returns: |
| 2214 |
* true if taking the address of `v` is problematic because of the lack of transitive `scope` |
| 2215 |
*/ |
| 2216 |
private bool checkScopeVarAddr(VarDeclaration v, Expression e, ref Scope sc, bool gag) |
| 2217 |
{ |
| 2218 |
if (!v.isScope()) |
| 2219 |
{ |
| 2220 |
doNotInferScope(v, e); |
| 2221 |
return false; |
| 2222 |
} |
| 2223 |
|
| 2224 |
if (!e.type) |
| 2225 |
return false; |
| 2226 |
|
| 2227 |
// When the type after dereferencing has no pointers, it's okay. |
| 2228 |
// Comes up when escaping `&someStruct.intMember` of a `scope` struct: |
| 2229 |
// scope does not apply to the `int` |
| 2230 |
Type t = e.type.baseElemOf(); |
| 2231 |
if ((t.ty == Tarray || t.ty == Tpointer) && !t.nextOf().toBasetype().hasPointers()) |
| 2232 |
return false; |
| 2233 |
|
| 2234 |
// take address of `scope` variable not allowed, requires transitive scope |
| 2235 |
return sc.setUnsafeDIP1000(gag, e.loc, |
| 2236 |
"taking address of `scope` variable `%s` with pointers", v); |
| 2237 |
} |
| 2238 |
|
| 2239 |
/**************************** |
| 2240 |
* Determine if `v` is a typesafe variadic array, which is implicitly `scope` |
| 2241 |
* Params: |
| 2242 |
* v = variable to check |
| 2243 |
* Returns: |
| 2244 |
* true if `v` is a variadic parameter |
| 2245 |
*/ |
| 2246 |
private bool isTypesafeVariadicArray(VarDeclaration v) |
| 2247 |
{ |
| 2248 |
if (v.storage_class & STC.variadic) |
| 2249 |
{ |
| 2250 |
Type tb = v.type.toBasetype(); |
| 2251 |
if (tb.isStaticOrDynamicArray()) |
| 2252 |
return true; |
| 2253 |
} |
| 2254 |
return false; |
| 2255 |
} |