preview in: it seems that return type auto solves scope variable assignment to this

Dmytro Katyukha firemage.dima at gmail.com
Thu Feb 9 17:42:00 UTC 2023


Hi,

Not sure it is bug, or feature, or what is going on in examples 
below (with `-preview=in` enabled).

For example, we have following code snippet:

```d
import std.stdio;
import std.path;

struct Path {
     private string _path;

     @safe pure nothrow this(in string path) {
         _path = path.dup;
     }

     @safe pure nothrow this(in string[] segments...) {
         this(std.path.buildNormalizedPath(segments));
     }

     /// Check if current path is inside other path
     @safe bool isInside(in Path other) const {
         import std.algorithm: startsWith;
         return this.toAbsolute.segments.startsWith(
             other.toAbsolute.segments);
     }

     @safe Path toAbsolute() const {
         return Path(
             std.path.buildNormalizedPath(
                 std.path.absolutePath(_path.dup.expandTilde)));
     }

     @safe pure auto segments() const {
         return std.path.pathSplitter(_path);
     }

}

unittest {
     assert(Path("my", "dir", "42").isInside(Path("my", "dir")) == 
true);
     assert(Path("my", "dir", "42").isInside(Path("oth", "dir")) 
== false);
}

void main()
{
     auto p = Path(".");
     auto h = Path("~");
     auto r = p.isInside(h);
}
```

Without `-preview=in` option, this code sample works just fine.
But when i enable `-preview=in` (or just manualy replace `in` 
with `scope const` in `isInside` method) it fails with following 
error:

```
source/app.d(19,13): Error: scope variable `other` assigned to 
non-scope parameter `this` calling `toAbsolute`
```

So, the first question is: where in this code assignment to 
`this` happens?

But, what is more strange, is that if i change return type for 
method `toAbsolute` to `auto`, error disappears:

```diff
-    @safe Path toAbsolute() const {
+    @safe auto toAbsolute() const {
```

So, the second question is: what happens in this case?

PS: What is the status of preview `in`? Do it have sense to take 
it into account?


More information about the Digitalmars-d mailing list