Re: How to find all modules in a package?
On Wednesday, 3 August 2022 at 03:36:55 UTC, Domain wrote: I want to find out all public functions in all modules in a package. Can I do that at compile time? I think it's not possible.
Re: Return values from auto function
On Friday, 6 November 2020 at 10:51:20 UTC, Andrey Zherikov wrote: struct Result(T) { struct Success { static if(!is(T == void)) { T value; } } struct Failure { string error; } Algebraic!(Success, Failure) result; this(Success value) { result = value; } this(Failure value) { result = value; } } auto success(T)(T value) { return Result!T(Result!T.Success(value)); } auto failure(string error) { return Result!void(Result!void.Failure(error)); } auto f(int i) { return i > 0 ? success(i) : failure("err text"); // Error: incompatible types for (success(i)) : (failure("err text")): Result!int and Result!void } I'd go with: struct Result(T) { Nullable!string error; static if(!is(T == void)) { T value; static Result!T success(T value) { return Result!T(Nullable!string.init, value); } static Result!T failure(string error) { return Result!T(nullable(error), T.init); } } else { static Result!T success() { return Result!T(Nullable!string.init); } static Result!T failure(string error) { return Result!T(nullable(error)); } } bool isSuccess() { return error.isNull(); } } // Demo Result!int intFun(int i) { return i > 0 ? Result!int.success(i) : Result!int.failure("Be positive!"); } Result!void voidFun(int i) { return i > 0 ? Result!void.success() : Result!void.failure("Be positive!"); } void main() { auto intFunRes = intFun(5); if(intFunRes.isSuccess) writefln("Result: %d", intFunRes.value); else writefln("ERROR: %s", intFunRes.error.get); } Does this satisfy your needs?
Re: What kind of Editor, IDE you are using and which one do you like for D language?
On Sunday, 22 December 2019 at 17:20:51 UTC, BoQsc wrote: There are lots of editors/IDE's that support D language: https://wiki.dlang.org/Editors What kind of editor/IDE are you using and which one do you like the most? IntelliJ IDEA CE with this extension: https://intellij-dlanguage.github.io/ Wow, nobody else uses this?
Re: Cannot take the .keys of shared AA. Is this a regression in 2.087 or a feature?
On Thursday, 15 August 2019 at 19:51:30 UTC, Jonathan M Davis wrote: Not being able to implicitly convert to const is a bit odd, but arguably, nothing should ever be called on a shared AA anyway. If an operation isn't thread-safe, then it shouldn't work with shared. To use a shared object safely, you have to protect access to it with a mutex or some other synchronization mechanism, after which you would normally cast away shared to operate on the object as thread-local while the lock is in place and then release the lock when you're done (also making sure that no thread-local references exist when the lock is released). Because keys is not at all thread-safe, I'd strongly argue that it should not work on a shared AA, and if it does, that's a bug. OK, I get the point. So I should go with something similar to this, right? import core.sync.mutex; import std; shared(string[string]) dict; shared(Mutex) mtx; shared static this() { mtx = new shared Mutex; } void main() { mtx.lock; (cast(string[string]) dict).keys; mtx.unlock; } Or I could use synchronized, if dict was inside a class. Thank you!
Cannot take the .keys of shared AA. Is this a regression in 2.087 or a feature?
Code: import std; shared(string[string]) dict; void main() { dict.keys; } Error: /dlang/dmd/linux/bin64/../../src/druntime/import/object.d(3417): Error: cannot implicitly convert expression aa of type shared(string[string]) to const(shared(string)[string]) onlineapp.d(7): Error: template instance `object.keys!(shared(string[string]), shared(string), string)` error instantiating Before D 2.087 it compiled - is this a regression?
Re: Is there a function for this?
On Saturday, 6 October 2018 at 13:17:22 UTC, bauss wrote: Let's say you have a range with struct, but some of the struct are duplicates of each other. Is there a standard function in Phobos to remove duplicates? My first thought was "uniq", but it can't really do it like that, but it doesn't work. See: https://run.dlang.io/is/IcFEtw Is there another function in Phobos that perhaps would work? I can of course write my own function, but if there is a standard function that can do it, then I'd rather use that. Unless you want to implement opCmp() and do the .sort.uniq then, you may find this one-liner helpful: randomAccessRange.fold!((arr, elem) => arr.canFind(elem) ? arr : (arr ~= elem))((ElementType!(typeof(randomAccessRange))[]).init) Applied in your example: https://run.dlang.io/is/3KjRvY But yes, it is de facto a custom function. I don't think that there is a function in Phobos that will perfectly deduplicate your range without having it sorted before.
@safe - why does this compile?
This code: import std.stdio; class X1 {} class X2 : X1 { void run() @safe { writeln("DONE"); } } void main() @safe { X1 x1 = new X1; X2 x2 = cast(X2) x1; x2.run(); } is obviously wrong gets killed by OS's signal. Why is it @safe? I thought @safe should prevent such errors as well.
Re: vibe.d: problematic "Non-@safe methods are deprecated in REST interfaces"
On Tuesday, 10 July 2018 at 13:24:43 UTC, WebFreak001 wrote: It's supposed to make webservers safe and not crash because of segmentation faults, etc. If you still want to write code like you are used to and don't care about that in your webserver, just mark everything in the implementation @trusted (but @safe in the interface) and it will be fine. I understand the motivation of this and this motivation is undoubtly correct. The problem is when you use the libraries, especially those interfacing with C code. The intention of @trusted is to use it to mark the code that *is* memory safe, but it cannot be verified automatically by the compiler (for example required checks are done before an array access). That's why there is a problem with the libraries that are *not* safe - or at least I don't know the code and cannot verify that they are.
vibe.d: problematic "Non-@safe methods are deprecated in REST interfaces"
Hello, I've recently started building a little REST application on vibe.d. I decided to use the "database" library, as I need to communicate with the PostgreSQL instance. During the compilation I see the deprecation warning: "Non-@safe methods are deprecated in REST interfaces" So two questions rise: 1. Will non-@safe methods in REST be disallowed someday? 2. Isn't it too restrictive? If it IS to be disallowed someday, I just won't be able to call most libraries from REST, as I expect the database library for example is definitely not @safe and cannot be. If I post in the wrong forum, please drop me a line where should I post instead.
Re: Sealed classes - would you want them in D? (v2)
On Thursday, 17 May 2018 at 02:32:07 UTC, KingJoffrey wrote: I propose an idea, for discussion (robust discussion even better ;-) Add an new attribute to class, named 'sealed'. No, not sealed as in Scala. No, not sealed as in C# sealed as in oxford dictionary (close securely, non-porous). when sealed is applied on the class, this means the class is sealed. the sealed attribute only makes sense within a module, and affects nothing outside of the module. When sealed is applied to the class, then, interfacing to a class within a module, from code outside that class - but still within the module, can now only occur via the published interface of the class. outside code in the module, can no longer directly access your private parts! The class is sealed. I don't think that "sealed" is the right name here. Currently C# has its sealed and Scala has its sealed - and these are different things (although I don't code C# and may be wrong, it seems like C#'s sealed is Java's or D's final). I believe that giving "sealed" keyword yet another sense in D is not the right approach. Furthermore, I don't believe that the proposed version of sealed would be a widely-used feature that broadens the language capabilities. It solves the problem that - as discussion in my thread shown - some people consider valid, and some not. My opinion is that it's not worth a new keyword and time for implementing. In the same manner you could ask for removing friend concept from C++ as a bad concept. I don't answer the question whether this concept is good or bad - just give an example. The difference is that you can just go without friend at all, and module-level private is forced. The other reason I don't think it is a feature significant enough is kind of library level. I expect that only author or limited team of people will freely modify the code of module. So there is limited number of people that have a control over the module and it shouldn't be a big deal not to refer to private fields outside the class or define it as a team rule. I believe that a nice approach here would be to add a check to DScanner, so that your editor or IDE could optionally warn you if you refer to the private member from outside the class. But as module is a small unit and its code should probably be controlled/verified by the limited number of people, I don't see this as a big deal. Note that Scala-like sealed from my proposal would have a greater impact (it blocks inheritance outside the module - helps to prevent the library code from being used in a way it is not designed to) and your proposal changes things in a very limited scope. OFC, I am not a "compiler person", nor Walter, Andrei and anyone from the team, so my opinion is definitely not decisive in any way :) To sum up [TLDR]: I don't see your arguments strong enough to alter the language (especially make a cross-language confusion over the "sealed" keyword), but DScaner check would still allow to track down what you consider bad.
Re: Sealed classes - would you want them in D?
On Saturday, 12 May 2018 at 15:36:56 UTC, Walter Bright wrote: On 5/12/2018 8:18 AM, Piotr Mitana wrote: What I am trying to do is: == a.d class P { private this(); } final class C1 : P { } final class C2 : P { } test.d import a; void foo() { P[] twoPs = [ new C1(), new C2() ]; // works } class C3 : P // fails { } dmd test a Error: constructor a.P.this is not accessible from module test OK, Walter, point for you for this :) I still think that this is a kind of a hack (if I need to create an instance of P directly, I need a factory method - it's also not that clean and obvious), but in fact it effectively seems to do what I want to achieve. Although I consider sealed as a nice addition still to make things nice and clean, I understand that it may be not enough justified to add a new keyword to the language. Thank you for all the opinions on that. :)
Re: Sealed classes - would you want them in D?
On Saturday, 12 May 2018 at 10:27:11 UTC, Walter Bright wrote: The solution is: private class MyClass { ... } public final MyClassSealed : MyClass { } Meaning other modules can use MyClassSealed but cannot derive from it. Other classes inside the module can derive from MyClass as required. It is not. Other modules can use MyClassSealed - yes. Inheritance is possible only im module - yes. But these are two different classes still. If we have two of extending classes: private class Parent {} public final class Child1 : Parent {} public final class Child2 : Parent {} Then it is true that I can inherit Parent outside the module, but I can't use it as well. In this case I can't create an array (other then Object[]) that can hold both Child1 and Child2 outside the module. What I want is to see the supertype *everywhere* and be able to use it for example to create an array of Parents, but not be able to create Child3 : Parent elsewhere then in the module where Parent resides. public final class ParentSealed : Parent {} won't help - it will be just the same as two ChildX classes and still won't have a *visible* supertype other then Object with them. What I am trying to do is: /* foo.d */ module foo; sealed class Parent {} final class Child1 : Parent {} final class Child2 : Parent {} /* bar.d */ module bar; import foo; static this { Parent[] twoParents = [new Child1(), new Child2()]; // Parent is still visible } class Child3 : Parent {} // ERROR: Parent is sealed and cannot be extended outside module foo I don't think that it is possible to rewrite this code without sealed, but still having Child3 illegal and the Parent[] array creatable in the module bar. Another example - taken directly from Scala. In Scala optionals are defined via a set of classes ("[T]" is Scala's version for Java's ""): sealed abstract class Option[T] {} final case class Some[T] extends Option[T] {} object None extends Option[Nothing] {} For the sake of simplicity let's don't dive in how "case class" and "object" are different from typical classes. Also let's assume that Nothing extends T (in fact Scala's Nothing extends every possible type) You can declare an Option[Int] variable everywhere and assign Some(value) or None to it. All three classes are visible from everywhere, but as Option is sealed, you can't create class OnlyOnMonday[T] extends Option[T] {} in the other module (effectively nowhere, as Option is a part of the standard library).
Re: Sealed classes - would you want them in D?
On Friday, 11 May 2018 at 23:28:48 UTC, Jonathan M Davis wrote: Except that if I understand correctly, what the OP wants is to have the class be publicly available while restricting who's allowed to derive from it, with the idea that a particular class hierarchy would have a well-defined set of classes that the person who wrote them had full control over rather than allowing anyone and everyone to derive from any class in the hierarchy except for any final classes at the leaves of the hierarchy. Exactly that is the point. I'll give you an example from an app I've started working on: I developed a little CQRS library. The structure of classes is based on the Entity type - an entity is a piece of data that is sent between a client and a server. Client/server that has received the entity, detects the right Handler class for the given entity class and triggers it. Handler for some entity types will generate other entities, which will be sent to their handlers respectively or sent back over the network to be handled remotely. There are four types of entitites: Commands, Queries, Responses and Events. The most typical patterns are: - Client sends a command to the server. Server uses a CommandHandler to generate resulting Events and EventHandlers to take actions corresponding to them. Eventually it may acknowledge the client that the command has been successfully processed, but without any data in response. - Client sends a Query. The server processes it in QueryHandler, which generates a Response that is sent back. Client uses its ResponseHandler to take actions corresponding to the response, such as presenting the results in the UI. Class-wise, we have: - abstract class Entity, - abstract classes Command, Event, Query and Response, each of them extends Entity, - a number of concrete classes being the particular Commands, Events, Queries and Responses. Now what I want to achieve is prevent library user to extend the Entity class. There are four classes inheriting the Entity class and the entire concept is built around these four. Library's internal code is also constructed to support only these four entity types, which make the concept complete and non-extendable by design. Currently user is able to create a fifth type of Entity, but the library will not - and is not meant to - support it in any other way then throwing an exception. If I made the Entity class private as Walter suggested, I could not create a method to transfer any entity type via network or couldn't create for example a log method that accepts Entity as a parameter (Yes, there is a Variant and Algebraic, but I don't think that it is the right use for them). What I want to have is an entity class visible everywhere, but extendable only inside my library. At the same time I want users to be able to freely extend the Command, Event, Query and Response classes, as this is exactly what the concept is about.
Re: Sealed classes - would you want them in D?
On Friday, 11 May 2018 at 15:02:08 UTC, jmh530 wrote: But a new keyword will not get added without a DIP. Yes, I know it definitely needs a DIP - I've opened a discussion in order to gather community members' opinions on sealed and decide whether to write this DIP at all and possibly track down some concept issues at the very beginning.
Re: Sealed classes - would you want them in D?
Might I suggest going back to the sealed classes topic? I don't think the discussion in this thread should go in the direction about the sense of using classes, proper encapsulation and the memory related stuff.
Re: Sealed classes - would you want them in D?
On Thursday, 10 May 2018 at 14:48:23 UTC, rikki cattermole wrote: module foo; class A { } final class B : A { } in one module, he wants to be able to create a new final class C : B { } and keep class B as final so that no one else can extend it in another module. Not entirely. Let's use code to explain. We have: module pack.foo; sealed class A {} class B : A {} // Legal final class C : A {} // Legal sealed(pack) class D {} class E : D {} === module pack.bar; class F : A {} // Illegal, A is sealed class B1 : B {} // Legal, B is not sealed - A is class C1 : C {} // Illegal of course, as C is final class D1 : D {} // OK, D is package-sealed class E1 : E {} // OK, E is neither sealed nor final === module anotherpack.baz; class G : A {} // Illegal, A is sealed class B2 : B {} // Legal, B is not sealed class C2 : C {} // Illegal, C is final class D2 : D {} // Illegal, D is package-sealed for pack class E2 : E {} // Legal, E is neither sealed nor final In general: sealed means a special case of neither private, protected nor final and it probably could not be achieved with a combination of these two. Sealed does not mean private, as access to the class is not restricted in any way. It is also not transitive - class extending a sealed class can be extended freely unless they are sealed as well or final. Given those classes: sealed class Pet {} class Cat : Pet {} class Dog : Pet {} we can implement a different types of Cats and Dogs - but creating a Ferret or Parrot is illegal. So it may be used to limit one level of inheritance, but retain the freedom to extend the few defined types. Making the base class private would not be OK, as we don't want to restrict the access to that class.
Sealed classes - would you want them in D?
Hello, I've recently thought of sealed classes (sealed as in Scala, not as in C#) and am thinking of writing a DIP for it. I decided to start this thread first though to gather some opinions on the topic. For those who never coded Scala and don't know sealed classes: a sealed class is a class which can be only extended in the same source file. sealed class MyClass {} Translating to D, a sealed class would could only be extended in the same module. Additionally I would suggest "sealed(some.package) MyClass {}" syntax for classes that could only be extended in the particular package. In Scala an important value of sealed classes is that compiler knows that and can aid programmer in pattern matching by detecting the missed cases. However, there is another value I see: limiting the extension of classes. Some time ago I was working on a simple CQRS library and created an Entity class, where I wanted only a few specific subtypes for it. The library is built over a few defined entity types and user is not able to create their own types (should extend the particular subtype instead). Sealing the Entity class could enable me to define the closed set of subtypes and prevent new direct subtype creation outside the library. Combining sealed with final library developer can create a completely closed type hierarchy. Any thoughts on that proposal?
Package method is not virtual and cannot override - a bug or a feature?
Given this code: abstract class A { package @property void x(int x); package @property int x(); } class B : A { package @property override void x(int x) {} package @property override int x() { return 0; } } void main() {} I get the following message: onlineapp.d(9): Error: function `onlineapp.B.x` package method is not virtual and cannot override onlineapp.d(10): Error: function `onlineapp.B.x` package method is not virtual and cannot override Why is that? If the access specifier is private, I can perfectly understand it - subclasses can't call the private method of parent class, so there's no need in making it virtual. For protected/public the code compiles. However, for the package protection it may happen that a subclass is in the same package (and just happened to me). Should I file a bug or is there a reason for such behavior?
Slide - what does withPartial do?
For some reason this is true: slide!(Yes.withPartial)([1, 2, 3, 4, 5], 3).array == [[1, 2, 3], [2, 3, 4], [3, 4, 5]] Shouldn't it rather return [[1], [1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5], [5]], or at least [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5], [5]]? I can see no difference on the result when withPartial is on and off. Is it a bug or I don't understand it correctly?
getSymbolsByUDA does not take private symbols under consideration. Should I file a bug?
Hello, The code below: import std.traits; enum Attr; class MyClass { private @Attr int a; static assert(getSymbolsByUDA!(typeof(this), MyClass).length == 1); } does not compile as static assertion fails. Making the filed a public makes it compile properly. Should I file a bug or is by design?
Suggestion: needleless findSplit* methods
Hello, I'd like to make a little suggestion for phobos: enrich findSplit* method family with the "needleless" predicate option. Motivation: Let's have a range of string tokens that - after cutting of the initial brace - looks like this: auto range = ["23", "42", "14.3", "-323", "}"] Now I want to map all the numbers to the array: auto array = range.findSplitBefore(x => !x.isNumeric).map(to!double).array; As you can see, I do not need the second parameter of prediate, as I am not comparing the subsequent haystack elements with any needle - I check the condition on the haystack elements alone instead. Unfortunately, It's not that simple, because I have only this prototype: auto findSplitBefore(alias pred, R1, R2)(R1 haystack, R2 needle) //[...] That's why I need to add a dummy parameter to achieve what I want to: auto array = range.findSplitBefore(x => !x.isNumeric)([""]).map(to!double).array; So I suggest adding this prototype as well for convenience: auto findSplitBefore(alias pred, R)(R haystack) //[...]
One path skips constructor - is this a bug?
Code: === import std.conv; import std.regex; struct A { int field1; int field2; this(int field1, int field2) { if(field1 > field2) throw new Exception("This is illegal!"); } this(string str) { if(str.match(ctRegex!(`^[0-9]{4}-[0-9]{2}`))) this(str[0..4].to!int, str[5..7].to!int); else throw new Exception("Invalid string"); } } void main() { A(2004, 43); A("2004-43"); } === This throws a compilation error: main.d(17): Error: one path skips constructor main.d(15): Error: return without calling constructor Why do I need the constructor call, if I throw the exception anyway? Is this a bug?
Base class' constructor is not implicitly inherited for immutable classes. A bug or a feature?
Hello, I have this code: immutable class Base { this() {} } immutable class Derived : Base {} void main() { new immutable Derived(); } I'd like class Derived to automatically inherit the default constructor from Base. However, this is not the case: main.d(6): Error: class main.Derived cannot implicitly generate a default ctor when base class main.Base is missing a default ctor Is it a bug or it should be like this?
Re: Snap packages for DMD and DUB
On Monday, 8 May 2017 at 20:05:01 UTC, Joseph Rushton Wakeling wrote: Hello all, As announced at DConf 2017, snap packages are now available for DMD 2.074.0 and DUB 1.3.0 in the official snap store. These should allow for installation on multiple different Linux distros (see below) on i386 and amd64 systems. [...] Hi, I got yet another error - this time Ubuntu 16.04 and rdmd. Failed to flush stdout: Permission denied Failed: ["dmd", "-v", "-o-", "main.d", "-I."] It seems like (despite classic confinement) apps ran by rdmd cannot print things on the screen...
Re: Snap packages for DMD and DUB
On Monday, 8 May 2017 at 20:05:01 UTC, Joseph Rushton Wakeling wrote: Hello all, As announced at DConf 2017, snap packages are now available for DMD 2.074.0 and DUB 1.3.0 in the official snap store. These should allow for installation on multiple different Linux distros (see below) on i386 and amd64 systems. Hello, I have tried those snaps recently on Ubuntu 16.10. There were -fPIC related errors (if you need the output, I can install the snap again and post it tomarrow).