Re: Give DLS a try
For those who like Vim, I opened an issue for adding dls support to ALE. https://github.com/w0rp/ale/issues/1812 I might work on it myself some day, or someone else can set it up. ALE is a linter plugin for Vim I wrote, which is now the most popular one after Syntastic and offers some language server support. It should be possible to set it up so ALE will find and run `dls` automatically.
Re: DIP 1017--Add Bottom Type--Community Review Round 1
On Thursday, 9 August 2018 at 10:37:36 UTC, Andrea Fontana wrote: On Thursday, 9 August 2018 at 04:10:47 UTC, Nicholas Wilson wrote: The DIP makes the claim that: * "[@noreturn] has the awkward result of a function specifying it has a return type T, but never returns that type". When it is deliberate (such as annotating a fatal error function) the is almost exclusively `void` (I know of no examples to the contrary). Let's say we need to implement an interface with a int func(); member. We can mark it with @noreturn but we can't use TBottom return type: we're going to break interface implementation. Andrea It will work, and why it will work requires some understanding of bottom types. You can define the function as `TBottom func()` and it should work, because `TBottom` is a subtype of `int`. In the same way you can implement `ParentClass func()` as `SubClass func()`, because `SubClass` is a subtype of `ParentClass`. Similarly, you can assign values of `TBottom` to `int`, because `TBottom` is a subtype of all types, but you cannot assign `int` to `TBottom`, because `int` is not a subtype of `TBottom`.
Re: DIP 1017--Add Bottom Type--Community Review Round 1
A better name for this type is `never`, which is the name of the TypeScript type with similar semantics. https://www.typescriptlang.org/docs/handbook/basic-types.html#never `nothing` is also a decent name, used in some other languages, but `never` makes it more obvious that a function never returns, and isn't as easy to confuse with `void`, which is a different kind of nothing.
Things I found great about TypeScript that D could benefit from
Hello everyone! I haven't written a post in a long time. I love D, and I've been a D hobbyist for years now. Though I haven't written any D in a long time, I keep an eye on the changelogs and such. More recently I've been using TypeScript (TS) at work for front end code. TypeScript is a very different kind of beast, compared to D, but there are some features in TypeScript I now use every working day which have really improved the quality of the software that I write, and I'd like to share my thoughts on them. I'll explain a few things and then say what I think D could learn from TS. The first feature I found really useful is the --strictNullChecks option that TypeScript has. I hate null dereferencing errors with a passion, and they have been the number one source of bugs that I've seen. The TS type system with the option off effectively treats `T` as `T | null | undefined` with the option off, and excludes `null | undefined` with the option on, meaning it forces you to check for `null` or `undefined` where such values are possible, according to the type system. What I found really interesting is that TS implements null checking not through more traditional means like a "Maybe" or "Option" monad, but through typical syntax. If you write `if (x != null) { }`, then TS narrows the type from `T | null | undefined` to just `T` inside of that if statement. This also works for more complex syntax, such as breaking a loop, returning early if something is null and pressing on if it isn't, inside expressions like `x != null && x.y`, and so on. I could never get colleagues on board with changing all of their code to use Maybe/Option types, but this kind of syntax is something they don't even have to think about. The second feature I found very useful is that TS uses "structural typing." You declare an interface with some properties, and any object which matches those properties is considered to be of that type. Meaning that TS doesn't care what the "class" or prototype of your object is, just that has the right stuff in it. This is essentially statically-checked duck typing. There is some algebra on types, so you can write `T & U` for something with the properties of types `T` and `U`, or `T | U` for either. What's very powerful about unions in TypeScript is that it automatically determines which fields can be used as tag attributes for tagged unions. This means you can declare tagged unions without thinking about writing a very specific tagged union type, and without using a special tagged union type. This largely works because of the nature of TS's basis on top of a dynamic type system where attribute lookup is all virtual. The third big feature I'll end on is just the quality of the tooling. There's great code completion, tools for fixing bugs, pretty good diagnostics, a protocol like LSP I integrated into Vim, etc. They have done a pretty good job of getting the tools right. What I think D could learn is pretty much... * Strict null checking is a winner, and you can use ordinary syntax to handle this. * Writing `(InputRange r)` instead of `(T)(T r) if (isInputRange!T)` would be a nice improvement, and writing something like this hypothetical `InputRange` concept could be a lot easier, somehow. (C++20 might finally include concepts.) * Good tooling makes everything better. Keep on working on good tools for D. That's it, let me know your thoughts.
Re: Maybe D is right about GC after all !
On Tuesday, 19 December 2017 at 09:54:05 UTC, Walter Bright wrote: "C, Python, Go, and the Generalized Greenspun Law" http://esr.ibiblio.org/?p=7804 I think D and the GC are highly appropriate for developing high performance application software. That's where D really shines. It's a shame that Qt is such a nightmare to use in anything that isn't C++. GTK is easy enough to use at least. What's funny is that both frameworks implement their own memory management schemes. That points to a need for automatic memory management.
Re: Project Elvis
One man's valid value is another man's invalid value. You can't test for a general concept of "invalid," as you need context. You can test for "falsy" with no context.
Re: Required Reading: "How Non-Member Functions Improve Encapsulation"
I've noticed the benefits of writing non member functions in Python codebases. Say if you have a User model in a Django ORM, and you have a Thing model, and some operation on User and Thing. I've noticed that your code is almost always better if you write a non member function on User and Thing, instead of a member of User or Thing. Often a function belongs to neither type. Instead the logic cuts across those two types. The key disadvantage I notice is ending up with very large and unreadable classes which poorly categorise business logic, when you could have been categorising functions in modules based on different business needs.
Re: is private broken?
https://wiki.dlang.org/Access_specifiers_and_visibility#private Private means that only members of the enclosing class can access the member, or members and functions in the same module as the enclosing class. You can access private attributes anywhere in the same module.
Re: all OS functions should be "nothrow @trusted @nogc"
Direct OS function calls should probably all be treated as unsafe, except for rare cases where the behaviour is very well defined in standards and in actual implementations to be safe. The way to get safe functions for OS functionality is to write wrapper functions in D which prohibit unsafe calls.
Re: proposed @noreturn attribute
I didn't look through all of the replies to this thread to check that this hasn't been mentioned yet, but TypeScript uses the 'never' return type for functions that never return. https://www.typescriptlang.org/docs/handbook/basic-types.html#never The type isn't used for any optimisations, it's only used for preventing you from adding lines of code after functions which never return. (Say if they run "forever" or throw exceptions.) I thought it would be worth mentioning how another language handles this currently.
Re: opEquals nothrow
On Thursday, 20 July 2017 at 15:10:24 UTC, Aldo wrote: On Thursday, 20 July 2017 at 14:59:50 UTC, Steven Schveighoffer wrote: On 7/20/17 10:38 AM, Aldo wrote: Hello, im tring to add nothrow keyword in my code, but compilation fails : function 'object.opEquals' is not nothrow its a simple comparison between 2 objects. How to make opEquals nothrow ? You can't. Object.opEquals is not nothrow, so object.opEquals is not nothrow (note the former is the virtual member function, the latter is a global function which is what the compiler actually calls). It is a legacy limitation. Until we get rid of all the Object base methods for things like opEquals and toHash, we will not be able to fix this. -Steve Im using DerelictGLFW3, to process events im doing this : glfwSetMouseButtonCallback(window, ); onMouseClick function must be nothrow. But now I can't do anything in this function because I can't convert my code to nothrow. Can I put a try catch in the body ? extern(C) nothrow { void onMouseClick(GLFWwindow* window, int button, int action, int d) { try { // my code } catch { } } } it seems its working but what about performances ? thanks You could also try assumeWontThrow. https://dlang.org/library/std/exception/assume_wont_throw.html
null analysis with control flow
null references. We hate them, they make our programs exit in circumstances we didn't anticipate. Tony Hoare called them a "billion dollar mistake." I've spoken about this issue in this forum before, others have, we know this issue well. TypeScript 2 and Swift, and some Java IDEs, implement a way of handling null references quite elegantly. I think we can learn from this. https://blogs.msdn.microsoft.com/typescript/2016/07/11/announcing-typescript-2-0-beta/ The method of handling null in functional programming languages is to represent possibly null types with an Option monad. Accessing the references to the real values within usually requires applying pattern matching, or by calling different functions on Option/Maybe types for checking the references to see if they are null and getting them out again. Other opinions may differ than this, but I think this method of handling the problem creates two issues. 1. Most languages (including D) do not support pattern matching. If pattern matching was added, it would be totally alien to any programmers coming from C, Java, JavaScript, Python, etc. This means this method of handling null might not be adopted. 2. Changing the access patterns when a type might possibly be null can confuse developers, and decreases the likelihood of adoption to fix what is a really essential issue in modern programming languages. I believe the solution presented in TypeScript, in Swift (if you can find it in the documentation at all), and somewhat in some Java IDEs is much better, and much more familiar to most programmers. I'll explain by using T? to refer to possibly null types, and T for types which are not nullable. As described above in the TypeScript blog, when you are handling a possibly null reference, assuming strict checking is turned on, you are forbidden from accessing any attributes or methods from that reference unless you first ensure that the reference is not null. To do this, you write an ordinary if statement or other Boolean expression. Within the confines of the area where you have checked for a null reference, if you say that the type is T?, the compiler knows that the type *must* be equivalent to T, as you have checked that the reference is not null. Assignment of null to a type T is forbidden. Assignment to a type T? forms a fence, which would imply an atomic fence. When a type T is assigned to a variable of type T?, then after that line of code, the value can be considered to be of type T. When a type T? is re-assigned to a variable value, then the null safety checks will be applied again, and either another assignment expression or condition must be used before access is made. In the case of TypeScript, you can also enforce access which might possibly crash your program if you really want to with x!.foo. (I personally wouldn't recommend ever doing this, but there might be some reason why it is needed.) I say we could consider adopting such a method of handling null references in D. We could liberally assume for a time that any type T is non-nulllable, and apply checks only for T?, until we can change to some future version of D where T can never be null. What does everyone think? Shall I write a DIP for this? Does everyone hate this idea and want to start hiring the hitmen to shoot me dead now? As Andrei says, "Destroy!"
Re: Lint D code while you type in Vim
On Saturday, 17 September 2016 at 04:57:03 UTC, Basile B. wrote: You should use Dscanner to do this, not DMD. DScanner does not (or few) semantic, so just the module AST is necessary. It's way faster. I know this because I was doing something similar to build the symbol list in Coedit 1 (using "-c -o- -Xf"). Finally a custom tool based on libdparse (and somehow doing one of the Dscanner job) was much faster. Also "dub describe" can be very slow. I just pushed a commit now which runs DUB in the Bash wrapper script as well, so it will never cause any input lag. I want to run DMD on D source files so I can get semantic analysis in Vim. That lets me know when a function call I am making is wrong, etc. Because the jobs run asynchronously, it doesn't matter if the job takes a few seconds to run. You will see the errors eventually without the process interrupting your editing of a particular file. I plan to add a DScanner linter command too, and I'll be adding a configuration variable for selecting particular linters, so you can only use DScanner if you only want that, or use both DScanner and DMD. I realised that I could easily get Windows support too by switching from using Bash to D for the wrapper script, and I could use maybe RDMD to compile and run the wrapper script. I'll do that eventually.
Lint D code while you type in Vim
I have been working on a plugin for Vim 8 and NeoVim which runs linters while you type in Vim, which is an improvement over the plugins for Vim so far which can only lint after you save a file back to disk. So far my plugin seems to work pretty well, and I have been using it for my job, mainly for Python and JavaScript code. https://github.com/w0rp/ale I'll note again, you need either NeoVim or Vim 8 to use this plugin, as it uses the new job control functionality for asynchronous execution in either editor. I'm pleased to announce I just managed to push some support for linting with DMD and some extra DUB support which actually works, with some caveats. It will try and find the DUB project directory, and use `dub describe --import-paths` to get the import paths automatically so it knows about the types imported into your files, which I helped add to DUB for this explicit purpose a while ago. (So it's probably in the version of DUB you are using now.) The caveats are that I haven't tested this that much, so there could be some bugs I don't know about, and that this won't work in Windows at the moment. In order to lint while you type, you must pass the contents of the file you are editing via stdin to a particular program. DMD doesn't accept source files via stdin, so I had to write a Bash wrapper script saved in the plugin directory which will do that for me. If anyone is running NeoVim or Vim 8, give it a go. Let me know what you think. Hopefully someone will find this useful. I've been dealing with some RSI issues recently, so I won't put too much work into this for the immediate future, but I'll work on this some more when my wrists heal up a bit just because I want to use it personally. For maintainers of DMD, I would love it if an option to read source files via stdin could be added. It could be something like -stdin. Then it would be very easy to use DMD to check source files from stdin input. It might also be an idea to add a second option for suggesting what the filename of the stdin input should be, in case that matters. I know eslint has such an option, and it could matter in some cases.
Re: Usability of D for Visually Impaired Users
On Sunday, 4 September 2016 at 20:01:21 UTC, Walter Bright wrote: https://news.ycombinator.com/item?id=12424656 It is our ethical duty to make D and dlang.org usable for visually impaired programmers. If any of you are visually impaired, or have programmer friends/colleagues who are, a review of what we can do to improve would be appreciated. A noble goal. The trick is probably all in careful use of markup. alt tags, aria text, tab ordering. You can probably test various pages on the site by listening to the output of screen readers.
Re: if-expressions
On Friday, 26 August 2016 at 18:25:00 UTC, Cauterite wrote: Here's a little patch you guys might enjoy: https://github.com/dlang/dmd/compare/master...Cauterite:ifExpr0 It enables this syntax: int foo = if(asdf: 5 else 6); equivalent to int foo = asdf ? 5 : 6; Here's some other examples which work: // any number of condition/predicate pairs foo = if( asdf : 5, doZxcv(bar) : 90 else 6 ); // redundant commas and colons permitted foo = if( a : 5, b : 90, else : 6, ); // roughly equivalent to // foo = asdf ? 5 : doZxcv(bar) ? 90 : assert(0); foo = if( asdf : 5, doZxcv(bar) : 90 ); Also it doesn't conflict with if-statement syntax, as far as I'm aware. Just a little experiment to learn my way around the parser. I don't think this particular syntax is desirable. We already have ternary expressions, and anything more complicated than a regular ternary should probably be written with a regular series of if statements. Having said that, it is good that you're trying to figure out how the compiler works. Keep doing that! You might be able to open a pull request for something else which is really valuable if you keep tinkering.
Re: The case for small diffs in Pull Requests
On Monday, 18 July 2016 at 22:30:56 UTC, Walter Bright wrote: https://medium.com/@kurtisnusbaum/large-diffs-are-hurting-your-ability-to-ship-e0b2b41e8acf#.h3eo1yvqv I've been advocating for a while now that PRs should be small, incremental, encapsulated and focused. This has not been without controversy. I hope the referenced article is a bit more eloquent and convincing than I have been. In my experience, the number of commits in a pull request is irrelevant. You can always merge the entire pull request with `git merge --squash` instead, and if you have the luxury of merging via GitHub as I do in my day job, you can even do that via GitHub now. What is definitely relevant is the lines of code. Once a pull request becomes too large, the probability that it will be merged decreases. At least that has been my experience. I agree that incremental changes are much more likely too succeed than large comprehensive changes. However, exceptions do have to be made, because there are some tasks which just cannot be completely incrementally, though they may be rare. Just my two cents.
Re: Our docs should be more beautiful
I like this kind of discussion. It's good to make the website look as attractive and functional as we can make it. I think we just need to remember to file each issue individually, then group all of the issues to track all of them. Then each individual issue can be tackled, and some work can get done while the rest of the issues are discussed. Maybe I'm just speaking common sense or something, but I think it's worth mentioning.
Re: QtE5 - is a wrapping of Qt-5 for D
On Monday, 20 June 2016 at 16:52:04 UTC, MGW wrote: This my library has about 400 functions from Qt and is quite efficient for small applications. https://github.com/MGWL/QtE5 Small video about QtE5 and id5 written on its basis - an example of use. QtE5 on Mac OSX https://www.youtube.com/watch?v=JBA4vkT5uKE This is very nice! I would love to know how you managed to get it working. I had trouble with signals and slots, the class hierarchy, and numerous other things when I was trying to get Qt4 to work in D. How did you handle the Qt class constructors and destructors, etc.?
Re: [OT] Things I like about Andrei
I've learned in software development that you hardly ever hear praise from others. Usually you only hear from others when you make mistakes. Such is life. Andrei is a pretty cool guy, and I'm totally pro Andrei. I'm thankful for the years of dedication and the development of a pretty wonderful language thus far.
Re: Why I won't fix phobos bugs anymore
I think a healthy option might be to find one or more professionals Andrei can respect and trust to delegate the work of approving pull requests and such to. As always with open source contributions, it's largely up to someone stepping up to the game. Then maybe bug fixes can be approved at a greater speed.
Re: [OT] A Rust tool for Cross-compilation
On Sunday, 15 May 2016 at 15:31:56 UTC, Joakim wrote: On Sunday, 15 May 2016 at 07:46:05 UTC, Adil wrote: Found this on Reddit. http://blog.rust-lang.org/2016/05/13/rustup.html Do you think it's possible to have this in D? It's worth reading the article even if we don't plan to build one of our own. Of course it's possible, shouldn't be too bad, whether it'll ever get done is another matter. There is dvm, but it's only for dmd right now: https://github.com/jacob-carlborg/dvm I'd love to have a tool for this which used either GCC or LLVM. I tried compiling for arm-none-eabi a while ago, and you could get it working, but it was a bit of a pain getting all of the right tools in place for it. I'd love to be able to juts type a command and have it all just work. I'd really love to have something which generated a DUB config which would cross compile.
Re: Github names & avatars
I stick with my pseudonym. I don't go to great lengths to protect my identity. You could probably figure out my name and address if you really wanted to. The concern isn't so much the government, but other individuals doing harm to you. We live in a world which is very politically correct, and on the other hand there are a lot of people who are just mean. You're much safer if you make a point not to give out too much personal information in public spaces. Brendan Eich is probably the best example I know of where someone lost their job for not having the right opinions.
Re: A Recurring Question
On Monday, 18 April 2016 at 20:24:40 UTC, Jesse Phillips wrote: On Sunday, 17 April 2016 at 15:23:50 UTC, w0rp wrote: void main() { // Print all directories from this one up to and including /. getcwd() .unaryRecurrence!dirName .until("/", OpenRight.no) .each!writeln; } FYI, OS independent version: void main() { // Print all directories from this one up to and including /. getcwd() .unaryRecurrence!dirName .until(rootName(getcwd()), OpenRight.no) .each!writeln; } Probably should also make a call to absolutePath. Nice!
Re: A Recurring Question
On Monday, 18 April 2016 at 12:02:24 UTC, thedeemon wrote: On Sunday, 17 April 2016 at 15:23:50 UTC, w0rp wrote: auto unaryRecurrence(alias func, T)(T initialValue) { return recurrence!((values, index) => func(values[0]))(initialValue); } This is kind of neat. My question is, should something like this function be included in std.range? Either way, it turned into an example of something cool you can do with D. It really looks like "iterate" combinator from Haskell's standard library: iterate :: (a -> a) -> a -> [a] Source iterate f x returns an infinite list of repeated applications of f to x: iterate f x == [x, f x, f (f x), ...] http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:iterate (which could be a hint to stdlib-includability and naming) If it's good enough for Haskell, maybe it's good enough for us. "iterate" does sound like a decent name.
A Recurring Question
I recently found myself wanting an algorithm to apply f(x) repeatedly, generating an infinite sequence, for a variety of reasons. One of those reasons is to generate ancestor directories. Typically when I desire such a thing, I find myself trying to find the existing algorithm which does this already. I eventually realised that recurrence is exactly what I need, if I just simplify it a little for this case. import std.range; import std.algorithm; import std.path; import std.file; import std.stdio; auto unaryRecurrence(alias func, T)(T initialValue) { return recurrence!((values, index) => func(values[0]))(initialValue); } void main() { // Print all directories from this one up to and including /. getcwd() .unaryRecurrence!dirName .until("/", OpenRight.no) .each!writeln; } This is kind of neat. My question is, should something like this function be included in std.range? Either way, it turned into an example of something cool you can do with D. While I was at it, I noticed that we could also consider a second form of recurrence which permits functions which accept a single argument, with only the Cycle. In that case, the range behind the recurrence could be potentially optimised to only hold the values, and forget about the index. It wouldn't be too far off from how foreach works. Then my function above would have had this lambda instead: x => func(x[0])
Re: So what does (inout int = 0) do?
On Friday, 15 April 2016 at 07:33:42 UTC, w0rp wrote: I think it has something to do with making the function, in this case a lambda, inout, so that it can accept inout types. Then the typeof bit is a weird way to writing something like __traits(compiles, ...) , because functions which have no type result in void, and that fails the typeof check. If we do end up replacing inout with something else, I would like something which solves the problem of declaring functions returning ranges of either mutable, const, or immutable. I've struggled with that before: https://github.com/w0rp/dstruct/blob/master/source/dstruct/graph.d#L628 To clarify my example. My problem was that I had a container which was immutable, and I wanted a range over the immutable elements, where the range itself is of course mutable. Getting that to work was a tad tricky. You can't take an inout() container and return an inout() range, because then an immutable container will produce an immutable range, which isn't useful. I don't think you can return a mutable range containing inout() elements either.
Re: So what does (inout int = 0) do?
I think it has something to do with making the function, in this case a lambda, inout, so that it can accept inout types. Then the typeof bit is a weird way to writing something like __traits(compiles, ...) , because functions which have no type result in void, and that fails the typeof check. If we do end up replacing inout with something else, I would like something which solves the problem of declaring functions returning ranges of either mutable, const, or immutable. I've struggled with that before: https://github.com/w0rp/dstruct/blob/master/source/dstruct/graph.d#L628
Re: Is it me, or the search doesn't work?
On Thursday, 14 April 2016 at 20:55:24 UTC, Vladimir Panteleev wrote: On Thursday, 14 April 2016 at 20:31:11 UTC, Andrei Alexandrescu wrote: What is happening there? Looking at the code, it appears to be "by design". Pressing the Enter key is simply not handled, instead it seems that you are expected to type a search term, then click with your mouse on one of the completion suggestions. From what I can see, there is an input field with name="q" which is hidden and replaced instead with another input field with no name, which has the placeholder "API Search". When you press return, it submits the form with a blank value, because you aren't typing text into the input field for the search query, which is hidden. I don't know what's really intended there, but that's what's happening.
Re: Let's move to github.com/dlang !
On Thursday, 14 April 2016 at 21:59:33 UTC, Vladimir Panteleev wrote: Daniel Lang, the previous owner of the GitHub dlang username, has graciously donated us the namespace: http://forum.dlang.org/post/fmarvvsgthihozcil...@forum.dlang.org For the sake of shorter URLs, less typing, and consistent branding, let's move! Moving should be painless, and everything will redirect to the new location. We only have to make sure our GitHub API clients support HTTP redirects. Any change to anything breaks something, but I'm generally in favour of this.
Re: I want this so badly, please implement
On Wednesday, 13 April 2016 at 13:17:57 UTC, cym13 wrote: There's a world between exceptionnaly getting a user password in order to detect and solve a bug through an error message and knowingly logging every single user password, be it only on the legal side. In France for example you don't have the right to log most sensitive things. On the security side it's the same thing: the chances for an attacker to retrieve a password by server crashing are quite small, while getting his hands on the log file would be a goldmine. This problem is typically solved by providing a list of keys to either whitelist or blacklist for logging from POST requests, so sensitive data is excluded from logs, but other data is available so you can find out what went wrong. I don't think Adam's request to log the index of an array will be a security risk worth worrying about, however, not that you were indicating that. I think his request is quite reasonable, any odd implementation details permitting.
Re: Could we reserve void[T] for builtin set of T ?
Has no one mentioned void[0][T] yet? alias Set(T) = void[0][T]; void add(T)(ref void[0][T] set, T key) { set[key] = (void[0]).init; } bool contains(T)(inout(void[0][T]) set, T key) { return (key in set) !is null; } void main() { Set!int set; set.add(1); assert(set.contains(1)); set.remove(1); assert(!set.contains(1)); }
Re: Clojure vs. D in creating immutable lists that are almost the same.
On Saturday, 27 February 2016 at 22:31:28 UTC, Brother Bill wrote: Clojure supports immutable lists that allow adding and removing elements, and yet still have excellent performance. For D language, what are the recommended techniques to use functional programming, without massive copying of data and garbage collection, so that it remains immutable. That is, how to create one-off changes to an immutable data structure, while keeping the original immutable, as well as the one-off change, and maintain good performance. Thank you I think this is a property of linked lists which could possibly be advantageous. However, I would keep in mind that memory layout is very important when it comes to execution speed, and that slices of memory are unbeatable in that regard. That's worth stating first. I think for linked lists, you can always create a new node which points to another node. So you start with element a as immutable, then you take a head element b and point to a, so you get b : a, then c : b : a, etc. So you can create larger and large immutable linked lists because you never actually change a list, you just produce a new list with an element pointing the head of a previous list. I'm not sure if Phobos has something suitable for this, but you could always implement your own singly linked list in such a manner pretty easily. I would be tempted just to use slices instead, though. Linked lists are rarely better.
Re: Speed kills
I think it's important that DMD gets more of the easier optimisations. Most new users won't bother trying GDC or LDC, and if DMD doesn't generate fast enough code, they might leave before they try the compilers with better optimisations.
Re: C++ UFCS update
Personally, I find this proposal for C++ to be laughable. It's like hitch hiking from New York to California, and only getting as far as Texas and calling it good. The great thing about our UFCS is the left-to-right chaining of algorithms. x.map!(...).filter!(...).reduce!(...) It beats the Hell out of... reduce!(...)(filter!(...)(map!(...)(x))) This proposal will encourage non member functions, which is good, but will never reach the "aha" moment D had which gave us UFCS chaining.
Re: Head Const
I think the point about name mangling is very true. That's the most important thing, being able to call all of the C++ functions. I personally love that const and immutable are transitive in D. I get annoyed in other languages when I have const objects containing mutable objects, and no real protection from the compiler from stopping the objects in the inside from being mutated. The way I see it, C++ const is a weaker form of const which doesn't complain about mutations enough. I think if we could avoid putting head const in the language, we'd be better off. If you ever really, really need to mutate something inside a const type, you can cast away const. It will rightly look ugly, and the compiler can complain that it's not @safe.
Re: Weird issue with std.range.iota.length
Maybe I'm missing something, but can't the length just be size_t? I doubt there is much you could do with code which generates finite sequences larger than the addressable memory space, aside from very abstract and inefficient mathematical calculations which skip over elements. iota would probably work better with size_t in most cases, and if you really well and truly need something which generates finite sequences of integers larger than the addressable memory space, you can always just write your own version.
Re: OT: 'conduct unbecoming of a hacker'
His article is way too long. It seems like an article about whining about how people whine too much.
Re: Just because it's a slow Thursday on this forum
I wonder if the addition of another function for printing will confuse some new users.
Re: D's equivalent to C++'s std::move?
Back on the original topic, Scott Meyers often says "std::move doesn't move." It's more like std::rvalue_cast. C++ uses r-value references in order to be able to rip the guts out of objects and put them into other objects. D doesn't have a distinct r-value reference type, and postblit is part of the struct types. If you write simply T foo(); and you return some struct T, D already moves the struct out of the function without you having to define any move constructors. That kind of return value optimisation was the original motivation for r-value references, for when C++98 RVO isn't good enough, from my understanding. The only remaining time you need to avoid copies is when you take something already on the stack, and then put it into some other object, into some collection, etc. That's the other power that std::move affords you. The move functions in std.algorithm should take care of that. Maybe someone else will correct me on a point or two there, but that's the understanding of move semantics in D that I have had.
Re: Just because it's a slow Thursday on this forum
On Wednesday, 10 February 2016 at 19:30:26 UTC, Andrei Alexandrescu wrote: On 02/10/2016 01:51 PM, w0rp wrote: I wonder if the addition of another function for printing will confuse some new users. In my experience: * two names for the same exact thing => annoyance (not only in D, e.g. dual use of "class" and "typename" in C++) * two different names that do the same thing in slightly different without a distinction, interchangeable ways => confusion and annoyance (e.g. "class" vs "struct" in C++) * two names that do the same thing, one poorly and one better => confusion (e.g. "stringstream" vs. "strstream", vector vs vector_bool in C++) * two names that do two similar, but distinct things => "oh ok" (e.g. "map" vs. "multimap"). So I think we're safe. Andrei Yeah, that makes sense. Fair enough.
Re: Safe cast of arrays
Yeah, I think it should only allow the equivalent of a dynamic_cast for types in @safe code, and not allow the equivalent of a reinterpret_cast, for T, T*, or T[].
Re: Safe cast of arrays
On Tuesday, 9 February 2016 at 21:20:53 UTC, Iakh wrote: https://dlang.org/spec/function.html#function-safety Current definition of safety doesn't mention cast of arrays. E.g this code allowed by DMD int[] f(void[] a) @safe pure { return cast(int[])a; } But same void* to int* cast is forbidden. So we need some rules for dynamic arrays casting. e.g allow only cast(void[]) as for pointers was done. And definition of safety should be changed. I think this should be addressed, as if you can't cast between pointer types, you shouldn't be allowed to cast between slice types either. Because slices are just a pointer plus a length. Another way to demonstrate the problem is like this. @safe int* badCast(long[] slice) { return (cast(int[]) slice).ptr; } @system void main(string[] argv) { auto larger = new long[5]; auto smaller = badCast(larger); } This is a complete program which will compile and run with the latest official release of DMD. The pointer slicing is unsafe, but once the slice is available, it can go off into @safe land, and could lead to memory corruption, due to the bad cast. I used .ptr here to show you can safely take the pointer of a badly casted slice, which seems to somewhat contradict the rule that no pointer casting is allowed. Maybe some exception is needed for casting slices of class types. That's about the only thing I can think of.
Re: Why do some attributes start with '@' while others done't?
I think we bicker and pontificate about these kinds of issues too much. Do we want @ for every attribute or not? If we haven't decided, we should decide. If we do want @ for everything, then create a pull request which does nothing but support @ for all current attributes, in addition to the attributes without @. Don't worry about "attribute sets" and other wild ideas for now. Just tackle that one issue, otherwise no progress will be made. Attributes without @ can become deprecation warnings, and can be removed later. If you worry about the compiler becoming too complicated, I can assure you it will barely have an impact on compilation speed, and that's all users will care about. If we don't want @ for everything, then propose something else. Sorry to be curt, but we've talked about this for long enough and gotten nowhere.
Re: Regex in ctfe?
Unless I'm mistaken, I think the compiler for regex currently works at compile time, but not the matcher. Maybe someone who knows the module could add support for that.
Re: What are the real advantages that D offers in multithreading?
The most important thing D does, which is fundamentally different, is that variables are thread local by default, and you must opt-in to variables that are shared across threads. Immutable data can be shared implicitly, because there are no writers. This means that if you keep only a small amount of shared state, it should be easy to track down what could possibly be affected by multi-threading issues. I haven't ever used synchronized classes myself, but it's probably a way of preventing mistakes where you synchronize some methods, but not others. You can also use synchronized {} blocks to introduce some recursive locking for a series of statements. So you could put that inside of a class method.
Re: forum.dlang.org is now available via HTTPS
This is pretty cool. We should maybe see if we can add it to the "HTTPS Everywhere" plugin. Does anyone else use that? I've always found it so hard to just add a new domain to its rule list.
Re: Struct initialization using member syntax without variable
Maybe there is some parsing difficulty, but if it's possible to add something like this, I think it would be nice.
Re: [dlang.org] new forum design - preview
I love this redesign. Anyone who complains about not taking up the full width of the screen is wrong. If lines stretch on eternally, they become harder to scan with your eyes. It's a well known effect which has been studied and documented. There is some difference of opinion on what the maximum should be, but the hard limit seems to be 110 CPL. 80 CPL or 90 CPL are commonly used. You have to stop expanding elements at some point.
Re: DIP86: Consistency for the "deprecated" attribute/storage class
On Thursday, 14 January 2016 at 02:54:01 UTC, Jack Stouffer wrote: On Thursday, 14 January 2016 at 02:31:38 UTC, Brian Schott wrote: http://wiki.dlang.org/DIP86 Your thoughts? I guess there's no reason not to, so LGTM. The use of the deprecated attribute on variables seems misguided in the first place though. I don't see much use for it vs possible use on functions, structs, classes, and modules other than with global variables. The number 10 is now deprecated. Please use 11 instead, which is 1 better.
Re: Proposal: Database Engine for D
I've played with the idea of using operator overloading for some kind of ORM before, but I don't think it's strictly necessary to use operator overloading for an ORM at all. Maybe in some cases it might make sense. I don't think the answer for building such a thing is to think of one idea, find out it won't work out well, and then give up. You have to be more creative than that.
Re: "Good PR" mechanical check
I think using dfmt for this is a good idea. If there any problems with dfmt which would prevent it from being used on Phobos, the problems can be patched and then that would strengthen dfmt.
Re: C++ std::string, std::vector and name mangling
Thank you for your work on this. Hopefully someone else knows enough about name mangling and is willing to do some work on it.
Re: Advent of Code
Thanks for suggesting this. This is fun! Although, I've taken on quite a different challenge myself. I'm computing all of the answers only by using my console in Firefox. I'm actually getting through these pretty quickly. (It helps to know some ES5 and ES6.) I can imagine the D code already, and they are actually pretty similar to the JavaScript I've been writing.
Easy and efficient database usage
I keep finding myself thinking about what an API in D for easy and efficient database usage would look like. I started thinking about how ORM is done in libraries in other languages, and started to become obsessed with the notion that perhaps there should be a library for D which is roughly as convenient to use as an ORM, but tends towards greater efficiency, in particular for encouraging more efficient queries through the API, and for cutting down on the number of allocations done. Has anyone had any thoughts on this so far? I work with Django in my day-to-day work, but I have often thought that it would be nice to have something for easy database access for D web server backends. So you can write low to medium scale web applications in some dynamic language, and high performance backends in D for large scale web projects. Django provides a variety of nice features for working with databases, and I wonder how they would be represented in D. Does anyone have any thoughts on this topic?
Re: Behavior of opEquals
On Wednesday, 2 September 2015 at 18:57:11 UTC, Jacob Carlborg wrote: I encountered a problem in the implementation of std.xml.Document.opEquals (yes, I've reported an issue). The problem is demonstrated with this example: class Base { int a; override bool opEquals (Object o) { if (auto base = cast(Base) o) return base.a == a; else return false; } } class Foo : Base { int b; override bool opEquals (Object o) { if (auto foo = cast(Foo) o) return super == cast(Base) foo && foo.b == b; else return false; } } void main() { auto f1 = new Foo; auto f2 = new Foo; assert(f1 == f2); } This code will result in an infinite recursion. I think the problem is in the super call, due to == being rewritten to call object.opEquals. The implementation of object.opEquals will call opEquals on the actual instances. The call will be dynamically resolved and end up calling Foo.opEquals instead of Base.opEquals. Is this really good behavior, something a developer would expect? I mean, in every other case calling super.someMethod will actually call the method in the base class. In this case the solution/workaround is to explicitly call super.opEquals, but that will miss some optimizations implemented in object.opEquals. Yeah, I would just call super.opEquals, like so. class Base { int a; override bool opEquals(Object o) { if (auto other = cast(Base) o) return a == other.a; return false; } } class Foo : Base { int b; override bool opEquals(Object o) { if (!super.opEquals(o)) return false; if (auto other = cast(Foo) o) return b == other.b; return false; } } void main() { auto f1 = new Foo; auto f2 = new Foo; assert(f1 == f2); } If some optimisations are missed by structuring the methods in this way, then maybe that's something the compiler should be programmed to handle.
Re: Moving forward with work on the D language and foundation
I'm a bit late to reply to this announcement, but I would like to say that I am quite surprised by it. I really respect your decision to leave what must have been a very lucrative job to double down on D. I have loved D since I picked it up years ago, and TDPL was my first real introduction to the language. You have really done a lot to contribute to a great language, and you are one of the software professionals I most respect. I'm looking forward to seeing what you can accomplish as a full time D overlord in the future.
Re: Object.factory() and exe file size bloat
I think this is another case where Walter has got it right, by and large. I think we should try and use 'export' to cut down on binary bloat, and it looks like an acceptable solution. I have said many times, lock your versions down, and don't update your D compiler until you're ready to pay the cost of updating. There is always a cost involved, small or great.
Re: foreach with a default range
On Thursday, 11 June 2015 at 08:24:25 UTC, Dmitry Olshansky wrote: On 11-Jun-2015 11:18, w0rp wrote: A thought just came to me. When I'm implementing foreach for a container, I'm left with the choice of using a range for a container or opApply. I've found often that I prefer the ranges, as it's easy for me to write a range that satisfies @nogc @safe pure nothrow, etc. This is because the ranges don't call delegates which are less restrictive, which opApply does. I've been thinking about how you would implement opApply so that it could allow you to run @system code while the iteration itself is @safe, but then I had another idea. Could we allow foreach to look for a method (UFCS include) for producing a default range for an object, from a function named 'range'? In short this... foreach(elem; container) {} Could be transformed into this. foreach(elem; container.range()) {} Already works. Just define opSlice for container that returns a range and then: foreach(elem; container) {} is lowered to: foreach(elem; container[]) {} Ah! I did not know that. I shall use that in future.
foreach with a default range
A thought just came to me. When I'm implementing foreach for a container, I'm left with the choice of using a range for a container or opApply. I've found often that I prefer the ranges, as it's easy for me to write a range that satisfies @nogc @safe pure nothrow, etc. This is because the ranges don't call delegates which are less restrictive, which opApply does. I've been thinking about how you would implement opApply so that it could allow you to run @system code while the iteration itself is @safe, but then I had another idea. Could we allow foreach to look for a method (UFCS include) for producing a default range for an object, from a function named 'range'? In short this... foreach(elem; container) {} Could be transformed into this. foreach(elem; container.range()) {} This is not too different from how iteration works in Python, Java, etc. The objects are asked for an iterator, and the iterator is used to iterate through the object. This would allow you to implement ranges with more qualifiers set on them, without having to type .range() everywhere. What do others think?
Re: Right after allocators: containers or database connectivity?
Containers seems like the best thing to work on after the allocators. Then you could start using the allocators for the containers, so you can choose different allocation strategies for them. I'd definitely like to see a standard container for sets, instead of the void[0][T] thing I usually do.
Re: stream == range ? [Sliding window]
I wonder if we even need something like popFrontN. Whenever I have wanted to read chunks at a time, like some data from a TCP socket, I have always specified a buffer size and tried to get as much data as I can fit into my buffer for each iteration. You can accomplish this with a range of chunks of data, like byChunk for a file, and then operate on the chunks instead of individual bytes. If you are writing code where you just want to grab large chunks of data from a socket at a time, and you don't care about the rest of the code operating on characters, you can do this. someSocket.byChunk(bufferSize).joiner.doSomething; But then many ranges will already use an internal buffer, but present a range of bytes anyway.
Re: Chainable template mixin and opCat()
I think my only complaint for this is that it wouldn't work for all ranges, so you'd be able to use the operator some times, but not others. This is because you have to define the operators inside of the structs or classes, and you can't write operators as free functions. (Which is a good feature in general.)
Re: Why aren't you using D at work?
I'll add in my story. My job is working as part of a team on a small-to-medium scale web application. Our application layer is implemented in Python and Django. This would be the place where D would fit in the most. So I think this comes down to an argument of why we would choose to use Python and Django instead of D and vibe.d. I can think of the following reasons. 1. Obviously, we have already written everything in Python, so we would have to justify the cost of moving to D quite strongly. 2. Django offers more features useful for developing a web application than vibe.d, like an excellent API for building SQL queries with an ORM. The South or first party migrations (ALTER TABLE, etc.) APIs in 1.7 are brilliant, and after you use them, you can't live without them. These APIs work well and save time. 3. Python has greater mind share, so switching to D would incur the cost of training everyone to use D. It's hard enough finding a decent Python programmer. 4. The third party libraries implement many things we need to use, like SSO support. 5. We use Celery a lot for task management, so to use D we would need similar software D could work with. 6. I must mention that the execution model makes the sites easier to develop. When you change a function and save the file, Django reloads the module, (when it doesn't break) so you can test the effects of your modification instantly. I can't compare on testing web pages in Django against vibe.d, as I've never tried it on vibe.d. I will add that Django allows you to send fake HTTP requests to your 'views' for web pages, so you can write automated tests for the pages on your site. This level of testing does wonders for code quality, and catches website regressions quickly. I hope that in the future some clever person could implement an API for generating SQL queries in an RDBMS indepent way for D, with support for creating ALTER TABLE statements automatically. I've thought about it, and it wouldn't even necessarily need to be ORM, as something like the data mapper pattern could work. Just something which lets you build queries for objects you can serialise, and generate queries needed to update the tables for the objects when you change them.
Re: 0 is not a power of 2
I believe you can also do x -x == x. I'm not sure if that will be actually faster or slower. You could maybe cut the instructions down a little with an asm{} block. The compiler might not figure out that it can re-use a register for x on the left and x on the right there. You might use popcnt in a version() block too, so you can use the instruction when you've got it.
Re: Any plans to support STL value types?
JMD is right. Using inheritance for value types is a bad idea, and it shouldn't be done. The problem is that when you assign a derived value type to a base value type, the members in the derived type are removed, and this can lead to very weird behaviour. You could enforce that derived value types can never add any members, but then what would be the point? For adding virtual method calls for changing behaviour? Using inheritance for reference types only was one of the better design decisions for D. If you want to treat a set of structs in a similar way, you can do it better with parametric polymorphism than with classes and virtual method calls.
Re: 0 is not a power of 2
On Tuesday, 19 May 2015 at 12:00:30 UTC, Almighty Bob wrote: On Tuesday, 19 May 2015 at 10:59:53 UTC, w0rp wrote: I believe you can also do x -x == x. I think that still returns true for x = 0. You are right. Disregard that.
Re: [dlang website] Up Arrow in library
Back to top links are dumb. Navigating to the top of the page is something the client browser should handle. In Firefox, I use a plugin with a mouse gesture myself, so holding right click and moving my mouse up takes me back to the top of the page. Either that, or I press my home or end keys.
Re: Let's improve D's exceptions
I wonder if enforce should throw an Error instead, if it exists at all. Because it's designed to throw an exception you shouldn't catch. If you are going to have it throw an Exception subclass, then it should take the exception type, like enforce!WhateverException(...), or something.
Re: dmd -profile=gc
On Sunday, 3 May 2015 at 21:11:58 UTC, Walter Bright wrote: Just merged in is a new compiler switch that instruments generated code to collect statistics on memory allocation usage and generates a report upon program termination. (Much like how -profile works.) This was based on a prototype Andrei had written earlier. Andrei and I suspect it can be of great use in figuring out why a program may be excessively slow or consume excessive memory. I encourage giving it a try on some non-trivial project, and see if it gives useful information. Nice! I bet this can be used to improve Phobos in tandem with @nogc.
Re: std.xml2 (collecting features)
On Sunday, 3 May 2015 at 17:47:15 UTC, Joakim wrote: On Sunday, 3 May 2015 at 17:39:48 UTC, Robert burner Schadek wrote: std.xml has been considered not up to specs nearly 3 years now. Time to build a successor. I currently plan the following featues for it: - SAX and DOM parser - in-situ / slicing parsing when possible (forward range?) - compile time switch (CTS) for lazy attribute parsing - CTS for encoding (ubyte(ASCII), char(utf8), ... ) - CTS for input validating - performance Not much code yet, I'm currently building the performance test suite https://github.com/burner/std.xml2 Please post you feature requests, and please keep the posts DRY and on topic. My request: just skip it. XML is a horrible waste of space for a standard, better D doesn't support it well, anything to discourage it's use. I'd rather see you spend your time on something worthwhile. If data formats are your thing, you could help get Ludwig's JSON stuff in, or better yet, enable some nice binary data format. I agree that JSON is superior through-and-through, but legacy support matters, and XML is in many places. It's good to have a quality XML parsing library.
Re: GTA5 mods in D?
On Saturday, 2 May 2015 at 18:51:53 UTC, Israel wrote: I know you guys are programmers and not gamers but it thought maybe you want to experiment or help expand D? Currently there is a Script hook program that allows users to create mods/scripts for GTA5. http://www.dev-c.com/gtav/scripthookv/ Some people have made plugins for script hook to support other languages like Lua and .Net languages like C# and VB. https://www.gta5-mods.com/tools. If this sounds interesting, maybe someone can make a plugin for D. Im not even sure if or how it will work. I wont hide anything from you though. It might dissuade you from trying. This will require you to obtain a copy of the game, obviously to test it. However, the company Rockstar doesnt like people modding the game so if you plan on playing Multiplayer, you will probably get banned. Anyways, Thanks for looking. If it's a C API, you can use it from D. You just need to write the bindings to the library to use it with some extern(C) functions. If it's a C++ API, you can kind of sort of use it from D, mileage may vary. It's a shame Rockstar is banning modding. They must hate fun.
Re: Possible to write a classic fizzbuzz example using a UFCS chain?
On Tuesday, 28 April 2015 at 10:46:54 UTC, Gary Willoughby wrote: After reading the following thread: http://forum.dlang.org/thread/nczgumcdfystcjqyb...@forum.dlang.org I wondered if it was possible to write a classic fizzbuzz[1] example using a UFCS chain? I've tried and failed. [1]: http://en.wikipedia.org/wiki/Fizz_buzz You can do this. import std.range : iota; import std.algorithm : map, each; import std.typecons : Tuple, tuple; import std.stdio : writeln; Tuple!(size_t, string) fizzbuzz(size_t number) { if (number % 3 == 0) { if (number % 5 == 0) { return tuple(number, fizzbuzz); } else { return tuple(number, fizz); } } else if (number % 5 == 0) { return tuple(number, buzz); } return tuple(number, ); } void main(string[] argv) { iota(1, 101) .map!fizzbuzz .each!(x = writeln(x[0], : , x[1])); } The desired output may vary, depending on variations of FizzBuzz. (Some want the number always in the output, some don't.) You could maybe do crazy ternary expressions instead of writing a function, or put it directly in there as a lambda, but both just look ugly, and you might as well just write a function for it.
Re: ReQL: pluses and minuses of pipeline-style queries
On Saturday, 25 April 2015 at 05:16:21 UTC, Andrei Alexandrescu wrote: Found this on reddit a few days ago: http://rob.conery.io/2015/04/17/rethinkdb-2-0-is-amazing/ A good discussion of the pros and cons of pipeline-style queries (the ReQL query language reminiscent of D's algorithms/ranges) vs. classic SQL. Andrei One thing *kind of* related that I have really enjoyed is Django's querysets for building SQL queries. In Django, a QuerySet has methods query yields new QuerySet objects, so you can build a set of parameters and SQL is eventually generated and then executed to yield the results. andrei_queryset = ( People.objects .filter(first_name=Andrei, last_name__startswith=Al) .order_by(-affinity_for_template_metaprogramming) .select_related(organisation) [0:5] ) The above would, when evaluated, generate something like the following in order to build the objects with. SELECT p.*, o.* FROM people AS p INNER JOIN organisation AS o ON o.id = p.organisation_id WHERE first_name = Andrei AND last_name LIKE Al% ORDER BY affinity_for_template_metaprogramming DESC LIMIT 5; I've been trying to think of a way to create something similar in D, maybe for something like HiberateD.
Re: if(arr) now a warning
On Wednesday, 22 April 2015 at 10:36:04 UTC, Jonathan M Davis wrote: D arrays were designed in a way that they avoid segfaults; otherwise an empty array and a null array would not be considered equal, and doing stuff like trying to append to a null array would segfault. You have to work at it to get a segfault with D arrays. That doesn't mean that the optimizer does the best job (as evidenced by 14436), but D arrays are quite clearly designed in a manner that avoids segfaults and conflates null with empty as a result. - Jonathan M Davis This is one of my favourite features of D. I've seen so many problems in Java where someone passes null instead of an ArrayList to a method and it throws a NullPointerException. I love that I can just use foreach on a null slice, or check its length, and not care if it's null most of the time. (But still check if it's null if I really, really care.)
Re: WTF: dmd 2.066 vs. dmd 2.067 really dangerous code breakage
You really should pay attention to the deprecation messages. immutable was unfortunately used as if it was a manifest constant before, but it ought to be a member of a struct, and that behaviour is changing. There's been a deprecation message there for a while, now the behaviour is changing, and eventually you'll be able to create immutable members of structs without any warnings, as it will just use the new behaviour.
Re: I have made a discovery
The interesting thing about this is that 'throw new ExceptionType(...)' could be reference counted. The downside of not getting rid of the 'new' overloading at some point is that it can make the operator do surprising and unexpected things, so the rationale for getting rid of it is similar to the rationale behind disallowing overloading of '' and '||'. What I found more interesting is that class constructors themselves can be marked @nogc, which I never thought to do before. So whatever syntax we end up with for 'allocate with this other allocator and call this constructor' could take advantage of that. I'm not sure how that will end up looking in the end, but I am reminded of Objective C again, where allocation and construction are explicitly separated. // Enough time in Wonderland makes this seem perfectly natural. MyClass* foo = [[MyClass alloc] initWithNumber:3];
Re: I have made a discovery
I *think* my PR might have also led me to discovering some kind of DMD bug to do with not being able to call a @nogc super class constructor from a constructor which isn't @nogc. It could be something else entirely, but it caused some undefined reference bugs to appear, which is odd.
Re: I have made a discovery
On Saturday, 18 April 2015 at 15:39:05 UTC, w0rp wrote: I *think* my PR might have also led me to discovering some kind of DMD bug to do with not being able to call a @nogc super class constructor from a constructor which isn't @nogc. It could be something else entirely, but it caused some undefined reference bugs to appear, which is odd. Disregard that, I needed to change the .di file too...
I have made a discovery
The following code almost compiles. import core.stdc.stdlib; class Foo : Exception { @nogc pure nothrow @safe this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null) { super(msg, file, line, next); } @nogc new(size_t size) { return malloc(size); } } @nogc void main() { throw new Foo(Oh no!); } That's right. An unofficially deprecated feature of the language and a newer feature of the language coming together in an interesting way. The only thing stopping this code from actually working is a trivial change to druntime to mark the Throwable, Exception, and Error constructors as @nogc, which I just created a pull request for directly through GitHub. https://github.com/D-Programming-Language/druntime/pull/1223 Now imagine that instead of just a malloc which leaks memory like the above, other allocation schemes are used here instead. Consider also the coming addition to the language for class reference counting methods opAddRef and opRelease. Then let your imagination run wild. Enjoy!
Re: groupBy/chunkBy redux
I wonder what it's going to look like to see byChunk and chunkBy next to each other.
Re: nginx module bindings
On Saturday, 18 April 2015 at 02:03:40 UTC, Shammah Chancellor wrote: Hello DForum! I wanted to attempt to write an nginx module in Dlang. However, the first step of generating some bindings is proving to be a pain on linux. Htod is windows only, and the other projects either generate incomprehensible modules, or are way out of date (it seems). Any pointers, or pre-existing bindings for nginx modules would be appreciated. -Shammah You might have to create the bindings yourself, if you do, please put them on GitHub and in a DUB package so others can benefit from them. I have been creating bindings for the Pebble SDK recently, and during my time working on that, I have come up with a process for creating the C bindings. 1. Apply dstep to the headers. Remove any parts from the header files which it won't accept. 2. Open the .d files and the .h files, and compare the two. 3. Implement whatever dstep missed out. dstep doesn't get you 100% of the way there, but it's a lot better than starting from nothing. I also have spent hours and hours working on the Pebble SDK headers recently, but that's only because I have been obsessed with translating all of the documentation to DDoc comments.
Re: T.zero and T.one for numeric types
On Friday, 17 April 2015 at 13:27:19 UTC, Biotronic wrote: I've been writing a lot of generic code lately that has to deal with various kinds of numbers, and have near been driven nuts by the fact there is no uniform way to get a zero or one. Consider: void foo(T)(T a) {} foo!T(0); Does this work with all built-in numeric types? Yes. Does it work with T=BigInt or Complex!float? No. Now, those are a limited set of possibilities, and one could easily enough create a template such that foo!BigInt(zero!BigInt); would work. But why can't I instead, for every numeric type, simply write foo(BigInt.zero); foo(float.one); foo(Complex!float.zero); foo(Rational!BigInt.one); foo(Meters.zero); ? This would also work for strong typedefs and units of measurement, where simply assigning 0 to a variable might not work (because it lacks the correct unit). It's a very simple change, both in the compiler and Phobos, and I could have a pull request ready tomorrow. -- Simen This can be implemented via a library without requiring any changes to the language. It would look like Zero!T or One!T instead. You create a value template for it. When you are writing less generic code, you can commit to zero or one in certain types via the prefixes. 1L, 1, 1.0, 1.0f. There's nothing for short or byte, but you can do short(1), byte(1). You can also write T(1) or T(0) to get a numeric type T with the value 0 or 1. That might be better than a template, I haven't tried it.
Re: Wanted: Review manager for std.data.json
On Wednesday, 8 April 2015 at 18:56:00 UTC, Iain Buclaw wrote: Frankly, if we are not as fast (or elegant) as Python's json library, it should be thrown out back to the drawing board. Iain. I'll leave the speed aside, as more recent posts show improvements and I think Sönke will be able to take what he has, tweak it, and get it close to the fastest libraries. I think we can beat the competition. For elegance, dynamic languages will always be able to deal with JSON with less syntax, as you get just the basic type back out of arrays and maps, without having to explictly request a string, integer, etc. Static languages will always have more verbose JSON libraries, but they might also catch bugs more easily. We just need the short properties for converting JSON values to basic types.
Re: Wanted: Review manager for std.data.json
On Thursday, 16 April 2015 at 12:17:55 UTC, Sönke Ludwig wrote: Am 16.04.2015 um 13:03 schrieb Jacob Carlborg: On 2015-04-16 11:29, Sönke Ludwig wrote: I'd like to let that be part of a more general serialization framework in top of this package instead of integrating a simplistic custom solution that will then later be obsoleted. I was thinking about some low level primitives that a serialization library could use. Types that cannot be broken in to smaller parts, integer, bool and so on. Having said that, you can go through JSONToken instead of JSONValue for lower (computational) overhead. Something like? JSONToken token; token.number = 3; token.kind = JSONToken.Kind.number; toJSON(token); Yes, just without setting the kind explicitly (it's set automatically by assigning to the number property). Instead of toJSON(), writeJSON() would probably be more appropriate to avoid additional allocations. Or what would you recommend a serialization library used? The simplest target for a serialization library would be to generate a stream of JSONParserNodes. That way the serializer doesn't have to keep track of nesting levels and can reuse the pretty printing functionality of stdx.data.generator. However, this currently requires an input range of JSONParserNodes, which looks like it is suboptimal for a serializer (either requires an explicitly allocated node array, or a strange serializer architecture that directly works as an input range). For that reason I'm thinking about providing an output range interface like so: auto dst = appender!string; auto rng = jsonOutputRange(dst); JSONParserNode n; // start an object n.kind = JSONParserNode.Kind.objectStart; rng.put(n); // write a single entry foo: 10.5 n.key = foo; rng.put(n); rng.put(10.5); // write another entry bar: true n.key = bar; rng.put(n); rng.put(true); // finish the object n.kind = JSONParserNode.Kind.objectEnd; rng.put(n); writefln(JSON: %s, dst.data); What do you think? BTW, looks like JSONToken could use a set of constructors for more convenient in-place construction. I think serialiastion for this JSON library should probably be considered out of scope until we have a general serisalisation API. Then once we have both, we can marry the two together. So as you say, the support from your end seems to be there. There just needs to be a serialiser to hook into it.
Re: D AutoCompletion: is ycmd integration valuable?
On Thursday, 16 April 2015 at 11:46:09 UTC, Idan Arye wrote: Some people - myself included - have already asked Brian to make DCD read the project's import paths from Dub or something. At first he claimed this is the editor's job - now he seems to be accepting the idea enough to accept a pull request - but he doesn't care about it enough to implement it himself. I won't be doing it either, because Dutyl is already doing this job and feeding the import paths to DCD, I'm assuming the other editor plugins also have their solutions for that already, so you can count their maintainers out. You'll need someone new to have enough motivation to do it - someone who wants to develop a new editor plugin(or plugin for ymcd or https://github.com/quarnster/completion or other stuff like that) and is willing to contribute to DCD on the way. A while back, I've looked a bit into integrating Dutyl with ycmd(http://forum.dlang.org/thread/qsvrvtpqrdvfujahk...@forum.dlang.org?page=2#post-ahwguxayeamrvdczlacu:40forum.dlang.org) and found out this connection is a waste of time, since I'll have to reimplement all the relevant parts in Python anyways so there is no point to make the semantic engine depend on Dutyl. I had to do some work to get Syntastic, which I use for syntax checking in Vim, to get the import paths in there from dub. I actually raised an issue for dub recently requesting dub to get a command to ouptut the import paths for you. The discussion led to me bineg able to finish my program. https://github.com/D-Programming-Language/dub/issues/542 My program can be seen here. https://github.com/w0rp/vim/blob/master/dub_paths.d It looks like Dutyl currently handles this by applying eval to the result of 'dub describe', then doing the rest in VimL. I might move to using Dutyl, as I am not currently running DScanner on my projects, and I think it's time that I did. Using DCD would also be nice, and having documentation on symbols would be nice. There is a way to implement this in Vim for mouse hovers. I'm not sure if Dutyl handles this already.
Re: D AutoCompletion: is ycmd integration valuable?
On Thursday, 16 April 2015 at 14:30:04 UTC, Idan Arye wrote: On Thursday, 16 April 2015 at 12:01:48 UTC, w0rp wrote: On Thursday, 16 April 2015 at 11:46:09 UTC, Idan Arye wrote: Some people - myself included - have already asked Brian to make DCD read the project's import paths from Dub or something. At first he claimed this is the editor's job - now he seems to be accepting the idea enough to accept a pull request - but he doesn't care about it enough to implement it himself. I won't be doing it either, because Dutyl is already doing this job and feeding the import paths to DCD, I'm assuming the other editor plugins also have their solutions for that already, so you can count their maintainers out. You'll need someone new to have enough motivation to do it - someone who wants to develop a new editor plugin(or plugin for ymcd or https://github.com/quarnster/completion or other stuff like that) and is willing to contribute to DCD on the way. A while back, I've looked a bit into integrating Dutyl with ycmd(http://forum.dlang.org/thread/qsvrvtpqrdvfujahk...@forum.dlang.org?page=2#post-ahwguxayeamrvdczlacu:40forum.dlang.org) and found out this connection is a waste of time, since I'll have to reimplement all the relevant parts in Python anyways so there is no point to make the semantic engine depend on Dutyl. I had to do some work to get Syntastic, which I use for syntax checking in Vim, to get the import paths in there from dub. I actually raised an issue for dub recently requesting dub to get a command to ouptut the import paths for you. The discussion led to me bineg able to finish my program. https://github.com/D-Programming-Language/dub/issues/542 My program can be seen here. https://github.com/w0rp/vim/blob/master/dub_paths.d It looks like Dutyl currently handles this by applying eval to the result of 'dub describe', then doing the rest in VimL. I might move to using Dutyl, as I am not currently running DScanner on my projects, and I think it's time that I did. Using DCD would also be nice, and having documentation on symbols would be nice. There is a way to implement this in Vim for mouse hovers. I'm not sure if Dutyl handles this already. Dutyl doesn't support that mouse hovering feature that you want, and I don't have any plans to implement it, but if you want it you can implement it and send a PR. Yeah, I was looking into it myself and thought, Oh, that would be a nice addition. So I'll probably fork it at some point and submit a pull request.
Re: Detect the bug in the following code
On Wednesday, 15 April 2015 at 15:17:32 UTC, Steven Schveighoffer wrote: On 4/15/15 10:44 AM, Idan Arye wrote: import std.stdio; struct Foo { bool registered = false; void register(int x) { writeln(Registering , x); register = true; } } void main() { Foo foo; foo.register(10); } Easy, the bug is in DMD improperly accepting property assignment without @property annotation :P -Steve Yep. Push patches for DIP23. Get it in the compiler already. Make only x.foo legal without @property.
Re: Mitigating the attribute proliferation - attribute inference for functions
On Monday, 13 April 2015 at 12:13:26 UTC, Kagamin wrote: On Saturday, 11 April 2015 at 21:47:20 UTC, Martin Nowak wrote: 1) If that function has source code available, it gets semantically analyzed and additional attributes are inferred. 2) The compiler errors because of missing attributes. I'd say, if you have the function body, you can infer its attributes, else you have its signature annotated with attributes, then they are honored normally. I was saying the same before. If you have the source, do inference. If you don't, no inference will be done. I think that will remove a lot of typing already. There are many cases where it won't be able to infer the attributes, but it's still better than nothing.
djinni and D
I was just watching this talk, and it is really interesting. https://www.youtube.com/watch?v=ZcBtF-JWJhM They are working with a C++ codebase they are sharing between different mobile platforms by mapping it to the languages specific to each platform. They explain in the talk, and as someone who has done a little iOS and Android development myself I understand this, that it's important to work with the platform specific tools so you can get the native look and feel specific to each platform. So they have a tool which generates code for connecting the platform languages to C++ and back. The best part is, this translation tool is actually free software. https://github.com/dropbox/djinni It uses Objective-C++ to connect to iOS with Objective-C, and JNI to connect to Android with Java. As I was watching this talk, my brain moved in a direction we can call a fanciful pipe dream. 1. Finish Objective-C support in D. 2. Finish iOS ARM support for GDC or LDC. 3. Finish Android ARM support for GDC or LDC. 4. Contribute to djinni, adding D (Objective-C) - Objective-C and D (JNI) - Java. 5. ??? 6. Profit! I'm pretty much just posting this to put that idea in the heads of others.
Re: Which D IDE do you use?(survey)
On Sunday, 12 April 2015 at 19:41:10 UTC, Atila Neves wrote: On Friday, 10 April 2015 at 17:59:45 UTC, Ali Çehreli wrote: On 04/10/2015 01:28 AM, Szymon Gatner wrote: A lot must have changed since I used Vim few years ago then. I hope this is not taken as an attack on Vim users but from my limited observations at work, users of Emacs use it powerfully and users of Vim use it as a simple editor. One example is dealing with multiple files (buffers): I and all the other Emacs users have dozens of files open at a time, switching between them seemlessly. I don't even close my Emacs sessions for months. On the other hand, most of the Vim users keep a single file open at a time. It is painful for me to watch how a Vim user goes to the definition of 'struct' that is already open in a .c file: exit Vim, change directory to 'include', start Vim again with the .h file. Argh! :) Ali It pains me to watch vim users do this. I'm an Emacs user myself, but I _know_ that what they're doing isn't necessary. I think I know more about vim than they do. Atila I personally use GVim with tabs and alias gvim in my terminal to open files in a new tab. I even use :mksession from time to time to save my current Vim session. Often I do like to start again, which I also do with my web browser, because starting from just a few files helps me think.
Re: DIP77 - Fix unsafe RC pass by 'ref'
I was thinking about this again, and how the first 'ref' would create a copy in order to keep the object around. At first I thought I didn't like that, but then I realised that it's actually not far from what I wanted for taking r-values by reference. I commonly write functions which take values either by reference or by value in this way. void foo(ref T value); void foo(T value) { foo(value); } Which obviously results in a combinatorial explosion of overloads, which you can write automatically some times with 'auto ref'. My question is, in the greater context of the language, supposing we had this copying behaviour for a first ref for reference counted objects, will it putting something in the language for copying r-values into functions, or will it provide a path to implement such a thing?
Re: __attribute__((used)) and druntime
On Saturday, 11 April 2015 at 15:59:53 UTC, David Nadlinger wrote: On Saturday, 11 April 2015 at 15:35:47 UTC, w0rp wrote: […] (Also LDC?) in druntime and flag all of the symbols like this appropriately, so that creating executables with gc-sections will Just Work in some cases without a linker script? LDC is shipping with --gc-sections enabled by default since a couple of releases, without a custom linker script. — David Ah. I was also wondering if this was now essentially a solved problem.
__attribute__((used)) and druntime
I've been looking into compiling smaller executables, and the trick I learned from watching sessions from the last DConf is to use the KEEP symbol in a linker script with something like gc-sections. So at the compilation stage, symbols are put in different sections, a linker script marks some symbols to be kept if they are not referenced, and then unreferenced symbols are removed, resulting in sometimes very small executables. The problem is that if you don't KEEP some symbols for druntime, or in your own program, you can run into errors because symbols which weren't apparently referenced now get used and your program breaks. I was just thinking, There must be a GCC extension for doing this without a linker script, I *think* there might be. From what I just read, __attribute__((used)) in GCC should do the job, and I think it should be usable from GDC with its attribute pragmas. I believe there's also an attribute for putting symbols in particular sections. I'm wondering, supposing I'm not completely wrong and this actually works, would it behoove us to add some version() blocks for GDC (Also LDC?) in druntime and flag all of the symbols like this appropriately, so that creating executables with gc-sections will Just Work in some cases without a linker script? What do people think? Am I on to something, or I am just making fanciful ideas which won't work?
Re: STL and Phobos
On Saturday, 11 April 2015 at 17:01:42 UTC, Dennis Ritchie wrote: Will the STL included in Phobos or is it impossible? STL won't be included in Phobos, at least as far as I know, but I believe it should be possible to interface to parts of it with extern(C++). To do it, you need to create names for every part of an STL type, including the allocator. Walter discussed all of this in a recent talk. https://www.youtube.com/watch?v=IkwaV6k6BmM It's really more for using existing C++ code which already uses the STL. In terms of algorithms, D is already in a better shape with std.algorithm. In terms of containers, you might find Phobos lacking for the moment, but progress will accelerate when Andrei's allocators are finally included in Phobos.
Re: DIP77 - Fix unsafe RC pass by 'ref'
On Saturday, 11 April 2015 at 09:28:46 UTC, Marc Schütz wrote: On Friday, 10 April 2015 at 23:12:55 UTC, deadalnix wrote: On Friday, 10 April 2015 at 10:02:01 UTC, Martin Nowak wrote: On Wednesday, 8 April 2015 at 23:11:08 UTC, Walter Bright wrote: http://wiki.dlang.org/DIP77 So someone passes an RCO via ref to avoid the inc/dec, and because that imposes safety issues we turn it into some sort of pass by value under the hood, defeating the purpose, and provide an opt-out via @system opAssign. Wouldn't it more straightforward to make pass-by-ref unsafe (@system) for RCOs? Then the only thing missing to make this equally powerful, would be an optimization opportunity for the compiler to elide copies of pass-by-value RCOs, e.g. it could avoid calling the postblit when the function retains the refcount. Only the first pass by ref create a copy. You can then pass the ref down all you want without copy. That is an acceptable cost IMO. It's not acceptable that it happens behind the user's back. Costly operations must be explicit. If we somehow know for a fact that the object really is a reference counted object, then the cost should be acceptable. Running the postblit will consist of incrementing a reference count and nothing else. There's no other way I can think of that permits passing the object safely. I think the one thing in the DIP I'm not sure of is the definition of what is a reference counted object. Say you write this. struct Widget { byte* data; size_t length; @trusted opAssign(ref const(Widget) other) { length = other.length; data = malloc(length); memcpy(cast(void*) data, cast(void*) other.data, length); } @trusted this(this) { auto oldData = data; data = malloc(length); memcpy(cast(void*) data, cast(void*) oldData, length); } @trusted ~this() { free(data); } } Why would you want to do this? Who knows. According to DIP77 the object above is defined to be a reference counted object, when it isn't. If we're rejecting the C++ answer of don't write code that way, then the same rejection should apply here. We need to be able to say with 100% certainty that we are dealing with a reference counted object, or at least an object where we know the postblit is so trivial the cost of calling it will be small.
Re: if(arr) now a warning
On Friday, 10 April 2015 at 18:32:39 UTC, Andrei Alexandrescu wrote: On 4/10/15 10:28 AM, Steven Schveighoffer wrote: On 4/10/15 11:57 AM, Andrei Alexandrescu wrote: On 4/10/15 6:26 AM, Meta wrote: On Friday, 10 April 2015 at 12:42:47 UTC, Steven Schveighoffer wrote: Plus, adding arr.empty into object is kind of redundant. The only reason we have arr.empty is so that it becomes a range. -Steve I find it extremely annoying to have to import std.array (or whatever the correct module is) just to use .empty, .front and .popFront on arrays. IMO they should all be in object.d. Yah, I was about to post the same. Range semantics are embedded in the language enough to warrant this. Also empty should work for AAs. How should abc.front work? Do you want to move unicode decoding of char and wchar arrays into object.d? Serious question, not rhetorical, because I'm not for or against it (except for the notion of changing things for the sake of changing them), I just want to point out what is required. Should decode. Meaning there's no change of semantics, just where the facility is defined. -- Andrei Having thought about it more, I think that is why we cannot put the range primitives for slices into object.d. Because that makes it impossible to define the primitives differently, so that no auto-decoding occurs. At the moment, auto-decoding isn't part of the language, it's just written in to the standard library. This would change that.
Re: Mitigating the attribute proliferation - attribute inference for functions
Shouldn't the inference with analysis be possible when you have the source available at least? You will still have to specify the attributes in a .di file if you are statically or dynamically linking to D libraries, but for source libraries or in parts of your project, you should be able to perform that inference. That would at the very least reduce attributes to the boundaries of APIs. // inferred private void bar() {} // inferred private void baz() {} @ngoc @safe pure nothrow public void foo() { bar(); baz(); } At some point in D, @safe should probably be the default, but that's a whole problem in itself.
Re: Which D IDE do you use?(survey)
On Saturday, 11 April 2015 at 10:27:15 UTC, weaselcat wrote: if you're using vim-dutyl you could just remap K to :DUjump or one of the split variants. (DUddoc also shows the documentation of the symbol under your cursor.) I'll have to try this myself. Vim has a feature for balloon messages, so I was wondering if there was something for that for D in Vim. You can see some examples if you run a Google image search for vim balloonexpr.
Re: DIP77 - Fix unsafe RC pass by 'ref'
On Thursday, 9 April 2015 at 18:44:10 UTC, Walter Bright wrote: The only real purpose to a postblit is to support ref counting. Why would a by-value container use a postblit and not ref count? A struct could have a postblit defined if you are implementing something like std::vector, where you you copy the memory when the struct is copied. I'm not sure why you would want to do such a thing in D, though. If allocating memory is your concern, you probably don't want any allocation, including malloc.