Re: Singleton in Action?

2019-02-02 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 02 Feb 2019 17:34:11 +, Eugene Wissner wrote:
> For creation get() should be always used, since it is the most
> convenient way to ensure that there is really only one instance of the
> singleton. Just make this() private, so only you can create new
> instances:
> 
> private this()
> {
> }

And consider putting the class in its own source file.


Re: How can I express the type of a function in D?

2019-01-30 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 30 Jan 2019 12:56:06 -0800, Ali Çehreli wrote:
> I remember names like _add. Is that a Windows thing?

A number of functions are implemented as manually-mangled names with 
preprocessor macros that forward to them. It's weird, but it happens.


Re: How can I express the type of a function in D?

2019-01-30 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 30 Jan 2019 10:39:21 -0800, Ali Çehreli wrote:
> import core.demangle;
> 
> extern(C) int add(int, int);
> 
> void main() {
>alias F = typeof(add);
>pragma(msg, mangle!F("add"));
>pragma(msg, add.mangleof);
> }
> 
> Output:
> 
> _D3addUiiZi
> add   <-- Is that correct?

`add.mangleof` is correct. In fact, it's definitively correct.

typeof(add) is extern(C) int function(int, int). Based on this output, 
core.demangle seems like it's not taking the extern(C) portion into 
account.


Re: DIP 1016--ref T accepts r-values--Formal Assessment

2019-01-30 Thread Neia Neutuladh via Digitalmars-d-announce
On Wed, 30 Jan 2019 09:15:36 -0800, Manu wrote:
> Why are you so stuck on this case? The DIP is about accepting rvalues,
> not lvalues...
> Calling with 'p', an lvalue, is not subject to this DIP.

The result of a CastExpression is an rvalue. An implicit cast is a 
compiler-inserted CastExpression. Therefore all lvalues with a potential 
implicit cast are rvalues.


Re: GtkD Blog Now Up and Running

2019-01-29 Thread Neia Neutuladh via Digitalmars-d-announce
On Tue, 29 Jan 2019 21:13:17 +, WebFreak001 wrote:
> dub.sdl:
> name "my-awesome-gtk-app"
> 
> dependency "gtk-d" version="~>3.8.5"

Might I recommend instead:

dependency "gtk-d" version="3.8.5"

This depends on gtk-d 3.8.5 and only that version. If there is a breaking 
change in 3.8.6 despite semantic versioning, your code keeps working.

In libraries, I prefer using ~> to give more freedom to people depending 
on my code. But in applications, that isn't a concern. May as well only 
allow the code to be built with the versions of your dependencies that 
you've actually tested.


Re: Should I prefix package names with the name of my program?

2019-01-28 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 28 Jan 2019 16:59:22 +, Victor Porton wrote:
> Should I prefix all module names with `xmlboiler.` (where XML Boiler is
> the name of my program). These packages are expected to be used
> internally by my program, not as an exported API (however there are some
> little chances that in the future I will make a public API)

You do you. I put all my source files inside a package unless it's a one-
file project mainly so that I can sort my import directives and have them 
organized nicely. But if you don't want to have to type `xmlboiler` five-
ish times per source file, you can skip it.


Re: Ordered set container?

2019-01-28 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 28 Jan 2019 17:18:52 +, Victor Porton wrote:
> I want "ordered set" container (like list or vector but with the
> warranty of no duplicate elements).
> 
> Which type can I use?

std.container.rbtree

It has options to preserve or squash duplicates.


Re: DIP 1016--ref T accepts r-values--Formal Assessment

2019-01-25 Thread Neia Neutuladh via Digitalmars-d-announce
On Fri, 25 Jan 2019 18:14:56 -0800, Manu wrote:
> Removing the `void` stuff end expanding such that the declaration +
> initialisation is at the appropriate moments; any function can throw
> normally, and the unwind works naturally?

The contention was that, if the arguments are constructed properly, 
ownership is given to the called function, which is responsible for 
calling destructors. But if the argument construction fails, the caller is 
responsible for calling destructors.

I'm not sure what the point of that was. The called function doesn't own 
its parameters and shouldn't ever call destructors. So now I'm confused.


Re: How is this code supposed to work?

2019-01-25 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 25 Jan 2019 19:14:51 -0500, Steven Schveighoffer wrote:
> Interestingly, It's not possible to do the second form, so it's a bit
> curious why we don't just drop the requirements for nested
> parentheses...

The error messages there are really hideous, too:

template Just(alias s) { alias Just = s; }
alias f = (Just!Just)!int;

scratch.d(16): Error: basic type expected, not (
scratch.d(16): Error: function declaration without return type. (Note that 
constructors are always named this)
scratch.d(16): Error: semicolon expected to close alias declaration
scratch.d(16): Error: found ; when expecting . following int
scratch.d(17): Error: found } when expecting identifier following int.
scratch.d(18): Error: found End of File when expecting ; following 
statement
scratch.d(18): Error: found End of File when expecting } following 
compound statement

So I guess this is just to make people less confused about order of 
operations, since it would be unexpectedly right-associative in a language 
where most things are left-associative?


Re: DIP 1016--ref T accepts r-values--Formal Assessment

2019-01-25 Thread Neia Neutuladh via Digitalmars-d-announce
On Fri, 25 Jan 2019 23:08:52 +, kinke wrote:

> On Friday, 25 January 2019 at 19:08:55 UTC, Walter Bright wrote:
>> On 1/25/2019 2:57 AM, kinke wrote:
>>> On Thursday, 24 January 2019 at 23:59:30 UTC, Walter Bright wrote:
 On 1/24/2019 1:03 PM, kinke wrote:
> (bool __gate = false;) , ((A __pfx = a();)) , ((B __pfy =
> b();)) , __gate = true , f(__pfx, __pfy);

 There must be an individual gate for each of __pfx and pfy.
 With the rewrite above, if b() throws then _pfx won't be destructed.
>>> 
>>> There is no individual gate, there's just one to rule the
>>> caller-destruction of all temporaries.
>>
>> What happens, then, when b() throws?
> 
> `__pfx` goes out of scope, and is dtor expression (cleanup/finally) is
> run as part of stack unwinding. Rewritten as block statement:

And nested calls are serialized as you'd expect:

int foo(ref S i, ref S j);
S bar(ref S i, ref S j);
S someRvalue(int i);

foo(
bar(someRvalue(1), someRvalue(2)),
someRvalue(4));

// translates to something like:
{
bool __gate1 = false;
S __tmp1 = void;
S __tmp2 = void;
S __tmp3 = void;
__tmp1 = someRvalue(1);
try
{
__tmp2 = someRvalue(2);
__gate1 = true;
__tmp3 = bar(__tmp1, __tmp2);
}
finally
{
if (!__gate1) __tmp1.__xdtor();
}
S __tmp4 = void;
bool __gate2 = false;
try
{
__tmp4 = someRvalue(4);
__gate2 = true;
return foo(__tmp3, __tmp4);
}
finally
{
if (!__gate2)
{
__tmp3.__xdtor();
}
}
}


Re: How is this code supposed to work?

2019-01-25 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 25 Jan 2019 09:34:47 +, AndreasDavour wrote:
>auto point3 = getResponse!Point!int("What's the point? ");

This could be:

getResponse!(Point!int)

or:

(getResponse!Point)!int

D requires this to be disambiguated at the parsing stage, before the 
compiler works out what getResponse might be.

An example of the latter:

template getResponse(alias n)
{
alias getResponse = n;
}

getResponse!Point is just Point.

I'm not sure why that tutorial has it wrong, but the way to get it fixed 
is to contact the author.


Re: std.socket.Address not allowed in tuples

2019-01-23 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 24 Jan 2019 01:35:57 +, Steven O wrote:
> Is there any documentation or examples of how to do that? The
> RedBlackTree documentation gives trivial examples like

You define a function implementing the "less" operation for a pair of 
Tuple!(Address, int) (or whatever you have).

---
alias V = Tuple!(Address, int);
bool less(V a, V b)
{
  if (a[0].classinfo != b[0].classinfo)
  {
return a[0].classinfo < b[0].classinfo;
  }
  // do something for InternetAddress, Internet6Address, etc
  return 0;
}
---

Then pass that to RedBlackTree:

---
alias VTree = RedBlackTree!(V, less);
VTree tree = new VTree();
---


Re: opEquals() non-standard return type

2019-01-23 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 23 Jan 2019 15:19:06 +, Jacob Shtokolov wrote:
> I'm wondering, is that possible to declare multiple versions of
> opEquals() and evaluate them in the different places depending on return
> type?

I looked at this a while ago for similar reasons. It didn't pan out.

When you override the comparison operator, you can't distinguish which 
comparison is overloaded. It takes at least 2^n evaluations of the 
function to determine all the comparisons, possibly more. (I *think* you 
can observe the short-circuiting logic as you do those evaluations to 
determine how each comparison is combined.)


Re: Top Five World’s Most Underrated Programming Languages

2019-01-23 Thread Neia Neutuladh via Digitalmars-d-announce
On Wed, 23 Jan 2019 14:37:30 +, Bienlein wrote:
> This is all true, but you need to keep in mind that Go had no real
> package manager for a long time. There was the "go get" command which
> loaded the code from some github repo in the state it was at the time
> when being loaded. There was no version control. Nobody really cared
> (the vendor stuff in Go was added with Go 1.10 or 1.11). Goroutines were
> the killer feature of the language that paved the way, because this was
> badly needed for writing server-side software.

Go has several killer features:
* It's got a GC and yet is endorsed by one of the major people behind C. 
This helps people get over their fear of garbage collection and into 
appreciating the benefits.
* It's also got "pointers". They're actually references with pointer-ish 
syntax, but that makes people coming from C/C++ more comfortable.
* It's not Java, and it's not slower than Java.
* There was a team in Google that would rewrite old, crufty C++ code in 
Go. Was Go a benefit? Maybe in some ways, but the major benefit was a 
rewrite that the owning team didn't have to do. That earned goodwill among 
thousands of developers attached to Go as a language.
* It's backed by Google (in large part because of that goodwill).

I don't think fibers are all that important for Go's success. Maybe for 
people who would have looked at node.js but didn't want to use javascript?


Re: std.socket.Address not allowed in tuples

2019-01-23 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 23 Jan 2019 15:56:15 +, Steven O wrote:
> Why am I not allowed to put Address types in tuples?

As always, it helps a lot to post the error message the compiler gave you. 
The message is:

/usr/include/dmd/phobos/std/functional.d-mixin-215(215): Error: template 
std.typecons.Tuple!(Address, int).Tuple.opCmp cannot deduce function from 
argument types !()(Tuple!(Address, int)) inout, candidates are:
/usr/include/dmd/phobos/std/typecons.d(806):std.typecons.Tuple!
(Address, int).Tuple.opCmp(R)(R rhs) if (areCompatibleTuples!
(typeof(this), R, "<"))
/usr/include/dmd/phobos/std/typecons.d(820):std.typecons.Tuple!
(Address, int).Tuple.opCmp(R)(R rhs) if (areCompatibleTuples!
(typeof(this), R, "<"))
/usr/include/dmd/phobos/std/container/rbtree.d(866): Error: template 
instance `std.functional.binaryFun!("a < b", "a", "b").binaryFun!
(inout(Tuple!(Address, int)), Tuple!(Address, int))` error instantiating
scratch.d(13):instantiated from here: RedBlackTree!(Tuple!
(Address, int), "a < b", false)

The last line says that the error came when trying to instantiate the 
RedBlackTree template. At that point, Tuple was instantiated. There is no 
issue putting an address in a Tuple.

The issue is that Address doesn't have a comparison operator defined, so 
the resulting tuple type can't be compared with the standard operators. 
You need to define your own function for comparing the tuples in question 
and pass that to RedBlackTree.


Re: Deprecation

2019-01-18 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 18 Jan 2019 22:53:23 +, Ali wrote:
> Hello. I am having an issue with the code below. the out put after
> compiling is this :
> 
> Deprecation: foreach: loop index implicitly converted from size_t to
> uint
> 
> the code is :
> 
> auto available = new int[cast(uint) max - min];
>   foreach (uint i, ref a; available)
>   a = min + i;
> 
> Any help would be highly appreciated.

You are trying to use a uint (max value 2^32-1) to give an index for an 
array (which might be more than 2^32-1 elements long). That's deprecated 
and will be gone from the language in a few releases.

Instead, write:

foreach (size_t i, ref a; available)
  a = cast(uint)(min + i);


Re: D-lighted, I'm Sure

2019-01-18 Thread Neia Neutuladh via Digitalmars-d-announce
On Fri, 18 Jan 2019 11:43:58 -0800, H. S. Teoh wrote:
> (1) it often builds unnecessarily -- `touch source.d` and it rebuilds
> source.d even though the contents haven't changed; and

Timestamp-based change detection is simple and cheap. If your filesystem 
supports a revision id for each file, that might work better, but I 
haven't heard of such a thing.

If you're only dealing with a small number of small files, content-based 
change detection might be a reasonable option.

> (2) it often fails to build necessary targets -- if for whatever reason
> your system clock is out-of-sync or whatever, and a newer version of
> source.d has an earlier date than a previously-built object.

I'm curious what you're doing that you often have clock sync errors.


Re: Is there a nice syntax to achieve optional named parameters?

2019-01-18 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 18 Jan 2019 09:39:31 +, John Burton wrote:
> On Thursday, 17 January 2019 at 01:43:42 UTC, SrMordred wrote:
> 
>> struct Config {
>>  string title;
>>  int width;
>> }
>>
>> struct Window {
>>  this(Config config)
> 
> It likely is a bad idea for a small struct like this but if it was much
> bigger would it makes sense to write this as :-
> 
>   this(const ref Config config)
> 
> Which is what you might do in C++ or does D handle this differently?

Creating a window is the dominating cost here. If you're creating enough 
windows that copying them is a problem, you're doing something seriously 
weird and it might be more productive to step back and think about that 
than to switch to const ref.


Re: Runtime heterogeneous collections?

2019-01-18 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 18 Jan 2019 10:07:41 -0500, Steven Schveighoffer wrote:
> But what is the common interface between those 2 types? Even in
> Dcollections, where RedBlackTree came from, there was no interfaces that
> didn't specify the type they were dealing with. In other words, there is
> no common interface for sets of 2 different types.

.empty(), .clear(), .length(), and .toString(sink, formatspec). Which is 
kind of anemic. Might as well use Object.


Re: Runtime heterogeneous collections?

2019-01-16 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 17 Jan 2019 02:21:21 +, Steven O wrote:
> I want to create a heterogeneous collection of red-black trees, and I
> can't seem to figure out if it's possible.

RedBlackTree!int and RedBlackTree!string are entirely different types 
(they just happen to be generated from the same template).

There are two reasonable ways of doing things:

1. Make a wrapper class. Now you can store Object[], or you can make a 
base class or base interface and use that.
2. Use Variant, which can wrap anything, or the related Algebraic, which 
can wrap a fixed collection of types.

You can use this technique either with the collection types themselves or 
with the value types.


Re: unittest which uses a disk file

2019-01-16 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 16 Jan 2019 21:07:24 +, Victor Porton wrote:
> What is the rule for unittest which uses a file (containing example data
> for testing) available only in the source distribution, not in binary
> distribution?
> 
> I am writing a library.

The easy way of doing things is to define a version for your library's 
unittests. Like I might write:

version (EpubTest) unittest
{
writeEbookFile("test.epub");
}

And then in dub.sdl, I'd have the test configuration add
-version=EpubTest. Dub has support for this sort of thing, but I don't 
know the details offhand.

If you have extra dependencies or need extra environment setup, you might 
want to make a second dub package inside the same repository and give it a 
path-based dependency on your library. Normal people won't touch that 
second package, so you can do whatever you want there, and it's a good 
place to add another README.


Re: What is the Utility of Parent Class Method Hiding in Inheritance?

2019-01-16 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 16 Jan 2019 12:01:06 -0500, Steven Schveighoffer wrote:
> It was 2.068 that removed the HiddenFuncError, and made this a compile
> error instead. If your compiler is that or newer, definitely file a bug
> report.

Oh god, that must have been awful. I'm glad we're no longer in those 
benighted times.


Re: My Meeting C++ Keynote video is now available

2019-01-15 Thread Neia Neutuladh via Digitalmars-d-announce
On Tue, 15 Jan 2019 11:59:58 +, Atila Neves wrote:
> He's not saying "kill classes in D", he's saying an OOP system in D
> could be implemented from primitives and classes don't need to be a
> language feature, similar to CLOS in Common Lisp.

As long as the syntax and behavior don't change, the error messages are 
good, and the compile-time overhead is similar, I won't complain.


Re: My Meeting C++ Keynote video is now available

2019-01-14 Thread Neia Neutuladh via Digitalmars-d-announce
On Mon, 14 Jan 2019 21:12:48 +, Paul Backus wrote:
> On Monday, 14 January 2019 at 21:08:50 UTC, Ben Jones wrote:
>> Is it possible to declare a function whose name is a CTFE computed
>> string?
> 
> Yes, if you do it with a string mixin.

And more simply, you can declare a function with a hard-coded name, then 
use an alias to expose it under a different name.


Re: problem extracting data from GtkSourceView using Gtkd

2019-01-14 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 14 Jan 2019 22:52:48 +, Chris Bare wrote:
>   auto start = new TextIter();
>   auto end = new TextIter();

You shouldn't need to new these. `out` means that the function is going to 
overwrite the variables.

Other than that, I'm not sure.


Re: What is the Utility of Parent Class Method Hiding in Inheritance?

2019-01-14 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 14 Jan 2019 09:10:39 +, Vijay Nayar wrote:
>  a.foo(1);  // issues runtime error (instead of calling
> A.foo(int))

Calling the function doesn't issue any sort of error. Overriding one 
overload without overloading or explicitly aliasing in the rest issues a 
compile-time error.

If you got a runtime error instead, please create a bug report.

> I ran into this the other day, where I had a function of the same name
> in a child class, and found that all functions in the parent of the same
> name now became hidden, unless I add an alias statement.

If the functions from the parent class are hidden but your code compiles, 
please create a bug report.


Re: code-d 0.20.0 - serve-d 0.4.0 - Happy new year!

2019-01-13 Thread Neia Neutuladh via Digitalmars-d-announce
On Sun, 13 Jan 2019 21:40:43 +, Murilo wrote:
> It would be a good idea to publish that on the facebook group for users
> of D. There you would be able to spread the information fast. It is
> called Programming in D. Here is the link:
> https://www.facebook.com/groups/662119670846705/

I think one post advertising the facebook group per week would be more 
appropriate than three in one day.


Re: nice-curses releases / dub version git?

2019-01-12 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 12 Jan 2019 12:10:25 +, Droggl wrote:
> 2. Is there a way to get a certain git-version (eg. commit or maybe even
> just "latest") for a package in dub?

git submodule and path-based dependencies, if you need a particular 
version.

> 3. How is everyone in general using curses with D? Is there maybe a
> different library I should checkout instead? Are you using latest git?

dstep on curses.h and including that directly in my project.


Re: Coedit almost works for me, except when I go to add peggged

2019-01-11 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 11 Jan 2019 17:25:29 +, Enjoys Math wrote:
> Package peggged not found for registry at https://code.dlang.org/

The package name is pegged, not peggged. Two g's, not three.


Re: Forward declaration inside Function block, no error?

2019-01-06 Thread Neia Neutuladh via Digitalmars-d-learn
On Sun, 06 Jan 2019 20:19:59 +, Rubn wrote:
> You can declare functions inside of functions in D. You weren't forward
> declare grow() in the module namespace, so much as you were forward
> declaring a new function grow.

Unfortunately, you can't do forward declarations for nested functions. If 
you could, that would be handy for mutual recursion:

void main()
{
int a(int i);
int b(int i)
{
if (i > 0) return a(i - 1);
return abs(i);
}
int a(int i)
{
if (i % 2 == 0) return b(i - 2);
return b(i - 1);
}
writeln(a(12));
}

Unfortunately, Error: declaration a is already defined

And omitting the forward declaration gets you: Error: undefined identifier 
a


Re: Co-developing application and library

2019-01-05 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 05 Jan 2019 17:44:27 +, Neia Neutuladh wrote:
> 2. Different build configurations. The same source code has two
> different build targets; the executable doesn't depend on the library.
> Or, with enough bludgeoning, you can make the executable depend on the
> library.

Hit 'send' too soon.

The build configuration way would be:

---
# dub.sdl
configuration "exe" {
  targetType "executable"
}
configuration "lib" {
  targetType "staticLibrary"
  excludedSourceFiles "src/cli/*"
}
---

Then you'd build with:

dub build --config=lib
dub build --config=exe

To make this version of things yield an executable depending on a library, 
you'd use something like:

---
# dub.sdl
configuration "exe" {
  targetType "executable"
  excludedSourceFiles "src/lib/*"
  importPaths "src/lib"
  libs "-L." "-L-l:libmyproject.so"
}
configuration "lib" {
  targetType "sharedLibrary"
  excludedSourceFiles "src/cli/*"
}
---

The one advantage of this is being able to use shared libraries. It's 
awkward.


Re: Co-developing application and library

2019-01-05 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 05 Jan 2019 13:01:24 +, Russel Winder wrote:
> Dub seems to have the inbuilt assumption that libraries are dependencies
> that do not change except via a formal release when you developing an
> application.
> Clearly there is the workflow where you want to amend the library but
> not release as a part of developing an application. Does Dub have a way
> of doing this, I haven't been able to infer one to date. But I am a
> beginner at Dub.

There are a few ways to do this:

1. Path dependency, as Alex mentioned.
2. Different build configurations. The same source code has two different 
build targets; the executable doesn't depend on the library. Or, with 
enough bludgeoning, you can make the executable depend on the library.
3. Subprojects.
4. dub add-local on the library, as Mike Parker mentioned.

I wouldn't depend on ~master because (a) that won't change until you 
commit stuff and (b) it might require also running dub upgrade to get the 
new source code.

The subproject way of doing things:

---
# dub.sdl
name "myproject"
targetType "none"
# So we build the child projects
dependency "myproject:lib" version="*"
dependency "myproject:exe" version="*"
# To define the child projects
subPackage "./lib"
subPackage "./exe"
---

---
# exe/dub.sdl
name "exe"
dependency "myproject:lib" version="*"
targetType "executable"
---

This will intuit a project structure like:

  dub.sdl
  exe/
dub.sdl
src/
  lib/
dub.sdl
src/

But if you prefer, you can modify that with "sourcePaths" in the 
subpackage dub.sdls.


Re: reimplementing an interface in a derived class

2019-01-04 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 04 Jan 2019 08:46:24 +, Alex wrote:
> Let's assume this is right. How to force a B object to behave like an A
> object? I thought casting is a possible approach...

It requires a bit of surgery:

import std.stdio;
class A
{
void foo() { writeln("hello from A!"); }
}
class B : A
{
override void foo() { writeln("hello from B!"); }
}
void main()
{
auto b = new B;
auto ptrB = cast(void**)b;
ptrB[0] = A.classinfo.vtbl.ptr;
b.foo();
}

This takes advantage of the object layout used by DMD. 'vtbl' is the 
virtual function table, which is basically an array of function pointers. 
Each member function defined in a type (and its super types) gets a unique 
index into that array.

So when you write:

b.foo();

That works out to:

(cast(void function(B))b.vtbl[5])(b);

We replace object b's vtbl with class A's, and now b is just an A with 
some extra stuff allocated in its memory block.

Don't do this in production code. This is a terrible thing to do in 
production code, or any code you intend to use other than to see how D's 
object model works.


Re: reimplementing an interface in a derived class

2019-01-03 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 04 Jan 2019 00:19:05 +, Alex wrote:
> B.foo overrides A.foo. By casting a B object to be an A object, A's
> behavior should be granted, shouldn't it?

I can't think of a single class system that works like that. C++, Java, 
C#, Dart, and TypeScript all work like D here. GObject in C works like D.

The point of OOP is that a bundle of data has particular ways of dealing 
with it. B has different data (at least theoretically), and that data has 
different ways of working with it. So if casting to a base class changed 
something to use the base class's behavior, you'd get bugs almost anywhere 
you used inheritance, since the derived class's data isn't being modified 
properly.

The only situation in which you might possibly want that sort of behavior 
is if inheritance were only for ease of implementation, but then you'd 
want to disallow that sort of cast anyway. It would be like trying to cast 
an object to one of its fields.


Re: reimplementing an interface in a derived class

2019-01-03 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 03 Jan 2019 23:44:15 +, Alex wrote:
> I assume that is another bug and has nothing to do with interfaces...

B.foo is both overriding A.foo and implementing D.foo, so that's not a bug.


Re: reimplementing an interface in a derived class

2019-01-03 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 03 Jan 2019 22:30:48 +, kdevel wrote:
> class A : D {
>  int foo() { return 1; }
> }
> 
> class B : A, D {
> [...]
>
> What is the meaning of the ", D"? It does not seem to make a difference
> if it is omitted.

B must provide its own implementation of D. It can't simply use A's 
implementation.


Re: What's wrong with this template function?

2019-01-03 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 03 Jan 2019 20:34:17 +, Machine Code wrote:
> Thank you very much, Ali. So the issue was basically I can't return from
> a static foreach() loop right?

The static foreach is done at compile time and the return is done at 
runtime.

After the template is expanded, your code ends up looking like:

Color first()
{
return Color.red;
return Color.blue;
return Color.green;
static assert(false);
}

And that doesn't compile, because there's a static assert there that 
fails. It's not at any line of code that would execute at runtime, but the 
compiler doesn't care about that.


Re: Subtypes with tighter constraints

2019-01-01 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 01 Jan 2019 14:05:43 +, Victor Porton wrote:
> In Ada2012 there are "subtypes". Subtypes can have tighter constraints
> (such as type invariants) than their base types.
> 
> I have a struct X in D. Is it possible to define a type equivalent to X
> except that having tighter invariants?

In D, structs don't participate in inheritance. Classes do, but invariants 
aren't inherited; they're specific to the class in which the function is 
defined. (Which is probably a bug and I filed https://issues.dlang.org/
show_bug.cgi?id=19537.)

I see three ways to make this work today:

1. Use alias this to wrap the struct. Add invariants that deal with the 
wrapped struct's fields.
2. Use compile-time reflection to copy the fields over, then manually copy 
the invariants over and add more.
3. Use a class. Define a virtual function like 'doInvariant()`. Call it 
from the base class's invariant{} block.

> As I understand if I derive Y from X, then it is no more X; that is I
> cannot use X (even provided it matches Y invariants) where I need Y. So
> in D it is impossible, right?

With classes, a derived class instance can be used anywhere you expect a 
base class instance. The reverse is not true.


Re: D-oriented Syntax Highlighting Plugin for WordPress?

2019-01-01 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 01 Jan 2019 14:46:15 +, Ron Tarrant wrote:
> I've found a ton of syntax highlighter plugins for WordPress, but none
> that admit to supporting D. Anyone know of one?

I believe I use Enlighter for that:
https://wordpress.org/plugins/enlighter/


Re: Why can't or shouldn't I just hash the address of an object? And how.

2018-12-29 Thread Neia Neutuladh via Digitalmars-d-learn
On Sun, 30 Dec 2018 05:36:41 +, Enjoys Math wrote:
> Is it:
> 
> typeof(T).getHash()?

This gets the hashcode for the object by calling toHash() on it.

> Or does that do something other than just get the address?

It XORs the address with a bitwise rotation of the address. This reduces 
collisions since objects are allocated aligned.

As for your larger problem, I'd strongly tend toward using a database to 
hold application state instead of keeping it in memory.


Re: class template conflict

2018-12-25 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 25 Dec 2018 18:34:04 +, bauss wrote:
> I think there is a bigger problem at stake here in terms of software
> architecture.
> 
> What's the point needed for them to have the same identifier?

A probably abstract base class with only one child class. Normally you 
have "Foo" and "FooImpl", or "IFoo" and "Foo", but that's ugly.

This was the primary example that Michelle Long gave. I'd expect that a 
fair portion of people people who have used C# encountered this kind of 
situtaion. Like this sort of thing works in C#:

class Foo {}
class Foo : Foo {}
class Foo : Foo {}

You can do this in C# because each of these are *classes*, and some just 
happen to have type parameters. In D, you'd have one class and two 
templates, and you can't overload two symbols of different kinds, so you 
have to write it as:

class Foo() {}
class Foo(T): Foo!() {}
class Foo(T, U): Foo!() {}

In Java, for legacy reasons, this pattern is baked into the language; 
Foo always has another class, Foo, that it implicitly casts to and 
from. Some people take advantage of that.

Most people who do both metaprogramming and OOP in D and have been doing 
that for a nontrivial amount of time probably encountered this exact same 
thing in D. I encountered it the first time before D2 was a thing.

> Clearly the two classes will have two different functions and should be
> named accordingly.

They will have different implementations and may have different 
interfaces. The proposed use case is inheritance, so X!10's public 
interface will be a superset of X's (and likely identical).

To give a slightly less contrived example, let's say you want to have some 
functions available to a scripting language. (I'm doing something like 
this in a side project for a CLI spreadsheet program.) Each function has a 
display name, help text, argument validation, and the function body.

If I had done this in an OOP style (and I might end up reworking it to look 
more like this), I'd have something like:

interface Function
{
  string helpText();
  string name();
  Nullable!Error validateParameters(Val[] parameters);
  Val execute(Val[] parameters);
}

And then I'd have a convenience mechanism to produce a conforming class 
from a function with UDAs:

class FunctionImpl(alias fn) : Function
{
override:
  string helpText() { return getUDAs!(fn, Help)[0].text; }
  string name() { return __traits(identifier, fn); }
  // etc
}

It would be slightly nicer to just have "Function" everywhere instead of 
both Function and FunctionImpl. Not enough to justify the complexity of 
the symbol lookup rules required. Not enough to make `class Foo(T)` mean 
something different from `template Foo(T) class Foo`. But it *would* be 
slightly nicer, and it would make things slightly more straightforward for 
people coming from C#.


Re: Determination of thread status.

2018-12-25 Thread Neia Neutuladh via Digitalmars-d-learn
1. Find the Thread object:
  Tid threadId = spawn();
  auto thread = Thread.getAll.filter!(x => x.id == threadId).front;
2. Check the `isRunning` property.

The indirection with spawn() is awkward.


Re: class template conflict

2018-12-25 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 25 Dec 2018 16:55:36 +, Neia Neutuladh wrote:

And I forgot part of it.

Let's say we did the work to make this function:

class X {}
template X(int N)
{
  // `: X` somehow refers to the X in the outer scope
  class X : X {}
}

How do you distinguish between the base class and the derived class in 
there? You'd have to use typeof(this) and typeof(super) everywhere.

And externally, how do you refer to class X and template X separately? If 
you have a template with an alias parameter and pass X, how do you pass 
class-X and how do you pass template-X?

This is already unpleasant with functions, and there's a way to 
distinguish them.


Re: class template conflict

2018-12-25 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 25 Dec 2018 13:03:13 +, Michelle Long wrote:
> But I am not talking about inside the template being used. The whole
> point of doing this is so that one can refer to the base class using the
> same name as the derived with a template parameter to make a composite
> structure.

The following are entirely equivalent:

class X(int N) : X {}

template X(int N)
{
  class X : X {}
}

You want to be able to do, essentially:

class X {}
template X(int N)
{
  // `: X` somehow refers to the X in the outer scope
  class X : X {}
}

And sure, this specific case obviously doesn't work if the `: X` refers to 
the template or the class inside the template. But the symbol lookup rules 
aren't "try everything and see what sticks". You look up the nearest 
symbol and then you just use that.

It would be like arguing that, in the following example, the compiler 
should know that ints aren't callable and should call the function:

void foo() { writeln("merr critmis"); }
void main()
{
int foo = 10;
foo();
}

Which isn't obviously wrong, but it does make things harder to understand.


Re: Mysteries of the Underscore

2018-12-24 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 24 Dec 2018 08:16:01 -0800, H. S. Teoh wrote:
> Rather, it's *conventionally* taken to mean "unused".  The language
> actually does not treat it in any special way apart from "normal"
> identifiers.  It's perfectly valid (though probably not recommended!) to
> declare functions or variables with the name "_" and use them.

I once, in my callow days, wrote a unittest with variables named _, __, 
___, etc. It did not pass code review, but it did amuse.


Re: How to deprecate member function from outside?

2018-12-22 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 22 Dec 2018 21:33:14 +, Dru wrote:
> The first example shows that it is possible to deprecate a function
> separately from it's definition.

No, it doesn't. You declared two *different* functions. One was 
deprecated; the other wasn't.

> I want to know if it is possible to "fix" the second example? (deprecate
> a member function separately from it's definition)

No. All functions must be deprecated where you declare them.


Re: How to deprecate member function from outside?

2018-12-22 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 22 Dec 2018 18:55:47 +, Dru wrote:
> I would like to use "deprecated" on a member function, but do it from a
> separate file
> 
> this works:
> ///
> void func() {}
> 
> deprecated {
>void func();
> }

You're defining two functions, presumably in two different modules and 
with two different fully qualified names. One function is deprecated but 
has no body, so you will get a deprecation warning and a linker error if 
you try using it. One function is not deprecated and has a body, so you'll 
get no errors if you try using it.

If, on the other hand, you define both the non-deprecated and deprecated 
functions in the same file, and you try using them, you'll get an error 
saying that the function call matches multiple functions.


Re: using dub to compile plugins

2018-12-21 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 21 Dec 2018 10:56:39 +, Atila Neves wrote:
> I don't see how you can do this with dub, and I wouldn't attempt it
> either. Just use make, and have make call dub for the main project (and
> potentially any plugins that need it). Remember to make the dub targets
> `.PHONY` since you don't want to be managing the D dependencies by hand.

Or you could have it depend on dub.sdl, dub.selections.json, your D source 
files, and your string import files. Which is a bit more work but will 
result in a little less recompilation.


Re: Blog post: What D got wrong

2018-12-20 Thread Neia Neutuladh via Digitalmars-d-announce
On Thu, 20 Dec 2018 14:19:33 +0100, Daniel Kozak wrote:
> default(attributes..) is no needed. You can already do this by:
> 
> pure @safe:
> // your code

That doesn't work if you have any member functions, and Walter says it's 
unlikely that that will ever change, even with a DIP.

default(pure) would be new syntax with no existing code broken.


Re: Blog post: What D got wrong

2018-12-19 Thread Neia Neutuladh via Digitalmars-d-announce
On Wed, 19 Dec 2018 17:28:01 +, Vijay Nayar wrote:
> Could you please elaborate a little bit more on this?  In the linked
> program, I had expected that "ref" would return a reference to "a" that
> would behave similar to a pointer.

They work like pointers that automatically dereference when assigning to 
the base type.

Only three things in D can be ref:
* A function parameter
* A function return value
* A foreach variable (since that's either going to be a function return 
value, a function parameter, or a pointer, depending on what you're 
iterating over)

So when the compiler sees something like:

ref int foo();
auto a = foo();

It sees that the type of 'a' has to be the same as the return type of 
'foo'. Except that's not possible, so it uses the nearest equivalent type: 
int.

And if you have:

ref int foo();
int a = foo();

That obviously converts by copying the value.


Re: Mixin operator 'if' directly

2018-12-19 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 19 Dec 2018 15:12:14 +, bauss wrote:
> That's assuming that it's compile-time data though.
> 
> If not then you can't do what you want to do.
> 
> What you can do is wrap it in a function in the mixin template which you
> just call after instantiating it.

Or while instantiating it:

mixin template foo()
{
  int _ignoreme()
  {
if (readln.strip == "abort") throw new AbortException;
return 1;
  }
  int _alsoIgnoreMe = _ignoreme();
}
void main()
{
  mixin foo;
}


Re: using dub to compile plugins

2018-12-19 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 19 Dec 2018 12:57:14 +, Codifies wrote:
> I could do this with a few simple rules in a Makefile, but I have no
> clue how to achieve this using dub.

If you need dub, you can create a wrapper script that generates the dub 
file for the plugins directory.

Make is a lot better for this kind of thing.


Re: Blog post: What D got wrong

2018-12-18 Thread Neia Neutuladh via Digitalmars-d-announce
On Wed, 19 Dec 2018 01:04:24 +, Nathan S. wrote:
> On Saturday, 15 December 2018 at 19:53:06 UTC, Atila Neves wrote:
>> Not the case in Rust, not the case in how I write D. TBH it's not such
>> a big deal because something has to be typed, I just default to const
>> now anyway instead of auto. @safe and pure though...
> 
> I'd be interested in seeing some of that Rust code. My impression from
> Clojure is that an all-immutable style requires leaning heavily on the
> garbage collector and as far as I know Rust has none.

It is greatly simplified by automatic memory management. Rust doesn't have 
a GC, but it has a complex ownership system instead, and that's the basis 
of its memory management. When that's insufficient, you use reference 
counting.

Besides which, this is about defaults. In cases where your data is 
actually mutable and it would be awkward to switch to a more Haskell-like 
way of coding, you can still use that.


Re: Blog post: What D got wrong

2018-12-18 Thread Neia Neutuladh via Digitalmars-d-announce
On Tue, 18 Dec 2018 08:17:28 +, Russel Winder wrote:
> I did a lightning talk at the GStreamer conference in Edinburgh a couple
> of months ago, concluding that I think D (which about half the audience
> knew of) is overall better than Rust for GTK+ and GStreamer
> applications, but recognising that Rust is actually the replacement for
> C and C++ for GTK+ and GStreamer applications. (Obviously Python has an
> ongoing role in all this as well.)

Is there a video link for that talk? I'd be interested in hearing it.


Re: saving std.random RNG state

2018-12-17 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 17 Dec 2018 22:20:54 +, harfel wrote:
> I am looking for a way to serialize/deserialize the state of the
> std.random.Random number generator, ideally using orange
> (https://github.com/jacob-carlborg/orange) or another serialization
> library. From looking at the module source code, I understand how to
> seed a random number generator with the state of another, but I do find
> a way to access the RNG's state, since it is hidden away in a private
> attribute. What is the recommended solution for this? Thanks in advance!

The .tupleof field allows you to access private members. This behavior 
might eventually change, but probably not without a long deprecation 
period.

If the struct stores everything by value:

cast(ubyte[])[0..1];

If you have typeinfo available, you can check if the thing has pointers 
with `(typeof(rng).flags & 1) == 0`. There's probably an equivalent in 
std.traits that works at compile time.


Re: A brief survey of build tools, focused on D

2018-12-15 Thread Neia Neutuladh via Digitalmars-d-announce
On Sun, 16 Dec 2018 00:17:55 +, Paul Backus wrote:
> On Wednesday, 12 December 2018 at 22:41:50 UTC, H. S. Teoh wrote:
>> It's time we came back to the essentials.  Current monolithic build
>> systems ought to be split into two parts: [...]
> You're missing (0) the package manager, which is probably the biggest
> advantage "monolothic" build tools like dub, cargo, and npm have
> compared to language-agnostic ones like make.

If I were to make a new build tool and wanted package manager integration, 
I'd choose Maven as the backend. This would no doubt be more frustrating 
than just making my own, but there would hopefully be fewer bugs on the 
repository side.

(I might separately make my own Maven-compatible backend.)

> There's something important you're glossing over here, which is that, in
> the general case, there's no single obvious or natural way to compose
> two DAGs together.

You do it like Bazel.

In Bazel, you have a WORKSPACE file at the root of your project. It 
describes, among other things, what dependencies you have. This might, for 
instance, be a git URL and revision. All this does is expose that 
package's build rules to you.

Separately, you have build rules. Each build rule can express a set of 
dependencies on other build rules. There's no difference between depending 
on a rule that your own code defines and depending on one from an external 
dependency.

It might be appropriate to have a hint on DAG nodes saying that this is 
the default thing that you should probably depend on if you're depending 
on the package. A lot of projects only produce one artifact for public 
consumption.


Re: Fuzzed - a program to find DMDFE parser crash

2018-12-15 Thread Neia Neutuladh via Digitalmars-d-announce
On Sat, 15 Dec 2018 21:09:12 +, Sebastiaan Koppe wrote:
> On Saturday, 15 December 2018 at 15:37:19 UTC, Basile B. wrote:
>> I think this is what Walter calls "AST poisoning" (never understood how
>> it worked before today). And the whole parser is like this.
>>
>> This poisoning kills the interest of using a fuzzer. 99% of the crashes
>> will be in hdrgen.
> 
> As is common with fuzzing, you'll need to ensure the program crashes.
> Sometimes that requires some tweaking.
> 
> Regardless, you still have the input to investigate.

I think the point is that DMD tries to recover from parsing failures in 
order to provide additional error messages. But those parsing failures 
leave the parser in an invalid state, and invalid states are fertile ground 
for crashes.

The way to fix this is to replace the entire parser and get rid of the 
idea of AST poisoning; at the first error, you give up on parsing the 
entire file. From there, you can try recovering from specific errors with 
proper testing.


Re: Shared static this() not executed for unittest

2018-12-15 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 15 Dec 2018 17:19:05 +, Timoses wrote:
> Running `dub test` will output:
> Running ./unit-test-library writeln: unittest All unit tests have been
> run successfully.
> 
> Why is the `shared static this()` not executed?

Run `dub clean; dub test -v` and you'll see that main.d isn't compiled 
into the test library.

dub test substitutes its own main() function over yours. In order to do 
this, it needs to not compile in your main() and to compile in its own. 
dmd doesn't have an option to replace main(), so dub drops that entire 
source file.


Re: How to initialize a globle variable nicely and properly?

2018-12-15 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 15 Dec 2018 13:49:03 +, Heromyth wrote:
> Yes, it's very dangerous to create a new thread in shared static this().
> For a big project, it sometimes hard to identify this problem. Maybe,
> the compiler should do something for this, should it?

The runtime, more likely. There are plenty of problems in this vein that 
the compiler can't detect, but the runtime should be able to detect all of 
them.

Filed https://issues.dlang.org/show_bug.cgi?id=19492


Re: How to initialize a globle variable nicely and properly?

2018-12-14 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 15 Dec 2018 02:54:55 +, Heromyth wrote:
>  shared static this() {
>  writeln("running A in shared static this(),
> sharedField=", sharedField);
> 
>  Thread th = new Thread(() {  });
>  th.start();

When you start a D thread, thread-local static constructors get run. So 
don't start threads until your shared static constructors finish.

If I encountered something like this, I would set up a queue of actions to 
be run at the start of main() and fill them with static constructors. 
Instead of this static constructor creating a thread, it would enqueue a 
delegate that starts the thread.


Re: Autowrap for .NET is Now Available

2018-12-14 Thread Neia Neutuladh via Digitalmars-d-announce
On Sat, 15 Dec 2018 00:43:42 +, j...@jjs.com wrote:
>>> Do you have plans to incorportae this as a VisualD project .csproj

Retaining the "On Sat, 15 Dec, Person A wrote:" lines is helpful for 
keeping track of the conversation.

> Using DLangInNet(I'm renamed your project for you ;)

Only the project maintainers have that authority. The project exposes D 
types and functions in Python, Excel, and .NET, so DLangInNet would be a 
terrible name for it.

> You should talk to Rainer about this. It shouldn't be all that difficult
> to do since C#'s PInvoke does all the real work. I assume DLangInNet
> just generates a C# equivalent that forwards all the calls to the D code
> using Pinvoke when necessary?

This is discussed in the Autowrap readme file.

> So the idea is that one can add .d files to .Net projects, when built:

Emitting the C# interface is a separate build target. You need to be able 
to specify Autowrap and the D compiler as dependencies. You need to hook 
this up into the build script.

> 2. DInNet runs on the D code and generates the C# output(could be
> modified for many other lannguages such as python, F#, Haskell, etc).
> Basically an autobinding generator from D to whatever, might be a good
> project to develop.

Perhaps a good name for that would be "Autowrap".

> The point of having it this way in Visual Studio is that one can on a
> single project that has many different languages involved and can setup
> a rather seamless connection.

Add a field to a wrapped D type and it won't show up on the C# side until 
you rebuild. This is not seamless. Making it seamless requires your IDE to 
know how the binding will be constructed and to have good support for 
every language you're using. Plus each language plugin needs to use a 
common set of data structures to represent your source code.

Technically, this isn't hard for a common set of languages, at least if 
you're only binding from a statically typed, strongly typed language with 
ideally little metaprogramming and in any case no ability to change types 
at runtime.

> What we need is an idea that just works and one can use any appropriate
> source language at any time and they all bind without hicup's in most
> cases.

Languages need a certain level of similarity for that to work. Haskell 
assumes immutability and would not work particularly well with a D 
function that mutates its input. Javascript objects can gain and lose 
fields and methods at runtime, something that D can't model well. A Python 
function can return a value of any type at all.



Re: Bug in shifting

2018-12-13 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 14 Dec 2018 00:16:51 +, Michelle Long wrote:
> byte x = 0xF;
> ulong y = x >> 60;

"Error: shift by 60 is outside the range 0..31"

This is the result of integer promotion rules. Change the 30 to a 60 and 
it works, and the result is, as you would expect, 0.

> I thought D required breaks for cases? Seems it doesn't any longer!

A number of things can terminate a case block:
* break
* continue
* goto
* assert
* throw
* return

Probably a few others.


Re: Blog post: What D got wrong

2018-12-13 Thread Neia Neutuladh via Digitalmars-d-announce
On Thursday, 13 December 2018 at 18:29:39 UTC, Adam D. Ruppe 
wrote:
Though, I think we could also get a lot of mileage out of 
fixing two glaring problems with the status quo: 1) making 
attr: at the top descend into aggregates consistently and 2) 
LETTING US TURN THEM OFF. SERIOUSLY WHY DON'T WE HAVE 
`virtual`, `throws`, `impure` AND THE REST?! THIS IS SO OBVIOUS 
AND THE LACK OF THEM IS UNBELIEVABLY FRUSTRATING.


While I might quibble about nothrow being the default, I wouldn't 
care once attributes descend into aggregates.


https://issues.dlang.org/show_bug.cgi?id=7616


Re: Blog post: What D got wrong

2018-12-13 Thread Neia Neutuladh via Digitalmars-d-announce

On Tuesday, 11 December 2018 at 10:45:39 UTC, Atila Neves wrote:
I think there’s a general consensus that @safe, pure and 
immutable should be default.


I recall there was a decent chunk of people around D2.007 who 
were pushing for const-by-default function parameters on the 
grounds of if we're going to have this controversial system, we 
may as well commit to it.


Also in the topic of defaults, you could potentially add inout as 
a default for member functions. It's a lot more strict, but no 
more so than immutable by default.


Re: A brief survey of build tools, focused on D

2018-12-12 Thread Neia Neutuladh via Digitalmars-d-announce

On Wednesday, 12 December 2018 at 22:41:50 UTC, H. S. Teoh wrote:
And here is the crux of my rant about build systems (earlier in 
this thread).  There is no *technical reason* why build systems 
should be constricted in this way. Today's landscape of 
specific projects being inextricably tied to a specific build 
system is completely the wrong approach.


You could reduce all this language-specific stuff to a way to 
generate a description of what needs to be built and what 
programs are suggested for doing it. This is quite a layer of 
indirection, and that means more work. "I can do less work" is a 
technical reason.


Ensuring that your output is widely usable is also extra work.

There is also a psychological reason: when you're trying to solve 
a set of problems and you are good at code, it's easy to tunnel 
vision into writing all the code yourself. It can even, 
sometimes, be easier to write that new code than to figure out 
how to use something that already exists (if you think you can 
gloss over a lot of edge cases or support a lot fewer pieces, for 
instance).


This is probably why Dub has its own repository instead of using 
Maven.


Seriously, building a lousy software project is essentially 
traversing a DAG of inputs and actions in topological order.  
The algorithms have been known since decades ago, if not 
longer, and there is absolutely no valid reason why we cannot 
import arbitrary sub-DAGs and glue it to the main DAG, and have 
everything work with no additional effort, regardless of where 
said sub-DAGs came from.  It's just a bunch of nodes and 
labelled edges, guys!  All the rest of the complications and 
build system dependencies and walled gardens are extraneous and 
completely unnecessary baggage imposed upon a straightforward 
DAG topological walk that any CS grad could write in less than 
a day.  It's ridiculous.


If any CS grad student could write it in a day, you could say 
that having a generic DAG isn't useful or interesting. That makes 
it seem pretty much useless to pull that out into a separate 
software project, and that's a psychological barrier.


Re: A brief survey of build tools, focused on D

2018-12-10 Thread Neia Neutuladh via Digitalmars-d-announce
On Mon, 10 Dec 2018 13:01:08 -0800, H. S. Teoh wrote:
> It also requires network access.  On *every* invocation, unless
> explicitly turned off.  And even then, it performs time-consuming
> dependency resolutions on every invocation, which doubles or triples
> incremental build times.  Again, unacceptable.

I feel like those should be configuration options at the very worst. And 
dub probably shouldn't even bother verifying your dependencies if you 
haven't changed dub.json.

> Then it requires a specific source layout, with incomplete /
> non-existent configuration options for alternatives.  Which makes it
> unusable for existing code bases.  Unacceptable.

A lot of people do find it acceptable to have a build tool that makes 
assumptions about your source code layout, but that's certainly not always 
possible or desirable.

> Worst of all, it does not support custom build actions, which is a
> requirement for many of my projects.

Yeah, there's a lot of neat metaprogramming stuff in D (like pegged) where 
it's awesome with small projects that it's part of compilation, but when 
I'm dealing with a nontrivial instance of it, I want to split it into a 
separate build step. Dub doesn't help me accomplish that.

> After so many decades of "advancement", we're still stuck in the
> gratuitously incompatible walled gardens, like the gratuitous browser
> incompatibilities of the pre-W3C days of the Web. And on modern CPUs
> with GHz clock speeds, RAM measured in GBs, and gigabit download speeds,
> building Hello World with a system like dub (or Gradle, for that matter)
> is still just as slow (if not slower!) as running make back in the 90's
> on a 4 *kHz* processor.  It's ridiculous.

Solving an NP-complete problem every time you build is not a great start.

> Why can't modern source code come equipped with dependency information
> in a *standard format* that can be understood by *any* build system?

Kythe is an attempt to make the relevant information available in a 
language-agnostic way. Might be a reasonable basis for a standardized 
build system. No clue how well it works or what it actually supports.

https://kythe.io/

> Build systems shouldn't need to reinvent their own gratuitously
> incompatible DSL just to express what's fundamentally the same old
> decades-worn directed graph. And programmers shouldn't need to repeat
> themselves by manually enumerating individual graph edges (like Meson
> apparently does).

Meson doesn't have you enumerate individual graph edges at that level. It 
just doesn't build your project correctly. Change a struct size in one 
file, and you get a host of weird errors when another file uses it.

Maven and Gradle also don't really have a DAG like that. If any file 
changed, your whole project needs to be rebuilt, and all your dependencies 
are immutable. Bazel has a DAG across build rules, not across individual 
files.

> - Efficient: the amount of work done by the build should be proportional
>   to the size of changes made to the source code since the last build,
>   NOT proportional to the size of the entire source tree (SCons fails in
>   this regard).

Would be great if the tool could pay attention to whether incremental 
builds saved time on average and just do a full build if it's better.

> - Language-agnostic: the build system should be essentially a dependency
>   graph resolver. It should be able to compile (possibly via plugins)
>   source code of any language using any given compiler, provided such a
>   combination is at all possible. In fact, at its core, it shouldn't
>   even have the concept of "compilation" at all; it should be able to
>   generate, e.g., .png files from POVRay scene description files, run
>   image post-processing tools on them, then package them into a tarball
>   and upload it to a remote webserver -- all driven by the same
>   underlying DAG.

You could support rsync just fine, but if it's just an HTTP upload, 
there's no standard way to tell if the server's got the file already.


Re: A brief survey of build tools, focused on D

2018-12-10 Thread Neia Neutuladh via Digitalmars-d-announce
On Tue, 11 Dec 2018 02:54:15 +, Mike Franklin wrote:
> Why not just write your build/tooling scripts in D?  That's what I
> prefer to do, and there's been a recent effort to do just that for the
> DMD compiler as well:
> https://github.com/dlang/dmd/blob/master/src/build.d  It still resembles
> the makefiles it was modeled from, but in time, I think it will clean up
> nicely.

That's fine for executables that don't depend on external libraries. It's 
not good for libraries that I want other people to use; dub's the easiest 
way to publish a thing. It also means I need to replicate that dependency 
graph logic in every single project, which is worse than replicating it 
once per language. We really should have a standard build tool supporting 
per-language plugins, like H. S. Teoh is recommending.


Re: A brief survey of build tools, focused on D

2018-12-10 Thread Neia Neutuladh via Digitalmars-d-announce
On Mon, 10 Dec 2018 21:53:40 +, GoaLitiuM wrote:
> The results for touching second file seems like an anomaly to me,

The generated ninja file had one rule per source file. If your modules 
tend to import each other a lot, or if they transitively import the code 
that's doing expensive stuff, then one rule per source file is bad. If 
your modules have few transitive dependencies and they're each fast to 
compile, one rule per source file is good.

My project used Pegged, and a lot of stuff referenced the grammar. That 
meant incremental builds went long and it would have been better to build 
the whole project at once.

Separating the grammar into a different build would reduce compile times 
significantly, and that might make incremental builds fast.

>From discussions on IRC about reducing compile times, though, using Phobos 
is a good way to get slow compilation, and I use Phobos. That alone means 
incremental builds are likely to go long.

> You also have to make sure the dependencies are built with the same
> compiler, which could explain the headache #3 in your article.

I've been using dmd as my primary compiler for ages, cleared out all the 
cached dub builds I could find, ran `dub build -v` to ensure that it was 
invoking dmd, and explicitly told Meson to use dmd.

Meson was still convinced that I'd built pegged with some other compiler.

> The comparison and some of the other headaches with meson does not seem
> to be fair as you are comparing dub, which is both a build system and a
> package manager, to meson which is only a build system, you have to make
> sure all the dependencies are installed to your system beforehand.

That *would* be a reasonable objection, but Meson explicitly advertises 
that you can use dub dependencies. The two flaws are the extra work 
required and the fact that it's broken. If it had not even pretended to 
support dub dependencies, I could have avoided several of the problems and 
just used git submodules from the start.

Just like with Bazel.


Re: How to set constant value to environment variable at compile time?

2018-12-10 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 10 Dec 2018 17:58:32 +, aliak wrote:
> string parseConfig(string str) {
>string ret;
>foreach (line; str.split("\n")) {
>  auto parts = line.split("=");
>  ret ~= `string ` ~ parts[0] ~ ` = "` parts[2] `";`;
>}
>return ret;
> }

That works as long as none of the environment variable values contain a 
double quote or a newline character.


Re: How to set constant value to environment variable at compile time?

2018-12-10 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 10 Dec 2018 11:08:23 +, Narxa wrote:
> Hello, people!
> 
> I would like to have a constant with the value of some environment
> variable that is defined at compile time.

In your build script, echo the environment variable into a file. Then 
import() that file and use the value.

> I know I could possibly use 'gdc' to achieve that but I want to use the
> 'dmd' compiler.

Defining variables like that is a language-level feature. gdc supports 
exactly the same options as dmd.


Re: dmd -unittest works poorly with executables

2018-12-08 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 08 Dec 2018 20:16:09 +, Andrew Pennebaker wrote:
> I think it's lame to have to use magical code like `version(unittest) {}
> else` to guard our main functions, when we run unit tests. Could D go
> ahead and do the right thing, automatically shadowing our main functions
> when the unit tests are run?

The original intent was for unittests to run before main(). Your debug / 
test builds always run the unittests. This is awkward because unittests 
might sometimes actually be heavier tests that talk to a database or write 
to local files or change global state that would be used in main().

The normal technique with dub is to put *only* main() in app.d. Sometimes 
I take that a step further: I put a runMain() function somewhere in my 
project, and app.d's main() just calls that. Dub automatically excludes 
app.d from the unittest build. Minimum possible code outside the tested 
zone.

Not necessarily awesome, but we do have workarounds.


Re: Compiling a template

2018-12-06 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 06 Dec 2018 22:50:49 +, albertas-jn wrote:
> If templates are a compile-time feature and instances of templates are
> generated by compiler at compile time, why is it possible to compile a
> template definition with dmd -lib or -c?

You compile files, not individual declarations like a template. If you 
have a source file containing a hundred templates and nothing else, and 
you compile it, you'll get the same output as if you had an empty source 
file, byte for byte.


Re: Trying to get current function name results in compiler error with __traits

2018-12-06 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 07 Dec 2018 02:37:34 +, Arun Chandrasekaran wrote:
> I'm trying to get the current function name and apparently the commented
> line errors out.
> 
> What am I doing wrong?

Referring to nested functions is weird.

Dotted identifiers let you traverse aggregates. Modules, C++ namespaces 
(ugh), enums, structs, identifiers, unions, that sort of thing. They 
*don't* let you traverse functions to refer to symbols defined inside 
those functions.

*Separately*, nested functions have names that look like dotted 
identifiers. But you can't use that to refer to them, because that would 
make it *very* awkward to do symbol lookup.

For example:

struct Foo { int bar; }
Foo test()
{
void bar() { }
writeln();
return Foo();
}

Should the `writeln` line invoke the `test` function, get the `bar` field 
from its result, and take its address? Or should it take the address of 
the nested function `bar`?


Re: .dup vs operation on all elements

2018-12-03 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 03 Dec 2018 21:27:52 +, faissaloo wrote:
> Then shouldn't the following output false, false, true?

An object reference is a pointer value. The pointer values are copied. The 
pointed-at objects are not copied.

Furthermore, the syntax

Object[6] array = new Object();

only allocates one Object. Each item in the array is an object reference 
to the same object.


Re: Visual D 0.48.0 released

2018-12-03 Thread Neia Neutuladh via Digitalmars-d-announce
On Mon, 03 Dec 2018 15:08:33 +, greatsam4sure wrote:
> It will be nice if you can port this code base to vs code. It is the
> same visual studio code base.

Pardon? VS Code is an Electron application written mainly in TypeScript, 
while Visual Studio is a Windows application written in C++ and C#. 
They're quite different codebases with quite different plugin 
architectures.


Re: what are the rules for @nogc and @safe attributes inference?

2018-11-30 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 30 Nov 2018 22:10:11 +, ikod wrote:
> Thanks for explanation, got it.
> 
> My case is actually
> 
> interface I(K,V)
> {
>  int get()(K);
> }

Interface functions must be abstract. Templated functions are implicitly 
final. Final things can't be abstract.

If there's something about types K and V that determine whether you should 
be able to use the GC or not, you'll have to encode that explicitly.


Re: what are the rules for @nogc and @safe attributes inference?

2018-11-30 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 30 Nov 2018 20:41:03 +, ikod wrote:
> I can't find the reason why nogc/nothrow can't be inferred in this case:
> 
> class S(K,V)
> {
>  auto get/*()*/(K a) {
>  return 0;
>  }
> }
> void main() @nogc nothrow {
>  S!(int, string) sia;
>  auto v = sia.get(1);
> }

class Nefarious : S!(int, string)
{
  override int get(int a)
  {
// Whoops, I used the GC
return new char[a].length;
  }
}

The compiler can't prove that a variable of type S!(int, string) will not 
be of type Nefarious, which uses the GC, so it can't infer @nogc for S.get.

However, if you make the function final, then the compiler can infer it to 
be pure nothrow @nogc @safe.

Or if you use a struct instead of a class, structs don't do inheritance, 
so the compiler can infer attributes without worrying about nefarious 
inheritance.

> But everything is ok if you uncomment parentheses after get.

Templated functions are implicitly final.


Re: Function signature as string

2018-11-29 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 29 Nov 2018 21:11:06 +, John Chapman wrote:
> Is there any way to get a string representing a function's exact
> signature as declared in the source? I can generate it myself using
> reflection but it might not be 100% verbatim so wanted to know if
> there's anything built in?
> 
>foreach (m; __traits(allMembers, T)) {
>  alias member = __traits(getMember, T, m);
>  string signature = // Call some function to get "member"'s
> signature as a string
>}

typeof().stringof should do it:

void bar(string s, ref Foo!int i) {}
void main()
{
writeln(typeof().stringof);
}

prints: void function(string s, ref Foo!int i)


Re: What can I use to parse a date string in a custom format?

2018-11-27 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 27 Nov 2018 18:22:17 +, PacMan wrote:
> I've been looking for a function or library to parse a date in a custom
> format (for validation) similar to C#'s [1]
> TryParseExactbut I couldn't find any. so far I only found
> fromISOExtString(), and fromSimpleString() which doesn't allow me to set
> a custom string format.

http://code.dlang.org/packages/datefmt didn't do it for you?

...that readme is pretty terrible, granted.


Re: How do I the temlate parameter name as string?

2018-11-26 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 27 Nov 2018 02:00:44 +, PacMan wrote:
> f is defined as:
> 
>> void f(T)(T t, string p)
>> if(is(T == A) || is(T == B))
>>{
>>  // ...
>>}
> 
> my goal is get "p" as string.

`f` is a template that generates functions. Before you instantiate that 
template, the function doesn't exist, so there's no function to get 
parameters from.

You can get the parameter names of any instantiation of that template, 
such as:

assert(ParameterIdentifierTuple!(f!A)[1] == "p");


Re: D Language 2.1

2018-11-25 Thread Neia Neutuladh via Digitalmars-d-learn
On Sun, 25 Nov 2018 20:46:28 +, Tony wrote:
> From std.compiler.D_major and std.compiler.D_minor I see that my D
> language version is at 2.0 . But the version of gdc front-end I am using
> (via Debian default gdc package as of a few months ago) from
> std.compiler.version_major and std.compiler.version_minor is at 2.68.

D_minor is 0 in both.
version_minor is 68 in your version of GDC, which matches version_minor 
for DMD 2.068.*.

> That is a lot of bug fixes, with 0 changes to the language.

In semantic versioning terms, the product is D2 and the current version is 
83.0.0.

> Actually, I realize that changes to the language are being reflected in
> compiler versions, not language versions. Just wondering why it was
> decided not to version the language (2.1, 2.2, etc.)

There are feature changes with every major compiler release, so it would 
be pointless complexity to version the language separate from DMD.


Re: How to get all modules in a package at CT?

2018-11-24 Thread Neia Neutuladh via Digitalmars-d-learn
Easiest way is to put this in your build script:

find path/to/package -name '*.d' | \
   xargs grep '^module ' | \
   sed 's,^module,import,' \
   > data/modules.d

Add `-J data` to your DMD command line, or add `"stringImportPaths":
["data"]` to dub.json.

Then in your file:

mixin(import("modules.d"));


Re: version(StdDoc)

2018-11-23 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 23 Nov 2018 21:43:01 -0700, Jonathan M Davis wrote:
> A solution like that might work reasonably well, but you still
> have the problem of what to do when a symbol is documented in multiple
> version blocks, and having almost all the documentation in one version
> block and a few pieces of it in other version blocks would risk getting
> confusing and messy.

Keeping symbol names and function arguments consistent between them is 
also an issue; it's not just the documentation. The normal solution is to 
put the version blocks inside the relevant symbols -- sometimes type 
aliases inside version blocks and consistent code outside, sometimes 
functions where the entire body is a set of version blocks.


Re: version(StdDoc)

2018-11-23 Thread Neia Neutuladh via Digitalmars-d-learn
On Fri, 23 Nov 2018 17:21:25 -0800, H. S. Teoh wrote:
> Ddoc may have its stink points, but in this case, the stuff inside
> version(Windows) blocks simply isn't compiled, so you can't expect ddoc
> to do much about it.  You can't just arbitrarily ddoc everything inside
> version blocks, because then you'll end up with ddocs for stuff inside
> version(none) and/or conflicting docs for alternative declarations in,
> say, OS-specific version blocks, or user-defined static if's.

That means that, instead of one site showing my project's documentation, I 
need a separate site for every combination of platform and version flags. 
And users who care about differences between platforms and version flags 
need to manually cross-reference docs for every symbol and overload.

It's a pretty terrible status quo.


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-22 Thread Neia Neutuladh via Digitalmars-d-learn
On Thu, 22 Nov 2018 15:50:01 +, Stefan Koch wrote:
> I'd say the problem here is not just false positives, but false
> negatives!

False negatives are a small problem. The compiler fails to catch some 
errors some of the time, and that's not surprising. False positives are 
highly vexing because it means the compiler rejects valid code, and that 
sometimes requires ugly circumlocutions to make it work.


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-21 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 21 Nov 2018 20:15:42 +, welkam wrote:
> In D classes are reference type and unless you mark them as final they
> will have vtable.

Even if you mark your class as final, it has a vtable because it inherits 
from Object, which has virtual functions. The ProtoObject proposal is for a 
base class that has no member functions. If you had a final class that 
inherited from ProtoObject instead of Object, it would have an empty 
vtable.

> Lets face it most people dont mark their classes as
> final. What all this mean is that EVERY access to class member value
> goes trough indirection (additional cost)

D classes support inheritance. They implicitly cast to their base types. 
They can add fields not present in their base types. If they were value 
types, this would mean you'd lose those fields when up-casting, and then 
you'd get memory corruption from calling virtual functions.

That is a cost that doesn't happen with structs, I'll grant, but the only 
way to avoid that cost is to give up inheritance. And inheritance is a 
large part of the reason to use classes instead of structs.

> and EVERY method call goes
> trough 2 indirections (one to get vtable and second to call
> function(method) from vtable).

Virtual functions do, that is. That's the vast majority of class member 
function calls.

> Now Java also have indirect vtable calls
> but it also have optimization passes that convert methods to final if
> they are not overridden. If Java didnt do that it would run as slow as
> Ruby.

Yeah, no.

https://git.ikeran.org/dhasenan/snippets/src/branch/master/virtualcalls/
results

Java and DMD both managed to de-virtualize and inline the function. DMD can 
do this in simple cases; Java can do this in a much wider range of cases 
but can make mistakes (and therefore has to insert guard code that will go 
back to the original bytecode when its hunches were wrong).

If it were merely devirtualization that were responsible for Java being 
faster than Ruby, Ruby might be ten times the duration of Java (just as 
dmd without optimizations is within times the duration of dmd without 
optimizations). You could also argue that `int += int` in Ruby is another 
virtual call, so it should be within twenty times the speed of Java.

Instead, it's 160 times slower than Java.

> On top of that some
> people want to check on EVERY dereference if pointer is not null. How
> slow you want your programs to run?

Every program on a modern CPU architecture and modern OS checks every 
pointer dereference to ensure the pointer isn't null. That's what a 
segfault is. Once you have virtual address space as a concept, this is 
free.

> Thats negatives but what benefit classes give us?
> First being reference type its easy to move them in memory. That would
> be nice for compacting GC but D doesnt have compacting GC.

You can do that with pointers, too. D doesn't do that because (a) it's 
difficult and we don't have the people required to make it work well 
enough, (b) it would make it harder to interface with other languages, (c) 
unions mean we would be unable to move some objects and people tend to be 
less thrilled about partial solutions than complete ones.

> Second they
> are useful for when you need to run code that some one else wrote for
> your project. Something like plugin system. [sarcasm]This is happening
> everyday[/sarcasm]
> Third porting code from Java to D.
> 
> Everything else you can do with struct and other D features.

Similarly, you can write Java-style object oriented code in C. It's 
hideously ugly and rather error-prone. Every project trying to do it would 
do it in a different and incompatible way.

Walter decided a long time ago that language support for Java-style OOP 
was a useful component for D to have, and having a standardized way of 
doing it with proper language support was better than leaving it to a 
library.


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-21 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 21 Nov 2018 17:00:29 +, Alex wrote:
> C# wouldn't reject the case above, would it?

C# *would* reject that (you can't call any methods on a null object), but 
in D, it compiles and runs and doesn't segfault.


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-20 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 20 Nov 2018 23:14:27 +, Johan Engelen wrote:
> When you don't call `a.foo()` a dereference, you basically say that
> `this` is allowed to be `null` inside a class member function. (and then
> it'd have to be normal to do `if (this) ...` inside class member
> functions...)

That's what we have today:

module scratch;
import std.stdio;
class A
{
int i;
final void f()
{
writeln(this is null);
writeln(i);
}
}
void main()
{
A a;
a.f();
}

This prints `true` and then gets a segfault.

Virtual function calls have to do a dereference to figure out which 
potentially overrided function to call.


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-20 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 20 Nov 2018 15:29:50 +, Kagamin wrote:
> On Tuesday, 20 November 2018 at 11:11:43 UTC, aliak wrote:
>> This only applies to little scripts and unittests maybe.
>>
>> Not when you're writing any kind of relatively larger application that
>> involves being run for longer or if there's more possible permutations
>> of your state variables.
> 
> Umm... if you write a larger application not knowing what is a reference
> type, you're into lots and lots of problems.

A pointer to a struct is a reference type.

There are plenty of cases where you need reference semantics for a thing. 
If you are optimistic about the attentiveness of your future self and 
potential collaborators, you might add that into a doc comment; people can 
either manually do escape analysis to check if they can store the thing on 
the stack, or allocate on the heap and pass a pointer, or embed the thing 
as a private member of another thing that now must be passed by reference.

If you're pessimistic and don't mind a potential performance decrease, you 
might defensively use a class to ensure the thing is a reference type.


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-19 Thread Neia Neutuladh via Digitalmars-d-learn
On Tue, 20 Nov 2018 00:30:44 +, Jordi Gutiérrez Hermoso wrote:
> On Monday, 19 November 2018 at 21:57:11 UTC, Neia Neutuladh wrote:
> 
>> Programmers coming from nearly any language other than C++ would find
>> it expected and intuitive that declaring a class instance variable
>> leaves it null.
> 
> What do you think about making the syntax slightly more explicit and
> warn or possibly error out if you don't do it that way?

The prevailing idea is that warnings are either non-problems, in which 
case they shouldn't be emitted, or things you really need to fix, in which 
case they should be errors.

Things that are sometimes errors can be left to lint tools.

> Either
> 
>SomeClass c = null;
> 
> or
> 
>SomeClass c = new SomeClass();
> 
> and nothing else.

That would work, though it would be mildly tedious.

However, the general philosophy with D is that things should be implicitly 
initialized to a default state equal to the `.init` property of the type. 
That default state can be user-defined with structs, but with other types, 
it is generally an 'empty' state that has well-defined semantics. For 
floating point values, that is NaN. For integers, it's 0. For arrays, it's 
a null array with length 0. For objects and pointers, it's null.

> Nulls/Nones are always a big gap in a language's type system. A common
> alternative is to have some Option/Maybe type like Rust or Haskell or
> D's Variant.

Variant is about storing arbitrary values in the same variable. Nullable 
is the D2 equivalent of Option or Maybe.

> How about making that required to plug the null gap?

That's extremely unlikely to make it into D2 and rather unlikely to make 
it into a putative D3. However, if you feel strongly enough about it, you 
can write a DIP.

I've used Kotlin with its null safety, and I honestly haven't seen 
benefits from it. I have seen some NullPointerExceptions in slightly 
different places and some NullPointerExceptions instead of empty strings in 
log messages, but that's it.


Re: What is best way to read and interpret binary files?

2018-11-19 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 19 Nov 2018 14:32:55 -0800, H. S. Teoh wrote:
>> Standard caveats about byte order and alignment.
> 
> Alignment shouldn't be a problem, since local variables should already
> be properly aligned.

Right, and the IO layer probably doesn't need to read to aligned memory 
anyway.

Struct fields, however, need to have the same relative alignment as the 
file.


Re: What is best way to read and interpret binary files?

2018-11-19 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 19 Nov 2018 21:30:36 +, welkam wrote:
> So my question is in subject/title. I want to parse binary file into D
> structs and cant really find any good way of doing it. What I try to do
> now is something like this
> 
> byte[4] fake_integer;
> auto fd = File("binary.data", "r");
> fd.rawRead(fake_integer);
> int real_integer = *(cast(int*)  fake_integer.ptr);
> 
> What I ideally want is to have some kind of c style array and just cast
> it into struct or take existing struct and populate fields one by one
> with data from file. Is there a D way of doing it or should I call
> core.stdc.stdio functions instead?

Nothing stops you from writing:

SomeStruct myStruct;
fd.rawRead((cast(ubyte*))[0..SomeStruct.sizeof]);

Standard caveats about byte order and alignment.


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-19 Thread Neia Neutuladh via Digitalmars-d-learn
On Mon, 19 Nov 2018 21:23:31 +, Jordi Gutiérrez Hermoso wrote:
> When I was first playing with D, I managed to create a segfault by doing
> `SomeClass c;` and then trying do something with the object I thought I
> had default-created, by analogy with C++ syntax. Seasoned D programmers
> will recognise that I did nothing of the sort and instead created c is
> null and my program ended up dereferencing a null pointer.

Programmers coming from nearly any language other than C++ would find it 
expected and intuitive that declaring a class instance variable leaves it 
null.

The compiler *could* give you a warning that you're using an uninitialized 
variable in a way that will lead to a segfault, but that sort of flow 
analysis gets hard fast.

If you wanted the default constructor to be called implicitly, that would 
make @nogc functions behave significantly differently (they'd forbid 
declarations without explicit initialization or would go back to default 
null), and it would be a problem for anything that doesn't have a no-args 
constructor (again, this would either be illegal or go back to null).

Easier for everything to be consistent and everything to be initialized to 
null.


Re: Neater enum + version

2018-11-18 Thread Neia Neutuladh via Digitalmars-d-learn
On Sun, 18 Nov 2018 17:47:07 +, Vladimirs Nordholm wrote:
> Is there anyway to make it "neater"? Maybe something in one line:
> 
>  enum foo = version (Posix) { "posix" } : { "other" } ;

If you're doing it often:

T ifPosix(T)(T a, T b)
{
  version (Posix) return a; else return b;
}
enum foo = ifPosix("posix", "other");

If it's a one-off thing, though, there's not much you can do.


Re: How do you debug @safe @nogc code? Can't figure out how to print.

2018-11-17 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 17 Nov 2018 21:16:13 +, aliak wrote:
> Could do. But it's not scalable. I'd have to comment out all the
> unittests that call the template function with a T that allocates inside
> the @nogc template (if I understood you correctly that it)

I meant something like:

void debugln(T...)(T args) @nogc
{
  import std.stdio;
  debug(MyProject) writeln(args);
}

You use that function instead of writeln in your @nogc-compatible 
templates:

void callFunc(alias func)()
{
  debugln("about to call function!");
  func();
  debugln("done calling function!");
}

Then I can write:

@nogc:
void foo() { printf("hello world\n"); }
void main() { callFunc!foo(); }


Re: Making external types available to mixins

2018-11-17 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 17 Nov 2018 17:58:54 +, John Chapman wrote:
> The idea is that users could type (for example) makeWith!`Calendar`(…)
> instead of the longer makeWith!ICalendarFactory(…).

Your project might define a hundred types named ICalendarFactory; the 
compiler can't figure out which one you're talking about unless you use 
the fully qualified name.

If you require that Calendar and ICalendarFactory be defined in the same 
module, you can use Calendar's module name to look up the appropriate 
ICalendarFactory.

You can also just build a string that the calling code mixes in.


Re: How do you debug @safe @nogc code? Can't figure out how to print.

2018-11-17 Thread Neia Neutuladh via Digitalmars-d-learn
On Sat, 17 Nov 2018 13:55:24 +, aliak wrote:
> You can use "debug blah" to hide inside functions that are attributed,
> but when you have an attributed function that calls a template,
> attribtues of which are supposed to be inferred, it seems to fail.

You can explicitly mark a templated function as @nogc. If you want your 
function's @nogc-ness inferred, you can pull out the debug logging into a 
separate function and explicitly mark it @nogc.


Re: DIP 1015--Deprecation of Implicit Conversion of Int. & Char. Literals to bool--Formal Assement

2018-11-14 Thread Neia Neutuladh via Digitalmars-d-announce
On Wed, 14 Nov 2018 13:40:46 -0500, Steven Schveighoffer wrote:
> You don't think this is confusing?
> 
> enum A : int {
>  val
> }
> 
> A a;
> foo(a); // error: be more specific
> int x = a;
> foo(x); // Sure

I find this confusing:

void foo(int i) {}
void foo(ubyte b) {}
enum A : int { val = 0 }
foo(A.val);  // calls foo(ubyte)
A a = A.val;
foo(a);  // calls foo(int)

If it instead produced an error, the error would look like:

Error: foo called with argument types (E) matches both:
example.d(1): foo(int i)
and:
example.d(2): foo(ubyte i)

Or else:

Error: none of the overloads of foo are callable using
argument types (A), candidates are:
example.d(1): foo(int i)
example.d(2): foo(ubyte i)

These aren't the intuitively obvious thing to me, but they're not going to 
surprise me by calling the wrong function, and there are obvious ways to 
make the code work as I want. Of the two, I'd prefer the former.

The intuitively obvious thing for me is:

* Don't use VRP to select an overload. Only use it if there's only one 
candidate with the right number of arguments.
* Don't use VRP if the argument is a ctor, cast expression, or symbol 
expression referring to a non-builtin. Maybe disallow with builtins.
* Don't use VRP if the argument is a literal with explicitly indicated type 
(0UL shouldn't match to byte, for instance).

I think this would make things more as most people expect:

foo(A.val);  // A -> int, but no A -> byte; calls foo(int)
foo(0);  // errors (currently calls foo(int))
foo(0L); // errors (currently calls foo(ubyte))
foo(cast(ulong)0);  // errors (currently calls foo(ubyte))

And when there's only one overload:

void bar(byte b) {}
bar(A.val);  // errors; can't convert A -> byte
bar(0);  // type any-number and fits within byte, so should work
bar(0UL);// errors; explicit incorrect type
bar(0UL & 0x1F);// bitwise and expression can do VRP
bar("foo".length);  // length is a builtin; maybe do VRP?
bar(byte.sizeof);   // sizeof is a builtin; maybe do VRP?


Re: Could not setup D extension on vs code

2018-11-14 Thread Neia Neutuladh via Digitalmars-d-learn
On Wed, 14 Nov 2018 19:28:44 +, WebFreak001 wrote:
> It's a real pain that you can't select specific commits in dub, but I
> try to keep up with the updates and make them work somehow.

Yeah, I've used submodules and path-based dependencies once or twice 
because of that. It's not the best.


Re: DIP 1015--Deprecation of Implicit Conversion of Int. & Char. Literals to bool--Formal Assement

2018-11-14 Thread Neia Neutuladh via Digitalmars-d-announce
On Tue, 13 Nov 2018 20:27:05 -0800, Walter Bright wrote:
> There have been various attempts over the years to "fix" various things
> in the D matching system by adding "just one more" match level.

I kind of feel like, if something would be confusing like this, maybe the 
compiler shouldn't be making an automatic decision. Not "just one more" 
match level, but just...don't match. If there are multiple matching 
overloads, just error out. Don't try to be clever and surprise people, 
just tell the user to be more explicit.


  1   2   3   4   >