Re: case statements

2009-10-10 Thread Jarrett Billingsley
On Sat, Oct 10, 2009 at 8:45 PM, Ellery Newcomer
ellery-newco...@utulsa.edu wrote:
 This is probably a bad idea, but from my readings of the dmd source, I
 noticed some preprocessor defines that looked useful, along the lines of

 #define CASES case A:case B: (etc)

 I'd kinda like something similar in D, but a naive attempt with mixins
 doesn't work, e.g.

 immutable string cases = case 1: case 2:; //my d2fu sucks

 ..

 switch(x){
    mixin(cases);
      dosomething();
    default:
      dosomething();
 }

 Any ideas (not including concatenating cases with body of case)?

A single string mixin must consist of an entire, fully-formed
statement, expression, or declaration (depending on where it's used).
Case labels do not, on their own, count as a statement.

In addition, there is a bug that prevents you from string-mixing-in
cases inside a switch. For some reason you have to mix in the entire
switch statement.


Re: How about macro == symbol for mixin statement? [was Re: Member functions C to D]

2009-10-08 Thread Jarrett Billingsley
On Thu, Oct 8, 2009 at 4:00 AM, Don nos...@nospam.com wrote:

 So it looks to me like the mechanics of it are basically identical.
 Just Nemerle's syntax is nicer.

 Only with trivial examples. With more complicated examples they look less
 identical. I'm basing my views on pages like this:

 http://nemerle.org/Macros_-_extended_course._Part_2

 Unless I'm totally misunderstanding this, it looks to me as though Nemerle
 macros are implemented as compiler plugins.
 All the advanced facilities are obtained by exposing the compiler's API!

Well they're not.. plugins per se as much as compiled modules.
Okay yes that's basically a plugin :P But it's not that different from
D, where you use compile-time executed functions to do the same sorts
of things. It's just that you precompile those functions instead of
having the compiler compile them on every compilation.

But really, I don't see how this is significantly different from
hooking into the D compiler's internals with __traits, .stringof,
.mangleof and the like. So it uses an object-oriented API to access
those things instead of ad-hoc hacks. And? I don't know how you can
trash Nemerle's approach while leaving D's unmentioned.


Re: How about macro == symbol for mixin statement? [was Re: Member functions C to D]

2009-10-08 Thread Jarrett Billingsley
On Thu, Oct 8, 2009 at 11:25 AM, Don nos...@nospam.com wrote:
 Jarrett Billingsley wrote:

 On Thu, Oct 8, 2009 at 4:00 AM, Don nos...@nospam.com wrote:

 So it looks to me like the mechanics of it are basically identical.
 Just Nemerle's syntax is nicer.

 Only with trivial examples. With more complicated examples they look less
 identical. I'm basing my views on pages like this:

 http://nemerle.org/Macros_-_extended_course._Part_2

 Unless I'm totally misunderstanding this, it looks to me as though
 Nemerle
 macros are implemented as compiler plugins.
 All the advanced facilities are obtained by exposing the compiler's API!

 Well they're not.. plugins per se as much as compiled modules.
 Okay yes that's basically a plugin :P But it's not that different from
 D, where you use compile-time executed functions to do the same sorts
 of things. It's just that you precompile those functions instead of
 having the compiler compile them on every compilation.

 No. CTFE is simply taking constant-folding to its logical conclusion.

All the Nemerle *implementation* is doing differently here is having
you precompile the functions that are to be executed at compile-time.
That's it. The resultant semantics are utterly the same. You are
running code at compile-time, it doesn't matter if that code is
running on the hardware or in a VM in the compiler.

 But really, I don't see how this is significantly different from
 hooking into the D compiler's internals with __traits, .stringof,
 .mangleof and the like. So it uses an object-oriented API to access
 those things instead of ad-hoc hacks. And?

 The thing I think is elegant about D's approach, ugly as the syntax
 currently is, is the complete separation of the lex - parse - semantic -
 codegen phases. And I think CTFE is fantastic (and I plan to fix it so it
 works properly). Think about how easy it is to explain.

And Nemerle's macros are *hard* to explain? They're a function that
executes at compile time. Oh, wait! That's exactly the same as CTFE.

 I don't know how you can trash Nemerle's approach while leaving D's
 unmentioned.

 What do you mean, 'unmentioned'? Hey, you started this by trashing D's
 approach!

I'm not talking about me. I'm talking about you. I don't know how you
can trash a language with macros that were designed *from the bottom
up* to be used as such and which are treated as first-class citizens,
while not admitting the hilariously ad-hoc nature of a language where
macros fall out as a consequence of a number of other, ill-defined
poorly-implemented unorthogonal features.

Sigh, I'm done.


Re: Member functions C to D

2009-10-07 Thread Jarrett Billingsley
On Wed, Oct 7, 2009 at 8:07 AM, Don nos...@nospam.com wrote:
 Craig Kuhnert wrote:

 downs Wrote:

 Craig Kuhnert wrote:

 Hi
 I am trying to convert some code I wrote in C++ to D to give it a try
 and I have come across some code that I dont know how to convert.
 I have simplified the code to illustrate the problem I have.
 How do I do this in D?

 class IFieldSetter
 {
 public:
        virtual void SetValue(void * object, const void * value) = 0;
 };

 template class C, class T
 class FieldSetter : public IFieldSetter
 {
 private:
        typedef T (C::* MemberField);
         MemberField field;

 public:
        FieldSetter(MemberField afield)
                : field(afield)
        {}

        void SetTypedValue(C * object, const T value)
        {
                object-*field = value;
        }

        void SetValue(void * object, const void * value)
        {
                SetTypedValue((C*) object, (const T) value);
        }
 };

 class MySampleClass
 {
 public:
        int Status;
        std::string Name;
 };

 void main(void)
 {
        IFieldSetter * StatusSetter = new
 FieldSetterMySampleClass,int(MySampleClass::Status);
        IFieldSetter * NameSetter   = new
 FieldSetterMySampleClass,std::string(MySampleClass::Name);

        MySampleClass * a = new MySampleClass();
        MySampleClass * b = new MySampleClass();

        StatusSetter-SetValue(a, (void*)20);
        StatusSetter-SetValue(b, (void*)40);

        NameSetter-SetValue(a, 2002);
        NameSetter-SetValue(b, 2002);
 }

 Thanks
 Craig

 If I'm getting this correctly, here's one way to do it ..

 module test;

 import std.stdio, tools.ctfe: ctReplace; // easy to write your own
 ctReplace function

 template Init(T) { T Init; }

 interface IFieldSetter {
  void setValue(Object obj, void* value);
 }

 class FieldSetter(T: Object, string Name) : IFieldSetter {
  override void setValue(Object obj, void* value) {
    auto tee = cast(T) obj;
    mixin(tee.%NAME = *cast(typeof(tee.%NAME)*) value;
 .ctReplace(%NAME, Name));
  }
  void setValue(T obj, typeof(mixin(Init!(T).~Name)) value) {
    mixin(obj.%NAME = value; .ctReplace(%NAME, Name));
  }
 }

 class Sample {
  int status;
  string name;
 }

 void main() {
  auto statSetter = new FieldSetter!(Sample, status);
  auto nameSetter = new FieldSetter!(Sample, name);
  auto sample = new Sample;
  int i = 20;
  statSetter.setValue(sample, i);
  statSetter.setValue(sample, 40);
  nameSetter.setValue(sample, Fooblr);
 }

 Thanks
 Thats brilliant! D rocks!
 I never though of using mixin for that purpose.

 There's almost NOTHING which is impossible with string mixins. With just
 recursive string mixins, coupled with .stringof and is(typeof()), you can
 get access to most of the compiler's semantic analysis, and its symbol
 table.
 Deep in the final semantic pass, just before code generation, when you have
 access to all the type information, you can generate new source code for the
 compiler to start again at the beginning with parsing.
 It's insanely powerful.

It's also insanely kludgy and ugly. Bleh.


Re: Get template and its instantiation parameters

2009-10-07 Thread Jarrett Billingsley
On Wed, Oct 7, 2009 at 12:54 PM, BCS n...@anon.com wrote:
 Hello Michal,

 If one has a template instance, is it possible to get template name
 and parameter type that was used for instantiating, at compile time?

 consider:

 class List (T) {}

 List!(int) lst;
 Foo (lst);
 I want to create such template Foo which prints:
 List!(int)
 List
 int

 You could try parsing T.stringof at compiletime to extract the parts you
 need.

This is *exactly* the kind of bullshit that I hate about string
mixins. The thought process just ends up going oh, why bother having
any terse, elegant mechanisms to get at program information when you
can *parse arbitrary code at compile time*? And why do you need macros
when a string substitution will do? Is it powerful? Sure. But it's
lame, ugly, slow, easy to mess up, lacks hygiene, and is unidiomatic.
String mixins are basically just a text preprocessor with user-defined
functionality. Neat, but it can only get you so far before you're in
tarpit territory.


Re: How about macro == symbol for mixin statement? [was Re: Member functions C to D]

2009-10-07 Thread Jarrett Billingsley
On Wed, Oct 7, 2009 at 11:21 AM, Don nos...@nospam.com wrote:
 Steven Schveighoffer wrote:

 On Wed, 07 Oct 2009 09:17:59 -0400, Jarrett Billingsley
 jarrett.billings...@gmail.com wrote:

 It's also insanely kludgy and ugly. Bleh.

 Ugly, yes. Kludgy, I don't think so. It's only a syntax issue. The basic
 concept of passing meta-code to the compiler in the form of raw text is
 simple:

 mixin() if you want to insert something into the parse step.
  is(typeof()) if you want to catch it again after the syntax pass.
  stringof if you want to catch it again after the semantic pass.

 And that's all. The syntax is ugly, but the semantics are beautifully
 elegant.

It'd be nice if they actually worked. is(typeof()) fails for *any*
error, and it eats those errors too, so if your code fails to compile
for some reason other than the one you're testing for, welp, good luck
figuring that out. And don't even get me started on .stringof.

Also, see my post on the get template and its instantiation
parameters thread for my detailed opinion on them.

 By contrast, something like Nemerle macros are a kludge. The idea of
 providing a 'hook' into the compiler is a horrible hack. It exposes all
 kinds of compiler internals. Yes, it has nicer syntax.

I.. don't even know how to begin to respond to that.


Re: Sizeof class instance

2009-10-03 Thread Jarrett Billingsley
On Sat, Oct 3, 2009 at 5:50 PM, Justin Johansson n...@spam.com wrote:
 How does one determine the sizeof (in bytes) of an instance of a class in D?

 .sizeof works as advertised for structs, but for reference types,
 .sizeof yields the sizeof the referencing variable (effectively same as size 
 of a pointer)
 and not the size of the underlying instance.

 I did try scanning the NG and read spec_D1.00.pdf.  Perhaps I missed it in 
 the latter.

 btw. I was poking under the hood of std.xml and though, wow, instances of 
 Element
 class look humongous, and so I'm interested to how exactly how humongous.

 Thanks for all help.
 Justin

There's no way to get it at compile-time in D1. The best you can do is
Class.classinfo.init.length.

In D2, you can use __traits(classInstanceSize, Class).


Re: implicit ubyte casting

2009-10-01 Thread Jarrett Billingsley
On Thu, Oct 1, 2009 at 2:00 PM, bearophile bearophileh...@lycos.com wrote:

 I have discussed such topics several times in the main D newsgroup, and in 
 the end no good solution has being found/accepted so far. But eventually some 
 better solution must be found...

Fucking A, bearophile. Bugzilla. How many fucking times do we have to tell you.


Re: template parameters

2009-09-25 Thread Jarrett Billingsley
On Fri, Sep 25, 2009 at 6:48 PM, Ellery Newcomer
ellery-newco...@utulsa.edu wrote:
 Christopher Wright wrote:
 Ellery Newcomer wrote:
 Okay, let me rephrase that:

 When you have a something preceded by a colon in a template value
 parameter, what are its semantics? Is it the same as a default parameter
 value? Is it some sort of constraining expression? Is it a vestige?

 void foo(T : int)(T value)
 {
     // value is implicitly convertible to int
 }

 It can do some pattern matching:

 void foo(T : V[U], V, U)(T dictionary)
 {
     // I have an associative array
 }

 In D2, it's usually going to be easier to use constraints:

 template foo(T) if (isAssociativeArray!T) {}

 Great, it does something specified for a type parameter.

 Now what does it do for a VALUE parameter?

Specialization for particular values. It's not really that useful in
the face of static if.

template fib(int n : 0) { const fib = 1; }
template fib(int n : 1) { const fib = 1; }
template fib(int n) { const fib = fib!(n - 2) + fib!(n - 1); }


Re: Linking in an .so on linux with rebuild?

2009-09-23 Thread Jarrett Billingsley
On Wed, Sep 23, 2009 at 1:11 AM, Daniel Keep
daniel.keep.li...@gmail.com wrote:


 Jarrett Billingsley wrote:
 On Wed, Sep 23, 2009 at 12:41 AM, Daniel Keep
 daniel.keep.li...@gmail.com wrote:
 I found a solution.

 See
 http://stackoverflow.com/questions/335928/linux-gcc-linking-ld-cannot-find-a-library-that-exists

 For me, I needed readline and history, so I did this:

 $ cd /lib
 $ sudo ln -s libreadline.so.5 libreadline.so
 $ sudo ln -s libhistory.so.5 libhistory.so

 After that, ld didn't complain.


 Oh yay. I was going to suggest that but I had never had that kind of
 problem on Ubuntu when building MiniD before. Maybe we're using
 different versions or something.

 Now I just have to figure out how to fix THIS:

 ../build/dsss_objs/D/sandbox.minid_repl.o: In function `_Dmain':
 sandbox/minid_repl.d:(.text._Dmain+0x6f): undefined reference to
 `_D5minid11commandline45__T3CLITS5minid11commandline14MDConsoleInputZ3CLI11interactiveMFPS5minid5types8MDThreadZv'

 I *hate* linker errors.  :(

Oh boy, looks like templates are at it again. I'm not sure what the
problem is there. Maybe minid.commandline isn't actually being
compiled somehow, only imported?


Re: Linking in an .so on linux with rebuild?

2009-09-22 Thread Jarrett Billingsley
On Wed, Sep 23, 2009 at 12:41 AM, Daniel Keep
daniel.keep.li...@gmail.com wrote:

 I found a solution.

 See
 http://stackoverflow.com/questions/335928/linux-gcc-linking-ld-cannot-find-a-library-that-exists

 For me, I needed readline and history, so I did this:

 $ cd /lib
 $ sudo ln -s libreadline.so.5 libreadline.so
 $ sudo ln -s libhistory.so.5 libhistory.so

 After that, ld didn't complain.


Oh yay. I was going to suggest that but I had never had that kind of
problem on Ubuntu when building MiniD before. Maybe we're using
different versions or something.


Re: ref arguments

2009-09-21 Thread Jarrett Billingsley
On Mon, Sep 21, 2009 at 11:12 AM, #ponce alil...@gmail.com wrote:
 Is there a reason to use ref instead of in, inout or out ?
 I'm using D1 and it's not in the spec.

'ref' and 'inout' are identical. 'ref' was introduced after D1 was
finalized for future expansion - 'inout' return values don't make much
sense.


Re: ref arguments

2009-09-21 Thread Jarrett Billingsley
On Mon, Sep 21, 2009 at 11:43 AM, Steven Schveighoffer
schvei...@yahoo.com wrote:

 in means that it's a reference that cannot be changed.  In D1, it means you
 cannot change the value, but if the value contains a reference to something
 else (like an array), you can change what it points to.

 in: Use this for pass by reference for a value that you won't change

No, sorry, this is wrong. In D1, 'in' is the default (pass by value)
and does nothing.


Re: Trying to get DMD bundled with libs

2009-09-08 Thread Jarrett Billingsley
On Tue, Sep 8, 2009 at 8:48 PM, Joel Christensenjoel...@gmail.com wrote:
 Jarrett Billingsley wrote:

 On Mon, Sep 7, 2009 at 6:44 AM, Joel Christensenjoel...@gmail.com wrote:

 div0 wrote:

 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 Joel Christensen wrote:

 I noticed you can get DMD bundled with various libraries. I found you
 had to login to another web site, but the registery page has 3 must
 fill
 in textbox's that are crazy.

 Where's that?
 AFAIK nobody has permission to distribute DMD other than Walter.

 http://www.digitalmars.com/d/download.html
 It's a Windows one, it's for dmd 1.030.

 Oh, that's EasyD I think. By crazy textboxes do you mean the login
 screen? I don't remember having to log in before. Chris hasn't posted
 on the NGs in a while either. In any case, 1.030 is *rather* old, and
 the libraries that would come with would be just as old.

 I mean by crasy text boxes three of the ones in the registery page, (for
 getting a log in), and I couldn't register because of them. If it's old and
 stuff, then why is it in the digital mars web site?


Because Walter's not very good at keeping things up to date? I dunno.
File a report on bugzilla.


Re: Trying to get DMD bundled with libs

2009-09-08 Thread Jarrett Billingsley
On Tue, Sep 8, 2009 at 9:17 PM, Jarrett
Billingsleyjarrett.billings...@gmail.com wrote:
 On Tue, Sep 8, 2009 at 8:48 PM, Joel Christensenjoel...@gmail.com wrote:
 Jarrett Billingsley wrote:

 On Mon, Sep 7, 2009 at 6:44 AM, Joel Christensenjoel...@gmail.com wrote:

 div0 wrote:

 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 Joel Christensen wrote:

 I noticed you can get DMD bundled with various libraries. I found you
 had to login to another web site, but the registery page has 3 must
 fill
 in textbox's that are crazy.

 Where's that?
 AFAIK nobody has permission to distribute DMD other than Walter.

 http://www.digitalmars.com/d/download.html
 It's a Windows one, it's for dmd 1.030.

 Oh, that's EasyD I think. By crazy textboxes do you mean the login
 screen? I don't remember having to log in before. Chris hasn't posted
 on the NGs in a while either. In any case, 1.030 is *rather* old, and
 the libraries that would come with would be just as old.

 I mean by crasy text boxes three of the ones in the registery page, (for
 getting a log in), and I couldn't register because of them. If it's old and
 stuff, then why is it in the digital mars web site?


 Because Walter's not very good at keeping things up to date? I dunno.
 File a report on bugzilla.

Also, if you can't answer the three questions at the bottom of the
registration page for Firestorm, you are not enough of a nerd to
register, I guess ;)


Re: Trying to get DMD bundled with libs

2009-09-07 Thread Jarrett Billingsley
On Mon, Sep 7, 2009 at 6:44 AM, Joel Christensenjoel...@gmail.com wrote:
 div0 wrote:

 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 Joel Christensen wrote:

 I noticed you can get DMD bundled with various libraries. I found you
 had to login to another web site, but the registery page has 3 must fill
 in textbox's that are crazy.

 Where's that?
 AFAIK nobody has permission to distribute DMD other than Walter.

 http://www.digitalmars.com/d/download.html
 It's a Windows one, it's for dmd 1.030.

Oh, that's EasyD I think. By crazy textboxes do you mean the login
screen? I don't remember having to log in before. Chris hasn't posted
on the NGs in a while either. In any case, 1.030 is *rather* old, and
the libraries that would come with would be just as old.


Re: How does D cope with aliasing

2009-09-05 Thread Jarrett Billingsley
On Sat, Sep 5, 2009 at 3:49 AM, #poncealil...@gmail.com wrote:
 I'm currently using a lot of pointers to perform heavy computation

 Has D the equivalent for C's restrict ? More generally, how does D cope with 
 the aliasing of pointers ? I think it's crucial for the code optimizer.

It doesn't.


Re: Trying to get DMD bundled with libs

2009-09-05 Thread Jarrett Billingsley
On Sat, Sep 5, 2009 at 6:53 AM, div0d...@users.sourceforge.net wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 Joel Christensen wrote:
 I noticed you can get DMD bundled with various libraries. I found you
 had to login to another web site, but the registery page has 3 must fill
 in textbox's that are crazy.

 Where's that?
 AFAIK nobody has permission to distribute DMD other than Walter.

Some others are allowed to distribute DMD (the Tango team, I think the
EasyD thing), but I've never heard of a site requiring you to fill out
info to get it.


Re: No $ for op overloads?

2009-09-04 Thread Jarrett Billingsley
On Sat, Sep 5, 2009 at 1:31 AM, Nick Sabalauskya...@a.a wrote:
 I made a simple struct that overloads opIndex and opSlice, and also exposed
 a length property. But when I try to use $ on it, I got:

 Error: undefined identifier __dollar

 I tried making a property __dollar that just returned length, but that
 didn't change anything.

 What's going on? Any ideas?

Nope, it's never been possible. :(

You can do silly things like defining a global __dollar, but it's
useless since it can't take params.


Re: Error: constant false is not an lvalue

2009-08-30 Thread Jarrett Billingsley
On Sun, Aug 30, 2009 at 5:34 AM, Rainer Deykerain...@eldwood.com wrote:
 Jarrett Billingsley wrote:
 Although teeechnically speaking that would be illegal code. The D
 spec says that it's not legal to use the value of uninitialized
 variables. Default initialization is kind of a poor man's substitute
 for actual flow control which determines that. By relying on default
 initialization, you're relying on what is actually nonconformant
 behavior, and it could be broken in the future or by a smarter
 compiler.

 No.  This is an uninitialized variable in D:

  int i = void;

 This is an initialized variable in D:

  int i;

 A default-initialized variable is not in any way less initialized than
 any other initialized variable.

It is an error to use a local variable without first assigning it a
value. The implementation may not always be able to detect these
cases. Other language compilers sometimes issue a warning for this,
but since it is always a bug, it should be an error.
http://www.digitalmars.com/d/1.0/function.html

I wouldn't be surprised if W himself has forgotten about this rule,
since other parts of the spec make no mention of it, or seem to depend
on the default-initialization of variables.

If the Initializer is void, however, the variable is not initialized.
If its value is used before it is set, undefined program behavior will
result.
http://www.digitalmars.com/d/1.0/declaration.html

But wait.. the previous statement said that it was an error to use a
local without first assigning it a value. Meaning the code snippet
given there (int x = void; writefln(x);) is invalid.

 It cannot ever alter the behavior of the following perfectly legal D
 function:

  int get_zero() {
    int i;
    return i;
  }

I interpret the first statement as saying that this isn't, and never
has been, legal D, and that DMD simply has never checked for it. It's
also illegal to declare variables that are never used, but you don't
get an error for that either.

As so many things in the D spec, this is unclear. The current behavior
might actually be conformant to the first statement; it's just that
the default initialization has made it all but pointless. The
section(s) on default initialization of course do not mention how it
interacts with the first rule. (Similar to how bools can't have any
silly things like arithmetic operations performed on them (good!) but
can be implicitly cast to almost every other basic type, meaning you
can do it anyway (bad!).)


Re: Error: constant false is not an lvalue

2009-08-30 Thread Jarrett Billingsley
On Sun, Aug 30, 2009 at 7:13 AM, grauzonen...@example.net wrote:
 Although teeechnically speaking that would be illegal code. The D
 spec says that it's not legal to use the value of uninitialized
 variables. Default initialization is kind of a poor man's substitute
 for actual flow control which determines that. By relying on default

 Am I the only one, who likes the current behaviour, and finds it annoying to
 be forced by the compiler to initialize all variables?

The default initialization in D certainly hasn't helped me catch any
bugs, only made them harder to spot. I'm a very big proponent of
catching things at compile time.

 initialization, you're relying on what is actually nonconformant
 behavior, and it could be broken in the future or by a smarter
 compiler.

 How is this nonconformant? Initialization is guaranteed by D.

This is where the spec is unclear, since why bother having the can't
access variables before assignment rule if the all variables are
default-initialized rule all but removes the need for it?


Re: Error: constant false is not an lvalue

2009-08-30 Thread Jarrett Billingsley
On Sun, Aug 30, 2009 at 3:14 PM, Jarrett
Billingsleyjarrett.billings...@gmail.com wrote:
 On Sun, Aug 30, 2009 at 3:02 PM, Rainer Deykerain...@eldwood.com wrote:
 The purpose of default initialization is not to find or reduce bugs, but
 to reduce the size of legal programs.

 I'm wondering where the heck you got that justification.

Also, the spec says this:

Members are always initialized to the default initializer  for their
type, which is usually 0 for integer types and NAN for floating point
types. This eliminates an entire class of obscure problems that come
from neglecting to initialize a member in one of the constructors.
http://www.digitalmars.com/d/1.0/class.html

This suggests, to me, that default initialization _is_ - at least in
Walter's mind - supposed to eliminate bugs.


Re: dmd deps switch

2009-08-30 Thread Jarrett Billingsley
On Sun, Aug 30, 2009 at 4:35 PM, Ary Borenszweiga...@esperanto.org.ar wrote:
 Hi,

 I'm trying to fetch a module's dependencies with the deps switch, but it
 gives me an empty list.

 dmd main.d -deps=foo.txt

 foo.txt is empty.

 main.d is:

 ---
 module main;

 import other;

 int main(char[][] args) {
        someVariable = 3;
        return 0;
 }
 ---

 and someVariable is defined in other.

 What am I doing wrong?



http://d.puremagic.com/issues/show_bug.cgi?id=3143


Re: Error: constant false is not an lvalue

2009-08-29 Thread Jarrett Billingsley
On Sun, Aug 30, 2009 at 12:24 AM, Ary Borenszweiga...@esperanto.org.ar wrote:
 Steven Schveighoffer escribió:

 On Sat, 29 Aug 2009 20:15:55 -0400, Ellery Newcomer
 ellery-newco...@utulsa.edu wrote:

 void blah(out bool a = false){
  // blah blah blah
 }

 compile time use of blah results in error.

 Am I doing anything wrong?

 out implies a reference.  You can't have a reference to a manifest
 constant like that.

 If you want to ensure a is false at the beginning of the function do:

 void blah(out bool a)
 {
  a = false;
  // blah blah blah
 }

 -Steve

 Or just not write it, because out automatically initializes the value of
 the variable to it's default one, in the case of bool it's false.

Although teeechnically speaking that would be illegal code. The D
spec says that it's not legal to use the value of uninitialized
variables. Default initialization is kind of a poor man's substitute
for actual flow control which determines that. By relying on default
initialization, you're relying on what is actually nonconformant
behavior, and it could be broken in the future or by a smarter
compiler.

But we're getting really technical here ;)


Re: What time is it?

2009-08-28 Thread Jarrett Billingsley
On Fri, Aug 28, 2009 at 11:03 PM, jicmancabre...@_wrc.xerox.com wrote:
 Chad J Wrote:

 Max wrote:
  Is there any way in Phobos to measure the current time with microsecond 
  accuracy?
 
  Max

 Might I suggest std.perf?

 I found it here some years ago:
 http://www.digitalmars.com/techtips/timing_code.html

 It even seems to have survived the transition from D1 to D2.

 Oddly enough, this rather useful module never seems to never be included
 in the web documentation.  :(

 Just read the comments in the source file that comes with your compiler.
 {dmd-path}/src/phobos/std/perf.d

 I've always used PerformanceCounter with good results.

 I also use it.  Why does it not get inserted on D1 and D2?

 thanks,

 josé

std.perf was added *years* ago, in D's infancy. It wasn't even written
by Walter, so the docs never made it into the DM pages. The
documentation embedded in it isn't even DDoc, it's Doxygen. It's
always been sort of a misfit.


Re: threads

2009-08-24 Thread Jarrett Billingsley
On Mon, Aug 24, 2009 at 12:19 PM, asdfa...@fdsa.asdf wrote:
 I just downloaded dmd 2.031 and it does not contain std.thread. Why not?


Because several releases ago, std.thread was replaced by core.thread.

http://www.digitalmars.com/d/2.0/changelog.html#new2_020

For some reason the Phobos docs still refer to it as std.thread, but
the documentation page itself says core.thread.


Re: Templates

2009-08-22 Thread Jarrett Billingsley
On Sat, Aug 22, 2009 at 12:11 PM, mm...@m.m wrote:
 Hello,

 i'm during reading of Learnt to Tango with D. In chapter 5 (about Templates) 
 there are few samples of using templates. I've got problem with one of them.

 1.
 template List( T )
 {
 pragma( msg, List( T ) );
 }
 template List( T : int )
 {
 pragma( msg, List( T : int ) );
 }
 template List( T : T[] )
 {
 pragma( msg, List( T : T[] ) );
 }
 void main()
 {
 alias List!(char) A;
 alias List!(int) B;
 alias List!(char[]) C;
 }

 Should produce messages (according to what is said in book):

 List( T )
 List( T : int )
 List( T : T[] )

 but i've got:

 List( T : int )
 List( T : int )
 List( T : T[])

 Is there are any error, or what?

It's because of an (absolutely silly) implicit conversion of char to
int, and the way D does template specialization.  Because char is
implicitly convertible to int, D sees that both List!(T) and List!(T:
int) as valid instantiations for 'char'.  Then, it decides that since
List!(T: int) is more specialized, it should use it instead of
List!(T).  You'll also get the same inane List!(T: int) specialization
if you try List!(bool), since bool is implicitly convertible to int
for some reason.

It's extremely frustrating.


Re: determining type a pointer points to.

2009-08-22 Thread Jarrett Billingsley
On Sat, Aug 22, 2009 at 5:58 PM, div0d...@users.sourceforge.net wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 Is there a function to do this?
 I Didn't find anything in traits or std.traits

 ty

template PtrElemType(T : T*) { alias T PtrElemType; }
template PtrElemType(T) { static assert(false, YOU FAIL); }


Re: determining type a pointer points to.

2009-08-22 Thread Jarrett Billingsley
On Sat, Aug 22, 2009 at 6:55 PM, Stewart Gordonsmjg_1...@yahoo.com wrote:
 div0 wrote:

 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 Is there a function to do this?
 I Didn't find anything in traits or std.traits

 snip

 Not a function as such, but

    typeof(*p)

If p is int[], that gets you int instead of an error.  I have no idea why.


Re: Export static data

2009-08-21 Thread Jarrett Billingsley
On Fri, Aug 21, 2009 at 11:10 AM, Dandan.r.stev...@gmail.com wrote:
 Is there a way to export static data from a DLL written in D?

 I'd like to write some extension DLLs for a program, but they need to have 
 certain static data exports to be recognized. I've been able to export 
 functions, but no data appears in the export table of the DLL.

 In MSVC 6 I can do it as follows:
 extern C __declspec(dllexport) ModDesc DescBlock = { ... };

extern(C) export ModDesc DescBlock = { ... };


 Another issue I had was with the name decoration. I need to be able to export 
 an InitProc. The closest I was able to get was _InitProc and INITPROC. 
 Is there a way to drop the leading underscore?

As far as I know, not within the language.  DMD for some reason thinks
that all Windows functions are preceded by an underscore when that is
clearly not the case.  You might be able to do something using a .def
file (linker script), but I've only had experience linking external
symbols in, not with exporting internal symbols.


Re: Template mixins: Why is the decision to mixin made at the call site?

2009-08-21 Thread Jarrett Billingsley
On Fri, Aug 21, 2009 at 1:36 PM, div0d...@users.sourceforge.net wrote:
 Not sure what the original choice was based on, but what you suggest
 looks wrong to me. You aren't necessarily using a template in order to
 mix it in somewhere.

 With that syntax it looks like you can only use foo as a mixin.

That's what he's suggesting, and it does make sense.  When you write a
template, *either* it's meant to be used as a mixin, *or* it's meant
to be used some other way.  Mixin in a template that wasn't meant to
be a mixin or vice versa usually makes no sense.

 If you
 change 'mixin' to 'paste' your way round looks even more wrong.

If you're thinking of 'mixin' as a verb, to mix in, I can understand
that.  But if you consider his syntax with mixin as a noun (like
class or template), it makes more sense.


Re: Partial template function specialization

2009-08-20 Thread Jarrett Billingsley
On Thu, Aug 20, 2009 at 10:34 AM, Bill Baxterwbax...@gmail.com wrote:
 On Thu, Aug 20, 2009 at 7:22 AM, Peter
 Alexanderpeter.alexander...@gmail.com wrote:
 Lars T. Kyllingstad Wrote:
 In my style of programming, I very rarely use member functions (I think they 
 are an atrocity in language design), so I create global functions for almost 
 everything, and when they need to access to private members, I have the 
 class declare the function as a friend.

 Does D support my style of programming?

 Instead of friend, in D everything within one file (==one module) has
 access to everything else in that same file/module.

 So you can use your style, as long as you put the global functions in
 the same module as the classes operated on.

Alternatively, you can mark the data members 'package', and then any
functions in the same package can access them.  But keep in mind that
'package' is limited in that you can't access those members from
sub-packages, meaning you are forced into a flat package hierarchy.


Re: deleting items from 2d arrays

2009-08-13 Thread Jarrett Billingsley
On Thu, Aug 13, 2009 at 10:59 PM, Michael P.baseball@gmail.com wrote:
 Okay, so I'm making a breakout type game in D. Using Derelict.
 I have a 2d array of Block type variables(not important what's in them) 
 declared like this:
 Block[][] level;
 and later load into like this:
 level = loadLevel( levels.txt, levelNumber );
 Anyways, what I want to do is that when the ball hits one of the blocks in 
 the array, I remove it. When a line no longer has any blocks in it, I remove 
 that line/row. When there are no more lines, I load the next level.
 Any ideas on how I could achieve this?

 foreach( Block[] ba; level )
 {
        foreach( Block b; ba )
        {
                if( checkCollision( ball, b.p ) )
                {
                        //remove the block??
                }
        }
 }

 The level array has 12 lines of 'x' amount of bricks. x can be as great as 10.

Okay.  First you need a remove function to take lines out of the
array.  Here's a general one:

import std.c.string; // phobos
import tango.stdc.string; // tango

void remove(T)(ref T[] arr, size_t idx)
{
assert(arr.length  0);

if(idx == 0)
arr = arr[1 .. $];
else if(idx == arr.length - 1)
arr = arr[0 .. $ - 1];

memmove(arr[idx], arr[idx + 1], T.sizeof * (arr.length - idx - 1));
arr = arr[0 .. $ - 1];
}

You use it like arr.remove(idx) (or alternately, remove(arr, idx)) and
the given element will be removed, everything after it will be shifted
down a slot, and the length of the array will be reduced by one.

Now you need to do collision with the blocks.  If Block is a class, we
can use 'null' in the array to indicate that there is not block there;
if it's a struct, you'll have to keep an 'active' member in the struct
or somesuch.  Either way, a quadratic algorithm for detecting
collision probably isn't necessary.  You can calculate which blocks
the ball is near with a little math.

const BlockHeight = 24; // fill these in
const BlockWidth = 60; // with whatever you're using

void checkRemoveLine(int row)
{
foreach(ref b; level[row])
if(b.active)
return;

// none of the blocks were active
level.remove(row);
}

void removeBlock(int row, int col)
{
level[row][col].active = false;
checkRemoveLine(row);
}

void collidePoint(int x, int y)
{
auto row = y / BlockHeight;
auto col = x / BlockWidth;

// assuming Block is a struct..
if(row  level.length  level[row][col].active)
removeBlock(row, col);
}

const BallDiam = 10; // this makes the ball 10 pixels across
const HalfBallDiam = BallDiam / 2;

void collide(Ball ball)
{
// collide all four corners of the ball's colbox
collidePoint(ball.x + HalfBallDiam, ball. y + HalfBallDiam);
collidePoint(ball.x - HalfBallDiam, ball. y + HalfBallDiam);
collidePoint(ball.x - HalfBallDiam, ball. y - HalfBallDiam);
collidePoint(ball.x + HalfBallDiam, ball. y - HalfBallDiam);
}

Your main game loop would probably look something like this:

foreach(levelFile; levelFiles)
{
level = loadLevel(levelFile); // load the level array

// while there are still lines..
while(level.length  0)
{
getUserInput();
updateStuff();
doCollision(); // ball runs into things yay
drawGraphics();
}
}

Well this has ended up being a bit long ;)


Re: win32 capCreateCaptureWindow problem

2009-08-11 Thread Jarrett Billingsley
On Tue, Aug 11, 2009 at 6:10 PM, Ivan Boritskynibble...@gmx.com wrote:
 i work on a win32 application. i try to access my web camera.
 when i use this api funtion;
 capCreateCaptureWindow(cam, WS_VISIBLE + WS_CHILD, 10, 10,266, 252, hWnd, 
 0);

 i get this error:
 Error: undefined identifier capCreateCaptureWindow

 my compile comman is:
 dmd webcam.d gdi32.lib advapi32.lib

 what am i doing wrong? how can i acces my web cam?

The Windows headers that come with Phobos are extremely incomplete.
Try the WindowsApi bindings project instead:
http://dsource.org/projects/bindings/wiki/WindowsApi


Re: At compile time

2009-08-05 Thread Jarrett Billingsley
*On Wed, Aug 5, 2009 at 7:23 AM, Ary Borenszweiga...@esperanto.org.ar wrote:
 bearophile escribió:

 Jarrett Billingsley:

 C++ has static initialization that occurs before main() too.  It's just..
 hidden.

 I see. I have to learn more about C++. Thank you.

 --
 Lars T. Kyllingstad:

 This is good news! The restrictions you are referring to, are they any of
 the ones documented here:
 http://www.digitalmars.com/d/2.0/function.html#interpretation 

 That list has a point regarding what I was trying to do:

 4. the function may not be a non-static member, i.e. it may not have a
 this pointer

 It's true regarding stucts used as values too, and not just classes...

 It would be nice if the compiler could say so: I can't evaluate it because
 you are using a this pointer. With other words, but much more useful than
 non-constant expression.

Yes, oh my God, this is the main reason I don't use CTFE: debugging
them is virtually impossible, and the compiler does nothing to help
there.


Re: Semantics of range::put

2009-08-05 Thread Jarrett Billingsley
On Wed, Aug 5, 2009 at 3:45 AM, Oliver Kanaioliverka...@googlemail.com wrote:
 Hello,
 according to my understanding of the put method for ranges, which is part 
 of the output-range interface, the following should work :

 private string[] m_arrHalloStrings = [Hallo, Du, Da, wie, ?];
 m_arrHalloStrings.put(Hallo);

 it compiles but does not execute:
 the compiler gives the message

 core.exception.asserter...@std.array(256): Assertion failure

I can't reproduce this.  It works for me.  I'm guessing you have an
older version of DMD, since with 2.031, std.array.put is no longer on
line 256.  Try updating.


Re: A floating-point puzzle

2009-08-05 Thread Jarrett Billingsley
On Wed, Aug 5, 2009 at 10:16 PM, Donnos...@nospam.com wrote:
 Lars T. Kyllingstad wrote:

 Lars T. Kyllingstad wrote:

 Here's a puzzle for you floating-point wizards out there. I have to
 translate the following snippet of FORTRAN code to D:

      REAL B,Q,T
 C     --
 C     |*** COMPUTE MACHINE BASE ***|
 C     --
      T = 1.
 10    T = T + T
      IF ( (1.+T)-T .EQ. 1. ) GOTO 10
      B = 0.
 20    B = B + 1
      IF ( T+B .EQ. T ) GOTO 20
      IF ( T+2.*B .GT. T+B ) GOTO 30
      B = B + B
 30    Q = ALOG(B)
      Q = .5/Q

 Of course I could just do a direct translation, but I have a hunch that
 T, B, and Q can be expressed in terms of real.epsilon, real.min and so
 forth. I have no idea how, though. Any ideas?

 (I am especially puzzled by the line after l.20. How can this test ever
 be true? Is the fact that the 1 in l.20 is an integer literal significant?)

 -Lars


 I finally solved the puzzle by digging through ancient scientific papers,
 as well as some old FORTRAN and ALGOL code, and the solution turned out to
 be an interesting piece of computer history trivia.

 After the above code has finished, the variable B contains the radix of
 the computer's numerical system.

 Perhaps the comment should have tipped me off, but I had no idea that
 computers had ever been anything but binary. But apparently, back in the 50s
 and 60s there were computers that used the decimal and hexadecimal systems
 as well. Instead of just power on/off, they had 10 or 16 separate voltage
 levels to differentiate between bit values.

 Not quite. They just used exponents which were powers of 10 or 16, rather
 than 2. BTW, T == 1/real.epsilon. I don't know what ALOG does, so I've no
 idea what Q is.

Apparently ALOG is just an old name for LOG.  At least that's what
Google tells me.


Re: At compile time

2009-08-04 Thread Jarrett Billingsley
On Tue, Aug 4, 2009 at 7:57 PM, bearophilebearophileh...@lycos.com wrote:
 D2 is now able to execute math functions (sin, cos, sqrt, etc) at compile 
 time.

 This little C++ program compiles correctly with G++:

 // C++ code
 #include math.h
 #include stdio.h

 struct V3 {
    double x, y, z;
    V3(const double a, const double b, const double c) : x(a), y(b), z(c) {}
    V3 operator*(const double d) const { return V3(x * d, y * d, z * d); }
    V3 norm() const { return *this * (1.0 / sqrt(magsqr())); }
    double dot(const V3 v) const { return x * v.x+y * v.y + z * v.z; }
    double magsqr() const { return dot(*this); }
 };

 const V3 v(V3(-0.5, -0.65, 0.9).norm());

 int main() {
    printf(%f %f %f\n, v.x, v.y, v.z);
    return 0;
 }


 But similar D2 program produces, with DMD v.2.031:
 test.d(12): Error: non-constant expression (V3(1,2,3)).norm()

 // D2 code
 import std.math, std.c.stdio;

 struct V3 {
    double x, y, z;
    V3 opMul(double d) { return V3(x * d, y * d, z * d); }
    V3 norm() { return this * (1.0 / sqrt(this.magsqr())); }
    double dot(ref V3 v) { return x * v.x+y * v.y + z * v.z; }
    double magsqr() { return dot(this); }
 }

 const V3 v = V3(1.0, 2.0, 3.0).norm();

 int main() {
    printf(%f %f %f\n, v.x, v.y, v.z);
    return 0;
 }

 Do you know why?

I don't think you can call struct methods at compile-time.  Kind of
lame, I know.  Try making norm a free function.

 Can the D2 compiler modified/improved to allow this?

It sure would be nice.


Re: At compile time

2009-08-04 Thread Jarrett Billingsley
On Tue, Aug 4, 2009 at 10:13 PM, bearophilebearophileh...@lycos.com wrote:
 Jarrett Billingsley:
 I don't think you can call struct methods at compile-time.  Kind of
 lame, I know.  Try making norm a free function.

 I see. It's a significant limitation, that curiously G++ doesn't share.

I don't think your C++ code is doing what you think it's doing.  I'm
pretty sure the C++ code:

const V3 v(V3(-0.5, -0.65, 0.9).norm());

is equivalent to the following D code:

const V3 v;
static this() { v = V3(-0.5, -0.65, 0.9).norm(); }

C++ has static initialization that occurs before main() too.  It's
just.. hidden.


Re: rvalues as ref arguments

2009-08-02 Thread Jarrett Billingsley
On Sun, Aug 2, 2009 at 10:51 AM, bearophilebearophileh...@lycos.com wrote:
 This code doesn't work in DMD 1.046 anymore (I think it may work in DMD 1.045 
 and it works for sure in DMD 1.042):

 struct V {
    int x;
    V opAdd(V v) { return V.init; }
 }
 void foo(ref V v) {}
 void main() {
    foo(V.init + V.init);
 }

 On IRC the gentle Daniel Keep has told me this seems an undocumented change. 
 Both LDC and my code may need to change a bit for this.

It's already been reported.

http://d.puremagic.com/issues/show_bug.cgi?id=3167


Re: alias syntax

2009-08-01 Thread Jarrett Billingsley
On Sat, Aug 1, 2009 at 8:31 PM, Ellery
Newcomerellery-newco...@utulsa.edu wrote:
 what is the purpose of the syntax

 alias StorageClasses Declarator

 ?

I don't know where you're getting that grammar.  Is that from the D spec?


Re: alias syntax

2009-08-01 Thread Jarrett Billingsley
On Sat, Aug 1, 2009 at 11:13 PM, Ellery
Newcomerellery-newco...@utulsa.edu wrote:

 um, yeah.

 Declaration:
        typedef Decl
        alias Decl
        Decl

 Decl:
        StorageClasses Decl
        BasicType Declarators ;
        BasicType Declarator FunctionBody
        AutoDeclaration


 Never mind that's wrong.

 but it looks like it should be

 alias StorageClasses BasicType Declarator

'Decl' is recursive.  So:

alias Decl

can expand to:

alias StorageClasses Decl

which expands to:

alias StorageClasses BasicType Declarators ;

But is this not what you're pointing out?  Are you instead taking
issue with the fact that the grammar accepts something like alias int
foo() {} whereas the compiler doesn't?

 Looking through declaration.c, I noticed that semantic disallows
 specifically

 alias const {blah blah blah}

 but not the others.

You mean how the compiler rejects alias const int x; but not alias
static int x;?  That is strange..


Re: aa bug?

2009-07-28 Thread Jarrett Billingsley
On Tue, Jul 28, 2009 at 6:09 PM, Saaaem...@needmail.com wrote:

 But you never inserted anything in aa[test].

 You must do:

 S s;
 aa[test] = s;
 aa[test].i = 10;

 or:

 S s;
 s.i = 10;
 aa[test] = s;

 erm, ok
 Thanks
 So no creation on use :)
 Personally I find the declation step clutter in the first case.
 Maybe promote the bug  to a request?

It won't happen.  The behavior you want *used* to be the AA behavior
but was changed after several years and much complaining.  It's not
going back.


Re: confused about scope storage class

2009-07-28 Thread Jarrett Billingsley
On Tue, Jul 28, 2009 at 10:46 PM, Trass3rmrmoc...@gmx.de wrote:
 So scope for class references guarantees that the destructor is called upon
 leaving the scope (why isn't this done automatically?).

Why isn't what done automatically?

 But what if scope is used with basic types like scope int x;
 What's the effect?

There is none.  The compiler will accept meaningless attributes.  It's
a point of contention.


Re: D1 vs D2 Feature comparison list

2009-07-28 Thread Jarrett Billingsley
On Tue, Jul 28, 2009 at 11:11 PM, Sam Husamhudotsa...@gmail.com wrote:
 Is there such stuff available in D website? Or the only choice to quick  
 check what features are supported by D2 also supported by D1 is to go through 
 the spec?

 Thanks in advance.
 Regards,
 Sam


http://www.digitalmars.com/d/2.0/features2.html


Re: setAssertHandler (druntime) segfaults

2009-07-24 Thread Jarrett Billingsley
On Fri, Jul 24, 2009 at 5:46 PM, Lutgerlutger.blijdest...@gmail.com wrote:
 Jarrett Billingsley wrote:

 On Fri, Jul 24, 2009 at 4:37 PM, Lutgerlutger.blijdest...@gmail.com
 wrote:
 There is a function setAssertHandler in druntime, but when I try to use
 it it segfaults. I'm not sure how it should be used, this is a complete
 example of what I try to do:

 import std.stdio;
 import core.exception;

 void handleAssertion(string file, size_t line, string msg = null)
 {
 writefln(assert in %s at line %s, file, line);
 };

 static this()
 {
 setAssertHandler( handleAssertion  );
 }

 unittest { assert(false); }

 void main() {}


 output:
 assert in test at line 16
 Segmentation fault

 This is with dmd 2.031 on linux. Is this a bug, am I doing something
 wrong?

 Hm, it might - and I'm just taking a wild guess here - be that
 std.stdio hasn't yet been initialized when you do the writefln in your
 assertion handler.  But you really should try using a debugger to get
 a stacktrace.

 Ok I tried. Funny thing, with -g enabled it doesn't segfault anymore.
 Without -g, the trace is not intelligible to me. Segfault also occurs when
 commenting out writefln.

 This is useless I assume but anyway, this is what gdb gives me:

 #0  0x0805292e in _TMP257 ()
 #1  0x000e in ?? ()
 #2  0xd02c in ?? ()
 #3  0x08048f79 in _D4test11__unittest1FZv ()
 Backtrace stopped: previous frame inner to this frame (corrupt stack?)

I'm.. utterly at a loss.  It seems that exiting the assertion handler
by doing anything other than throwing an exception causes the
segfault.  And like you said, -g makes the problem disappear.  I have
no idea what's going on.


Re: Execute process and read its stdout/stderr asynchronously

2009-07-22 Thread Jarrett Billingsley
On Wed, Jul 22, 2009 at 4:41 AM, kklla...@b.com wrote:
 I'm trying out D2+phobos on OSX and would like to write wrapper around few 
 shell commands.

 I've found only very basic exec() and system() in std lib, but I need to 
 launch few things at once and get all their output.

 Is there something like Cocoa's NSTask in D?


There is for D1, in Tango.  You might be able to port it over.


Re: Execute process and read its stdout/stderr asynchronously

2009-07-22 Thread Jarrett Billingsley
On Wed, Jul 22, 2009 at 8:42 AM, Jarrett
Billingsleyjarrett.billings...@gmail.com wrote:
 On Wed, Jul 22, 2009 at 4:41 AM, kklla...@b.com wrote:
 I'm trying out D2+phobos on OSX and would like to write wrapper around few 
 shell commands.

 I've found only very basic exec() and system() in std lib, but I need to 
 launch few things at once and get all their output.

 Is there something like Cocoa's NSTask in D?


 There is for D1, in Tango.  You might be able to port it over.


Er, it's in tango.sys.Process :)


Re: XML D2.x parsing amp;

2009-07-21 Thread Jarrett Billingsley
On Tue, Jul 21, 2009 at 11:53 PM, Brad Robertsbra...@puremagic.com wrote:
 Jesse Phillips wrote:
 On Wed, 22 Jul 2009 01:37:38 +0100, Stewart Gordon wrote:

 Jesse Phillips wrote:
 According to the documentation having amp; in a tag will be turned to
 

 http://digitalmars.com/d/2.0/phobos/std_xml.html#text

 I observe that this is not the case. And if an attribute contains amp;
 it is turned into amp;amp; What is the best way to receive the same
 output for both. The code that follows outputs

 Attr: What amp;amp; Up
 Elem: What amp; Up



 *testfile.xml:*

 ?xml version=1.0 encoding=utf-8? Tests
     Test thing=What amp; UpWhat amp; Up/Test
 /Tests
 Clearly std.xml is buggy.  Correct behaviour would be

 Attr: What  Up
 Elem: What  Up

 The best place for bug reports is

 http://d.puremagic.com/issues/

 Stewart.

 http://d.puremagic.com/issues/show_bug.cgi?id=3200
 http://d.puremagic.com/issues/show_bug.cgi?id=3201

 The xml parsing code in D2 could use some love and care.  It was originally
 written by Janice who seems to have dropped off the face of the planet.  It's
 little more than a first draft with serious performance problems and several
 important bugs.

 Anyone want to volunteer to invest some time in improving it?

I don't mean to shoot down the idea?  But Tango already has three XML
parsers which are, like, the fastest.  Ever.

http://dotnot.org/blog/archives/2008/03/04/xml-benchmarks-updated-graphs/

I'm just saying, it'd seem like pointless duplication of effort with
such parsers _already available_.  If it could be relicensed, I'd say
that's the best route.


Re: There is not std.stdio.flush

2009-07-20 Thread Jarrett Billingsley
2009/7/20 Haruki Shigemori rayerd@gmail.com:
 Hi.

 The std.cstream.dout has a member function dout.flush.
 But the std.stdio has not a function flush or a similar function.
 Why? Don't you want to have it?
 Give me the std.stdio.flush!

You don't need it.  Just import std.c.stdio and fflush(stdout).


Re: closures

2009-07-16 Thread Jarrett Billingsley
On Thu, Jul 16, 2009 at 8:02 AM, Jensjens-theisen-tm...@gmx.de wrote:
 Hello there,

 I'm new to D and experimenting with closures. I know the basics of how 
 compilers translate things, especially in C++. So I appreciate the difficulty 
 of implementing closures correctly and been wondering if it really works. I 
 found a place where dmd 2 appears to fail, but I don't know whether that's a 
 bug or just not supported:

 import std.stdio;

 struct Foo
 {
  int a = 7;
  int bar() { return a; }

  int delegate() makedelegate() {
    int abc() { return a; }
    return abc;
  }
 }

 void call(int delegate() dg)
 {
  writefln(foo: %d, dg());
 }

 int delegate() makedelegate1()
 {
  int x = 27;
  int abc() { return x; }
  return abc;
 }

 int delegate() makedelegate2()
 {
  Foo f;
  int abc() { return f.a; }
  return abc;
 }

 int delegate() makedelegate3()
 {
  Foo f;
  return f.bar;
 }

 int delegate() makedelegate4b(ref Foo f)
 {
  int abc() { return f.a; }
  return abc;
 }

 int delegate() makedelegate4()
 {
  Foo f;
  return makedelegate4b(f);
 }


 void main(string[] args)
 {
  // On dmd v2.029, linux build, this...

  call(makedelegate1()); // ...works: 27
  call(makedelegate2()); // ...works: 7
  call(makedelegate3()); // ...doesn't work: 134518855
  call(makedelegate4()); // ...doesn't work: 134518947

  Foo f;
  call(f.bar); // ...works: 7
 }

 In case 4 the reference is explicit, so it's somehow easier to see that 
 something dangerous is being done, but in case 3, D seems to make it too easy 
 to shoot yourself in the foot.

 Is there a resource discussing these issues?

Yeah, you've found it :)

I think what's going on here is that the compiler will *only* allocate
closures for nested functions.  However allocating a closure for a
delegate of a value object would be a nice addition.


Re: closures

2009-07-16 Thread Jarrett Billingsley
On Thu, Jul 16, 2009 at 1:24 PM, BCSa...@pathlink.com wrote:
 Reply to Jarrett,

 I think what's going on here is that the compiler will *only* allocate
 closures for nested functions. However allocating a closure for a
 delegate of a value object would be a nice addition.


 This will quickly devolve into the general escape analysts problem and here
 there be dragons. I think the correct solution is to say it's unsupported by
 calling this an escaping reference bug in the user code.

At least for non-ref-param value types, I don't think it's
unreasonable to say that obj.func should allocate a closure.  I mean,
it's the same as saying

int delegate() dg;
dg.funcptr = typeof(obj).func;
dg.ptr = obj;

and the last line there would be illegal to return under normal
circumstances anyway.

But you're probably right that it might just be easier to disallow it
and force people to write { return f.func(); } instead.  :)


Re: closures

2009-07-16 Thread Jarrett Billingsley
On Thu, Jul 16, 2009 at 2:22 PM, Steven
Schveighofferschvei...@yahoo.com wrote:

 What about syntax to force closure behavior (on or off)?  Not that I have
 any to suggest, but if the compiler is going to remain ignorant about escape
 analysis, then we should be able to supply the intelligence, and hacking an
 extra wrapper function to force behavior seems... well, hackish :)

There already is, at least for turning closures off.  A common design
pattern in D1 is to pass the address of a nested function as a
callback.  This is convenient and performant:

void putChar(char c)
{
write(c);
}

std.format.doFormat(putChar, blahblahblah); // or so

If D2 were to allocate a closure for putChar, suddenly your
formatting function that's called several hundred times a second
starts eating memory.  The solution is to put 'scope' on the
parameter:

void doFormat(scope void delegate(char) dg, blahblah) { .. }

DMD2 will not allocate a closure for the initial code if 'scope' is
present, and if removed, it will.


Re: closures

2009-07-16 Thread Jarrett Billingsley
On Thu, Jul 16, 2009 at 2:33 PM, bearophilebearophileh...@lycos.com wrote:
 Jens:
  // On dmd v2.029, linux build, this...
   call(makedelegate1()); // ...works: 27
   call(makedelegate2()); // ...works: 7
   call(makedelegate3()); // ...doesn't work: 134518855
   call(makedelegate4()); // ...doesn't work: 134518947
   Foo f;
   call(f.bar); // ...works: 7

 I have run your code with DMD v2.031 on Windows, and it prints:
 foo: 27
 foo: 7
 foo: 7
 foo: 7
 foo: 7

Strange.  I use 2.031 on Windows too, and I get strange values for the
third and fourth items, as expected.


Re: Why can't return an object instance by ref?

2009-07-16 Thread Jarrett Billingsley
On Thu, Jul 16, 2009 at 9:47 PM, Sam Husamhudotsa...@gmail.com wrote:
 Hi,

 With below code:
 class A
 {
 }
 class B
 {
 public:
 ref A createA() //  q2:without type name A is also OK?
 {
    return new A;//q1
 }

 }
 My questions are:
 q1.why this can't work?

Because 'new A' is not an lvalue.  Why do you want to return a
reference to a class, anyway?  Classes already *are* by reference.


Re: formatting floating point

2009-07-11 Thread Jarrett Billingsley
On Sat, Jul 11, 2009 at 5:50 PM, Saaaem...@needmail.com wrote:
 double d[2] = [ 0, 1, double.max];
 char[] c = format(d);

  How do I get c to represent full precision?

 [0,1,1.7976931348623157e+308] // but then with double.max being
 represented fully

You want a 309-digit number consisting mostly of 0s?


Re: formatting floating point

2009-07-11 Thread Jarrett Billingsley
On Sat, Jul 11, 2009 at 6:44 PM, Saaaem...@needmail.com wrote:
 double d[2] = [ 0, 1, double.max];
 char[] c = format(d);

 How do I get c to represent full precision?

 [0,1,1.7976931348623157e+308] // but then with double.max being
 represented fully

 You want a 309-digit number consisting mostly of 0s?

 Yes, but only if they are necessary.
 0 doesn't need all hose digits for instance.

Um, doubles don't have infinite precision.  See those digits that it
output?  That's all you get.  Those are the only digits that are
necessary because those are the only digits that are *stored*.  Just
because it's followed by almost 300 0s doesn't mean that 300 0s are
actually stored in the number; it just means the exponent is that
large.

 What else is the point in saving doubles.

If you're saving doubles in a textual format, try using the %a format
specifier.  It outputs a float in hexadecimal notation, which is a bit
more precise than decimal (since no rounding has to be performed).  I
don't know if Phobos' unformatting can actually _read_ hex floats,
though.


Re: formatting floating point

2009-07-11 Thread Jarrett Billingsley
On Sat, Jul 11, 2009 at 7:39 PM, Saaaem...@needmail.com wrote:

 Um, doubles don't have infinite precision.  See those digits that it
 output?  That's all you get.  Those are the only digits that are
 necessary because those are the only digits that are *stored*.  Just
 because it's followed by almost 300 0s doesn't mean that 300 0s are
 actually stored in the number; it just means the exponent is that
 large.

 I now see what you mean by 309 digits.. No I don't want that !! :D
 string.format does only 6 digits by default, I added the extra double.max
 digits in myself from wikipedia :)
 I overestimated the precision of a double, my bad.
 (53bits != 309 digits !)
 How can I format to the full number of digits, like I did for c?

Ohh, I see.  Your initial question was really vague, now that I see
what you were asking.  You'd just have to convert each element of the
array separately.


Re: Specify the type but not number of function arguments in an interface?

2009-07-07 Thread Jarrett Billingsley
On Tue, Jul 7, 2009 at 8:29 AM, downsdefault_357-l...@yahoo.de wrote:

 But then isn't what he asks for kinda impossible by design? I mean, 
 interfaces are bound at runtime. That's what they _do_.


Now read *my* post, downs.  ;)


Re: Specify the type but not number of function arguments in an interface?

2009-07-05 Thread Jarrett Billingsley
On Sun, Jul 5, 2009 at 5:44 AM, downsdefault_357-l...@yahoo.de wrote:
 Doctor J wrote:
 I want to write an interface that expresses the following idea: classes 
 implementing this interface must have a void function named update, with a 
 fixed but indeterminate number of parameters of the same (template 
 parameter) type.

 Use a typesafe variadic function, i.e.

 void test(int[] integers...);


Read the rest of his post, downs.  Particularly option 2.


Re: Specify the type but not number of function arguments in an interface?

2009-07-03 Thread Jarrett Billingsley
On Fri, Jul 3, 2009 at 2:54 PM, Doctor Jnob...@nowhere.com wrote:
 I want to write an interface that expresses the following idea: classes 
 implementing this interface must have a void function named update, with a 
 fixed but indeterminate number of parameters of the same (template parameter) 
 type.  In other words, some implementing classes will have void update(T a), 
 some void update(T a, T b), etc.  Admittedly, this kind of defeats the 
 purpose of an interface, but I thought I would try to hack around it anyhow.  
 :)

 Option 1: put lots of update() functions in the interface, one with each 
 possible number of parameters; implement every one in every derived class; 
 and spew some static asserts if you try to use the wrong ones.  Yuck.

 Option 2: variadic functions: declare void update(T[] params ...) in the 
 interface, and try to specialize to a fixed number of parameters in 
 implementing classes.  D doesn't want to let me do this literally, and 
 params.length nor _arguments.length are static constants -- though it seems 
 like they could be.  I want to catch calls with the wrong number of arguments 
 at compile time.

 Option 3: variadic templates: declare void update(P...)(P args) in the 
 interface, and then define what you like in implementing classes.  This 
 works, but too well: there doesn't seem to be any way to constrain the type 
 of the arguments, which I would like the interface to do.

 Other options?  Is there a way to do this?

No, not really.  The entire purpose of putting a function in an
interface is so that anything that implements it conforms to it
exactly, so you can call the method on any interface reference.  How
the heck would you call .update() on an interface reference if you
didn't know, at compile time, how many params the derived class's
update method took?

This sounds more like a job for duck typing, but I don't know what you're doing.


Re: How to release memory? (D2.0.30)

2009-07-03 Thread Jarrett Billingsley
On Fri, Jul 3, 2009 at 4:30 PM, AxelSa_bo...@gmx.net wrote:
 Hello everyone,
 I've got a problem with the following (very simple) code:

 void foo()
 {
      void[] dat=new void[50_000_000]; // allocate 50 MByte of dummy-data
      delete dat;
 }

 after I called foo() and watched the memory usage in the windows taskmanager, 
 the program blowed up to 50 MBytes although I deleted the allocated memory...

 Why can't the GC remove that data and how CAN I remove it?

 Thanks in advance!

If you're using Tango or D2, you can use the GC.minimize() function
(in tango.core.Memory or core.memory) to release memory back to the
OS, but as BCS said, the amount of virtual memory is not really a
useful indicator anyway.


Re: How to print Chinese characters in console in window XP?

2009-06-27 Thread Jarrett Billingsley
On Sat, Jun 27, 2009 at 10:55 AM, Sam Husamhudotsa...@gmail.com wrote:
 and I start cmd.exe with /u switch.

 I also tried being inspired by below article:
 http://www.codeproject.com/KB/cpp/unicode_console_output.aspx?display=Print

 but unfortunately also failed.



Well I don't know how else to help, I just know that cmd.exe sucks
when it comes to Unicode :\


Re: main return again

2009-06-25 Thread Jarrett Billingsley
On Thu, Jun 25, 2009 at 6:11 PM, bearophilebearophileh...@lycos.com wrote:
 I may have found my 44th bug in DMD:

 void main() { return a; }

 It outputs to me, on Windows:
 Internal error: ../ztc/cgcod.c 1479

How about instead of counting them up and posting them on the
newsgroups, you put them in Bugzilla?  Or are you just completely
thick?


Re: Why use float and double instead of real?

2009-06-23 Thread Jarrett Billingsley
On Tue, Jun 23, 2009 at 8:44 AM, Lars T.
Kyllingstadpub...@kyllingen.nospamnet wrote:
 Is there ever any reason to use float or double in calculations? I mean,
 when does one *not* want maximum precision? Will code using float or double
 run faster than code using real?

As Witold mentioned, float and double are the only types SSE (and
similar SIMD instruction sets on other architectures) can deal with.
Furthermore most 3D graphics hardware only uses single or even
half-precision (16-bit) floats, so it makes no sense to use 64- or
80-bit floats in those cases.

Also keep in mind that 'real' is simply defined as the largest
supported floating-point type.  On x86, that's an 80-bit real, but on
most other architectures, it's the same as double anyway.


Re: max function

2009-06-19 Thread Jarrett Billingsley
On Fri, Jun 19, 2009 at 5:05 PM, Paul D.
Andersonpaul.d.removethis.ander...@comcast.andthis.net wrote:
 Okay, where is the max(a,b) function in phobos?

 I realize it's a dead simple template implementation but I thought it would 
 be implemented somewhere.

 Paul



In D2, it's in std.algorithm.  There isn't one in D1.


Re: bitfields

2009-06-18 Thread Jarrett Billingsley
On Thu, Jun 18, 2009 at 9:16 AM, novice2so...@noem.ail wrote:
 does anyone know: is D2 std.bitmanip compatible with C bitfields?
 can i use it, if i need translate .h file with something like this:

 typedef struct {
    unsigned int can_compress : 1;
    unsigned int can_uncompress : 1;
    unsigned int can_get_info : 1;
    unsigned int : 7;
    unsigned int : 16;
    unsigned int : 16;
    unsigned int : 16;
    unsigned int : 16;
    unsigned int : 16;
 } capabilities;

 Thanks.

Theoretically speaking, it's not possible to answer your question
because the ordering, padding, and arrangement of bitfields in C is
not defined.  It's entirely possible to have two different C compilers
output different code for the same bitfield definitions.  For that
reason, it may not be possible to interface with the corresponding C
library with any other language than C or any other compiler than the
one it was compiled with.

Practically speaking, sure.  Most C compilers will take the path of
least resistance and just pack all the bitfields together as tightly
as they can starting with the LSB, and that is - AFAIK - what
std.bitmanip's bitfield support does.  But there are no guarantees.


Re: bitfields

2009-06-18 Thread Jarrett Billingsley
On Thu, Jun 18, 2009 at 10:28 AM, novice2so...@noem.ail wrote:
 Jarrett Billingsley Wrote:

 It's entirely possible to have two different C compilers
 output different code for the same bitfield definitions.  For that

 Dut how is include files for interfacing is published officialy? For example 
 Sun Java SDK .h files have bitfields to interfacing with java VM (without 
 specifing wich compiler must be used).

I would imagine they're depending on undefined behavior and just
hoping for the best ;)  As I said, most compilers do what you'd expect
them to, it's just that there's the possibility that they won't.


A public apology.

2009-06-15 Thread Jarrett Billingsley
I am sorry for everything.

I am sorry for the negativity.

I am sorry for the lack of faith in the the qualifications and skills
of the leaders of D.

I am sorry for shooting down so many ideas; for treating people who
are new to the language as subhuman; for I was once new to the
language, and didn't understand how it worked either.

I am sorry, Andrei, JJR, and others, for treating you as part of the
privileged few who know what was going on in the development of D,
it's libraries, and its supporting sites.  All of you put in far more
much of your free time than is necessary.  You pour yourselves into
this project, and it was disrespectful of me to question any of it.

I am sorry, Brad, for having projected such a horrible image of myself
on the community.  I want you to know that in spite of my negativity,
and my complaints, and my ridicules, I really find you to be an
inspiration.  I would to anything to be as understanding, intelligent,
and experienced as you.

I am sorry, bearophile, for disregarding your invaluable contributions
as insignificant, petty quibbles over things that didn't matter.
Benchmarks are more important as the million fucking bikeshed
discussions over how the syntax of what checked floating-point
operations should look like, or how operators should be overloaded.
Furthermore I respect you for (and Mr. Gromov) your choice of
lifestyle that you choose, and how you don't back down to anyone for
being what you are.

I am sorry, superdan, for treating you as less than a human because
you didn't express yourself in the way I wanted you to.  Please keep
contributing to the community.   Your common sense evaluation of
social situations is invaluable.  But keep in mind that your current
writing style is not likely to influence many.  Your replacement of
common words with cellphone-text-abbreviations and prodigious curses
does not help to get your point across.  I think you are a very
intelligent man, and that your arguments would be much better-received
if you were to express them in a more formal manner, no matter what
you think.  I'm sorry, but that's the way this community works.

And most of all, I am sorry, Walter, for making so much fun of how
much you've done.  You have brought a language to life, and shown the
world that C++ and its ilk can be better.  You have poured
unimaginable amounts of time, effort, and yourself into this language,
and being the inventor of a language myself, I can't help but relate.
I know you don't have much time to respond to every thread and
suggestion; but I am hoping you can realize that there are people
other than yourself and Andrei who are qualified to help support your
language.  I haven't been able to accept that myself w.r.t my own
language.  Please understand that all of us want D to succeed, and
when you get several requests to fix forward references, or OPTLINK,
or some other basic, not-very-fun aspect of the language, that it is
just as important as the basic conceptual underpinnings of the
language specification itself.  Take Christian Kamm/Tomas Lindquist
Olsens' suggestions and patches to heart.  Be more liberal in
delegating responsibility.  And please let D live up to the
qualification mentioned in the spec: that it is a community-driven
language.

I am sorry.


Re: A public apology.

2009-06-15 Thread Jarrett Billingsley
On Mon, Jun 15, 2009 at 10:15 PM, Derek Parnellde...@psych.ward wrote:
 On Mon, 15 Jun 2009 21:47:53 -0400, Jarrett Billingsley wrote:

 I am sorry for everything.

 Who are you, and what have you done to the real JB?

 LOL ... thanks for this morning chuckle ... unless of course you're serious
 ... in which case I don't get it. Maybe I'm too much like yourself??

I think you and I have a lot in common.  I'm just drunk right now.

 I've actually given up trying to influence D ... the patricians have made
 it too hard to contribute and I've haven't got *that* much free time.

So have I.  But we can at least still shout.


Re: tuples

2009-06-12 Thread Jarrett Billingsley
On Fri, Jun 12, 2009 at 12:10 AM, Ellery
Newcomerellery-newco...@utulsa.edu wrote:
 what is up with this code?

 auto t = tuple(1,'a',3.333,false);
 pragma(msg,typeof(t.tupleof[2 .. $]).stringof);

 spits out

 (double, bool, int, char, double, bool)


It has to do with the way Tuple is implemented in std.typecons:

union
{
Types field;
mixin(tupleFields!(0, T));
}

field is of type (double, bool, int, char), and the mixin defines
something like struct { double _0; bool _1; int _2; char _3; }.
Since it's a union, the field member overlaps with the anonymous
struct, just giving you two different ways of accessing the same
member: t.field[0] or t._0.

When DMD does the tupleof, it puts all the union members in the tuple,
giving you what looks like a duplicated type list.

You can instead use:

pragma(msg,typeof(t.field[$ - 2 .. $]).stringof);


Re: tuples

2009-06-12 Thread Jarrett Billingsley
On Fri, Jun 12, 2009 at 11:00 AM, Jarrett
Billingsleyjarrett.billings...@gmail.com wrote:
 On Fri, Jun 12, 2009 at 12:10 AM, Ellery
 Newcomerellery-newco...@utulsa.edu wrote:
 what is up with this code?

 auto t = tuple(1,'a',3.333,false);
 pragma(msg,typeof(t.tupleof[2 .. $]).stringof);

 spits out

 (double, bool, int, char, double, bool)


 It has to do with the way Tuple is implemented in std.typecons:

    union
    {
        Types field;
        mixin(tupleFields!(0, T));
    }

 field is of type (double, bool, int, char), and the mixin defines
 something like struct { double _0; bool _1; int _2; char _3; }.
 Since it's a union, the field member overlaps with the anonymous
 struct, just giving you two different ways of accessing the same
 member: t.field[0] or t._0.

 When DMD does the tupleof, it puts all the union members in the tuple,
 giving you what looks like a duplicated type list.

 You can instead use:

        pragma(msg,typeof(t.field[$ - 2 .. $]).stringof);

Er,

pragma(msg,typeof(t.field[2 .. $]).stringof);


Re: array depth template

2009-06-11 Thread Jarrett Billingsley
On Thu, Jun 11, 2009 at 9:15 PM, Saaaem...@needmail.com wrote:
 Is this a good way to get the depth of an array?

 int getArrayDepth(T)(ref T array)
 {
 static if( is(T A:A[]) )
 {
 A arr;
 return 1 + getArrayDepth(arr);
 }
 else
 {
 return 0;
 }
 return -1;
 }

It's kind of the right idea, but.. it's also kind of weird.

template ArrayDepth(T: T[]) { const ArrayDepth = 1 + ArrayDepth!(T); }
template ArrayDepth(T)   { const ArrayDepth = 0; }

This lets you get the depth of any array _type_, like
ArrayDepth!(int[][]) gives 2.


Re: array depth template

2009-06-11 Thread Jarrett Billingsley
On Thu, Jun 11, 2009 at 11:02 PM, Saaaem...@needmail.com wrote:
 Any advantage to using two?

I just tend to prefer template specialization when doing type pattern
matching.  It works out better than is() in some cases.

 He also does :  is( T B ==B[])  iso  is( T B:B[] )
 Any significant difference there?

I'm.. not sure, in this case anyway.  Normally == does strict type
comparison while : does implicit type conversion, but in this case,
is() is being (ab)used to pick apart a type rather than test one.  I
think it'll always return 'true' in either case if T is an array, so I
don't think there's a functional difference.

 Also, what's the advantage of explicitly defining it as a template?

As opposed to what, implicitly defining it as a template?  This
question doesn't really make sense.


Re: array depth template

2009-06-11 Thread Jarrett Billingsley
On Fri, Jun 12, 2009 at 12:04 AM, Saaaem...@needmail.com wrote:

 template BaseType(T: T[]) { const BaseType = BaseType!(T); }
 template BaseType(T) {const BaseType = T; }

 ..
 else static if( std2.traits.isNumeric!( BaseType!(T) ) )
 {
 ..

 ddata\ddata.d(192): template instance isNumeric!(int) does not match any
 template declaration
 ddata\ddata.d(192): Error: expression isNumeric!(int) is not constant or
 does not evaluate to a bool

 What am I doing wrong?

Your template.  Types are not values, you cannot declare a constant
that is a type.  You have to use alias instead:

template BaseType(T: T[]) { alias BaseType!(T) BaseType; }
template BaseType(T) { alias T BaseType; }


Re: array depth template

2009-06-11 Thread Jarrett Billingsley
On Thu, Jun 11, 2009 at 11:45 PM, Saaaem...@needmail.com wrote:

 I'm.. not sure, in this case anyway.  Normally == does strict type
 comparison while : does implicit type conversion, but in this case,
 is() is being (ab)used to pick apart a type rather than test one.  I
 think it'll always return 'true' in either case if T is an array, so I
 don't think there's a functional difference.

 Implicit convertion sounds a bit dangerous, might start using == instead

Um, there's no one's better than the other.  Don't overgeneralize on
things you don't understand.  Implicit conversion is necessary in some
cases, and in others, exact comparison is needed.

 Also, what's the advantage of explicitly defining it as a template?

 As opposed to what, implicitly defining it as a template?  This
 question doesn't really make sense.

 I mean, I was using a function template.

A function template is just a function in a template.  Templates can
work just fine on their own.  If you're manipulating types, there's
really no need to get functions involved.

 template ArrayDepth(T: T[]) { const ArrayDepth = 1 + ArrayDepth!(T); }
 template ArrayDepth(T)       { const ArrayDepth = 0; }

 The code looks a bit strange to me:
 ArrayDepth is both a (const) value and template name and where is the return
 value ?

See Implicit Template Properties here:
http://www.digitalmars.com/d/1.0/template.html

When you create a member in a template with the same name as the
template, you can access it from the template without explicitly
writing ArrayDepth!(int[]).ArrayDepth.


Re: array of functions

2009-06-04 Thread Jarrett Billingsley
On Thu, Jun 4, 2009 at 12:42 PM, Trass3r mrmoc...@gmx.de wrote:
 I tried to use a function lookup table to quickly access a particular one.
 But the compiler (dmd1) complains about
 Error: non-constant expression  func

 I guess because it's used inside a class since func is of type function,
 not delegate?

You've got it the other way around.  If func is an instance method
(non-static method) of a class, func is a delegate, not a function.

It can't evaluate func at compile-time because there is no way to
create a delegate at compile-time.  You need an instance to create a
delegate, which you can only create by using 'new', which only works
at runtime.


Re: const confusion

2009-06-01 Thread Jarrett Billingsley
On Mon, Jun 1, 2009 at 4:01 PM, Witold Baryluk bary...@smp.if.uj.edu.pl wrote:
 Dnia 2009-05-31, nie o godzinie 15:36 -0400, Jarrett Billingsley pisze:
 On Sun, May 31, 2009 at 3:26 PM, Witold Baryluk
 bary...@smp.if.uj.edu.pl wrote:
 
  Horrible.
 
  How to ensure constness of data, and still have possibility of changing 
  references of local variables?

 Rebindable.

 http://www.digitalmars.com/d/2.0/phobos/std_typecons.html#Rebindable

 Thanks. I was already thinking about implementing something like this.
 It is very thin, and probably doesn't eat even single byte more than
 original reference.

 So generally we need to cheat: union with const and non-const version +
 opAssign/opDot, and some hidden casts. If everybody is doing this, why
 not.

 Only one problem is that i need to make some wrappers for it:

 alias Rebindable!(C) CC;


 first try:

 auto c1 = CC(new C(1));
 auto c2 = CC(new C(2, c1)); // oops doesn't work
 c2 = c2.b();

 second try:

 auto c1 = CC(new C(1));
 auto c2 = CC(new C(2, c1.opDot())); // ok, works
 c2 = c2.b();


 define some function on original data:

 int something(in C c) {
        return c.a;
 }

 something(c2); // oops, doesn't work

 something(c2.opDot()); // ok, works



 So generally now i need to overload all my functions to support also
 Rebindable!(C), where I will unwrap object and call original function?
 The same with constructors.

 Can't be this done more simpler?

 As I remember there was something like opCast (for explicit casts)?
 Maybe Rebindable should have it casting to original type (with const)?

This seems like a perfect application for opImplicitCast, a feature
that has been bandied about for years and which Andrei seems to have
hinted at coming soon.  Using implicit casts, you would be able to
make a perfectly transparent wrapper type such as Rebindable.

For now, you're stuck overloading on Rebindable!(T) :\


Re: const confusion

2009-05-31 Thread Jarrett Billingsley
On Sun, May 31, 2009 at 3:26 PM, Witold Baryluk
bary...@smp.if.uj.edu.pl wrote:
 Hi,

 i haven't been here for so long time. So hi all. I'm back again.

 I was considering myself as hardcore D hacker, but
 in one point I fail completly. Constness.

 Consider this simple code:

 module ct;

 class C {
        const int a;
        const C b;

        this(int a_) {
                a = a_;
                b = null;
        }
        this(int a_, in cord b_) {
                a = a_;
                b = b_;
        }
        C m() const { // line 16
            return b;
        }
 }

 void main() {
        C c1 = new C(1);
        C c2 = new C(2, c1);
        c2 = c2.m(); // 23
 }

 So I have class C which all methods are const. So it is completly immutable 
 object,
 one can say.

 The problem is with line 16, I define function m which is const (because it
 doesn't change anything). But i'm returing some part of it, so actually somone
 else can change it hypotetically

 Actually it is impossible for two reasons:
  * all fields are const,
  * there is no non-consts methods beside constructors.

 Of course compiler says here: (dmd 2.028)
 ct.d(16): Error: cannot implicitly convert expression (this.b) of type 
 const(C) to ct.C



 so we change line 16 to:
 const(C) m() const { // line 16

 And I can agree that this is correct solution.

 but then there is another problem, now in main() function:
 ct.d(23): Error: cannot implicitly convert expression (c2.m()) of type 
 const(C) to ct.C

 So now, i need to change all occurence of C to const(C), ok no problem:
 void main() {
        const(C) c1 = new C(1);
        const(C) c2 = new C(2, c1);
        c2 = c2.m();  // line 23
 }

 Ok, nice. I can create some alias so it will be easier to use, also.

 But now is another problem:
 ct.d(23): Error: variable ct.main.c2 cannot modify const


 But I wan't to have possibility to change local reference to this class!
 Shouldn't const be about content of object?

 Ok, go and just create new variable:
 void main() {
        const(C) c1 = new C(1);
        const(C) c2 = new C(2, c1);
        auto c3 = c2.m();  // line 23
 }

 compiler now will be happy.

 Ok, it is good for functional style of programing, but consider this:

 void main() {
        const(C) c1 = new C(1);
        const(C) c2 = new C(2, c1);
        while (c2 !is null) {
                c2 = c2.m();  // line 23
        }
        writefln(c2.a);
 }


 So now i need to write tail recursive version of this loop, because compiler
 doen't allow me to reuse variable.

 I can write tail recursive loop, but it's:
  * not so efficient
  * users of my library are not familiary with functional programing
  * it's unnatural.

 Horiblle.

 How to ensure constness of data, and still have possibility of changing 
 references of local variables?

Rebindable.

http://www.digitalmars.com/d/2.0/phobos/std_typecons.html#Rebindable


Re: Template subclasses

2009-05-28 Thread Jarrett Billingsley
On Thu, May 28, 2009 at 11:11 PM, Andrew andrew.sp...@gmail.com wrote:
 I'm curious how someone implements a templated class.  Basically, how do I do 
 this:

 Class Foo(T) {
  T bar;
 }

 Class Fee:Foo {
  T fum;
 }

 Any ideas?

 thanks

 -Andrew


You instantiate the base class.

class Fee(T) : Foo!(T)
{
T fum;
}


Re: Encoding problems...

2009-05-27 Thread Jarrett Billingsley
On Wed, May 27, 2009 at 8:55 PM, Robert Fraser
fraseroftheni...@gmail.com wrote:
 Hi all,

 Quick question: I want to use some unicode identifiers, but I get
 unsupported char 0xe2, both with using and not using a BOM. The characters
 in question are the superset/subset-equals operators: ⊇ and ⊆... Perhaps
 these are just unsupported by DMD (in which case, I'll file a bug)?

 Thanks,
 Robert

If they're not classified as universal alpha I don't think you can
use them in identifiers.


Re: Determine if template argument is an array

2009-05-22 Thread Jarrett Billingsley
On Thu, May 21, 2009 at 8:00 PM, Fractal happycod...@server.com wrote:
 Fractal Wrote:

 Hello

 Any body can explan me how to determine if a template argument is an array?

 ...And also if is an associative array

 Thanks


You can also use template specialization, which, depending on your use
case, might be shorter and clearer than a static if.

template Foo(T: T[]) will specialize for dynamic array arguments.  T
will be the element type (so for int[], T will be int).
template Foo(T: T[n], size_t n) will specialize for static array
arguments. T will be the element type like above, and n will be the
size of the array.
template Foo(T: T[K], K) will specialize for associative array
arguments.  T will be the value type, and K will be the key type.


Re: Class allocation from tuple

2009-05-21 Thread Jarrett Billingsley
On Thu, May 21, 2009 at 11:13 AM, bearophile bearophileh...@lycos.com wrote:
 Jarrett Billingsley:

 When it tries to parse
 the type following 'new', it interprets the brackets as meaning an
 array type,

 I agree. But not even this works:
 new (ClassTuple[0]);

 Bye,
 bearophile

Have you tried reading the errors?

dtest.d(187): basic type expected, not ;

It's parsing the parenthesized expression as an argument to new, then
wondering where your type is (like if you were doing new(blah)
ClassName()).


Re: invariant

2009-05-20 Thread Jarrett Billingsley
On Wed, May 20, 2009 at 2:41 PM, Stewart Gordon smjg_1...@yahoo.com wrote:
 Jarrett Billingsley wrote:

 On Tue, May 19, 2009 at 8:55 PM, Stewart Gordon smjg_1...@yahoo.com
 wrote:

 Jarrett Billingsley wrote:

 snip

 Stewart, you've been here for years.  I *know* that you know that the
 D documentation is often incomplete or incorrect.  You're acting like
 you don't ;)

 Where do you get that idea from?

 Stewart.

 I don't know, the numerous comments and bugzilla reports about how
 lacking you feel the spec - and the quality of its spelling - is?

 That might have something to do with your first two sentences, but I'm still
 lost for where you got the third from.

 Stewart.


Why would invariant be deprecated before there's any documentation on
the meaning of immutable?

Because the docs are usually out of sync with the compiler (which you
know) and because features and changes fall out of the sky with no
prior indication (which you also know)?


Re: invariant

2009-05-19 Thread Jarrett Billingsley
On Tue, May 19, 2009 at 8:55 PM, Stewart Gordon smjg_1...@yahoo.com wrote:
 Jarrett Billingsley wrote:

 On Thu, May 14, 2009 at 7:40 PM, Stewart Gordon smjg_1...@yahoo.com
 wrote:

 Why would invariant be deprecated before there's any documentation on the
 meaning of immutable?

 Stewart, you've been here for years.  I *know* that you know that the
 D documentation is often incomplete or incorrect.  You're acting like
 you don't ;)

 Where do you get that idea from?

 Stewart.

I don't know, the numerous comments and bugzilla reports about how
lacking you feel the spec - and the quality of its spelling - is?


Re: Comparing D structs

2009-05-17 Thread Jarrett Billingsley
On Sun, May 17, 2009 at 3:55 PM, Dan twinbe...@skytopia.com wrote:
 Structs can't easily be compared in C because of potential 'padding' inside 
 the struct which may (or may not) exist.

 I was jut wondering if D somehow gets round this, and allows something like 
 memcmp to easily compare two structs.

As grauzone said, you just use == to compare them.  D solves the issue
with C's uninitialized holes by always initializing structs.
Therefore the padding holes are always filled with 0s.


Re: invariant

2009-05-15 Thread Jarrett Billingsley
On Thu, May 14, 2009 at 7:40 PM, Stewart Gordon smjg_1...@yahoo.com wrote:

 Why would invariant be deprecated before there's any documentation on the
 meaning of immutable?

Stewart, you've been here for years.  I *know* that you know that the
D documentation is often incomplete or incorrect.  You're acting like
you don't ;)


Re: Finding out about D - 102

2009-05-11 Thread Jarrett Billingsley
On Mon, May 11, 2009 at 1:48 PM, Steve Teale
steve.te...@britseyeview.com wrote:

 Then I chase a bug in my program, which compiled OK. After some time, I 
 realize that

   A ntl = nameTooLong[whatever.whatever];

 is doing a copy, which is not what I was thinking about at all - old C++ 
 habits.

Um, C++ works exactly the same way, if you're using classes/structs by value.


Re: dmd on ubuntu installation

2009-05-10 Thread Jarrett Billingsley
On Sun, May 10, 2009 at 10:17 PM, grauzone n...@example.net wrote:

 The files are probably not readable (r) or executable (x) by all other users
 (o). Try chmod o+rx /usr/local/bin/dmd.

Of course, prepend 'sudo' :|


Re: Need direction guide

2009-05-04 Thread Jarrett Billingsley
On Mon, May 4, 2009 at 5:55 AM, Sam Hu samhudotsa...@gmail.com wrote:
 Correctness:
 But to be honest,almost all D members in the forum are a bit  lost for the 
 going of D1 vs D2---
 Here the the forum I mean the Chinese D forums.

Then more of you should speak up in the newsgroups.  Walter doesn't
speak Chinese.


Re: Need direction guide

2009-05-04 Thread Jarrett Billingsley
On Mon, May 4, 2009 at 5:52 AM, Sam Hu samhudotsa...@gmail.com wrote:

 I do know many projects there written by D1,but how come D1 seems to ppl  
 just a  pass-by,please correct me if I am wrong.

Where do you get that impression?  Most code that has been written in
D has been written in D1.  Most D libraries are D1-only or at least
D1-compatible.  There is a very small number of D2 projects, and given
how much D2 and Phobos 2 are changing, I doubt that they're terribly
stable.

If you get the impression that since most of the discussions are about
D2 then D1 is dead, well, no.  It's just that D1 doesn't (and can't)
change anymore, so there's no point discussing it.


Re: how to initialize an array of typedef-ed type?

2009-05-02 Thread Jarrett Billingsley
On Sat, May 2, 2009 at 2:29 AM, Daniel Keep daniel.keep.li...@gmail.com wrote:

 (or tango.util.Convert, with identical syntax)

 Never heard of it.  :)

Oh, I see, that was written by the other Daniel Keep.  It's easy to
get you mixed up.


Re: how to initialize an array of typedef-ed type?

2009-05-01 Thread Jarrett Billingsley
On Fri, May 1, 2009 at 9:15 AM, MLT n...@anone.com wrote:

 typedef long location ;
 location a[] = cast(location[])[1,2,3,4] ;

 Seems to work.
 I was afraid of the mess that would happen if I cast (int *) to (long *) in 
 C...
 Can I trust it? Is that the right way to do it?

Have you actually run it and seen what the results are?  If it works,
well, use it :)

(It does work, and that is the right way to do it.)


Re: How to get the base type of a typedef

2009-05-01 Thread Jarrett Billingsley
On Fri, May 1, 2009 at 9:54 AM, MLT n...@anone.com wrote:

 and it works! Great!!
 Hmmm... but how?
 in is( T BaseType1 == typedef ) Basetype1 seems to be a variable of type T.
 Then calling 'alias BaseTypedef!(BaseType1) BaseTypedef;' does not seem to 
 strip away a layer... isn't it still called on a variable of type T? Or does 
 'is()' do some magic?

is() does a lot of magic.  It has the worst, most confusing thing in
the language.

When you do is(T U == typedef), it will evaluate to true if T is a
typedef, and if so, will declare an alias U which is aliased to the
base type of the typedef.  It's not a variable, just a type.

The recursive call to BaseTypedef!(BaseType1) is there because
BaseType1 _itself_ may be a typedef.  For instance:

typedef int a;
typedef a b;

If you call BaseTypedef!(b), the is() will figure out that its base
type is a; then it recursively calls BaseTypedef!(a), which determines
the base type is int; then it recursively calls BaseTypedef!(int),
where the is() evaluates to false, it hits the base case of recursion,
and evaluates to int.  That propagates up, and so BaseTypedef!(b)
evaluates to int.


Re: how to initialize an array of typedef-ed type?

2009-05-01 Thread Jarrett Billingsley
On Fri, May 1, 2009 at 10:07 AM, MLT n...@anone.com wrote:

 At first I thought that maybe on my machine int and long have the same 
 length, or some such. But it works, for int, long, and short. And they do 
 have different lengths.

D's integer types are not like C's.  They are fixed size and do not
vary from platform to platform.  See
http://www.digitalmars.com/d/1.0/type.html

 I tried a bit more:
 ---
 typedef long tlong ;

 void main()
 {
        int[] x = [1,2,3,4] ;

        tlong[] y = cast(tlong[])[1,2] ; // - this works

        Stdout(y).newline ;

        y = cast(tlong[]) x ; // This doesn't

        Stdout(y).newline ;
 }
 ---
 prints out:
 [1, 2]
 [8589934593, 17179869187]

 The the initialization works, but casting from int[] to long[] in general 
 doesn't.

You're actually doing two different things there.

Initialization is treated as a special case and casting it will cast
each element.

But array casts done at runtime will do a bit cast - that is, given
your int[] [1, 2, 3, 4], when you cast it to a long[] at runtime, it
takes that chunk of memory, figures out how many longs will fit in it
(in this case 2), and gives you a new array reference to the same data
but with a different type.  Those big weird numbers are
0x0002_0001 and 0x0004_0003, respectively.  Woah look
at that, 1, 2, 3, 4!

To make it more apparent, try casting an int[] to a byte[] or
something.  You'll see that it then splits up each original int into
four bytes.


Re: how to initialize an array of typedef-ed type?

2009-05-01 Thread Jarrett Billingsley
On Fri, May 1, 2009 at 11:34 AM, MLT n...@anone.com wrote:


 Is there an easy way to convert arrays from one type to another?
 int[] a=[1,2,3,4] ;
 long[] b ;

Not really.  The best you can do is:

b.length = a.length;
foreach(i, ref v; b) v = a[i];


Re: isatty and Pavel stream.d

2009-05-01 Thread Jarrett Billingsley
On Fri, May 1, 2009 at 11:52 AM, Carlos Smith carlos-sm...@sympatico.ca wrote:


 So may be there is a problem with fileno() ??

I have no idea.

 You mean std.stream?  That's been part of Phobos .. well, forever. At
 least 5 years anyway.

 No, i mean the stream.d that comes in stream.zip from the
 Pavel's site: http://int19h.tamb.ru/files/stream.zip
 His stream library seems different. as, it have functions to
 read Unicode strings from the console. I tried to compile
 it with dmd 1.043 but there are many errors.

std.stream *is* Pavel's code.  That zip is absolutely ancient.  It's
no surprise it doesn't compile.

 I know that function. But it allows to read
 char[] arrays only. (if i read well the declarations).

Sure, but char[] IS Unicode!  It's just UTF-8.

 How do i read wchar[] arrays from the console with it ?

Use std.cstream.din.readLineW() if you want a wchar[] so badly.


Re: how to initialize an array of typedef-ed type?

2009-05-01 Thread Jarrett Billingsley
On Sat, May 2, 2009 at 12:21 AM, Daniel Keep
daniel.keep.li...@gmail.com wrote:


 import std.conf;
 b = to!(long[])(a);

 That should work, in theory.

In reality, it's std.conv ;)

(or tango.util.Convert, with identical syntax)


Re: Get the name of a function and the parameters?

2009-04-29 Thread Jarrett Billingsley
On Wed, Apr 29, 2009 at 3:03 AM, grauzone n...@example.net wrote:

 Wow, it actually works. But I really don't understand why. It seems the
 compiler directly passes symbols as tuple arguments, and later dumbs it down
 to what it needs (like an alias, a type, ...).

 Makes me think nobody will ever be able to write a separate bug-free DMD
 frontend. I'm scared.

Precisely.  There is no principle of least surprise in the DMD
metaprogramming implementation.  There is no consistency.  And worst
of all, there is no specification.


Re: Get the name of a function and the parameters?

2009-04-29 Thread Jarrett Billingsley
On Wed, Apr 29, 2009 at 2:52 AM, Georg Wrede georg.wr...@iki.fi wrote:
 Jarrett Billingsley wrote:

 Don't you love it?  Most C++ template features are discovered.  So are
 D's.

 Well, one could say that this is the very definition of a well working
 metaprogramming system. After all, the whole idea of templates is to let the
 programmer invent new ways to use the lanaguage, the compiler, and the
 template system.

That's not.. really at all what the issue is here.  The issue is more
that most of the metaprogramming features in D are completely
unspecified, and when we discover that something works, it's hard to
tell if it's _supposed_ to be that way or if we're taking advantage of
some weird bug in the compiler.  Show me a page that documents
.stringof!  Thought not.

As some other examples, did you know it's possible to get the names of
the fields of a struct type (and probably a class type too with a
similar method)?  It only works under extremely contrived
circumstances, using .stringof, and parsing out the names yourself
from a very horrible-looking string.  It's also possible to get the
name of a local variable by instantiating a template in a local scope
and parsing a horrid .mangleof string.  You can also determine some
(not *all*, but some) interesting properties of functions and methods
- things like final, static, abstract - by creating dummy inherited
classes and attempting to do awful things to them.

Metaprogramming should be _well-specified_ and _orthogonal_.  I agree
with you that the _possibilities_ of metaprogramming should be almost
boundless and should allow you to come up with your own DSLs.  But the
compiler shouldn't hold information about your program ransom and
make you work so goddamn hard to get at it.  I should be able to just
write, I don't know, __traits(parameterNames, f) and get a tuple of
parameter names!  I'm tired of puzzling out information that should be
directly available!


  1   2   3   >