Re: The Status of Const

2010-08-12 Thread Jonathan M Davis
On Thursday 12 August 2010 22:10:20 Kagamin wrote:
> Jonathan M Davis Wrote:
> > but the bugs related to it have made
> > it difficult, and I just haven't written very much large stuff in D - and
> > that's where you really need it.
> 
> How I'm working on a large project written in C#. C# has only D1 const
> system. Here I've seen no bugs caused by all data beign mutable. Even with
> public mutable fields. Usually bugs we have are unimplemented logic,
> incorrectly implemented logic, exceptions swallowing, undocumented
> external unmanaged (and buggy) library, that wants nice parameters. And
> bad design, oh... desing is bd.

Of course, you can write large projects without const. Many other languages 
which are heavily used lack const. However, there is great benefit in having 
const, and you're most likely to derive that benefit from large projects where 
things are much more complex then you are with small projects where you can 
probably keep most of it in your head and/or you're the only one working on it. 
You can obviously do lots of quality programs without const, but having it is a 
big plus.

- Jonathan M Davis


Re: The Status of Const

2010-08-12 Thread Kagamin
Adam Ruppe Wrote:

> On the subject of rebindable, what about:
> 
> const Object o; // not rebindable, the whole thing is set once and const
> const(Object) o; // the Object is const, but the reference is not.

Oops, this violates the const system because it unclear, whether const(Object)* 
is a pointer to rebindable or non-rebindable reference.


dmd as link driver

2010-08-12 Thread SK
Hello D'ers,

Can dmd drive the linking process in two step compile-then-link builds?

Lacking this capability complicates the CMake discovery process that uses
small test compiles.  In short, the problem is that CMake needs, but does
not have, full knowledge of the C environment (to handle linking) before
testing the D environment.  I'm not a cmake expert, but I don't think I can
express this dependency between two tool chains.  A few experiments have
failed to get this working.

If the answer is that dmd cannot drive the linker, would a patch be easy
enough to consider?

-steve


Re: The Status of Const

2010-08-12 Thread Kagamin
Adam Ruppe Wrote:

> On the subject of rebindable, what about:
> 
> const Object o; // not rebindable, the whole thing is set once and const
> const(Object) o; // the Object is const, but the reference is not.
> 
> So, everything is rebindable unless the declaration has a
> const/immutable on the outside.
> 
> int a; // rebindable (obviously)
> const(int) a; // the int never changes... but the variable a might.

int "value" is effectively immutable, it doesn't matter what qualifier you 
apply to it. The variable can be still reassignable to a different value.

> Meaningless for a value type, but makes sense for a reference type
> const int a; // the whole thing is set once and never changes. The
> const applies to the variable a itself, but the transitive property
> propagates it down to the int type too.

There is a difference between whether you can assign the whole struct or its 
distinct members. There was some words about this in the docs.


Re: The Status of Const

2010-08-12 Thread Kagamin
Walter Bright Wrote:

> Graham St Jack wrote:
> > However, I still regard the language design decision of a class 
> > reference having the same constness as the object it refers to as a 
> > major language design problem.
> 
> We tried for months. It just doesn't work to make it any other way than it is 
> now.

Is it compiler infrastructure's or syntactical issue?


alias this and immutable shenanigans

2010-08-12 Thread Yao G.

Consider this code:

---
module test;

struct Foo
{
this( int f ) {
_foo = f;
}

@property int baz() {
return _foo;
}

// alias _foo this;
// alias baz this;  

immutable int _foo;
}

struct Bar
{
this( int f ) {
_foo  = Foo(f);
}

private:
immutable Foo _foo;
}
---

If I uncomment the alias _foo this line, I get the following error message:

% Test.d(22): Error: can only initialize const member _foo inside  
constructor


WTF! I'm initializing it in a constructor! Is this a bug? Or by design you  
cannot alias this to a immutable member of a struct. It seems that there's  
a hidden temp created that wants to initialize the field. Also, I wanted  
to alias the property Foo.baz, but it also caused the following errors:


% Test.d(22): Error: function test.Foo.baz () is not callable using  
argument types (Foo) immutable
% Test.d(22): Error: expected 0 arguments, not 1 for non-variadic function  
type @property int()


It seems that somehow the property is used as a "setter", not as a  
"getter".


So, my questions are:
1. Why is disallowed to alias this an immutable data inside a struct?
2. Why is disallowed to alias this a struct "getter" property?


--
Yao G.


Re: The Status of Const

2010-08-12 Thread Kagamin
Kagamin Wrote:

> Now I'm working on a large project written in C#. C# has only D1 const 
> system. Here I've seen no bugs caused by all data beign mutable. Even with 
> public mutable fields. Usually bugs we have are unimplemented logic, 
> incorrectly implemented logic, exceptions swallowing, undocumented external 
> unmanaged (and buggy) library, that wants nice parameters. And bad design, 
> oh... desing is bd.

Ah, and many casts to object and from object. This caused many bugs. That's why 
I will always advocate for throwing cast, it's unacceptable that D by default 
provides bug-prone behavior. I will never accept this.


Re: The Status of Const

2010-08-12 Thread Kagamin
Jonathan M Davis Wrote:

> The lack of a mutable qualifier seems like it could be 
> another big problem, but I haven't yet written enough code in D to run into 
> that 
> issue (still I'm sure I'll run into it eventually and be highly annoyed - 
> it's 
> just needed too often in C++ for me not to be happy about it missing in D).

I've run into it - Exception, generating its error message on demand and 
caching it in const toString. I think, it's no problem no not have mutable 
qualifier, because I don't want it often. And you can create a function like 
void cacheValue!(T)(ref const T storage, T value);

> I'm a huge fan of const in C++, and I _really_ want to be able to use it in D 
> (the lack of const in D1 is one of the big reasons that chose to use D2 even 
> when it was new rather than mess with D1),

Same here :)
I think, const can be made to work.

> but the bugs related to it have made 
> it difficult, and I just haven't written very much large stuff in D - and 
> that's 
> where you really need it.

How I'm working on a large project written in C#. C# has only D1 const system. 
Here I've seen no bugs caused by all data beign mutable. Even with public 
mutable fields. Usually bugs we have are unimplemented logic, incorrectly 
implemented logic, exceptions swallowing, undocumented external unmanaged (and 
buggy) library, that wants nice parameters. And bad design, oh... desing is 
bd.


Re: The Status of Const

2010-08-12 Thread Walter Bright

dsimcha wrote:

3.  inout is currently so bug-ridden it's not even funny.  (Though this is
clearly fixable long-term, once we get higher priority stuff off our plates.)


I know. It's just that the 64 bit port has priority at the moment.


Re: The Status of Const

2010-08-12 Thread Walter Bright

Graham St Jack wrote:
However, I still regard the language design decision of a class 
reference having the same constness as the object it refers to as a 
major language design problem.


We tried for months. It just doesn't work to make it any other way than it is 
now.


Re: The Status of Const

2010-08-12 Thread Graham St Jack

On 13/08/10 12:16, Jonathan M Davis wrote:

On Thursday 12 August 2010 19:09:51 Michel Fortin wrote:
   

On 2010-08-12 18:56:50 -0400, dsimcha  said:
 

How can these limitations be worked around and/or fixed?
   

Unsatisfaction about Rebindable seems pretty generalized.

Here's an idea for a solution. Basically the problem is only in the
syntax, where the reference is implicitly part of the object's type and
thus impossible to put outside from the type modifier. An easy solution
would be to add an explicit reference marker, but this would change the
syntax for existing code, and I have to admit the current syntax is
nice (up until you try to add a modifier). But we could make the
reference marker optional, like this:

Object o; // implicitly a reference
Object ref o; // explicit reference marker

Both would be allowed and equivalent. While the first form is nicer to
the eye, the second makes it easy to apply a type modifier while
excluding the reference:

const(Object)ref o;
shared(Object)ref o;
 

Now, _that_ seems like a good idea. It doesn't even require a new keyword. It's
also quite clear and understandable. It would be a big improvement I think.
There may be downsides of some kind, but I can't think of any. Unless someone
can come up with a reason _not_ to do this, it seems to me like it's a really
good idea.

- Jonathan M Davis


P.S. I believe that the word that you were looking for was dissatisfaction, not
unsatisfaction (which isn't a real word).
   

I like it too.

A complimentary change is to automatically apply type modifiers when 
creating objects, but not when making references to them, like so:


immutable class Foo {...}
Foo foo = new Foo();

Here, the object on the heap would be immutable and foo would not.

Currently class (and struct) type modifiers don't get automatically 
applied - at least not in ways that I find useful, and I keep having to 
do laborious stuff like this, which I don't like at all:


synchronized class _Foo {}
alias shared(_Foo) Foo;
Foo foo = new Foo();

or even worse:

synchonized class Foo {}
shared(Foo) foo = cast(shared) new Foo();

--
Graham St Jack



Re: The Status of Const

2010-08-12 Thread Nick Sabalausky
"Justin Johansson"  wrote in message 
news:i42ba3$1b...@digitalmars.com...
> Nick Sabalausky wrote:
>> "Justin Johansson"  wrote in message 
>> news:i424ac$27n...@digitalmars.com...
>>> Graham St Jack wrote:
 Is there any plan to introduce some way of having a mutable reference 
 to an immutable class object on the heap? Do others see this as a 
 problem at all?
>>> For embedded microsystems (i.e. with ROM/RAM) this is a problem.  It
>>> is a common use case to have a mutable reference (in RAM) to some
>>> objects that reside in ROM.  Obviously anything in ROM is guaranteed
>>> by hardware to be immutable.  So, yes, this is a problem in a
>>> wider sense.
>>
>> Would there every really be anything in ROM though that would be 
>> appropriate as a class though, as opposed to, say, a struct? I've never 
>> heard of an object with a vtable being stored in ROM.
>
> Yes, well back in my embedded C++ days yes did so.  But just because I
> did doesn't necessarily make it a common use case.  Strike 'common'
> above and replace with 'valid.
>

Interesting.

> Anyway, what about a mutable reference to an immutable struct (in ROM)?

Since structs are value types in D, wouldn't a reference to it (mutable or 
otherwise) *have* to be a pointer?





Re: The Status of Const

2010-08-12 Thread Jonathan M Davis
On Thursday 12 August 2010 18:57:26 Michel Fortin wrote:
> Const-correctness can't work the same in D as in C/C++. Even if you had
> a mutable member in your class, D can't allow you to modify this member
> from a const member function, because this const member function can be
> called when your class is immutable, and if the class is immutable it
> can be shared across threads, in which case modifying the member
> (without synchronization) would cause races. Basically, D const system
> isn't build for const-correctness or to enforce what logically looks
> like const, it's built to ease concurrency and sharing of data between
> threads. All this to say that when something is const, it *is* const
> and it can't cause races.

That is, unfortunately, a very good point. It's still seriously limiting, 
however. What it means is that there is going to be code out there (and 
possibly 
a lot of it) which _should_ be const but can't be.

I confess that the more that I deal with immutable, the less I like it. const 
doesn't complicate things all that much and brings a lot of improvements. 
immutable complicates things quite a lot more and does not bring the same level 
of improvements to the table. However, it does help with multi-threaded apps 
which _is_ very important, and increasingly so, so it's probably better to have 
it than not. Still, it can be very frustrating. However, if there's a better 
way 
to do it, it'll likely be found with either a future version of D or a language 
which replaces D. There's a shortage of languages which have tried to mix 
const, 
mutable, and immutable together (D may be the only one actually), so there 
isn't 
much experience to base improvements on. And is usually the case, it's much 
easier to see the problems than their solutions.

- Jonathan M Davis


Re: The Status of Const

2010-08-12 Thread Jonathan M Davis
On Thursday 12 August 2010 19:09:51 Michel Fortin wrote:
> On 2010-08-12 18:56:50 -0400, dsimcha  said:
> > How can these limitations be worked around and/or fixed?
> 
> Unsatisfaction about Rebindable seems pretty generalized.
> 
> Here's an idea for a solution. Basically the problem is only in the
> syntax, where the reference is implicitly part of the object's type and
> thus impossible to put outside from the type modifier. An easy solution
> would be to add an explicit reference marker, but this would change the
> syntax for existing code, and I have to admit the current syntax is
> nice (up until you try to add a modifier). But we could make the
> reference marker optional, like this:
> 
>   Object o; // implicitly a reference
>   Object ref o; // explicit reference marker
> 
> Both would be allowed and equivalent. While the first form is nicer to
> the eye, the second makes it easy to apply a type modifier while
> excluding the reference:
> 
>   const(Object)ref o;
>   shared(Object)ref o;

Now, _that_ seems like a good idea. It doesn't even require a new keyword. It's 
also quite clear and understandable. It would be a big improvement I think. 
There may be downsides of some kind, but I can't think of any. Unless someone 
can come up with a reason _not_ to do this, it seems to me like it's a really 
good idea.

- Jonathan M Davis


P.S. I believe that the word that you were looking for was dissatisfaction, not 
unsatisfaction (which isn't a real word).


Re: The Status of Const

2010-08-12 Thread Justin Johansson

Nick Sabalausky wrote:
"Justin Johansson"  wrote in message 
news:i424ac$27n...@digitalmars.com...

Graham St Jack wrote:
Is there any plan to introduce some way of having a mutable reference to 
an immutable class object on the heap? Do others see this as a problem at 
all?

For embedded microsystems (i.e. with ROM/RAM) this is a problem.  It
is a common use case to have a mutable reference (in RAM) to some
objects that reside in ROM.  Obviously anything in ROM is guaranteed
by hardware to be immutable.  So, yes, this is a problem in a
wider sense.


Would there every really be anything in ROM though that would be appropriate 
as a class though, as opposed to, say, a struct? I've never heard of an 
object with a vtable being stored in ROM. 



Yes, well back in my embedded C++ days yes did so.  But just because I
did doesn't necessarily make it a common use case.  Strike 'common'
above and replace with 'valid.

Anyway, what about a mutable reference to an immutable struct (in ROM)?
Same argument.  Also there is no reason why vtables cannot be stored
in ROM along with code.

The only stuff to have in RAM is the mutable stuff! :-)




Re: The Status of Const

2010-08-12 Thread Adam Ruppe
On the subject of rebindable, what about:

const Object o; // not rebindable, the whole thing is set once and const
const(Object) o; // the Object is const, but the reference is not.

So, everything is rebindable unless the declaration has a
const/immutable on the outside.

int a; // rebindable (obviously)
const(int) a; // the int never changes... but the variable a might.
Meaningless for a value type, but makes sense for a reference type
const int a; // the whole thing is set once and never changes. The
const applies to the variable a itself, but the transitive property
propagates it down to the int type too.


Re: The Status of Const

2010-08-12 Thread Michel Fortin

On 2010-08-12 18:56:50 -0400, dsimcha  said:


How can these limitations be worked around and/or fixed?


Unsatisfaction about Rebindable seems pretty generalized.

Here's an idea for a solution. Basically the problem is only in the 
syntax, where the reference is implicitly part of the object's type and 
thus impossible to put outside from the type modifier. An easy solution 
would be to add an explicit reference marker, but this would change the 
syntax for existing code, and I have to admit the current syntax is 
nice (up until you try to add a modifier). But we could make the 
reference marker optional, like this:


Object o; // implicitly a reference
Object ref o; // explicit reference marker

Both would be allowed and equivalent. While the first form is nicer to 
the eye, the second makes it easy to apply a type modifier while 
excluding the reference:


const(Object)ref o;
shared(Object)ref o;

--
Michel Fortin
michel.for...@michelf.com
http://michelf.com/



Re: The Status of Const

2010-08-12 Thread Michel Fortin

On 2010-08-12 21:37:11 -0400, Jonathan M Davis  said:


3. The lack of a mutable modifier.

There are times when you need a mutable modifier to sanely use const (it
obviously wouldn't work with immutable regardless). I don't know if there's any
way to safely do this with a library or not. It just seems like a deficiency in
the language itself. As I understand it, Walter thinks that there are serious
issues with mutable in C++, and I don't know what those are, but I know that
there are going to be cases where I'd like my code to be const-correct, and I
won't be able to because there is no mutable in D.


Const-correctness can't work the same in D as in C/C++. Even if you had 
a mutable member in your class, D can't allow you to modify this member 
from a const member function, because this const member function can be 
called when your class is immutable, and if the class is immutable it 
can be shared across threads, in which case modifying the member 
(without synchronization) would cause races. Basically, D const system 
isn't build for const-correctness or to enforce what logically looks 
like const, it's built to ease concurrency and sharing of data between 
threads. All this to say that when something is const, it *is* const 
and it can't cause races.


Perhaps there could be *synchronized* or *shared* islands that could 
encapsulate mutable state inside of something immutable -- this would 
avoid races -- but I think the addition of such a thing should be 
delayed until we get the current system working and we have some 
experience with it.



--
Michel Fortin
michel.for...@michelf.com
http://michelf.com/



Re: The Status of Const

2010-08-12 Thread Jonathan M Davis
On Thursday, August 12, 2010 18:16:01 Graham St Jack wrote:
> On 13/08/10 10:18, Jonathan M Davis wrote:
> > On Thursday, August 12, 2010 17:38:28 Graham St Jack wrote:
> >> For me, the key problem is that a class object reference has the same
> >> const/immutable/shared attribute as the object on the heap that it
> >> refers to. This is sometimes what you need, but more often you want a
> >> non-shared, mutable reference to a const/immutable/shared object.
> >> 
> >> You can achieve this with pointers for arrays, structs and primitive
> >> types, but not with classes because a class pointer is just a pointer to
> >> a reference.
> > 
> > Hence the hack that is Rebindable!().
> > 
> > Oh, and you _can_ achieve pointers to classes, but what you normally use
> > are references, which do have the problem of not being able to be split
> > between the reference and referent types.
> > 
> > - Jonathan M Davis
> 
> So how do you get a pointer to an object? Taking the address of an
> object reference gives you a pointer to the reference, not the object,
> which is fair enough. As far as I know there isn't a way to get a
> pointer to the object itself, and even if you could, how do you use such
> a thing?

Hmm. I was thinking that you could just do

T* t = new T();

but that doesn't work. I know that people have talked about doing it here on 
the 
newsgroup, so there must be a way. You can do

T t1 = new T();
T* t2 = &t1;

but I guess that that's a pointer to a reference rather a pointer to the object 
itself. Maybe if you want pointers to classes you need to use manual memory 
manegement rather than the GC and new. Hopefully someone else can enlighten us. 
I have generally avoided pointers in D.

- Jonathan M Davis


Re: The Status of Const

2010-08-12 Thread Jonathan M Davis
On Thursday, August 12, 2010 18:12:25 dsimcha wrote:
> == Quote from Brad Roberts (bra...@slice-2.puremagic.com)'s article
> 
> > For discussions like this, I think it's essential to distinguish between
> > the language vs the runtime + core libraries.  I recognize what matters
> > is the end result usability, but examining the layers independently is
> > really important.
> > So, which are you talking about (could well be both)?
> 
> I disagree.  A major reason why the libraries are broken is because the
> language is broken.  const/immutable is very hard to use with generic
> code, meaning that anything short of impeccable discipline and testing
> will lead to bugs galore. Fixing the language would make it a lot easier
> to fix the libraries.

I see three primary issues with const/immutable beyond whatever bugs we have, 
and while improvement to the libraries would help, I'm not sure that they can 
fix 
them.

1. The fact that const references make both the reference and the referent 
const.

Rebindable!() works to some extent, but it really feels like a hack and is 
nowhere near as smooth as some kind of tail const solution would be (though I 
do 
understand that having head const and tail const would complicate things 
considerably). I think that it would have been far better had const and 
immutable references just made the referent const/immutable. There just _has_ 
to 
be a better way to handle it. Maybe have rconst for references or something. It 
almost tempts me to see if I should just try and use pointers everywhere 
instead 
of references.

2. The shear difficulty in getting in getting immutable versions of stuff. 
There is 
no automated way to do it other than idup with arrays.

I really don't know the cleanest way to solve this. The nature of immutable 
makes casting to it not work, so you're going to have to make a copy, and if 
that needs a deep copy, you're going to need clone() for classes and a copy 
constructor or assignment operator for structs. It's not at all obvious how to 
make this cleaner. Maybe there could be a function in Phobos that abstracts it 
out; it would know the correct, standard way to get an immutable copy of 
classes, structs, arrays, etc. and return the appropriate type. Then generic 
code could just use that function. Still, getting immutable copies of stuff 
which 
isn't always immutable is not pretty.

3. The lack of a mutable modifier.

There are times when you need a mutable modifier to sanely use const (it 
obviously wouldn't work with immutable regardless). I don't know if there's any 
way to safely do this with a library or not. It just seems like a deficiency in 
the language itself. As I understand it, Walter thinks that there are serious 
issues with mutable in C++, and I don't know what those are, but I know that 
there are going to be cases where I'd like my code to be const-correct, and I 
won't be able to because there is no mutable in D.

I really don't know how many of these issues can be fixed at this stage in the 
game, and ultimately, the current bugs in dmd make them pretty much a moot 
issue 
because the bugs make using const and immutable near impossible in many cases. 
Still, it would be nice to resolve these issues in a better manner than what we 
currently have does.

- Jonathan M Davis


Re: The Status of Const

2010-08-12 Thread Graham St Jack

On 13/08/10 10:18, Jonathan M Davis wrote:

On Thursday, August 12, 2010 17:38:28 Graham St Jack wrote:
   

For me, the key problem is that a class object reference has the same
const/immutable/shared attribute as the object on the heap that it
refers to. This is sometimes what you need, but more often you want a
non-shared, mutable reference to a const/immutable/shared object.

You can achieve this with pointers for arrays, structs and primitive
types, but not with classes because a class pointer is just a pointer to
a reference.
 

Hence the hack that is Rebindable!().

Oh, and you _can_ achieve pointers to classes, but what you normally use are
references, which do have the problem of not being able to be split between the
reference and referent types.

- Jonathan M Davis
   
So how do you get a pointer to an object? Taking the address of an 
object reference gives you a pointer to the reference, not the object, 
which is fair enough. As far as I know there isn't a way to get a 
pointer to the object itself, and even if you could, how do you use such 
a thing?



--

Graham St Jack



Re: The Status of Const

2010-08-12 Thread dsimcha
== Quote from Brad Roberts (bra...@slice-2.puremagic.com)'s article
> For discussions like this, I think it's essential to distinguish between
> the language vs the runtime + core libraries.  I recognize what matters is
> the end result usability, but examining the layers independently is really
> important.
> So, which are you talking about (could well be both)?

I disagree.  A major reason why the libraries are broken is because the language
is broken.  const/immutable is very hard to use with generic code, meaning that
anything short of impeccable discipline and testing will lead to bugs galore.
Fixing the language would make it a lot easier to fix the libraries.


Re: The Status of Const

2010-08-12 Thread Nick Sabalausky
"Justin Johansson"  wrote in message 
news:i424ac$27n...@digitalmars.com...
> Graham St Jack wrote:
>> Is there any plan to introduce some way of having a mutable reference to 
>> an immutable class object on the heap? Do others see this as a problem at 
>> all?
>
> For embedded microsystems (i.e. with ROM/RAM) this is a problem.  It
> is a common use case to have a mutable reference (in RAM) to some
> objects that reside in ROM.  Obviously anything in ROM is guaranteed
> by hardware to be immutable.  So, yes, this is a problem in a
> wider sense.

Would there every really be anything in ROM though that would be appropriate 
as a class though, as opposed to, say, a struct? I've never heard of an 
object with a vtable being stored in ROM. 




Re: The Status of Const

2010-08-12 Thread Jonathan M Davis
On Thursday, August 12, 2010 17:38:28 Graham St Jack wrote:
> For me, the key problem is that a class object reference has the same
> const/immutable/shared attribute as the object on the heap that it
> refers to. This is sometimes what you need, but more often you want a
> non-shared, mutable reference to a const/immutable/shared object.
> 
> You can achieve this with pointers for arrays, structs and primitive
> types, but not with classes because a class pointer is just a pointer to
> a reference.

Hence the hack that is Rebindable!().

Oh, and you _can_ achieve pointers to classes, but what you normally use are 
references, which do have the problem of not being able to be split between the 
reference and referent types.

- Jonathan M Davis


Re: The Status of Const

2010-08-12 Thread Justin Johansson

Graham St Jack wrote:
Is there any plan to introduce some way of having a mutable reference to 
an immutable class object on the heap? Do others see this as a problem 
at all?


For embedded microsystems (i.e. with ROM/RAM) this is a problem.  It
is a common use case to have a mutable reference (in RAM) to some
objects that reside in ROM.  Obviously anything in ROM is guaranteed
by hardware to be immutable.  So, yes, this is a problem in a
wider sense.


Re: The Status of Const

2010-08-12 Thread dsimcha
== Quote from bearophile (bearophileh...@lycos.com)'s article
> Jonathan M Davis:
> > The lack of a mutable qualifier seems like it could be
> > another big problem,
> I was thinking about a Deconst!() template...
> Bye,
> bearophile

Are you sure std.traits.Unqual doesn't do what you want?  It shallowly removes
const/immutable/shared.  For example:

static assert(is(Unqual!(immutable(char[])) == immutable(char)[])));
static assert(is(Unqual!(immutable(int) == int));


Re: The Status of Const

2010-08-12 Thread Graham St Jack

On 13/08/10 10:08, Andrei Alexandrescu wrote:

Trass3r wrote:
Well isn't it natural that a constness system has a much larger 
impact than just some syntax additions.
I don't see any flaws in its design. The implementation is of course 
still buggy though and needs to mature.


I agree. There are very severe bugs and undue limitations in today's 
const. Having a comprehensive discussion of const's status and role in 
current and future D idioms is a great idea. We should start it with a 
scrutiny of the reported and possibly unreported bugs in the feature.



Andrei

I also agree that cost is worth the effort.

Most of the roadblocks are relatively easy to overcome by rolling 
const-correctness through druntime and phobos.


However, I still regard the language design decision of a class 
reference having the same constness as the object it refers to as a 
major language design problem. I would be delighted if someone could 
point out to me how to neatly work around this though.


--
Graham St Jack



Re: The Status of Const

2010-08-12 Thread Graham St Jack

On 13/08/10 09:51, Brad Roberts wrote:

On Thu, 12 Aug 2010, dsimcha wrote:

   

This is from a discussion that originated on the Phobos mailing list, but I
thought I'd bring up the question of what should be done about const on the
newsgroup to see what others think:

Despite its theoretical beauty, I find D's const/immutable system to be
utterly useless for all but the simplest use cases.  I made a serious attempt
a while back to use it in a real multithreaded program.  In hindsight it was
more trouble than it was worth, largely for three reasons:

1.   It's difficult to create non-trivial immutable data structures, and often
impossible without relying on either unchecked casts or unnecessary copying.

2.  Much generic code in Phobos (even things as simple as std.math.pow()
before I recently fixed it) behaves incorrectly when given const/immutable
data.  This also applies to other libraries I use, including ones that I'm the
main author of, so I'm just as guilty of it as anyone.  Given that noone,
including me, seems to be able to get const to interact well with generic
code, perhaps we need a language-level solution.

3.  inout is currently so bug-ridden it's not even funny.  (Though this is
clearly fixable long-term, once we get higher priority stuff off our plates.)

It would have probably been better if this was brought to a head sooner, but
it's better late than never.  Do others agree that D's const system is
difficult to impossible to use properly?  Has anyone successfully used D's
const system in a non-trivial setting despite these limitations?  If so, was
it more trouble than it was worth in hindsight?  How can these limitations be
worked around and/or fixed?
 

For discussions like this, I think it's essential to distinguish between
the language vs the runtime + core libraries.  I recognize what matters is
the end result usability, but examining the layers independently is really
important.

So, which are you talking about (could well be both)?
   
For me, the key problem is that a class object reference has the same 
const/immutable/shared attribute as the object on the heap that it 
refers to. This is sometimes what you need, but more often you want a 
non-shared, mutable reference to a const/immutable/shared object.


You can achieve this with pointers for arrays, structs and primitive 
types, but not with classes because a class pointer is just a pointer to 
a reference.



--
Graham St Jack



Re: The Status of Const

2010-08-12 Thread Andrei Alexandrescu

Trass3r wrote:
Well isn't it natural that a constness system has a much larger impact 
than just some syntax additions.
I don't see any flaws in its design. The implementation is of course 
still buggy though and needs to mature.


I agree. There are very severe bugs and undue limitations in today's 
const. Having a comprehensive discussion of const's status and role in 
current and future D idioms is a great idea. We should start it with a 
scrutiny of the reported and possibly unreported bugs in the feature.



Andrei


Re: The Status of Const

2010-08-12 Thread Jonathan M Davis
Jonathan M Davis wrote:
> The
> lack of a mutable qualifier seems like it could be another big problem,
> but I haven't yet written enough code in D to run into that issue (still
> I'm sure I'll run into it eventually and be highly annoyed - it's just
> needed too often in C++ for me not to be happy about it missing in D).

Or rather, it's just needed too often in C++ for me not to be _un_happy 
about it missing in D.

- Jonathan M Davis



Re: The Status of Const

2010-08-12 Thread Brad Roberts
On Thu, 12 Aug 2010, dsimcha wrote:

> This is from a discussion that originated on the Phobos mailing list, but I
> thought I'd bring up the question of what should be done about const on the
> newsgroup to see what others think:
> 
> Despite its theoretical beauty, I find D's const/immutable system to be
> utterly useless for all but the simplest use cases.  I made a serious attempt
> a while back to use it in a real multithreaded program.  In hindsight it was
> more trouble than it was worth, largely for three reasons:
> 
> 1.   It's difficult to create non-trivial immutable data structures, and often
> impossible without relying on either unchecked casts or unnecessary copying.
> 
> 2.  Much generic code in Phobos (even things as simple as std.math.pow()
> before I recently fixed it) behaves incorrectly when given const/immutable
> data.  This also applies to other libraries I use, including ones that I'm the
> main author of, so I'm just as guilty of it as anyone.  Given that noone,
> including me, seems to be able to get const to interact well with generic
> code, perhaps we need a language-level solution.
> 
> 3.  inout is currently so bug-ridden it's not even funny.  (Though this is
> clearly fixable long-term, once we get higher priority stuff off our plates.)
> 
> It would have probably been better if this was brought to a head sooner, but
> it's better late than never.  Do others agree that D's const system is
> difficult to impossible to use properly?  Has anyone successfully used D's
> const system in a non-trivial setting despite these limitations?  If so, was
> it more trouble than it was worth in hindsight?  How can these limitations be
> worked around and/or fixed?

For discussions like this, I think it's essential to distinguish between 
the language vs the runtime + core libraries.  I recognize what matters is 
the end result usability, but examining the layers independently is really 
important.

So, which are you talking about (could well be both)?


Re: The Status of Const

2010-08-12 Thread Trass3r
Well isn't it natural that a constness system has a much larger impact  
than just some syntax additions.
I don't see any flaws in its design. The implementation is of course still  
buggy though and needs to mature.


Re: The Status of Const

2010-08-12 Thread Graham St Jack
I have tried using const/immutable/shared several times, and am 
currently in the process of giving it another shot, with much more 
success that before, but it is hard work.


The major language hassle for me is that a class reference has the same 
const/immutable/shared type as the object is refers to, unlike pointers. 
I know that Rebindable is a workaround, but I don't find it satisfactory 
- essentially it uses brute-force casting to defeat the type system, and 
isn't syntactically identical to the bound type.


The data I pass between threads has to pass the !hasAliasing test, and I 
haven't found a practical way to make it work for classes. What works 
best for me is a struct with a pointer to immutable data like so:


struct Foo {
struct Payload {
...
   }
   immutable(Payload)* payload;
   ...
}

Foo can then be passed, contained by value and assigned to, just like 
any other value type. Containing an immutable instance of Foo is ok too, 
if you need another layer of !hasAliasing. I tend to define all my 
non-trivial building-block data types this way, and pass them by value.


With careful design of my multi-threaded code, I can define a set of 
messages to pass between threads that don't need to contain complex data 
structures. The resultant design is always an improvement over the more 
complex interface that first comes to mind, so I find that the type 
system is pushing me in a good direction.


The next big hurdle (as you pointed out) is that druntime and phobos 
aren't designed for const/immutable/shared. For example, InternetAddress 
fails the !hasAliasing test, and concurrency Mailboxes defeat the type 
system rather than being shared themselves, and don't insisting that 
message parameters have to be !hasAliasing. So far I have had to 
implement my own concurrency, socket and condition modules to overcome 
these issues, and I'm sure those are just the beginning.


So there are plenty of bumps in the road, but it does look like it is 
finally possible to use const/immutable/shared if you are determined 
enough. That said, it needs to be way, way easier before wide adoption.


The library issues can be addressed easily enough - It didn't take me 
long to pull off versions that worked ok (Linux only I'm afraid). 
However, the issue with classes doesn't look so easy, and that seriously 
limits what can be passed in messages.


Is there any plan to introduce some way of having a mutable reference to 
an immutable class object on the heap? Do others see this as a problem 
at all?


On 13/08/10 08:26, dsimcha wrote:

This is from a discussion that originated on the Phobos mailing list, but I
thought I'd bring up the question of what should be done about const on the
newsgroup to see what others think:

Despite its theoretical beauty, I find D's const/immutable system to be
utterly useless for all but the simplest use cases.  I made a serious attempt
a while back to use it in a real multithreaded program.  In hindsight it was
more trouble than it was worth, largely for three reasons:

1.   It's difficult to create non-trivial immutable data structures, and often
impossible without relying on either unchecked casts or unnecessary copying.

2.  Much generic code in Phobos (even things as simple as std.math.pow()
before I recently fixed it) behaves incorrectly when given const/immutable
data.  This also applies to other libraries I use, including ones that I'm the
main author of, so I'm just as guilty of it as anyone.  Given that noone,
including me, seems to be able to get const to interact well with generic
code, perhaps we need a language-level solution.

3.  inout is currently so bug-ridden it's not even funny.  (Though this is
clearly fixable long-term, once we get higher priority stuff off our plates.)

It would have probably been better if this was brought to a head sooner, but
it's better late than never.  Do others agree that D's const system is
difficult to impossible to use properly?  Has anyone successfully used D's
const system in a non-trivial setting despite these limitations?  If so, was
it more trouble than it was worth in hindsight?  How can these limitations be
worked around and/or fixed?
   



--
Graham St Jack



Re: The Status of Const

2010-08-12 Thread Andrej Mitrovic
A few years ago I had a look at D, and I remember there were some NG posts
about broken const and such. I honestly thought whatever that was broken was
fixed by now. I haven't used D too much, so I'm yet to be affected by this.
>From the looks of posts it seems to be bad though.

On Fri, Aug 13, 2010 at 1:48 AM, bearophile wrote:

> Jonathan M Davis:
> > The lack of a mutable qualifier seems like it could be
> > another big problem,
>
> I was thinking about a Deconst!() template...
>
> Bye,
> bearophile
>


Re: The Status of Const

2010-08-12 Thread Michel Fortin

On 2010-08-12 18:56:50 -0400, dsimcha  said:

It would have probably been better if this was brought to a head 
sooner, but it's better late than never.  Do others agree that D's 
const system is difficult to impossible to use properly?


I agree. Rebindable looks like a hack, as do creating immutable objects 
or structs.



Has anyone successfully used D's const system in a non-trivial setting 
despite these limitations?


I tried to use immutable objects once, to then find out I'd need to use 
Rebindable everywhere, and not being able to use Rebindable correctly 
(it was buggy) made me abandon the idea. Related bugs:






If so, was it more trouble than it was worth in hindsight?


At one point, I gave up. I don't use const or immutable except for 
trivial things, such as array of primitive types.




How can these limitations be worked around and/or fixed?


There need to be a concerted effort to make Phobos more aware of 
not-so-new-anymore features such as const/immutable. Phobos should be 
the test bed for any new feature. Currently, it seems that new features 
got added to the compiler one after another, but they were never really 
tested in a real setting, only in small synthetic test cases. This is 
not how you make a practical language.


Those "new features" I'm talking about includes the most notable D2 
features: const/immutable, shared, @safe, pure, did I miss any? It's 
simple: only once Phobos becomes -correct will we be able 
to use  in our own programs. And this process of improving 
Phobos will reveal lacking areas in the specification/implementation of 
the language that will need to be fixed: I know because I stumbled upon 
a couple of them myself.



--
Michel Fortin
michel.for...@michelf.com
http://michelf.com/



Re: The Status of Const

2010-08-12 Thread bearophile
Jonathan M Davis:
> The lack of a mutable qualifier seems like it could be 
> another big problem,

I was thinking about a Deconst!() template...

Bye,
bearophile


Re: The Status of Const

2010-08-12 Thread Justin Johansson

dsimcha wrote:

This is from a discussion that originated on the Phobos mailing list, but I
thought I'd bring up the question of what should be done about const on the
newsgroup to see what others think:

Despite its theoretical beauty, I find D's const/immutable system to be
utterly useless for all but the simplest use cases.  I made a serious attempt
a while back to use it in a real multithreaded program.  In hindsight it was
more trouble than it was worth, largely for three reasons:

1.   It's difficult to create non-trivial immutable data structures, and often
impossible without relying on either unchecked casts or unnecessary copying.

2.  Much generic code in Phobos (even things as simple as std.math.pow()
before I recently fixed it) behaves incorrectly when given const/immutable
data.  This also applies to other libraries I use, including ones that I'm the
main author of, so I'm just as guilty of it as anyone.  Given that noone,
including me, seems to be able to get const to interact well with generic
code, perhaps we need a language-level solution.

3.  inout is currently so bug-ridden it's not even funny.  (Though this is
clearly fixable long-term, once we get higher priority stuff off our plates.)

It would have probably been better if this was brought to a head sooner, but
it's better late than never.  Do others agree that D's const system is
difficult to impossible to use properly?  Has anyone successfully used D's
const system in a non-trivial setting despite these limitations?  If so, was
it more trouble than it was worth in hindsight?  How can these limitations be
worked around and/or fixed?


Unfortunately, from my experience in a non-trivial setting, the
work-around seems to be not to use const/immutable.  It is very
very br o  k   e n.  As the const/immutable implementation
currently stands, it definitely not worth the trouble.  You will
have weeks and weeks of pain only to have to just about throw
your work out and start over.

Sad but true.  Your sentiments are mine also.

Justin Johansson


Re: The Status of Const

2010-08-12 Thread Jonathan M Davis
On Thursday, August 12, 2010 15:56:50 dsimcha wrote:
> This is from a discussion that originated on the Phobos mailing list, but I
> thought I'd bring up the question of what should be done about const on the
> newsgroup to see what others think:
> 
> Despite its theoretical beauty, I find D's const/immutable system to be
> utterly useless for all but the simplest use cases.  I made a serious
> attempt a while back to use it in a real multithreaded program.  In
> hindsight it was more trouble than it was worth, largely for three
> reasons:
> 
> 1.   It's difficult to create non-trivial immutable data structures, and
> often impossible without relying on either unchecked casts or unnecessary
> copying.
> 
> 2.  Much generic code in Phobos (even things as simple as std.math.pow()
> before I recently fixed it) behaves incorrectly when given const/immutable
> data.  This also applies to other libraries I use, including ones that I'm
> the main author of, so I'm just as guilty of it as anyone.  Given that
> noone, including me, seems to be able to get const to interact well with
> generic code, perhaps we need a language-level solution.
> 
> 3.  inout is currently so bug-ridden it's not even funny.  (Though this is
> clearly fixable long-term, once we get higher priority stuff off our
> plates.)
> 
> It would have probably been better if this was brought to a head sooner,
> but it's better late than never.  Do others agree that D's const system is
> difficult to impossible to use properly?  Has anyone successfully used D's
> const system in a non-trivial setting despite these limitations?  If so,
> was it more trouble than it was worth in hindsight?  How can these
> limitations be worked around and/or fixed?

I've tried to use const, but it typically doesn't happen much because of the 
bugs with inout and the fact that Object isn't yet const-correct (that being a 
huge const-killer). Also, the fact that you have to use Rebindable is highly 
annoying. Still, aside from the bugs, const doesn't seem all that bad to deal 
with (still I just don't have enough experience with it due to aforementioned 
bugs). immutable is far worse because there's no easy way (certainly no generic 
way) to get immutable versions of stuff other than arrays. At least with const, 
you can generally pass non-const stuff to it and it's fine, but you can't do 
the 
same with immutable. The lack of a mutable qualifier seems like it could be 
another big problem, but I haven't yet written enough code in D to run into 
that 
issue (still I'm sure I'll run into it eventually and be highly annoyed - it's 
just needed too often in C++ for me not to be happy about it missing in D).

I'm a huge fan of const in C++, and I _really_ want to be able to use it in D 
(the lack of const in D1 is one of the big reasons that chose to use D2 even 
when it was new rather than mess with D1), but the bugs related to it have made 
it difficult, and I just haven't written very much large stuff in D - and 
that's 
where you really need it.

- Jonathan M Davis


The Status of Const

2010-08-12 Thread dsimcha
This is from a discussion that originated on the Phobos mailing list, but I
thought I'd bring up the question of what should be done about const on the
newsgroup to see what others think:

Despite its theoretical beauty, I find D's const/immutable system to be
utterly useless for all but the simplest use cases.  I made a serious attempt
a while back to use it in a real multithreaded program.  In hindsight it was
more trouble than it was worth, largely for three reasons:

1.   It's difficult to create non-trivial immutable data structures, and often
impossible without relying on either unchecked casts or unnecessary copying.

2.  Much generic code in Phobos (even things as simple as std.math.pow()
before I recently fixed it) behaves incorrectly when given const/immutable
data.  This also applies to other libraries I use, including ones that I'm the
main author of, so I'm just as guilty of it as anyone.  Given that noone,
including me, seems to be able to get const to interact well with generic
code, perhaps we need a language-level solution.

3.  inout is currently so bug-ridden it's not even funny.  (Though this is
clearly fixable long-term, once we get higher priority stuff off our plates.)

It would have probably been better if this was brought to a head sooner, but
it's better late than never.  Do others agree that D's const system is
difficult to impossible to use properly?  Has anyone successfully used D's
const system in a non-trivial setting despite these limitations?  If so, was
it more trouble than it was worth in hindsight?  How can these limitations be
worked around and/or fixed?


Matlab and D

2010-08-12 Thread Trass3r
Has anyone tried to create MEX files or manipulate MAT files with D yet  
(and thus probably has bindings or a wrapper)?


So far I only found a C++ wrapper for MAT written by Christian Kamm here:
http://www.incasoftware.de/~kamm/projects/index.php/2007/10/05/matlab-file-access/


Re: LDC can't import std.stdio

2010-08-12 Thread mwarning
On Thu, 12 Aug 2010 23:21:15 +0200, Borneq wrote:

> I install ldc under Ubuntu. When I compile import std.stdio show error:
> first.d(1): Error: module stdio cannot read file 'std/stdio.d'

LDC doesn't support D2 or Phobos, but D1/Tango (dsource.org/projects/
tango):

try this:

import tango.io.Stdout;

void main()
{
  Stdout("Hello World!").newline;
}


Re: Time for ng name fixes?

2010-08-12 Thread Trass3r
I don't know, a distinction based on language and library specific stuff  
could also be made.


LDC can't import std.stdio

2010-08-12 Thread Borneq

I install ldc under Ubuntu. When I compile import std.stdio
show error:
first.d(1): Error: module stdio cannot read file 'std/stdio.d'


Re: Destructor semantics

2010-08-12 Thread Michel Fortin

On 2010-08-12 16:08:17 -0400, Don  said:

That's the only example of an nearly unlimited resource which I've 
heard thus far, but that raises the question, why the hell would you be 
using malloc if you're not going to free it, when you have a language 
with a gc? Effectively, the gc is freeing your malloced memory.


I can think of a couple of reasons for using malloc, but finalisers 
aren't a good solution to any of them.


For one thing, you could ask Andrei why he based std.containers.Array 
on malloc/free with a reference counter. Not being able to use Array as 
a member of a class would be quite drastic.



Hypothesis: if a finalizer is run, where it actually DOES something (as 
opposed to, for example, running a pile of asserts), there's always a 
bug.


It's an extreme hypothesis, so it should be really easy to disprove.
Can you come up with a counterexample?


Here is a real-world example: the D/Objective-C bridge use a class 
destructor/finalizer to release the Objective-C counterpart of a 
wrapper (by calling the release method on the Objective-C object). The 
Objective-C object is not something I can allocate with the D GC, and 
the D counterpart wouldn't be very usable if it was not managed by the 
D GC. So finalization does the cleanup, and that works just fine.


I wonder what QtD does, but it's probably something similar too.

--
Michel Fortin
michel.for...@michelf.com
http://michelf.com/



Head-to-head comparison of Go and D on golang-nuts

2010-08-12 Thread Andrei Alexandrescu

Just got wind from a kind soul:

http://groups.google.com/group/golang-nuts/browse_thread/thread/f24e7d46091e27ab?pli=1

You may want to contribute with information and informed opinions.


Andrei


Re: Overloading Lazy Vs. Non-Lazy

2010-08-12 Thread Jonathan M Davis
On Thursday, August 12, 2010 13:47:40 dsimcha wrote:
> Just to clarify:  enforce() calls a function called bailOut() if necessary
> that actually does the throwing.  This of course is not inlined w.r.t.
> enforce(). However, the lazy parameter also prevents inlining of enforce()
> itself and generates a ton of code at the ASM level.
> 
> Don is right, though.  In principle, when a statically known delegate D
> (lazy is just syntactic sugar for delegates) that returns a statically
> known constant is passed to a statically known function F, D can be
> inlined w.r.t. F and F can be inlined w.r.t. its caller.
> 
> The problem, though, is that F needs to be inlined first so that the
> compiler can optimize F w.r.t. the parameters passed to it from a specific
> caller.  However, F won't look worth inlining until the compiler realizes
> that it can inline D w.r.t. F.  Therefore, the compiler would need an
> inliner that uses something more sophisticated than a simple greedy
> algorithm to discover this optimization opportunity.

Well, from everything I've heard about the inliner, we're going to need a 
smarter one at some point. Whether we need one soon is another matter, but at 
some point, we really should have an inliner capable of handling these sort of 
cases. It sounds like dmd's inliner is pretty simplistic, and that's going to 
make it harder to make stuff like Phobos properly efficient.

- Jonathan M Davis


Re: Overloading Lazy Vs. Non-Lazy

2010-08-12 Thread dsimcha
== Quote from Don (nos...@nospam.com)'s article
> Steven Schveighoffer wrote:
> > On Thu, 12 Aug 2010 02:00:00 -0400, Brad Roberts 
> > wrote:
> >
> >> On 8/11/2010 6:19 AM, dsimcha wrote:
> >>> An issue that's come up here several times before is that enforce()
> >>> effectively disables inlining of the function it's used in.  From
> >>> reading some
> >>> disassemblies, the reason seems to be because of all the ASM code that's
> >>> required for lazy parameters.  I wonder if either of the following is
> >>> feasible:
> >>>
> >>> 1.  When a function takes a lazy parameter, the compiler automatically
> >>> generates two versions under the hood:  One that actually takes a
> >>> non-lazy
> >>> parameter and is used when the value is known at compile time and
> >>> another that
> >>> works like current lazy functions.  The only problem here is that
> >>> this might
> >>> create issues when using function pointers/delegates.
> >>>
> >>> 2.  Allow overloading of lazy and non-lazy functions, with the rule
> >>> that the
> >>> lazy version gets called whenever the value must be computed at
> >>> runtime and
> >>> the non-lazy version gets called if the value is statically known and
> >>> thus
> >>> there's no evaluation to speak of.
> >>
> >> It's the throw that blocks inlining right now.  Lazy might also
> >> disable inlining
> >> too, I haven't looked for that case.  Either way, that's purely a
> >> quality of
> >> implementation issue.  I don't think it'd be a good idea to bend the
> >> library all
> >> that much to work around that kind of limitation.  It's something that
> >> will get
> >> better as time permits.
> >
> > Well, there's something to be said about preventing the bloated
> > generation of code that accompanies lazy.
> Inlining a lazy function that only returns a compile-time constant could
> inline very nicely. The delegate would disappear completely.

Just to clarify:  enforce() calls a function called bailOut() if necessary that
actually does the throwing.  This of course is not inlined w.r.t. enforce().
However, the lazy parameter also prevents inlining of enforce() itself and
generates a ton of code at the ASM level.

Don is right, though.  In principle, when a statically known delegate D (lazy is
just syntactic sugar for delegates) that returns a statically known constant is
passed to a statically known function F, D can be inlined w.r.t. F and F can be
inlined w.r.t. its caller.

The problem, though, is that F needs to be inlined first so that the compiler 
can
optimize F w.r.t. the parameters passed to it from a specific caller.  However, 
F
won't look worth inlining until the compiler realizes that it can inline D 
w.r.t.
F.  Therefore, the compiler would need an inliner that uses something more
sophisticated than a simple greedy algorithm to discover this optimization
opportunity.


Re: [OT] LALR table-generation docs?

2010-08-12 Thread Justin Johansson

Though it sounds like you are looking for something more distilled,
this is the definitive resource:

Alfred V. Aho, Ravi Sethi, and Jeffrey D. Ullman. Compilers: Principles, 
Techniques, and Tools Addison--Wesley, 1986. (AKA The Dragon Book, 
describes the traditional techniques for building LALR(1) parsers.)


Cheers
Justin Johansson


Nick Sabalausky wrote:
Does anyone have any particular recommendations for a good book/webpage that 
explains how to generate LALR tables? Something that, as much as possible, 
assumes a programmer audience, not a mathematician audience.





Re: Time for ng name fixes?

2010-08-12 Thread Nick Sabalausky
"Trass3r"  wrote in message 
news:op.vhccppb73nc...@enigma.fem.tu-ilmenau.de...
> Am 12.08.2010, 21:00 Uhr, schrieb Nick Sabalausky :
>
>> Considering the recent flood of posts in here that have D.learn content,
>> maybe it's time to finally do the NG name changes that have been talked
>> about before?
>
> Yep, at least D should be renamed into something that indicates the 
> discussion of language-specific stuff.

It would help to have a clear set of requirements. For instance, should 
off-topic and "general" topics:

- Stay in this "language discussion" area (so maybe rename "D" to "D.misc"?)
- Move to the "asking/learning about the language" area (so maybe rename 
"D.learn" to "D.users" and "D" to "D.dev")
- Or have it's own area (so create a "D.misc" and rename "D" to "D.dev")

?

And I still think D.learn (or whatever it ends up beng called) should be 
listed *first* on the website.




Re: Overloading Lazy Vs. Non-Lazy

2010-08-12 Thread Don

Steven Schveighoffer wrote:
On Thu, 12 Aug 2010 02:00:00 -0400, Brad Roberts  
wrote:



On 8/11/2010 6:19 AM, dsimcha wrote:

An issue that's come up here several times before is that enforce()
effectively disables inlining of the function it's used in.  From 
reading some

disassemblies, the reason seems to be because of all the ASM code that's
required for lazy parameters.  I wonder if either of the following is 
feasible:


1.  When a function takes a lazy parameter, the compiler automatically
generates two versions under the hood:  One that actually takes a 
non-lazy
parameter and is used when the value is known at compile time and 
another that
works like current lazy functions.  The only problem here is that 
this might

create issues when using function pointers/delegates.

2.  Allow overloading of lazy and non-lazy functions, with the rule 
that the
lazy version gets called whenever the value must be computed at 
runtime and
the non-lazy version gets called if the value is statically known and 
thus

there's no evaluation to speak of.


It's the throw that blocks inlining right now.  Lazy might also 
disable inlining
too, I haven't looked for that case.  Either way, that's purely a 
quality of
implementation issue.  I don't think it'd be a good idea to bend the 
library all
that much to work around that kind of limitation.  It's something that 
will get

better as time permits.


Well, there's something to be said about preventing the bloated 
generation of code that accompanies lazy.


Inlining a lazy function that only returns a compile-time constant could 
inline very nicely. The delegate would disappear completely.



But throwing preventing inlining is a bad one, that should be fixed.

-Steve


Re: Destructor semantics

2010-08-12 Thread Don

Steven Schveighoffer wrote:
On Thu, 12 Aug 2010 13:05:53 -0400, Joe Greer  
wrote:



"Steven Schveighoffer"  wrote in
news:op.vhbtwjhoeav...@localhost.localdomain:


Logically speaking if an object isn't destructed, then it lives
forever and if it continues to hold it's resource, then we have a
programming error.  The GC is for reclaiming memory, not files.  It
can take a long time for a GC to reclaim an object and you surely
don't want a file locked for that long anymore than you want it held
open forever.  My point is, that it is a programming error to expect
the GC be involved in reclaiming anything but memory.  IMO, the best
use of a finalizer is to error out if an object holding a resource
hasn't been destructed, because there is obviously a programming
error here and something has leaked. GCs aren't there to support
sloppy programming.  They are there to make your life easier and
safer.


An open file maybe, but why should the compiler decide the severity of
not  closing the resource?  What if the resource is just some
C-malloc'd memory?


That's the only example of an nearly unlimited resource which I've heard 
thus far, but that raises the question, why the hell would you be using 
malloc if you're not going to free it, when you have a language with a 
gc? Effectively, the gc is freeing your malloced memory.


I can think of a couple of reasons for using malloc, but finalisers 
aren't a good solution to any of them.


That's a possible solution.  I just don't like the blanket assumptions 
being made.


Actually it's the absence of a use case.

Hypothesis: if a finalizer is run, where it actually DOES something (as 
opposed to, for example, running a pile of asserts), there's always a bug.


It's an extreme hypothesis, so it should be really easy to disprove.
Can you come up with a counterexample?


Re: Time for ng name fixes?

2010-08-12 Thread Trass3r

Am 12.08.2010, 21:00 Uhr, schrieb Nick Sabalausky :


Considering the recent flood of posts in here that have D.learn content,
maybe it's time to finally do the NG name changes that have been talked
about before?


Yep, at least D should be renamed into something that indicates the  
discussion of language-specific stuff.


[OT] LALR table-generation docs?

2010-08-12 Thread Nick Sabalausky
Does anyone have any particular recommendations for a good book/webpage that 
explains how to generate LALR tables? Something that, as much as possible, 
assumes a programmer audience, not a mathematician audience.




Re: Destructor semantics

2010-08-12 Thread Michel Fortin
On 2010-08-12 15:18:33 -0400, "Steven Schveighoffer" 
 said:



On Thu, 12 Aug 2010 13:05:53 -0400, Joe Greer   wrote:


I think you misunderstand what I was saying.  The compiler doesn't decide
any of that.  The programmer conserned with correctness has the option of
making his finalizer complain about unfreed resources.  I language
shouldn't be your nanny, but it should encourage and enable you to do the
right thing.  There is just no substitute for knowing how to program.


So you mark a struct something like:

@noheap struct File
{...}

That's a possible solution.  I just don't like the blanket assumptions  
being made.


I don't like this assumption either. But short of a type system that 
track the owner of each memory block, all our choices will rely on the 
assumption that the programmer has done the finalizer right. Separating 
the concept of destructor and finalizer should help people realize the 
difference, but finalizers will still be a very tricky thing.


By the way, there's currently a couple of structs in Phobos that aren't 
GC-friendly -- they basically have races when their destructor is 
called during the collection cycle (and File is one of them). I'm more 
and more of the opinion that the language itself should just block you 
from dereferencing members in the finalizer (with some sort of cast to 
bypass this if needed, but then you'll think twice about what you're 
doing). See bug 4624:




--
Michel Fortin
michel.for...@michelf.com
http://michelf.com/



Re: Custom Blocks

2010-08-12 Thread KennyTM~

On Aug 13, 10 02:56, KennyTM~ wrote:

On Aug 12, 10 23:42, Robert Jacques wrote:

On Thu, 12 Aug 2010 07:43:25 -0400, KennyTM~  wrote:


On Aug 12, 10 10:25, Robert Jacques wrote:

On Wed, 11 Aug 2010 17:54:35 -0400, Tomek Sowiński  wrote:


Robert Jacques napisał:


I was thinking something like this:

void fun(int x, int y, int z, delegate void(int, int, int) dg)

fun(x, y, z, a, b, c) { body }

|
V

fun(x, y, z, (a, b, c) { body });


Mixing function args with delegate args makes me think of foreach:

fun(x, y, z, (a, b, c) { body }); <=> fun(a, b, c; x, y, z) { body }


All great, but if there's no remedy for the return WTF, I'd leave this
(nice) feature in the drawer.

void foo() {
fun(a, b, c; x, y, z) {
return; // who returns?
}
}


Tomek


Fun does. This is the same as function/delegate literals today.
Of course, putting a return statement inside a foreach block is
probably
a buggy edge case right now; sometimes it causes the parent scope to
return and sometimes it doesn't compile.


This is an unacceptable buggy edge case. Consider the already-working
code

int find_three(int[] arr) {
foreach (i, x; arr) {
if (x == 3)
return i;
}
return -1;
}

If I replace the foreach with a custom block e.g.

int find_three_retro(int[] arr) {
foreach_retro (i, x; arr) {
if (x == 3)
return i;
}
return -1;
}

then suddenly the function doesn't work anymore. It's better not to
provide a feature inconsistent with other parts of the language.


Code that exploits a bug in the implementation isn't "working" in any
sense of the word. One of the points I was making is that return
statements inside a foreach do different things depending on what you're
foreaching over. So this feature would be adding consistency, not
removing it.




void locate_three_or_five(int[] arr) {
int res = -1;
foreach (i, x; arr) {
if_is_one_of(x, [3, 5]) {
res = i;
break; // now what?
}
}
writeln("found 3 or 5 at ", res);
}



This could be resolved by just disallowing local return in this syntax. 
And then make these @keyword functions (foreach_retro, if_is_one_of) to 
be written like opApply. Of course this means things like


int foo = reduce( ... ) {
  ...
}

is impossible.


Re: Destructor semantics

2010-08-12 Thread Steven Schveighoffer
On Thu, 12 Aug 2010 13:05:53 -0400, Joe Greer   
wrote:



"Steven Schveighoffer"  wrote in
news:op.vhbtwjhoeav...@localhost.localdomain:


Logically speaking if an object isn't destructed, then it lives
forever and if it continues to hold it's resource, then we have a
programming error.  The GC is for reclaiming memory, not files.  It
can take a long time for a GC to reclaim an object and you surely
don't want a file locked for that long anymore than you want it held
open forever.  My point is, that it is a programming error to expect
the GC be involved in reclaiming anything but memory.  IMO, the best
use of a finalizer is to error out if an object holding a resource
hasn't been destructed, because there is obviously a programming
error here and something has leaked. GCs aren't there to support
sloppy programming.  They are there to make your life easier and
safer.


An open file maybe, but why should the compiler decide the severity of
not  closing the resource?  What if the resource is just some
C-malloc'd memory?

Note, you are free to write your finalizer to do exactly what you want
 (print some error if it's called and the file's still open).  I just
don't  think the compiler should be involved in the decision, because
it's too  ill-equipped to make one.

-Steve


I think you misunderstand what I was saying.  The compiler doesn't decide
any of that.  The programmer conserned with correctness has the option of
making his finalizer complain about unfreed resources.  I language
shouldn't be your nanny, but it should encourage and enable you to do the
right thing.  There is just no substitute for knowing how to program.


So you mark a struct something like:

@noheap struct File
{...}

That's a possible solution.  I just don't like the blanket assumptions  
being made.


-Steve


Re: Integer Square Root

2010-08-12 Thread Don

Mike James wrote:
Would it be more useful to have a true integer square root rather than 
overloading the real square root? 


cast(int)sqrt() is MUCH quicker than any other way of doing it. Note 
that overloading sqrt is a temporary hack.

BTW, your code fails for intsqrt(0x8000 * 0x8000) and higher.



Time for ng name fixes?

2010-08-12 Thread Nick Sabalausky
Considering the recent flood of posts in here that have D.learn content, 
maybe it's time to finally do the NG name changes that have been talked 
about before?

Or at the very least, on the website page that lists the NGs, maybe D.learn 
should be placed first?




Re: TDPL: Manual invocation of destructor

2010-08-12 Thread Steven Schveighoffer

On Thu, 12 Aug 2010 14:46:00 -0400, Don  wrote:


bearophile wrote:

Steven Schveighoffer:

By clearing that resource in the destructor, and allowing a way to   
manually call that destructor, the class works in all three  
situations:   manual resource management (via clear), scoped  
destruction, and GC  destruction.

 From what I have seen so far:
1) the semantics of clear() is a mess
2) objects don't get deallocated deterministically when they go out of  
scope
3) and the GC is not deterministic, you can only partially hope your  
destructor will be called at program end, in some random order. And  
sometimes your object destructors will not be called even at the end of  
the program.
 The only thing I see good here is to use a scope(exit) to close the  
file:

auto f = new File(...);
scope(exit) f.close();
...
 While clear, scoped destruction of the object, and GC destruction  
don't seem enough in this situation, or any other situation where there  
you have a resource that is not RAM.


I completely agree. Everything I've read about finalizers indicates that  
it's a completely broken concept. It seems as though it was initially  
envisioned (in Java, in the early documents of C#, etc) as equivalent to  
destructors. Apparently it took some time to realize that the value in  
destructors comes almost entirely from the deterministic lifetime.
Instead, finalizers seem to be equivalent to registering a callback with  
the runtime.


No, it's purpose is to be a last-ditch effort to clean up unmanaged  
resources.  It's kind of like a safety net.


Essentially, if you are relying on the GC to destroy your object, and you  
haven't cleaned up all the resources in that object, you don't want those  
resources to leak.  Once the object is destroyed, the resource is leaked  
if it's not cleaned up.  Is allowing the destructor to clean up your  
resource a program error?  It's up to the developer to decide that.


D still lacks a standard way of deterministic destruction.  Clear doesn't  
work because it still calls the destructor, and the destructor must assume  
it's non-deterministic.


Their main legitimate use seems to be for contract programming (though  
I've never heard it described in that way): at the moment of garbage  
collection, check that the destructor has actually been run.


It can be set up this way, just throw an exception if the resource isn't  
cleaned up instead of silently cleaning up the mess in your destructor.


-Steve


Re: Custom Blocks

2010-08-12 Thread KennyTM~

On Aug 12, 10 23:42, Robert Jacques wrote:

On Thu, 12 Aug 2010 07:43:25 -0400, KennyTM~  wrote:


On Aug 12, 10 10:25, Robert Jacques wrote:

On Wed, 11 Aug 2010 17:54:35 -0400, Tomek Sowiński  wrote:


Robert Jacques napisał:


I was thinking something like this:

void fun(int x, int y, int z, delegate void(int, int, int) dg)

fun(x, y, z, a, b, c) { body }

|
V

fun(x, y, z, (a, b, c) { body });


Mixing function args with delegate args makes me think of foreach:

fun(x, y, z, (a, b, c) { body }); <=> fun(a, b, c; x, y, z) { body }


All great, but if there's no remedy for the return WTF, I'd leave this
(nice) feature in the drawer.

void foo() {
fun(a, b, c; x, y, z) {
return; // who returns?
}
}


Tomek


Fun does. This is the same as function/delegate literals today.
Of course, putting a return statement inside a foreach block is probably
a buggy edge case right now; sometimes it causes the parent scope to
return and sometimes it doesn't compile.


This is an unacceptable buggy edge case. Consider the already-working
code

int find_three(int[] arr) {
foreach (i, x; arr) {
if (x == 3)
return i;
}
return -1;
}

If I replace the foreach with a custom block e.g.

int find_three_retro(int[] arr) {
foreach_retro (i, x; arr) {
if (x == 3)
return i;
}
return -1;
}

then suddenly the function doesn't work anymore. It's better not to
provide a feature inconsistent with other parts of the language.


Code that exploits a bug in the implementation isn't "working" in any
sense of the word. One of the points I was making is that return
statements inside a foreach do different things depending on what you're
foreaching over. So this feature would be adding consistency, not
removing it.




void locate_three_or_five(int[] arr) {
   int res = -1;
   foreach (i, x; arr) {
  if_is_one_of(x, [3, 5]) {
 res = i;
 break; // now what?
  }
   }
   writeln("found 3 or 5 at ", res);
}



Re: Is there a report for performance compared with popular languarge?

2010-08-12 Thread Nick Sabalausky
"cglee"  wrote in message 
news:i3vpkj$1mi...@digitalmars.com...
> Hi,
>
> I have used 'C' and 'jav'a for several years.
> When I need speed, I used 'C'.
> When I have to reduce implemetation time, I used 'java'.
> In my view, D language has both merits from 'C' and 'java'.
> It means that it is OOP, but it generates native binary
> without VM. We already have C++ as this. But C++ makes me
> more confused when I use it.
>
> Now, I have questions about how much 'D' is fast comparing with 'java'
> and how much bigger in binary size generated by 'D' comparing with
> 'C'.  Is there anyone has information about this?.
>

http://dotnot.org/blog/archives/2008/03/10/xml-benchmarks-updated-graphs-with-rapidxml/

http://dotnot.org/blog/archives/2008/03/10/xml-benchmarks-parsequerymutateserialize/

http://dotnot.org/blog/archives/2008/03/12/why-is-dtango-so-fast-at-parsing-xml/





Phobos urllib

2010-08-12 Thread Mengu
Hello everyone,

Python has a library named urllib which can be found at 
http://docs.python.org/library/urllib2.html. 

Does Phobos have anything similar to this library? All I need is fetching data 
from a web site.


Re: How Garbage Collector works?

2010-08-12 Thread Rory Mcguire
Borneq wrote:

> Użytkownik "Lars T. Kyllingstad"  napisał w
> wiadomości news:i40dhi$55...@digitalmars.com...
>> Since the GC keeps track of the length of the memory block, it can also
>> tell whether the pointer is inside the memory block.
>>  if (pointer >= startOfBlock && pointer < startOfBlock + blockLength)
>>  doNotCollect();
> 
> How compute startOfBlock ? GC keep startOfBlock for each pointer (pointer
> consits of actual pointer and pointer to startOfBlock)?
> or search for pointer such Block that pointer betwen
> startOfBlock..startOfBlock + blockLength ?

GC doesn't keep track of pointer, it only keeps track of the start of 
allocated memory and the length of that allocated block.

it then has to scan to see if there are any pointers into that allocated 
block. This is why if you slice a subsection of an array the memory doesn't 
just get freed.

-Rory


Re: TDPL: Manual invocation of destructor

2010-08-12 Thread Don

bearophile wrote:

Steven Schveighoffer:

By clearing that resource in the destructor, and allowing a way to  
manually call that destructor, the class works in all three situations:   
manual resource management (via clear), scoped destruction, and GC  
destruction.


From what I have seen so far:
1) the semantics of clear() is a mess
2) objects don't get deallocated deterministically when they go out of scope
3) and the GC is not deterministic, you can only partially hope your destructor 
will be called at program end, in some random order. And sometimes your object 
destructors will not be called even at the end of the program.

The only thing I see good here is to use a scope(exit) to close the file:
auto f = new File(...);
scope(exit) f.close();
...

While clear, scoped destruction of the object, and GC destruction don't seem 
enough in this situation, or any other situation where there you have a 
resource that is not RAM.


I completely agree. Everything I've read about finalizers indicates that 
it's a completely broken concept. It seems as though it was initially 
envisioned (in Java, in the early documents of C#, etc) as equivalent to 
destructors. Apparently it took some time to realize that the value in 
destructors comes almost entirely from the deterministic lifetime.
Instead, finalizers seem to be equivalent to registering a callback with 
the runtime.


Their main legitimate use seems to be for contract programming (though 
I've never heard it described in that way): at the moment of garbage 
collection, check that the destructor has actually been run.







I think in time, the GC may be associated with it's own thread, and may  
run on a schedule vs. having to wait for a memory allocation to run.  When  
this happens, it's more likely you can rely on the GC to free the  
resources in a reasonable amount of time.


I'll believe that only when I see it. Even one of the most advanced GC around, 
the one in the Sun JVM, doesn't act as deterministically as you say (maybe the 
G1 now does, I am not sure).

Instead of a clear() function it can be added to classes and structs an 
optional standard method (like .clear()) that when called performs the cleaning 
of the object, frees all resources (but not the RAM used by the object 
instance), puts references to null, etc. The deallocation of the RAM is fully 
left to the GC later. An class that defines clear() keeps the extra bit of 
state to tell apart the living or dead state of the object, plus an extra 
assert in the class invariant. This is just an idea, probably not too much good 
:-)

Bye,
bearophile


Re: A const idiom + a different 'delete'

2010-08-12 Thread Pillsy
Shin Fujishiro Wrote:

> bearophile  wrote:
> > This is an alternative way to write it that I've never used 
> < because I don't like it much:

> > void main() {
> > const(int[int]) aa = {
> > int[int] result;
> > foreach (i; 0 .. 10)
> > result[i] = i * i;
> > return result;
> > }();
> > }

> It looks like LISP's (let ...) expression and personally I like it.
> The idiom is really useful for building immutable things, including
> compile-time constants.

It also makes for a fine replacement for the comma operator, because you can 
use it anywhere you can use an expression. 

I'd love a bit of syntactic sugar for the idiom, that would do the same thing 
the Lisp LET does, transforming

   let (x = a, y = b) { foo(x); bar(y); return quux(x, y); } 

into 

   (x, y){ foo(x); bar(y); return quux(x, y); }(a, b)

automatically.

Cheers,
Pillsy


Re: Destructor semantics

2010-08-12 Thread Joe Greer
"Steven Schveighoffer"  wrote in
news:op.vhbtwjhoeav...@localhost.localdomain: 

>> Logically speaking if an object isn't destructed, then it lives
>> forever and if it continues to hold it's resource, then we have a
>> programming error.  The GC is for reclaiming memory, not files.  It
>> can take a long time for a GC to reclaim an object and you surely
>> don't want a file locked for that long anymore than you want it held
>> open forever.  My point is, that it is a programming error to expect
>> the GC be involved in reclaiming anything but memory.  IMO, the best
>> use of a finalizer is to error out if an object holding a resource
>> hasn't been destructed, because there is obviously a programming
>> error here and something has leaked. GCs aren't there to support
>> sloppy programming.  They are there to make your life easier and
>> safer. 
> 
> An open file maybe, but why should the compiler decide the severity of
> not  closing the resource?  What if the resource is just some
> C-malloc'd memory? 
> 
> Note, you are free to write your finalizer to do exactly what you want
>  (print some error if it's called and the file's still open).  I just
> don't  think the compiler should be involved in the decision, because
> it's too  ill-equipped to make one.
> 
> -Steve

I think you misunderstand what I was saying.  The compiler doesn't decide 
any of that.  The programmer conserned with correctness has the option of 
making his finalizer complain about unfreed resources.  I language 
shouldn't be your nanny, but it should encourage and enable you to do the 
right thing.  There is just no substitute for knowing how to program.

joe


Re: Overloading Lazy Vs. Non-Lazy

2010-08-12 Thread dsimcha
== Quote from Pillsy (pillsb...@gmail.com)'s article
> ...if you have to write
> enforce(condition,
>(){ return "compile-time-string" ~ type.stringof; });
> one time in a hundred, is it really that bad?
> Cheers,
> Pillsy

I think the point was that even this should be automagically evaluated at 
compile
time, since type.stringof is a compile time constant.


Re: Fwd: ddoc file on command line

2010-08-12 Thread Yao G.
Correction, it still don't work. I was eagerly optimistic in my early  
message. But I think I found out what's happening. I'll do a little bit  
more of test with my modified ddoc file and will post the results.


Re: Destructor semantics

2010-08-12 Thread Rainer Deyke
On 8/12/2010 06:59, Joe Greer wrote:
> Logically speaking if an object isn't destructed, then it lives forever 
> and if it continues to hold it's resource, then we have a programming 
> error.  The GC is for reclaiming memory, not files.  It can take a long 
> time for a GC to reclaim an object and you surely don't want a file 
> locked for that long anymore than you want it held open forever.

Furthermore, the GC is conservative, so it isn't guaranteed to collect
any particular object at all, even if manually invoked.  (This also
means that any D program that relies in the GC potentially leaks memory.)


-- 
Rainer Deyke - rain...@eldwood.com


Re: Fwd: ddoc file on command line

2010-08-12 Thread Yao G.
Yep. That seems to do the trick. Maybe this should be documented, that the  
ddoc file should be the first file passed to the command line. Thanks  
Walter.


--
Yao G.


Re: Overloading Lazy Vs. Non-Lazy

2010-08-12 Thread Pillsy
Steven Schveighoffer Wrote:
[...]
> Hold on, can't we have enforce and lenforce (lazy enforce)?

Or couldn't we have an overload for enforce that takes a string, and another 
overload that takes a void delegate returning a string? 

It makes the syntax a little grottier, but...

>  From a simple grep, 99% of enforce instances are:

> enforce(condition)
>   -or-
> enforce(condition, "compile-time-string")
>   -or-
> enforce(condition, "compile-time-string" ~ type.stringof)

...if you have to write

enforce(condition, 
   (){ return "compile-time-string" ~ type.stringof; });

one time in a hundred, is it really that bad? 
 
Cheers,
Pillsy


Re: Custom Blocks

2010-08-12 Thread Robert Jacques

On Thu, 12 Aug 2010 07:43:25 -0400, KennyTM~  wrote:


On Aug 12, 10 10:25, Robert Jacques wrote:

On Wed, 11 Aug 2010 17:54:35 -0400, Tomek Sowiński  wrote:


Robert Jacques napisał:


I was thinking something like this:

void fun(int x, int y, int z, delegate void(int, int, int) dg)

fun(x, y, z, a, b, c) { body }

|
V

fun(x, y, z, (a, b, c) { body });


Mixing function args with delegate args makes me think of foreach:

fun(x, y, z, (a, b, c) { body }); <=> fun(a, b, c; x, y, z) { body }


All great, but if there's no remedy for the return WTF, I'd leave this
(nice) feature in the drawer.

void foo() {
fun(a, b, c; x, y, z) {
return; // who returns?
}
}


Tomek


Fun does. This is the same as function/delegate literals today.
Of course, putting a return statement inside a foreach block is probably
a buggy edge case right now; sometimes it causes the parent scope to
return and sometimes it doesn't compile.


This is an unacceptable buggy edge case. Consider the already-working  
code


int find_three(int[] arr) {
  foreach (i, x; arr) {
if (x == 3)
  return i;
  }
  return -1;
}

If I replace the foreach with a custom block e.g.

int find_three_retro(int[] arr) {
  foreach_retro (i, x; arr) {
if (x == 3)
  return i;
  }
  return -1;
}

then suddenly the function doesn't work anymore. It's better not to  
provide a feature inconsistent with other parts of the language.


Code that exploits a bug in the implementation isn't "working" in any  
sense of the word. One of the points I was making is that return  
statements inside a foreach do different things depending on what you're  
foreaching over. So this feature would be adding consistency, not removing  
it.


Re: How Garbage Collector works?

2010-08-12 Thread Leandro Lucarella
Nick Sabalausky, el 12 de agosto a las 01:00 me escribiste:
> "Borneq"  wrote in message 
> news:i3vt2q$285...@digitalmars.com...
> > Unlike Java, in D there are pointers and structs. Did not prevent it from 
> > operation of Garbage Collector? Where is described garbage collection 
> > algorithm ?
> 
> Most things that are frequently believed to require a sandboxed VM langauge 
> like the JVM are misconceptions. There's nothing about pointers that 
> prevents garbage collection. The pointers do cause some complication, 
> though. For instance, D's GC is a conservative one, and therefore is prone 
> to false pointers occasionally preventing an object from being collected.

Conservativeness have nothing to do with pointers, and actually *all* GC
deal with pointers, is all the GC does, follow pointers to see what
chunks of memory are alive :)

There is a patch[1] to make D support semi-precise GC (only the heap
have type information).

[1] http://d.puremagic.com/issues/show_bug.cgi?id=3463

-- 
Leandro Lucarella (AKA luca) http://llucax.com.ar/
--
GPG Key: 5F5A8D05 (F8CD F9A7 BF00 5431 4145  104C 949E BFB6 5F5A 8D05)
--
PROTESTA EN PLAZA DE MAYO: MUSICO SE COSIO LA BOCA
-- Crónica TV


Re: Am I doing it wrong or is this a bug ?

2010-08-12 Thread Ezneh
Mafi Wrote:

> Hi,
> returning an int works because D's int and most other language's (eg 
> C's) int are identical. D's string is an alias for 'immutable(char)[]'. 
> The brackets [] idicate an D array. D arrays are not the same as C 
> arrays. In C strings are char* pointing to a null terminated sequence of 
> chars. In D they are more complicated.
> Just let your function return char* replace 'return xy;' with 'return 
> toStringz(xy);'. Then put 'import std.string' at the begining of your 
> file. Then you do this your function will return c-like strings for 
> interfacing with C and C++.


Thanks ! It works well :-), and for integers (other message), I didn't replace 
the DLL so I got wrong value.

I think I should learn phobos and druntime libraries before asking something 
like that.


Ok, there's no problem now.


Re: How Garbage Collector works?

2010-08-12 Thread BCS

Hello Borneq,


Użytkownik "Lars T. Kyllingstad"  napisał
w wiadomości news:i40dhi$55...@digitalmars.com...


Since the GC keeps track of the length of the memory block, it can
also
tell whether the pointer is inside the memory block.
if (pointer >= startOfBlock && pointer < startOfBlock + blockLength)
doNotCollect();

How compute startOfBlock ? GC keep startOfBlock for each pointer
(pointer
consits of actual pointer and pointer to startOfBlock)?
or search for pointer such Block that pointer betwen
startOfBlock..startOfBlock + blockLength ?


The GC keeps a some sort of table of what it has allocated. IT can then just 
look up all the startOfBlock/blockLength values.


http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)#Na.C3.AFve_mark-and-sweep

--
... <





Re: How Garbage Collector works?

2010-08-12 Thread Leandro Lucarella
Borneq, el 12 de agosto a las 11:44 me escribiste:
> Użytkownik "Lars T. Kyllingstad" 
> napisał w wiadomości news:i40dhi$55...@digitalmars.com...
> >Since the GC keeps track of the length of the memory block, it can also
> >tell whether the pointer is inside the memory block.
> > if (pointer >= startOfBlock && pointer < startOfBlock + blockLength)
> > doNotCollect();
> 
> How compute startOfBlock ? GC keep startOfBlock for each pointer
> (pointer consits of actual pointer and pointer to startOfBlock)?
> or search for pointer such Block that pointer betwen
> startOfBlock..startOfBlock + blockLength ?

You might find this blog posts interesting, they explain in relative
detail how the D's GC works:
http://www.llucax.com.ar/blog/blog/tag/understanding%20the%20current%20gc
(you probably want to read it in reverse order :)

-- 
Leandro Lucarella (AKA luca) http://llucax.com.ar/
--
GPG Key: 5F5A8D05 (F8CD F9A7 BF00 5431 4145  104C 949E BFB6 5F5A 8D05)
--
Qué sabía Galileo de astronomía, Mendieta! Lo que pasa es que en este
país habla cualquiera.
-- Inodoro Pereyra


Re: Am I doing it wrong or is this a bug ?

2010-08-12 Thread Ezneh
Ezneh Wrote:

> Richard Webb Wrote:
> 
> > Is returning a D string to a non-D language going to cause problems?
> 
> Hmm it seems that returning an int works but returning string / char types 
> doesn't work ...
> 
> 
> Anyone knows why ?


PS : "works" is kinda like "doesn't return an exception" but there's still 
something wrong with the DLL.


//mydll.d
module mydll;
import std.stdio;

extern (C) export int dllprint(int something) { return 
something^^something; }

//test.d
import mydll;
import std.stdio;

int main(string args[])
{
   writeln(mydll.dllprint(2));
   return 0;
}

//Fine prints 4

But using it in .Net environment it prints "0" ...


Re: Am I doing it wrong or is this a bug ?

2010-08-12 Thread Mafi

Am 12.08.2010 15:59, schrieb Ezneh:

Richard Webb Wrote:


Is returning a D string to a non-D language going to cause problems?


Hmm it seems that returning an int works but returning string / char types 
doesn't work ...


Anyone knows why ?

Hi,
returning an int works because D's int and most other language's (eg 
C's) int are identical. D's string is an alias for 'immutable(char)[]'. 
The brackets [] idicate an D array. D arrays are not the same as C 
arrays. In C strings are char* pointing to a null terminated sequence of 
chars. In D they are more complicated.
Just let your function return char* replace 'return xy;' with 'return 
toStringz(xy);'. Then put 'import std.string' at the begining of your 
file. Then you do this your function will return c-like strings for 
interfacing with C and C++.


Re: Am I doing it wrong or is this a bug ?

2010-08-12 Thread Ezneh
Richard Webb Wrote:

> Is returning a D string to a non-D language going to cause problems?

Hmm it seems that returning an int works but returning string / char types 
doesn't work ...


Anyone knows why ?


Re: Destructor semantics

2010-08-12 Thread Steven Schveighoffer
On Thu, 12 Aug 2010 08:59:31 -0400, Joe Greer   
wrote:



"Steven Schveighoffer"  wrote in
news:op.vhbpkcaieav...@localhost.localdomain:



Destructors as they are now are too limited, because they cannot be
sure  they are being called by the GC or not, they must assume so.  So
in one  sense I agree with you.  But in another sense, we *still* need
a way to  clean up non-GC resources from GC-allocated items.
Preventing GC  allocated items from holding non-GC resources is a step
in a very wrong  direction.

I think any one of the proposals here that separates finalizers from
destructors should be adequate.  My backwards-compatible one is to
pass a  parameter to the destructor indicating whether it's being
called  deterministically or not, but that doesn't lend itself to
preventing @safe  finalizers.  Michael also has one for using ~~this()
and ~this().  We  could designate a method that clear uses, like
dispose() that  deterministically disposes all resources.  I don't
really like the  interface solution, because looking up an interface
is expensive, plus  clear is a template so it doesn't need to use
interfaces.

Whatever gets decided, I don't think anything should prevent them from
 being GC allocated, it's just too limiting for useful code.  The one
initiative the compiler could take is to prevent writing a finalizer
in  @safe code, since that can lead to memory corruption.

-Steve



Logically speaking if an object isn't destructed, then it lives forever
and if it continues to hold it's resource, then we have a programming
error.  The GC is for reclaiming memory, not files.  It can take a long
time for a GC to reclaim an object and you surely don't want a file
locked for that long anymore than you want it held open forever.  My
point is, that it is a programming error to expect the GC be involved in
reclaiming anything but memory.  IMO, the best use of a finalizer is to
error out if an object holding a resource hasn't been destructed, because
there is obviously a programming error here and something has leaked.
GCs aren't there to support sloppy programming.  They are there to make
your life easier and safer.


An open file maybe, but why should the compiler decide the severity of not  
closing the resource?  What if the resource is just some C-malloc'd memory?


Note, you are free to write your finalizer to do exactly what you want  
(print some error if it's called and the file's still open).  I just don't  
think the compiler should be involved in the decision, because it's too  
ill-equipped to make one.


-Steve


Re: Destructor semantics

2010-08-12 Thread Joe Greer
"Steven Schveighoffer"  wrote in
news:op.vhbpkcaieav...@localhost.localdomain: 

> 
> Destructors as they are now are too limited, because they cannot be
> sure  they are being called by the GC or not, they must assume so.  So
> in one  sense I agree with you.  But in another sense, we *still* need
> a way to  clean up non-GC resources from GC-allocated items. 
> Preventing GC  allocated items from holding non-GC resources is a step
> in a very wrong  direction.
> 
> I think any one of the proposals here that separates finalizers from  
> destructors should be adequate.  My backwards-compatible one is to
> pass a  parameter to the destructor indicating whether it's being
> called  deterministically or not, but that doesn't lend itself to
> preventing @safe  finalizers.  Michael also has one for using ~~this()
> and ~this().  We  could designate a method that clear uses, like
> dispose() that  deterministically disposes all resources.  I don't
> really like the  interface solution, because looking up an interface
> is expensive, plus  clear is a template so it doesn't need to use
> interfaces. 
> 
> Whatever gets decided, I don't think anything should prevent them from
>  being GC allocated, it's just too limiting for useful code.  The one 
> initiative the compiler could take is to prevent writing a finalizer
> in  @safe code, since that can lead to memory corruption.
> 
> -Steve
> 

Logically speaking if an object isn't destructed, then it lives forever 
and if it continues to hold it's resource, then we have a programming 
error.  The GC is for reclaiming memory, not files.  It can take a long 
time for a GC to reclaim an object and you surely don't want a file 
locked for that long anymore than you want it held open forever.  My 
point is, that it is a programming error to expect the GC be involved in 
reclaiming anything but memory.  IMO, the best use of a finalizer is to 
error out if an object holding a resource hasn't been destructed, because 
there is obviously a programming error here and something has leaked.  
GCs aren't there to support sloppy programming.  They are there to make 
your life easier and safer.

joe


Integer Square Root

2010-08-12 Thread Mike James
Would it be more useful to have a true integer square root rather than 
overloading the real square root? Something like:


T intsqrt(T)(T i) {
   T bitMask = 1;
   T result = 0;

   bitMask <<= T.sizeof * 4 - 1;

   while (bitMask) {
   result |= bitMask;
   if ((result * result) > i) {
   result &= ~bitMask;
   }
   bitMask >>= 1;
   }

   return result;
}


-=mike=- 



Re: Overloading Lazy Vs. Non-Lazy

2010-08-12 Thread Steven Schveighoffer

On Wed, 11 Aug 2010 18:10:53 -0400, Tomek Sowiński  wrote:


Steven Schveighoffer napisał:


Hold on, can't we have enforce and lenforce (lazy enforce)?

From a simple grep, 99% of enforce instances are:

enforce(condition)
-or-
enforce(condition, "compile-time-string")
-or-
enforce(condition, "compile-time-string" ~ type.stringof)

There are a few ones which actually would be allocating strings at
runtime, but seriously, can't we just modify those to lenforce and get
inlining everywhere else?  I think phobos would see both a huge speedup
and a smaller footprint immediately if enforce did not take a lazy arg.


I like this idea. But > 1 option makes you think and that's painful;)


One possibility is to have enforce force you to pass in a compile-time  
evaluatable string.  I don't really know if this is possible.  But then at  
least the compiler could prevent you from accidentally using the wrong  
enforce.


BTW, am I the only person surprised that in a language whose generic  
code to fit the need can transform like Optimus Prime himself you

can't do lazy <-> non-lazy automagically?


It's been suggested before (by me even):  
http://d.puremagic.com/issues/show_bug.cgi?id=1817


But that would be limited to templates only.  A non-template function  
which takes a lazy argument could not make any conversions.


I'd rather see an overload, or just separate the names.

-Steve


Re: A const idiom + a different 'delete'

2010-08-12 Thread bearophile
Shin Fujishiro:
> import std.conv;
> 
> auto ref reverseArgs(alias fun, Args...)(auto ref Args args)
> {
> return mixin(
> {
> string rargs;
> foreach (i, Arg; Args)
> {
> if (i > 0)
> rargs ~= ", ";
> rargs ~= "args[" ~ to!string(args.length - i - 1) ~ "]";
> }
> return "fun(" ~ rargs ~ ")";
> }());
> }
> 
> void main()
> {
> int div(int a, int b) { return a / b; }
> 
> assert(reverseArgs!div(3, 27) == 9);
> }

I think this is more readable (not tested much):

import std.typecons: TypeTuple;

// this needs to be template of std.typecons
template ReverseTypeTuple(T...) { // too much long name
static if (T.length)
alias TypeTuple!(ReverseTypeTuple!(T[1 .. $]), T[0]) ReverseTypeTuple;
else
alias T ReverseTypeTuple;
}

auto ref reverseArgs(alias fun, Args...)(auto ref Args args) {
return fun(ReverseTypeTuple!args);
}

int div(int a, int b) { return a / b; }

void main() {
assert(reverseArgs!div(3, 27) == 9);
}

Bye,
bearophile


Re: Overloading Lazy Vs. Non-Lazy

2010-08-12 Thread Steven Schveighoffer
On Thu, 12 Aug 2010 02:00:00 -0400, Brad Roberts   
wrote:



On 8/11/2010 6:19 AM, dsimcha wrote:

An issue that's come up here several times before is that enforce()
effectively disables inlining of the function it's used in.  From  
reading some

disassemblies, the reason seems to be because of all the ASM code that's
required for lazy parameters.  I wonder if either of the following is  
feasible:


1.  When a function takes a lazy parameter, the compiler automatically
generates two versions under the hood:  One that actually takes a  
non-lazy
parameter and is used when the value is known at compile time and  
another that
works like current lazy functions.  The only problem here is that this  
might

create issues when using function pointers/delegates.

2.  Allow overloading of lazy and non-lazy functions, with the rule  
that the
lazy version gets called whenever the value must be computed at runtime  
and
the non-lazy version gets called if the value is statically known and  
thus

there's no evaluation to speak of.


It's the throw that blocks inlining right now.  Lazy might also disable  
inlining
too, I haven't looked for that case.  Either way, that's purely a  
quality of
implementation issue.  I don't think it'd be a good idea to bend the  
library all
that much to work around that kind of limitation.  It's something that  
will get

better as time permits.


Well, there's something to be said about preventing the bloated generation  
of code that accompanies lazy.


But throwing preventing inlining is a bad one, that should be fixed.

-Steve


Re: Custom Blocks

2010-08-12 Thread KennyTM~

On Aug 12, 10 10:25, Robert Jacques wrote:

On Wed, 11 Aug 2010 17:54:35 -0400, Tomek Sowiński  wrote:


Robert Jacques napisał:


I was thinking something like this:

void fun(int x, int y, int z, delegate void(int, int, int) dg)

fun(x, y, z, a, b, c) { body }

|
V

fun(x, y, z, (a, b, c) { body });


Mixing function args with delegate args makes me think of foreach:

fun(x, y, z, (a, b, c) { body }); <=> fun(a, b, c; x, y, z) { body }


All great, but if there's no remedy for the return WTF, I'd leave this
(nice) feature in the drawer.

void foo() {
fun(a, b, c; x, y, z) {
return; // who returns?
}
}


Tomek


Fun does. This is the same as function/delegate literals today.
Of course, putting a return statement inside a foreach block is probably
a buggy edge case right now; sometimes it causes the parent scope to
return and sometimes it doesn't compile.


This is an unacceptable buggy edge case. Consider the already-working code

   int find_three(int[] arr) {
 foreach (i, x; arr) {
   if (x == 3)
 return i;
 }
 return -1;
   }

If I replace the foreach with a custom block e.g.

   int find_three_retro(int[] arr) {
 foreach_retro (i, x; arr) {
   if (x == 3)
 return i;
 }
 return -1;
   }

then suddenly the function doesn't work anymore. It's better not to 
provide a feature inconsistent with other parts of the language.


Re: Destructor semantics

2010-08-12 Thread Steven Schveighoffer

On Wed, 11 Aug 2010 16:14:56 -0400, Don  wrote:


Michel Fortin wrote:
On 2010-08-11 15:09:45 -0400, Jonathan M Davis   
said:



On Wednesday, August 11, 2010 11:33:54 Michel Fortin wrote:

I'm not too sure that'll work very well. I think a better solution
would be to have a way to distinguish between a struct that can be put
on the GC heap and one that cannot. A struct that cannot go on the GC
heap make it safe to access GC-managed members in its destructor, and
thus can have a @safe destructor.


But couldn't the fact that a struct has a destructor make it so that  
it can't be

declared anywhere but on the heap? The destructor itself could be what
distinguishes them. I don't see a need for any other @attributes or  
whatnot to

distinguish them.
 Sure, and now you can't use std.containers.Array as a member in a  
Class, neither std.stdio.File, etc. Is there something left classes can  
do?


As far as I can tell, the use cases for finalizers are very limited. To  
me, destructors don't make any sense unless they are deterministic.
For example, I think having a File class is probably a bug. You may be  
on a system which has no limit on the number of file handles, but  
generally, if you need resource management, you need a guarantee that  
the destructor will be called.


If a file handle is stored as part of a class, with a destructor that  
closes the file, the file might never get closed. So I don't think it's  
unreasonable to say that a struct with a destructor cannot be a member  
of a class.


So classes are not allowed to have open files?  That's too limited.   
Deterministic closing of the file is still possible, just not guaranteed.


Here's the thing, we shouldn't be preventing smart people from writing  
useful code because we can't think of a way to make sure all idiot  
programmers close all their resources.  Note also that a resource leak is  
not as damaging as memory corruption, which we have somewhat of an  
obligation to try and prevent idiots from doing.




Personally I think destructors should be restricted to structs and scope  
classes. I suspect that some form of registration with the gc could do  
the job of finalizers.


Destructor <=> deterministic destruction.


Destructors as they are now are too limited, because they cannot be sure  
they are being called by the GC or not, they must assume so.  So in one  
sense I agree with you.  But in another sense, we *still* need a way to  
clean up non-GC resources from GC-allocated items.  Preventing GC  
allocated items from holding non-GC resources is a step in a very wrong  
direction.


I think any one of the proposals here that separates finalizers from  
destructors should be adequate.  My backwards-compatible one is to pass a  
parameter to the destructor indicating whether it's being called  
deterministically or not, but that doesn't lend itself to preventing @safe  
finalizers.  Michael also has one for using ~~this() and ~this().  We  
could designate a method that clear uses, like dispose() that  
deterministically disposes all resources.  I don't really like the  
interface solution, because looking up an interface is expensive, plus  
clear is a template so it doesn't need to use interfaces.


Whatever gets decided, I don't think anything should prevent them from  
being GC allocated, it's just too limiting for useful code.  The one  
initiative the compiler could take is to prevent writing a finalizer in  
@safe code, since that can lead to memory corruption.


-Steve


Re: Is there a report for performance compared with popular languarge?

2010-08-12 Thread bearophile
cglee:

> Now, I have questions about how much 'D' is fast comparing with 'java'
> and how much bigger in binary size generated by 'D' comparing with
> 'C'.  Is there anyone has information about this?.

Performance comes from many different kinds of optimizations. In modern 
languages things as:
- Partial unrolling of loops even when the number of cycles is not known at 
compile-time
- Inlining, even in presence of virtual calls
- If the code performs lot of heap activity (as Java-style code) then a 
significant percentage of the performance comes from the efficiency of the GC.

But today the GPU is used more and more by serious number crunchers. A 
numerical program written in Python that implements its numerical kernels on 
good GPUs using PyCuda, PyopenCL, may be tens of times more efficient than 
average C code written for the CPU (and for numerical kernels on the CPU there 
is corepy). Intel says that the GPU is on average 2.5 only times faster, but in 
practice you need to be a Wizard to squeeze that amount of performance from 
very costly CPUs.

If you compile D1 code with LDC you get a good performance, comparable with C 
or sometimes better. If you use DMD you get lower performance (usually no more 
than 2-3 times slower) on both FP and integer code.

The D GC is not efficient enough yet, so efficient D1/D2 programs need to 
minimize heap activity, and use stack-allocates structs as much as possible, 
and avoid Java-style code.

Currently D programs use less memory than Java, thanks to structs too, but as D 
gets a better GC, it will probably use more RAM too. With GCs there is a 
tradeoff between speed and amount of memory usage.

D binary size is larger than C but comparable to C++ code that uses many 
templates, there is a constant overhead given by statically linked runtime 
that's bigger than the C++ one (GC, array concat, etc). The more templates you 
use, the bigger the binary becomes. Phobos uses templates heavily, Tango for D1 
uses them less often.

Bye,
bearophile


Re: Am I doing it wrong or is this a bug ?

2010-08-12 Thread Richard Webb
Is returning a D string to a non-D language going to cause problems?


Re: Is there a report for performance compared with popular languarge?

2010-08-12 Thread Pelle

On 08/12/2010 05:26 AM, cglee wrote:

Hi,

I have used 'C' and 'jav'a for several years.
When I need speed, I used 'C'.
When I have to reduce implemetation time, I used 'java'.
In my view, D language has both merits from 'C' and 'java'.
It means that it is OOP, but it generates native binary
without VM. We already have C++ as this. But C++ makes me
more confused when I use it.

Now, I have questions about how much 'D' is fast comparing with 'java'
and how much bigger in binary size generated by 'D' comparing with
'C'.  Is there anyone has information about this?.

Thanks
cglee


Last I looked, java is faster than D in some cases, and vice versa.

D will blow up the size of executables by quite a lot, though. Due to 
templates and static linking of libraries, mostly.


Re: How Garbage Collector works?

2010-08-12 Thread Borneq
Użytkownik "Lars T. Kyllingstad"  napisał w 
wiadomości news:i40dhi$55...@digitalmars.com...

Since the GC keeps track of the length of the memory block, it can also
tell whether the pointer is inside the memory block.
 if (pointer >= startOfBlock && pointer < startOfBlock + blockLength)
 doNotCollect();


How compute startOfBlock ? GC keep startOfBlock for each pointer (pointer 
consits of actual pointer and pointer to startOfBlock)?
or search for pointer such Block that pointer betwen 
startOfBlock..startOfBlock + blockLength ?




Re: Am I doing it wrong or is this a bug ?

2010-08-12 Thread Ezneh
Don Wrote:


> You need to make dllprint an extern(C) function. If you just mark it as 
> 'extern', it uses D name mangling, which the other language won't 
> understand.

Seems to work with test.d but I got something like "AccessViolationException - 
Trying to access to a protected memory (read/write). This often means that the 
memory is corrupted" when I try to use it somewhere else. 


Well, I think I'm doing something wrong with that but I dunno what. Maybe I 
need a working dll example ... 


Re: How Garbage Collector works?

2010-08-12 Thread Lars T. Kyllingstad
On Thu, 12 Aug 2010 10:44:51 +0200, Borneq wrote:

> Użytkownik "Nick Sabalausky"  napisał w wiadomości
> news:i40b9m$1ti...@digitalmars.com...
>> The GC keeps track of the starting address and the length of each
>> allocation.
> 
> How to deal with:
> 1.alloc 1000 bytes to pointer
> 2.increment pointer by 500 bytes
> 3.checking if block 1000 bytes is reachable but only pointer is in roots

Since the GC keeps track of the length of the memory block, it can also 
tell whether the pointer is inside the memory block.

  if (pointer >= startOfBlock && pointer < startOfBlock + blockLength)
  doNotCollect();

-Lars


Re: How Garbage Collector works?

2010-08-12 Thread Borneq
Użytkownik "Nick Sabalausky"  napisał w wiadomości 
news:i40b9m$1ti...@digitalmars.com...
The GC keeps track of the starting address and the length of each 
allocation.


How to deal with:
1.alloc 1000 bytes to pointer
2.increment pointer by 500 bytes
3.checking if block 1000 bytes is reachable but only pointer is in roots





Re: Am I doing it wrong or is this a bug ?

2010-08-12 Thread Don

Ezneh wrote:

Hello !

I'm doing some tests with the DLL example which is in the samples directory but 
I have some problem with it.


Well, when I'm compiling the DLL with that files, I got no error and it works 
in the test.d sample but doesn't work in another project (in another language) :

//mydll.d
module mydll;
import std.c.stdio;

export string dllprint() { return "hello"; }


//dll.d

import std.c.windows.windows;
import core.dll_helper;

__gshared HINSTANCE g_hInst;

extern (Windows)
BOOL DllMain(HINSTANCE hInstance, ULONG ulReason, LPVOID pvReserved)
{
switch (ulReason)
{
case DLL_PROCESS_ATTACH:
g_hInst = hInstance;
dll_process_attach( hInstance, true );
break;

case DLL_PROCESS_DETACH:
dll_process_detach( hInstance, true );
break;

case DLL_THREAD_ATTACH:
dll_thread_attach( true, true );
break;

case DLL_THREAD_DETACH:
dll_thread_detach( true, true );
break;
}
return true;
}

// .def file
LIBRARY "mydll.dll"
EXETYPE NT
SUBSYSTEM WINDOWS
CODE SHARED EXECUTE
DATA WRITE

// test.d
import mydll;
import std.stdio;

int main(string args[])
{
   writeln(mydll.dllprint());
   return 0;
}


With all theses files, test.exe works well.

But when I want to use it with another programming language, I got this error :

"Cannot find the entry point for 'dllprint' in 'mydll.dll'


So, I tried to change the .def file like this :

LIBRARY "mydll.dll"
EXETYPE NT
SUBSYSTEM WINDOWS
CODE SHARED EXECUTE
DATA WRITE
EXPORTS
dllprint

but I got this error :

D:\D\dmd\samples\d\mydll>dmd -ofmydll.dll -L/IMPLIB mydll.d dll.d mydll.def
OPTLINK (R) for Win32  Release 8.00.2
Copyright (C) Digital Mars 1989-2009  All rights reserved.
http://www.digitalmars.com/ctg/optlink.html
OPTLINK : Error 180: No Match Found for Export/ENTRY -  : dllprint
OPTLINK : Error 81: Cannot EXPORT : dllprint


So what I'm doing wrong ? Is this a bug from optlink ?
You need to make dllprint an extern(C) function. If you just mark it as 
'extern', it uses D name mangling, which the other language won't 
understand.


Re: How Garbage Collector works?

2010-08-12 Thread Nick Sabalausky
"Borneq"  wrote in message 
news:i4074v$187...@digitalmars.com...
> U¿ytkownik "Nick Sabalausky"  napisa³ w wiadomo¶ci 
> news:i3vv48$2j1...@digitalmars.com...
>> langauge  like the JVM are misconceptions. There's nothing about
>> pointers that  prevents garbage collection. The pointers do cause some
>
> We have array and pointer that not points at start array. When we have 
> want to free memory we mantain 4 bytes pointer+ 4 bytes array positions = 
> 8 bytes (=16 bytes on 64 bits !) ?
> How can free block when pointer not points to begin of block?

The GC keeps track of the starting address and the length of each 
allocation.




Re: A const idiom + a different 'delete'

2010-08-12 Thread Shin Fujishiro
bearophile  wrote:
> This is an alternative way to write it that I've never used because I don't 
> like it much:
> 
> void main() {
> const(int[int]) aa = {
> int[int] result;
> foreach (i; 0 .. 10)
> result[i] = i * i;
> return result;
> }();
> }

It looks like LISP's (let ...) expression and personally I like it.
The idiom is really useful for building immutable things, including
compile-time constants.

And recently I found it works well with string mixins.

import std.conv;

auto ref reverseArgs(alias fun, Args...)(auto ref Args args)
{
return mixin(
{
string rargs;
foreach (i, Arg; Args)
{
if (i > 0)
rargs ~= ", ";
rargs ~= "args[" ~ to!string(args.length - i - 1) ~ "]";
}
return "fun(" ~ rargs ~ ")";
}());
}

void main()
{
int div(int a, int b) { return a / b; }

assert(reverseArgs!div(3, 27) == 9);
}


Am I doing it wrong or is this a bug ?

2010-08-12 Thread Ezneh
Hello !

I'm doing some tests with the DLL example which is in the samples directory but 
I have some problem with it.


Well, when I'm compiling the DLL with that files, I got no error and it works 
in the test.d sample but doesn't work in another project (in another language) :

//mydll.d
module mydll;
import std.c.stdio;

export string dllprint() { return "hello"; }


//dll.d

import std.c.windows.windows;
import core.dll_helper;

__gshared HINSTANCE g_hInst;

extern (Windows)
BOOL DllMain(HINSTANCE hInstance, ULONG ulReason, LPVOID pvReserved)
{
switch (ulReason)
{
case DLL_PROCESS_ATTACH:
g_hInst = hInstance;
dll_process_attach( hInstance, true );
break;

case DLL_PROCESS_DETACH:
dll_process_detach( hInstance, true );
break;

case DLL_THREAD_ATTACH:
dll_thread_attach( true, true );
break;

case DLL_THREAD_DETACH:
dll_thread_detach( true, true );
break;
}
return true;
}

// .def file
LIBRARY "mydll.dll"
EXETYPE NT
SUBSYSTEM WINDOWS
CODE SHARED EXECUTE
DATA WRITE

// test.d
import mydll;
import std.stdio;

int main(string args[])
{
   writeln(mydll.dllprint());
   return 0;
}


With all theses files, test.exe works well.

But when I want to use it with another programming language, I got this error :

"Cannot find the entry point for 'dllprint' in 'mydll.dll'


So, I tried to change the .def file like this :

LIBRARY "mydll.dll"
EXETYPE NT
SUBSYSTEM WINDOWS
CODE SHARED EXECUTE
DATA WRITE
EXPORTS
dllprint

but I got this error :

D:\D\dmd\samples\d\mydll>dmd -ofmydll.dll -L/IMPLIB mydll.d dll.d mydll.def
OPTLINK (R) for Win32  Release 8.00.2
Copyright (C) Digital Mars 1989-2009  All rights reserved.
http://www.digitalmars.com/ctg/optlink.html
OPTLINK : Error 180: No Match Found for Export/ENTRY -  : dllprint
OPTLINK : Error 81: Cannot EXPORT : dllprint


So what I'm doing wrong ? Is this a bug from optlink ?


Re: How Garbage Collector works?

2010-08-12 Thread Borneq
Użytkownik "Nick Sabalausky"  napisał w wiadomości 
news:i3vv48$2j1...@digitalmars.com...

langauge  like the JVM are misconceptions. There's nothing about
pointers that  prevents garbage collection. The pointers do cause some


We have array and pointer that not points at start array. When we have want 
to free memory we mantain 4 bytes pointer+ 4 bytes array positions = 8 bytes 
(=16 bytes on 64 bits !) ?
How can free block when pointer not points to begin of block?