Re: is my code to get CTFE instantiated object valid D ?

2016-05-28 Thread Mike Parker via Digitalmars-d-learn

On Sunday, 29 May 2016 at 05:35:33 UTC, Mike Parker wrote:

Well then, this completely breaks my understanding of variable 
scope.


OK, I see now at [1] the following:

" Immutable data doesn't have synchronization problems, so the 
compiler doesn't place it in TLS."


I've read that page more than once, but I had forgotten this bit. 
Still, I don't see anything there about const. I would not expect 
const variables to behave the same way, given the weaker 
guarantee about modification. But if they are intended to behave 
that way, then, IMO, it should not be possible to reinitialize 
them in a static constructor.


https://dlang.org/migrate-to-shared.html


Re: is my code to get CTFE instantiated object valid D ?

2016-05-28 Thread Mike Parker via Digitalmars-d-learn

On Saturday, 28 May 2016 at 15:39:44 UTC, ag0aep6g wrote:

On 05/28/2016 10:34 AM, Mike Parker wrote:

On Saturday, 28 May 2016 at 05:30:26 UTC, chmike wrote:

[...]

Is a static const Category c variable a TLS variable ?


Yes. All variables are TLS unless explicitly marked with 
__gshared or

shared.


I don't think that's true.



Prints (for example):

7F554F9E1710 695FF0 695FF4
7F554EDDA5D0 695FF0 695FF4


So there are two different `m`s, but the `c`s and `i`s have the 
same address on both threads. Seems to me that `m` is in TLS, 
but `c` and `i` are not.


Well then, this completely breaks my understanding of variable 
scope. Consider this:


--
class Foo {
int x;
this(int i) { x = i; }
}

class Bar {
static const Foo f;
static this() {
__gshared static firstRun = true;
f = new Foo(firstRun ? 10 : 20);
firstRun = false;

import std.stdio;
writeln("static con");
}
}

void main() {
import core.thread;
print();
new Thread().start();
Thread.sleep(1.seconds);
print();

}

void print() {
import std.stdio;
writefln("Bar.f.x = %s,  = %s", Bar.f.x, );
}


The static constructor is run per thread. The second iteration 
reinitializes the const reference 'f' with a new instance. Not at 
all what I would expect. IMO, either its a bug that there is only 
one instance of 'f', or it's a bug that it can be reinitialized.


Re: standard alias for a class name inside the class code?

2016-05-28 Thread dan via Digitalmars-d-learn

On Sunday, 29 May 2016 at 02:44:33 UTC, jhps wrote:

On Sunday, 29 May 2016 at 00:48:20 UTC, dan wrote:

Especially in a declaration like
static typeof(this) make_instance( )
but also in the 'new typeof(this)'.  In both cases, 'this' 
doesn't even exist.



https://dlang.org/spec/declaration.html#Typeof

it's another 'this' that has not the same semantic as the 
reference holder.

Just like 'const' can have 3 meanings, 'this' also:

- this.member: typical usage, it hold the instance reference
- void foo(this T)(): template this parameter, T is 
typeof(this) where the template is used.
- typeof(this): you can use it in static func, this 'this' is 
not the 'this' instance.


OK, thanks JHPS for the detailed explanation of this construction 
Mithun pointed out, and also for the link.  It makes a lot of 
sense the way you put it.




Re: standard alias for a class name inside the class code?

2016-05-28 Thread jhps via Digitalmars-d-learn

On Sunday, 29 May 2016 at 00:48:20 UTC, dan wrote:

Especially in a declaration like
static typeof(this) make_instance( )
but also in the 'new typeof(this)'.  In both cases, 'this' 
doesn't even exist.



https://dlang.org/spec/declaration.html#Typeof

it's another 'this' that has not the same semantic as the 
reference holder.

Just like 'const' can have 3 meanings, 'this' also:

- this.member: typical usage, it hold the instance reference
- void foo(this T)(): template this parameter, T is typeof(this) 
where the template is used.
- typeof(this): you can use it in static func, this 'this' is not 
the 'this' instance.


Re: standard alias for a class name inside the class code?

2016-05-28 Thread dan via Digitalmars-d-learn

On Sunday, 29 May 2016 at 00:28:13 UTC, Mithun Hunsur wrote:

On Sunday, 29 May 2016 at 00:14:17 UTC, dan wrote:

Is there a standard alias for a class name inside class code?

Something like 'this' referring to a class instance, but 
referring instead to the class itself?


[...]


typeof(this) gets you the type of the current class. :)


Great!!

Thanks Mithun!

That certainly works.

But i sure don't understand how.

Especially in a declaration like
static typeof(this) make_instance( )
but also in the 'new typeof(this)'.  In both cases, 'this' 
doesn't even exist.


In fact, if you make a reference to this inside the static 
function make_instance(), you get an error:
'this' is only defined in non-static member functions, not 
make_instance


So the compiler itself states that 'this' is not defined.

But nevertheless, your method absolutely does work.

So i suppose i should not look a gift horse in the mouth, but i'm 
still puzzled.


Anyhow, thanks a million, because whether or not i understand 
your idiom, it is exactly what i need.


dan


Re: @trusting generic functions

2016-05-28 Thread Era Scarecrow via Digitalmars-d-learn

On Saturday, 28 May 2016 at 14:54:13 UTC, Era Scarecrow wrote:
 Well here's what i got. Maybe someone else will tell me how i 
did this wrong...


 Using the pragma to output how the lines were being generated i 
finally figured out why it kept complaining about the stack 
pointer and 'this'. So adding in a simple check to ignore 'this' 
entries.


So, final version:

bool areAllFunctionsSafe(T)() {
  foreach(member; __traits(allMembers, T)) {
static if(member!="this" && isCallable!(__traits(getMember, 
T, member)))

  if (!isSafe!(__traits(getMember, T, member))) return false;
  }
  return true;
}



Re: standard alias for a class name inside the class code?

2016-05-28 Thread Mithun Hunsur via Digitalmars-d-learn

On Sunday, 29 May 2016 at 00:14:17 UTC, dan wrote:

Is there a standard alias for a class name inside class code?

Something like 'this' referring to a class instance, but 
referring instead to the class itself?


[...]


typeof(this) gets you the type of the current class. :)


standard alias for a class name inside the class code?

2016-05-28 Thread dan via Digitalmars-d-learn

Is there a standard alias for a class name inside class code?

Something like 'this' referring to a class instance, but 
referring instead to the class itself?


What i would like to do is have something like

class Clas {
   // alias Clas THIS; <- don't want this boilerplate
   static THIS make_instance(  ) {
   auto x = new THIS( );
   
   return x;
   }
}

This would be great for copy/paste, changing class names, and in 
general communicating your intention.


I'm guessing the answer is no, and that there's some compelling 
reason why a compiled language wouldn't want to provide this 
feature.  (But the php interpreter, whatever else is good or bad 
about it, does let you write 'new self(...)' and does the right 
thing with it.)


TIA for any clues.

dan


Re: is my code to get CTFE instantiated object valid D ?

2016-05-28 Thread ag0aep6g via Digitalmars-d-learn

On 05/28/2016 09:54 PM, chmike wrote:

The only inconvenience left is that we can't have mutable references
to immutable objects.


There is std.typecons.Rebindable for that.


Re: I wrote a function that accepts input ranges, and I get compile errors when passing an array

2016-05-28 Thread Seb via Digitalmars-d-learn

On Saturday, 28 May 2016 at 20:43:00 UTC, pineapple wrote:

On Saturday, 28 May 2016 at 16:25:02 UTC, Seb wrote:
If you are interested how it works under the hood - it's 
pretty simple & elegant:


I checked up on the phobos implementation and found that arrays 
are mutated when iterated over as ranges, which didn't rest 
well with me. Nor did the idea of importing some module having 
such a significant side-effect as whether some type can act as 
a range or not. So I ended up making a sort of factory that 
turns arbitrary objects into ranges, including arrays. Seems to 
work pretty well.


Arrays in D work differently to other languages. That's why we 
call them Slices ;-)


See: https://dlang.org/d-array-article.html

Phobos just modifies the pointer - so `a = a[1 .. $];` is nothing 
more than creating a new pointer.



are mutated when iterated over as ranges,


Btw all ranges are modified during iteration, they have a state 
and with every popFront you change that. If you want to save the 
state before, you can call `.save` if it's at least a ForwardRange


Re: I wrote a function that accepts input ranges, and I get compile errors when passing an array

2016-05-28 Thread pineapple via Digitalmars-d-learn

On Saturday, 28 May 2016 at 16:25:02 UTC, Seb wrote:
If you are interested how it works under the hood - it's pretty 
simple & elegant:


I checked up on the phobos implementation and found that arrays 
are mutated when iterated over as ranges, which didn't rest well 
with me. Nor did the idea of importing some module having such a 
significant side-effect as whether some type can act as a range 
or not. So I ended up making a sort of factory that turns 
arbitrary objects into ranges, including arrays. Seems to work 
pretty well.


Re: is my code to get CTFE instantiated object valid D ?

2016-05-28 Thread chmike via Digitalmars-d-learn

On Friday, 27 May 2016 at 20:20:36 UTC, chmike wrote:

I need to create an app wide singleton instance for my class.
The singleton is immutable, but I want to allow mutable 
references to that singleton object so that I can do fast 'is' 
tests.


I declared this

class Category
{
 protected static immutable Category instance_ = new 
Category;

 Category instance() { return cast(Category)instance_; }
 ...
}

It compiles and the instance should be instantiated at compile 
time. I couldn't check yet.


The public interface of Category is designed so that the 
object's state can't be modified and thus remains immutable.


Is this code valid D or is the behavior undefined due to the 
cast ?



A variant implementation would have a method that modifies the 
object but only internally and in a very controlled way to 
store strings in a cache for faster access. Would it still be 
valid D code ?



I answer to myself on this question because I finally found out.

Creating an app wide singleton object is as simple as this

class Category
{
this() { assert __ctfe); } // Just to make sure
private __gshared instance_ = new Info;
static Category instance() { return _instance; }
}


It works as long as the constructor doesn't reference other 
global or static variables.


Unfortunately this is what I have in my use case. I had this

final class Info
{
Info(Category category, string name)
{
category_ = category;
name_ = name;
assert(__ctfe);
}
private string name_;
private Category category_;
string name() { return name_; }
Category category() { return category_; }
}

This class can't be instantiated as compile time because the 
constructor depends on the global variable Category.instance_.


Category {
...
__gshared Info a1 = new Info(Category.instance(), "I'm a1");
__gshared Info a2 = new Info(Category.instance(), "I'm a2");
...
}


The problem is solved by changing Category into an immutable 
class and instance. It's Ok in my case because it is immutable. 
The only inconvenience left is that we can't have mutable 
references to immutable objects.


But at least now I can write

Info x1 = Cateqory.a1, x2 = Category.a2;
Info x3 = x1, x4;

assert(x3 is x1);
assert(x3 !is x2);
assert(x1.category is x2.category);
assert(x4 is null);

And of course we can also access all the properties of the Info 
values. Objects are identified by their unique address.


Another problem left is that synchronization


Re: Does this C callback call look correct?

2016-05-28 Thread WhatMeWorry via Digitalmars-d-learn
Never mind.  D was fine. Needed an alureUpdate() to trigger the 
call back.


Re: Is it possible to forbid synchronization on an object ?

2016-05-28 Thread Meta via Digitalmars-d-learn

On Saturday, 28 May 2016 at 16:24:21 UTC, chmike wrote:
In my long quest to implement a flyweight pattern with objects 
instantiated at compile time, I was indirectly notified of the 
possible problem of synchronization.


In a flyweight pattern the user has the impression there are 
distinct instances where in fact objects with the same state 
(member variable value) are the same instance.


Since with play a trick with the users assumption, there is a 
high risk that user produces logically invalid code when using 
synchronization with such a flyweight object.


In order to avoid this problem I would need a solution to make 
synchronization impossible on an object ? It is preferable if 
this could be enforced at compile time. Is this possible with D 
? 


Not currently. However, there was a proposal to remove monitors 
from objects by default unless they have a special UDA on them, 
so if that change ever goes through it's as simple as not 
annotating your class.


https://github.com/dlang/druntime/pull/789


Re: I wrote a function that accepts input ranges, and I get compile errors when passing an array

2016-05-28 Thread Seb via Digitalmars-d-learn

On Friday, 27 May 2016 at 14:59:25 UTC, Adam D. Ruppe wrote:

On Friday, 27 May 2016 at 14:54:30 UTC, pineapple wrote:
I've encountered one remarkable difference: The phobos 
function accepts arrays and mine does not.


add `import std.array;` i think to your module and it should 
make arrays ranges


you would get a more fine-grained import with
std.range (or more even more detailed std.range.primitives).

If you are interested how it works under the hood - it's pretty 
simple & elegant:


https://github.com/dlang/phobos/blob/master/std/range/primitives.d#L2038



Re: is my code to get CTFE instantiated object valid D ?

2016-05-28 Thread ag0aep6g via Digitalmars-d-learn

On 05/28/2016 06:09 PM, chmike wrote:

In the following instruction of the above commit, what effect has the []
after init ?

  _store[0 .. __traits(classInstanceSize, T)] = typeid(T).init[];

T is a template argument that is a class derived from Error.

I couldn't find an explanation here
https://dlang.org/spec/property.html#init.

I saw that this is a concise implementation of what is being done in
emplace().


`typeid(T).init` is a different `init` than the one you linked. We have 
since renamed it to `initializer` to fix the name clash.


Documentation is here:
http://dlang.org/phobos/object.html#.TypeInfo.initializer

As you can see there, it's a `const(void)[]`.

The statement is a form of "array copying":
http://dlang.org/spec/arrays.html#array-copying

As you can see there, it would also work without the `[]`. With them 
it's a bit clearer that array copying is going on, and not "array 
setting" (next section on the spec page).


Is it possible to forbid synchronization on an object ?

2016-05-28 Thread chmike via Digitalmars-d-learn
In my long quest to implement a flyweight pattern with objects 
instantiated at compile time, I was indirectly notified of the 
possible problem of synchronization.


In a flyweight pattern the user has the impression there are 
distinct instances where in fact objects with the same state 
(member variable value) are the same instance.


Since with play a trick with the users assumption, there is a 
high risk that user produces logically invalid code when using 
synchronization with such a flyweight object.


In order to avoid this problem I would need a solution to make 
synchronization impossible on an object ? It is preferable if 
this could be enforced at compile time. Is this possible with D ? 


Re: is my code to get CTFE instantiated object valid D ?

2016-05-28 Thread chmike via Digitalmars-d-learn

On Saturday, 28 May 2016 at 08:47:48 UTC, Kagamin wrote:
For a trick of static mutable allocation see 
https://github.com/dlang/druntime/pull/1325


In the following instruction of the above commit, what effect has 
the [] after init ?


 _store[0 .. __traits(classInstanceSize, T)] = typeid(T).init[];

T is a template argument that is a class derived from Error.

I couldn't find an explanation here 
https://dlang.org/spec/property.html#init.


I saw that this is a concise implementation of what is being done 
in emplace().





Re: Easier way to add libraries to visual d?

2016-05-28 Thread Basile B. via Digitalmars-d-learn

On Saturday, 28 May 2016 at 15:31:18 UTC, TheDGuy wrote:

On Saturday, 28 May 2016 at 15:29:36 UTC, TheDGuy wrote:


Thanks a lot for the fast hot fix, now everything works fine! 
:) Great IDE!


Do you mind implementing an option to reset the layout to 
default? Because i think i messed up and no i don't know how i 
can get the file view for the project (which was originally on 
the left side) back?


You must delete the option file that's name "docking.xml", so 
under windows in the folder appdata\roaming\coedit. Once done, 
rebuild your layout and most important: 'lock it' ! It also 
happened to me some time to time.


See also the wiki: https://github.com/BBasile/Coedit/wiki#docking

Another way to preserve the docking is to kill the application by 
hand, so that the new xml is not written. But this is not always 
doable since in this case no settings are saved at all (e.g if a 
new custom tool was added or a new libman entry then they're 
lost).


Re: is my code to get CTFE instantiated object valid D ?

2016-05-28 Thread ag0aep6g via Digitalmars-d-learn

On 05/28/2016 10:34 AM, Mike Parker wrote:

On Saturday, 28 May 2016 at 05:30:26 UTC, chmike wrote:

[...]

Is a static const Category c variable a TLS variable ?


Yes. All variables are TLS unless explicitly marked with __gshared or
shared.


I don't think that's true.


import core.thread;
import std.stdio;

int m;
const int c;
immutable int i;

void main()
{
printAddresses();
new Thread().start();
}

void printAddresses() { writeln(, " ", , " ", ); }


Prints (for example):

7F554F9E1710 695FF0 695FF4
7F554EDDA5D0 695FF0 695FF4


So there are two different `m`s, but the `c`s and `i`s have the same 
address on both threads. Seems to me that `m` is in TLS, but `c` and `i` 
are not.


Re: Easier way to add libraries to visual d?

2016-05-28 Thread TheDGuy via Digitalmars-d-learn

On Saturday, 28 May 2016 at 15:29:36 UTC, TheDGuy wrote:


Thanks a lot for the fast hot fix, now everything works fine! 
:) Great IDE!


Do you mind implementing an option to reset the layout to 
default? Because i think i messed up and no i don't know how i 
can get the file view for the project (which was originally on 
the left side) back?


Re: Easier way to add libraries to visual d?

2016-05-28 Thread TheDGuy via Digitalmars-d-learn

On Saturday, 28 May 2016 at 13:25:14 UTC, Basile B. wrote:


I've released a hot fix yesterday and now it works with latest 
DUB tag (0.9.25).


But registering from the project that's loaded was already 
working yesterday. I think that you have forgotten to choose 
the right configuration to compile, example with serial-port:


http://imgur.com/7wAwqPz

- open the dub json
- to the left, the DUB inspector: the green arrow must be on a 
config that's dedicated to build the library

- double click to select a config
- compile the project
- to the bottom library manager: click the icon with a book and 
link on the top


Thanks a lot for the fast hot fix, now everything works fine! :) 
Great IDE!


Re: @trusting generic functions

2016-05-28 Thread Era Scarecrow via Digitalmars-d-learn

On Saturday, 28 May 2016 at 14:11:56 UTC, Lodovico Giaretta wrote:

On Saturday, 28 May 2016 at 14:01:35 UTC, Era Scarecrow wrote:

 Do you still want the template i'm building?


Thank you very much for your effort.
Please if you don't need it, don't make it, because I don't 
know if I'll use it.


 Well here's what i got. Maybe someone else will tell me how i 
did this wrong...


[code]
import std.traits;

template areAllFunctionsSafe(T)
if (!isNested!T) { //nested may be lifted later when i fix this
  enum areAllFunctionsSafe = check();

  bool check() {
foreach(member; __traits(allMembers, T)) {
  static if(isCallable!(__traits(getMember, T, member))) {
if (!isSafe!(__traits(getMember, T, member)))
  return false;
  }
}
return true;
  }
}

unittest {
  static struct S {
int y;
void foo() @safe {}
void bar() @safe {}
  }
  static struct S2 {
int y;
void foo() @safe {}
void bar() {}
  }

  assert(areAllFunctionsSafe!S);
  assert(!areAllFunctionsSafe!S2);
}
[/code]


Re: @trusting generic functions

2016-05-28 Thread ag0aep6g via Digitalmars-d-learn

On 05/28/2016 02:43 PM, Lodovico Giaretta wrote:

struct S1
{
 int doSomething() @safe
 {
 // do something safely
 return 1;
 }
}

struct S2
{
 int doSomething() @system
 {
 // do something usafe
 return 2;
 }
}

auto doSomethingDumb(T)(ref T t)
{
 T* pt = 
 return pt.doSomething();
}

auto s1 = S1();
auto s2 = S2();
auto x = doSomethingDumb(s1); // this call should be possible in @safe code
auto y = doSomethingDumb(s2); // this should only be possible in @system
code


I'm not sure if should mention it, but there is this little trick:


auto doSomethingDumb(T)(ref T t)
{
T* pt;
() @trusted { pt =  } (); /* Ok, because the reference is never 
returned. NOTE: DON'T RETURN THIS POINTER! */

return pt.doSomething();
}


Though in cases like this it's kind of an anti-pattern. The trusted code 
itself isn't actually safe, but the compiler thinks so. So you have to 
manually verify that doSomethingDumb is safe, even though it's not 
marked @trusted. That's pretty bug-prone.


Re: @trusting generic functions

2016-05-28 Thread Era Scarecrow via Digitalmars-d-learn

On Saturday, 28 May 2016 at 14:11:56 UTC, Lodovico Giaretta wrote:

On Saturday, 28 May 2016 at 14:01:35 UTC, Era Scarecrow wrote:

 Do you still want the template i'm building?


Thank you very much for your effort.
Please if you don't need it, don't make it, because I don't 
know if I'll use it. If I'll decide to go with it, I'll make it 
myself. I don't want to waste your time in something I may not 
use.


Sorry for using your time, and thank you again.


 It's very much a learning experience. I'll tinker with this more.


Re: @trusting generic functions

2016-05-28 Thread Lodovico Giaretta via Digitalmars-d-learn

On Saturday, 28 May 2016 at 14:01:35 UTC, Era Scarecrow wrote:
On Saturday, 28 May 2016 at 13:10:56 UTC, Lodovico Giaretta 
wrote:
The only problem is that these structures are parameterized, 
and the type parameters may have unsafe operations that I use.


 Do you still want the template i'm building? It doesn't like 
stack frame pointers, but will work with regular structs. I'm 
still new to using traits myself so why it's getting me i don't 
know.


Thank you very much for your effort.
Please if you don't need it, don't make it, because I don't know 
if I'll use it.
If I'll decide to go with it, I'll make it myself. I don't want 
to waste your time in something I may not use.


Sorry for using your time, and thank you again.


Re: @trusting generic functions

2016-05-28 Thread Era Scarecrow via Digitalmars-d-learn

On Saturday, 28 May 2016 at 13:10:56 UTC, Lodovico Giaretta wrote:
The only problem is that these structures are parameterized, 
and the type parameters may have unsafe operations that I use.


 Do you still want the template i'm building? It doesn't like 
stack frame pointers, but will work with regular structs. I'm 
still new to using traits myself so why it's getting me i don't 
know.


Re: Easier way to add libraries to visual d?

2016-05-28 Thread Basile B. via Digitalmars-d-learn

On Friday, 27 May 2016 at 19:30:10 UTC, TheDGuy wrote:

On Thursday, 26 May 2016 at 22:15:17 UTC, Basile B. wrote:

gfm doesn't yield a .lib because of this:

https://github.com/d-gamedev-team/gfm/blob/master/dub.json#L22

it should be "library" or staticLibrary or "sourceLibrary"

thus it can't be registered. Bad luck here you've chosen the 
wrong stuff to test.


Okay, i now tried requests and serial-port and with both i have 
the same problem that i can't add them to the library manager.


I've released a hot fix yesterday and now it works with latest 
DUB tag (0.9.25).


But registering from the project that's loaded was already 
working yesterday. I think that you have forgotten to choose the 
right configuration to compile, example with serial-port:


http://imgur.com/7wAwqPz

- open the dub json
- to the left, the DUB inspector: the green arrow must be on a 
config that's dedicated to build the library

- double click to select a config
- compile the project
- to the bottom library manager: click the icon with a book and 
link on the top


Re: @trusting generic functions

2016-05-28 Thread Era Scarecrow via Digitalmars-d-learn

On Saturday, 28 May 2016 at 13:10:56 UTC, Lodovico Giaretta wrote:

On Saturday, 28 May 2016 at 13:03:10 UTC, Adam D. Ruppe wrote:
What kind of pointer usage do you have? Remember that basic & 
and * operations ARE @safe.


If you have more internally, you might be able to wrap them up 
in an @trusted function to again allow inference to work.


Ouch! I was under the impression that any pointer usage was 
forbidden in @safe code.


 Pointers by themselves are safe (as they have to point to 
something valid to start with); It's manipulating pointers that's 
usually unsafe (and the easiest source of bugs with pointers 
involved).


Re: @trusting generic functions

2016-05-28 Thread Lodovico Giaretta via Digitalmars-d-learn

On Saturday, 28 May 2016 at 13:03:10 UTC, Adam D. Ruppe wrote:
What kind of pointer usage do you have? Remember that basic & 
and * operations ARE @safe.


If you have more internally, you might be able to wrap them up 
in an @trusted function to again allow inference to work.


Ouch! I was under the impression that any pointer usage was 
forbidden in @safe code.


I have some structures holding pointers to other structures, and 
I'd like all of this structures being usable in @safe code. The 
problem of some structures being deallocated while others are 
holding pointers to them cannot exist in my scenario, so I'm sure 
that my code can be @trusted.


The only problem is that these structures are parameterized, and 
the type parameters may have unsafe operations that I use.


Re: @trusting generic functions

2016-05-28 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 28 May 2016 at 11:50:33 UTC, Lodovico Giaretta wrote:
Let's say I have a generic function that uses pointers. It will 
be inferred @system by the compiler, but I know that the 
pointer usage can be @trusted.


What kind of pointer usage do you have? Remember that basic & and 
* operations ARE @safe.


If you have more internally, you might be able to wrap them up in 
an @trusted function to again allow inference to work.


Re: @trusting generic functions

2016-05-28 Thread Lodovico Giaretta via Digitalmars-d-learn

On Saturday, 28 May 2016 at 12:45:21 UTC, Era Scarecrow wrote:
 Fourth, you could create a helper function/template that 
cycles through a struct of your choice and tells you if any of 
it's methods fail to be safe. This will require a little more 
work, but it could be used as a full insurance and only 
requires a single template call on your function to ensure the 
safety.


 I can try and make this fourth one, but this isn't something 
I've done often.


Thank you.
This solution has the advantage of not bloating the code too 
much, but the drawback that it forces all methods of the template 
argument to be at least @trusted, and not only the methods that 
my function needs to use, so imposing a stricter-than-necessary 
limit on its use in @safe code.




Re: @trusting generic functions

2016-05-28 Thread Lodovico Giaretta via Digitalmars-d-learn

On Saturday, 28 May 2016 at 12:45:21 UTC, Era Scarecrow wrote:
On Saturday, 28 May 2016 at 12:25:14 UTC, Lodovico Giaretta 
wrote:
The problem is that T is a type, and I should check for safety 
of every method of T that I'm using in my function. This does 
not scale well, and if I change the body of the function to 
use a new method, I may forget to add it to the isSafe checks.


 I think i see what's going on then. Had to re-read it a few 
times. So ignore my previous reply.




 Easiest solution is to mark the entire struct as @safe or 
@trusted. Problem goes away (as long as you don't forcibly 
change it)


 Second is to force the check on the function before the call.

  static assert(isSafe!T.dosomething);
  pt.dosomething();

 Third... You could put in @safe code and have it complain? 
(might not work)


 @safe {
   pt.dosomething(); //if not @safe/@trusted it will refuse to 
compile

 }

 Fourth, you could create a helper function/template that 
cycles through a struct of your choice and tells you if any of 
it's methods fail to be safe. This will require a little more 
work, but it could be used as a full insurance and only 
requires a single template call on your function to ensure the 
safety.


 I can try and make this fourth one, but this isn't something 
I've done often.


Thank you for your answer.

I guess I'll got with overloading and if:

auto doSomethingDumb(T)(ref T t) @trusted
if (isSafe!(T.doSomething))
{
}

auto doSomethingDumb(T)(ref T t) @system
if (!isSafe!(T.doSomething))
{
}

The only annoyance is this:

auto doSomethingInRealLife(T)(T t) @trusted
if (isSafe!(T.doSomething1)
 && isSafe!(T.doSomething2)
 && isSafe!(T.doSomething3)
 ... and so on ...
{
}

auto doSomethingInRealLife(T)(T t) @system
if (!isSafe!(T.doSomething1)
 || !isSafe!(T.doSomething2)
 || !isSafe!(T.doSomething3)
 ... and so on ...
{
}


Re: @trusting generic functions

2016-05-28 Thread Era Scarecrow via Digitalmars-d-learn

On Saturday, 28 May 2016 at 12:25:14 UTC, Lodovico Giaretta wrote:
The problem is that T is a type, and I should check for safety 
of every method of T that I'm using in my function. This does 
not scale well, and if I change the body of the function to use 
a new method, I may forget to add it to the isSafe checks.


 I think i see what's going on then. Had to re-read it a few 
times. So ignore my previous reply.




 Easiest solution is to mark the entire struct as @safe or 
@trusted. Problem goes away (as long as you don't forcibly change 
it)


 Second is to force the check on the function before the call.

  static assert(isSafe!T.dosomething);
  pt.dosomething();

 Third... You could put in @safe code and have it complain? 
(might not work)


 @safe {
   pt.dosomething(); //if not @safe/@trusted it will refuse to 
compile

 }

 Fourth, you could create a helper function/template that cycles 
through a struct of your choice and tells you if any of it's 
methods fail to be safe. This will require a little more work, 
but it could be used as a full insurance and only requires a 
single template call on your function to ensure the safety.


 I can try and make this fourth one, but this isn't something 
I've done often.


Re: @trusting generic functions

2016-05-28 Thread Lodovico Giaretta via Digitalmars-d-learn

On Saturday, 28 May 2016 at 12:33:28 UTC, Era Scarecrow wrote:
On Saturday, 28 May 2016 at 12:25:14 UTC, Lodovico Giaretta 
wrote:

On Saturday, 28 May 2016 at 11:57:09 UTC, Era Scarecrow wrote:

auto doSomethingDumb(T)(ref T t) if(isSafe!(T))


The problem is that T is a type, and I should check for safety 
of every method of T that I'm using in my function. This does 
not scale well, and if I change the body of the function to 
use a new method, I may forget to add it to the isSafe checks.


 Hmmm that doesn't sound right. Safe code can't call unsafe 
code (or it shouldn't), it continues @safe/@trusted all the way 
down. So if you are passed a safe/trusted function, then it 
shouldn't need other checks.


 Or am i reading the question wrong?


Sorry for not being clear. Look at this example:

struct S1
{
int doSomething() @safe
{
// do something safely
return 1;
}
}

struct S2
{
int doSomething() @system
{
// do something usafe
return 2;
}
}

auto doSomethingDumb(T)(ref T t)
{
T* pt = 
return pt.doSomething();
}

auto s1 = S1();
auto s2 = S2();
auto x = doSomethingDumb(s1); // this call should be possible in 
@safe code
auto y = doSomethingDumb(s2); // this should only be possible in 
@system code


Re: @trusting generic functions

2016-05-28 Thread Era Scarecrow via Digitalmars-d-learn

On Saturday, 28 May 2016 at 12:25:14 UTC, Lodovico Giaretta wrote:

On Saturday, 28 May 2016 at 11:57:09 UTC, Era Scarecrow wrote:

auto doSomethingDumb(T)(ref T t) if(isSafe!(T))


The problem is that T is a type, and I should check for safety 
of every method of T that I'm using in my function. This does 
not scale well, and if I change the body of the function to use 
a new method, I may forget to add it to the isSafe checks.


 Hmmm that doesn't sound right. Safe code can't call unsafe code 
(or it shouldn't), it continues @safe/@trusted all the way down. 
So if you are passed a safe/trusted function, then it shouldn't 
need other checks.


 Or am i reading the question wrong?


Re: @trusting generic functions

2016-05-28 Thread Lodovico Giaretta via Digitalmars-d-learn

On Saturday, 28 May 2016 at 11:57:09 UTC, Era Scarecrow wrote:

 Use traits..

https://dlang.org/phobos/std_traits.html#isSafe

so your function becomes (i believe)


auto doSomethingDumb(T)(ref T t) if(isSafe!(T))


The problem is that T is a type, and I should check for safety of 
every method of T that I'm using in my function. This does not 
scale well, and if I change the body of the function to use a new 
method, I may forget to add it to the isSafe checks.


Re: @trusting generic functions

2016-05-28 Thread Era Scarecrow via Digitalmars-d-learn

On Saturday, 28 May 2016 at 11:57:09 UTC, Era Scarecrow wrote:

auto doSomethingDumb(T)(ref T t) if(isSafe!(T))


 Should also probably test for a function or delegate. So...?


  auto doSomethingDumb(T)(ref T t)
if(isSafe!T && (isFunctionPointer!T || isDelegate!T)) {
  T* pt = 
  return pt.doSomething();
}


Re: @trusting generic functions

2016-05-28 Thread Era Scarecrow via Digitalmars-d-learn

On Saturday, 28 May 2016 at 11:50:33 UTC, Lodovico Giaretta wrote:
Is there any way around this? Any way to declare a function 
@trusted as long as the methods of the template argument are at 
least @trusted?


Thank you in advance.


 Use traits..

https://dlang.org/phobos/std_traits.html#isSafe

so your function becomes (i believe)


auto doSomethingDumb(T)(ref T t) if(isSafe!(T))


@trusting generic functions

2016-05-28 Thread Lodovico Giaretta via Digitalmars-d-learn
Let's say I have a generic function that uses pointers. It will 
be inferred @system by the compiler, but I know that the pointer 
usage can be @trusted.
The problem is that if I declare the function @trusted, I'm also 
implicitly trusting any call to @system methods of the template 
parameter.


Dumb example (pointer usage can be trusted, but doSomething may 
not):


auto doSomethingDumb(T)(ref T t) // I want it @trusted if 
doSomething is at least @trusted

{
T* pt = 
return pt.doSomething();
}

Is there any way around this? Any way to declare a function 
@trusted as long as the methods of the template argument are at 
least @trusted?


Thank you in advance.

Lodovico Giaretta


Re: is my code to get CTFE instantiated object valid D ?

2016-05-28 Thread chmike via Digitalmars-d-learn

On Saturday, 28 May 2016 at 08:47:48 UTC, Kagamin wrote:
For a trick of static mutable allocation see 
https://github.com/dlang/druntime/pull/1325


Thank you that looks promising. I'll study an experiment with the 
code.
If I would like that the instances are not in TLS, can I use the 
following ?


private __gshared void[...] store;

I then need to be sure that the objects are instantiated at 
compile time.

Will Emplace do the trick ?




Re: asm woes...

2016-05-28 Thread Era Scarecrow via Digitalmars-d-learn

On Saturday, 28 May 2016 at 10:10:19 UTC, ZombineDev wrote:

The great thing about D's UFCS is that it allows exactly that:



Also, you can implement inc() in terms of ulong[2] - void 
inc(ref ulong[2] w), which makes it applicable for other types, 
with the same memory representation. E.g. cent - 
(cast(ulong[2]*)).inc(), arrays - ulong[] arr; 
arr[0..2].inc(), and so on.


 Hmmm if it wasn't wideint being template I'd agree with you. 
Then again the way you have it listed the increment would 
probably call the version that's generated and doesn't require 
specific template instantiation to work.


 I don't know, personally to me it makes more sense to replace 
functions rather than export them and add an unknown generated 
type. If inherited structs worked (as i have them listed) then 
you could export all the CPU specific code to another file and 
never have to even know it exists. And if my impressions of code 
management and portability are accurate, then having 
OS/Architecture specific details should be separate from what is 
openly shared.


 Besides I'd like to leave the original source completely 
untouched if i can while applying updates/changes that don't add 
any confusion to the existing source code; Plus it's more an 
opt-in option at that point where you can hopefully have both 
active at the same time to unittest one against the other. (A is 
known to be correct, so B's output is tested against A).


Re: asm woes...

2016-05-28 Thread ZombineDev via Digitalmars-d-learn

On Saturday, 28 May 2016 at 08:10:50 UTC, Era Scarecrow wrote:

On Friday, 27 May 2016 at 09:22:49 UTC, Guillaume Piolat wrote:

You have to write your code three times, one for

version(D_InlineAsm_X86)
version (D_InlineAsm_X86_64)
and a version without assembly.


 Rather than make a new thread I wonder if struct inheritance 
wouldn't solve this, as trying to manage specific versions, 
lack of versions, checks for CTFE all became a headache. and 
bloated a 4 line function (2 of which were the 
opening/declaration) to something like 20 lines and looks like 
a huge mess.


 So...

 Let's assume structs as they are don't (otherwise) change.
 Let's assume structs can be inherited.
 Let's assume inherited structs change _behavior_ only 
(overridden functions as final), but don't add/expand any new 
data (non-polymorphic, no vtables).


 Then I could do something like this!

  //contains plain portable version
  struct base {}

  version(X86) {
struct inherited : base {
  //only adds or replaces functions, no data changes
  //all asm injection is known to be 32bit x86
}
  }
  version(X86_64) {
...
  }

 Truthfully going with my example, only a couple functions 
would be considered, namely multiply and divide as they would 
be the slowest ones, while everything else has very little to 
improve on, at least based on how wideint.d was implemented.


The great thing about D's UFCS is that it allows exactly that:

void main()
{
WideInt myInt;
myInt.inc(); // looks like a member function
myInt++; // can be hidden behind operator overloading
}

struct WideInt
{
ulong[2] data;

int opUnary(string s)()
{
static if (s == "++")
this.inc();
}
}

version(D_InlineAsm_X86_64)
{
void inc(ref WideInt w) { /* 32-bit increment implementation 
*/ }

}
else version(D_InlineAsm_X86)
{
void inc(ref WideInt w) { /* 64-bit increment implementation 
*/ }

}
else
{
void inc(ref WideInt w) { /* generic increment implementation 
*/ }

}

Also, you can implement inc() in terms of ulong[2] - void inc(ref 
ulong[2] w), which makes it applicable for other types, with the 
same memory representation.
E.g. cent - (cast(ulong[2]*)).inc(), arrays - ulong[] arr; 
arr[0..2].inc(), and so on.





Re: Alias this member shadowed by imported function identifier?

2016-05-28 Thread Johan Engelen via Digitalmars-d-learn
On Friday, 27 May 2016 at 17:00:04 UTC, Steven Schveighoffer 
wrote:


Now, the question here is, when does alias this kick in? I 
would say it should follow alias this before looking outside 
the module, so I say it's a bug.


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



Re: is my code to get CTFE instantiated object valid D ?

2016-05-28 Thread Kagamin via Digitalmars-d-learn

On Saturday, 28 May 2016 at 05:30:26 UTC, chmike wrote:
Would it be different if the object was declared const instead 
of immutable ?


Sometimes compiler is able to figure out that const data is 
immutable.


This is a bit frustrating because it is trivial to implement in 
C and C++.


For a trick of static mutable allocation see 
https://github.com/dlang/druntime/pull/1325


Re: is my code to get CTFE instantiated object valid D ?

2016-05-28 Thread Mike Parker via Digitalmars-d-learn

On Saturday, 28 May 2016 at 08:34:17 UTC, Mike Parker wrote:


const(F) cf = f;
immutable(f) if = f;


And, of course, those should be const(Foo) and immutable(Foo).


Re: is my code to get CTFE instantiated object valid D ?

2016-05-28 Thread Mike Parker via Digitalmars-d-learn

On Saturday, 28 May 2016 at 05:30:26 UTC, chmike wrote:

What is the difference between a const and immutable object ? 
would a const object be allowed to modify itself by using a 
hash table or caching results inside ?


The difference lies in the guarantees of const and immutable.

Foo f = new Foo;
const(F) cf = f;

The above is legal. The single instance can modify itself in 
methods called via f, but not those called via cf. So the answer 
to the second question is no, not directly.


Foo f = new Foo;
immutable(f) if = f;

This will not compile. The compiler expects that any reference 
assigned to if will not be modified anywhere in the program, 
ever. It does not have the same expectation of const references.



Is a static const Category c variable a TLS variable ?


Yes. All variables are TLS unless explicitly marked with 
__gshared or shared.


Re: asm woes...

2016-05-28 Thread Era Scarecrow via Digitalmars-d-learn

On Friday, 27 May 2016 at 09:22:49 UTC, Guillaume Piolat wrote:

You have to write your code three times, one for

version(D_InlineAsm_X86)
version (D_InlineAsm_X86_64)
and a version without assembly.


 Rather than make a new thread I wonder if struct inheritance 
wouldn't solve this, as trying to manage specific versions, lack 
of versions, checks for CTFE all became a headache. and bloated a 
4 line function (2 of which were the opening/declaration) to 
something like 20 lines and looks like a huge mess.


 So...

 Let's assume structs as they are don't (otherwise) change.
 Let's assume structs can be inherited.
 Let's assume inherited structs change _behavior_ only 
(overridden functions as final), but don't add/expand any new 
data (non-polymorphic, no vtables).


 Then I could do something like this!

  //contains plain portable version
  struct base {}

  version(X86) {
struct inherited : base {
  //only adds or replaces functions, no data changes
  //all asm injection is known to be 32bit x86
}
  }
  version(X86_64) {
...
  }

 Truthfully going with my example, only a couple functions would 
be considered, namely multiply and divide as they would be the 
slowest ones, while everything else has very little to improve 
on, at least based on how wideint.d was implemented.


Re: Benchmark Dlang vs Node vs Ruby

2016-05-28 Thread yawniek via Digitalmars-d-learn

On Friday, 27 May 2016 at 16:47:19 UTC, Daniel Kozak wrote:

Why not to use distribute oprion?
Dne 27. 5. 2016 17:35 napsal uživatel "yawniek via 
Digitalmars-d-learn" <

digitalmars-d-learn@puremagic.com>:


it its a flawed strategy.
what you should do is let the kernel handle it and use SO_ 
REUSEPORT

libasync supports it.

see e.g. https://github.com/rejectedsoftware/vibe.d/issues/1139
and https://lwn.net/Articles/542629/