missing: __traits(isPublic (private, etc...)
I am working a reflection / introspection library (dynamic / at runtime, as opposed to compile time with template and mixin). Now I can create PropertyInfo classes for property with very little code and it all works well. I'm hitting a problem, trying to register all property of my class automatically. I have a vanilla implementation like that: = void RegisterProperties(T)() { foreach(mn ; __traits(derivedMembers, T)) GetProperty!(T, mn); } = The problem is, it's trying to register private properties! (and of course fail, due to access rights...) So far I have test like === static if(mixin(__traits(compiles, t. ~memberName ~)) ) { getter = GETTER!(T, memberName); } which test that the thing is a property. But how could I test it's a ***public*** property? if not possible, wouldn't it be a nice trait addition?
Re: missing: __traits(isPublic (private, etc...)
Hey Adam! Thanks again for your web.d! My introspection class went along quite well, thanks in no small part to you! ;) implementing INotifyPropertyChanged now and .. data binding next! :) Adam Ruppe wrote in message news:itnfqc$kg2$1...@digitalmars.com... Indeed, this would be nice. I want it for my web.d thing. But, as far as I know, there's no way to get it at all right now. A while ago, I tried to add it to the compiler. The problem is protection is stored with the symbol itself, not the thingy returned by getMember - that's always considered public by the compiler. So if you pass the actual Class.member, it's easy to see if it's public or not, but the getMember doesn't say. (Which is why it compiles in the first place... otherwise the private members would give visibility errors when you tried to use it there.) In the compiler, if there was an informational field for protection added, the trait could be made to work, but I haven't gotten around to trying to patch that yet and afaik no one else is interested enough to look either.
struct as dictionary key
I am creating a struct that I want to use as dictionary (associative array) key Initially it was a class and I overrode toHash and opCmp. I just made it a struct to be more lightweight on the system, but can't override toHash anymore! How can I make it a good dictionary key? Here is the struct struct PropertyId { TypeInfo declaringType; /// ditto string propertyName; /// ditto }
Re: struct as dictionary key
Never mind, just found it! http://www.digitalmars.com/d/2.0/hash-map.html
problem with array of delegates!
the following code seem problematic to compile... import std.algorithm; private alias void delegate(int, int) SlotDelegate; class A { void DIT(int a, int b) { } } int main(string[] argv) { A a; SlotDelegate x= a.DIT; SlotDelegate[] _slotDg; _slotDg.remove(x); return 0; } I have some strange error: Error: incompatible types for ((pos) (from)): 'uint' and 'void delegate(int, int)' C:\D\dmd2\windows\bin\..\..\src\phobos\std\algorithm.d5609 I try a method like that as well (but similar problem! :( ) void removeAt(T)(ref T[] array, int index) { if(index 0 || index = array.length) return; const T[] empty = null; array.replaceInPlace(index, index + 1, empty); }
Re: problem with array of delegates!
There is a remove() method in std.algorithm!I even got asked why I was reimplementing it! (well, because I didn't know it existed hey!) works fine with, say, int... but not with delegate! associative array will solve the problem indeed.. (I hope) but they use way more memory! it would be nice to have remove working() :) Further, as you can see in my post, even my (reasonable) implementation of removeAt() fail! :( (but, again, it works for int!) Andrej Mitrovic wrote in message news:mailman.1010.1308495216.14074.digitalmars-d-le...@puremagic.com... Remove takes an offset, not a value as far as I know. If you need fast lookup and removal you could use hashes instead: int main(string[] argv) { auto a = new A; SlotDelegate x = a.DIT; bool[SlotDelegate] _slotDg; _slotDg.remove(x); return 0; }
Re: Any (working) JSON library for D2?
Doost : http://www.dsource.org/projects/doost Has a serializer that can read value to and from JSon! ;) Johannes Pfau wrote in message news:20110619193834.2c6afdf7@jpf-Satellite-A100... std.json doesn't work at all because of bug #2962 . I tried to remove the problematic part from std.json and got it to compile (by disabling support for floating point numbers...) but using it correctly creates very verbose code: -- JSONValue a; if(a.type == JSONTYPE.OBJECT) if(member in a) if(a[member].type == TYPE.NUMBER) uint count = a[member].number; -- (pseudo-code, but that's the basic workflow when using std.json) I know there also was a std.json replacement proposed by Robert Jacques but it requires significant patches to phobos, a std.variant replacement and the patches are against phobos 2.050 or something like that, so those could be out of date. To cut a long story short: does anyone know of another JSON library for D2? -- Johannes Pfau
Re: dummy question : runtime type testing...
That simple hey?!? Awesome! You are a week-end saver! :) Mike Wey wrote in message news:ithv61$2j5t$1...@digitalmars.com... bool isTypeOf(T)(TypeInfo ti) { return ( typeid(T) is ti ); } bool isTypeOf(TypeInfo ti1, TypeInfo ti2) { return ( ti1 is ti2 ); } -- Mike Wey
Re: dummy question : runtime type testing...
on a related not. in the (templated) function taking a variant, I use the coerce() method which does some conversion (byte to int, for example) the suggested code (while excellent, much thanks again!) is very stringent, doesn't allow for such implicit conversion i.e. with bool isTypeOf(TypeInfo ti1, TypeInfo ti2) { return ( ti1 is ti2 ); } isTypeOf(typeid(byte), typeid(int)) will return false. is there (I might be pushing it here, I know :P) a way to make it return true in such case?? Mike Wey wrote in message news:ithv61$2j5t$1...@digitalmars.com... On 06/18/2011 05:28 AM, Lloyd Dupont wrote: ho... easy hey! but how about the other 2 test I'd like be able to run? bool isTypeOf(T)(TypeInfo ti) { return T is ti } bool isTypeOf(TypeInfo ti1, TypeInfo ti2) { return ti1 is ti2 } bool isTypeOf(T)(TypeInfo ti) { return ( typeid(T) is ti ); } bool isTypeOf(TypeInfo ti1, TypeInfo ti2) { return ( ti1 is ti2 ); } -- Mike Wey
Re: smarter reflection issue
It helped! it's working now! :) Thanks! Jesse Phillips wrote in message news:itgg6i$2tf3$1...@digitalmars.com... Lloyd Dupont Wrote: Hi Jesse, this won't work! It's my fault in not explaining my problem well though... I forget to mention something... I'm using property syntax and try to call the method Say I have = private int _foo; @property public int Foo() { return _foo; } @property public void Foo(int value) { _foo = value; } = if I call MEMBER(MyClass, Foo) I'd like to do some static test for int Foo() and void Foo(int) So... how will I go on solving that? I don't remember how to package these up nicely: void MEMBER(T, string fun)(T m) if(expectedType!(T, fun).valid) { } template expectedType(T, string fun) { private T s; static if(mixin(__traits(compiles, s.~fun~ = 0) is(typeof(s.~fun~) : int))) enum valid = true; else enum valid = false; }
dummy question : runtime type testing...
given A a = class A {} class B : A {} how could I test, at runtime, if a is just a A or is a B? also, give a type T and a TypeInfo variable, how can I know if a variable of type T is attributable to a variable of type described by TypeInfo? i.e. how could I implement the method below? bool isTypeOf(T)(TypeInfo ti) { /* how to check and return whether T is a ti or a subclass */ }
Re: dummy question : runtime type testing...
ho... easy hey! but how about the other 2 test I'd like be able to run? bool isTypeOf(T)(TypeInfo ti) { return T is ti } bool isTypeOf(TypeInfo ti1, TypeInfo ti2) { return ti1 is ti2 } Jonathan M Davis wrote in message news:mailman.988.1308367581.14074.digitalmars-d-le...@puremagic.com... On 2011-06-17 19:58, Lloyd Dupont wrote: given A a = class A {} class B : A {} how could I test, at runtime, if a is just a A or is a B? Cast it. The result will be null if the cast fails. if(cast(B)a) //it's a B else //it's an A but not a B - Jonathan M Davis
D documentation
I'm working a small but reasonably interesting D project which I'd like to, ultimately, open source. To make it attractive I need to document my class. Is there anything remotely like Javadoc which works with D?
Re: D documentation
Thanks bearophile! bearophile wrote in message news:itcs1k$1l8t$1...@digitalmars.com... Lloyd Dupont: I'm working a small but reasonably interesting D project which I'd like to, ultimately, open source. To make it attractive I need to document my class. Is there anything remotely like Javadoc which works with D? http://www.digitalmars.com/d/2.0/ddoc.html I suggest you to take a general look at D documentation. Bye, bearophile
__traits, compile time member type info
I'm trying to build an introspection system for a project I have. I already have a working template to get members value === working members getter === Variant GETTER(T, string member)(Object target) { T tt = cast(T)target; if (!tt) throw new ReflectionException(target is null or not ~T.stringof ~ value: ~target.toString()); return Variant(__traits(getMember, tt, member)); } === Now I'm trying to implement a working setter. I have a problem for testing and converts the value. Ideally I'd like something like the code below = not compiling setter void SETTER(T, string member)(Object target, Variant value) { T tt = cast(T)target; if (!tt) throw new ReflectionException(target is null or not ~T.stringof ~ value: ~target.toString()); if(!value.convertsTo!( typeid(__traits(getMember, T, member))) ) throw new ReflectionException(Can't convert ~value.stringof ~ to ~typeid(__traits(getMember, T, member)).toString()); __traits(getMember, tt, member) = value.coerce( typeid(__traits(getMember, T, member)) ); } == it doesn't compile because I don't know how to get the type, at compile time, of member member of type T how do I do that please?
Solved!
work with typeinfo!! :) = void SETTER(T, string member)(Object target, Variant value) { T tt = cast(T)target; if (!tt) throw new ReflectionException(target is null or not ~T.stringof ~ value: ~target.toString()); if(!value.convertsTo!( typeof(__traits(getMember, T, member)) )) throw new ReflectionException(Can't convert ~value.stringof ~ to ~typeof(__traits(getMember, T, member)).stringof); __traits(getMember, tt, member) = value.coerce!( typeof(__traits(getMember, T, member)) ); } ==
Re: __traits, compile time member type info
works with typeinfo! void SETTER(T, string member)(Object target, Variant value) { T tt = cast(T)target; if (!tt) throw new ReflectionException(target is null or not ~T.stringof ~ value: ~target.toString()); if(!value.convertsTo!( typeof(__traits(getMember, T, member)) )) throw new ReflectionException(Can't convert ~value.stringof ~ to ~typeof(__traits(getMember, T, member)).stringof); __traits(getMember, tt, member) = value.coerce!( typeof(__traits(getMember, T, member)) ); } Lloyd Dupont wrote in message news:itcthc$1onk$1...@digitalmars.com... I'm trying to build an introspection system for a project I have. I already have a working template to get members value === working members getter === Variant GETTER(T, string member)(Object target) { T tt = cast(T)target; if (!tt) throw new ReflectionException(target is null or not ~T.stringof ~ value: ~target.toString()); return Variant(__traits(getMember, tt, member)); } === Now I'm trying to implement a working setter. I have a problem for testing and converts the value. Ideally I'd like something like the code below = not compiling setter void SETTER(T, string member)(Object target, Variant value) { T tt = cast(T)target; if (!tt) throw new ReflectionException(target is null or not ~T.stringof ~ value: ~target.toString()); if(!value.convertsTo!( typeid(__traits(getMember, T, member))) ) throw new ReflectionException(Can't convert ~value.stringof ~ to ~typeid(__traits(getMember, T, member)).toString()); __traits(getMember, tt, member) = value.coerce( typeid(__traits(getMember, T, member)) ); } == it doesn't compile because I don't know how to get the type, at compile time, of member member of type T how do I do that please?
templated overloaded operator problem.. :~
I have 2 overload of the opCall() in one of my class. They cause a compile time error / conflict... any idea on how to solve it? = class MemberDesc { Variant opCall(Object target) { return getter(target); } void opCall(T)(Object target, T value) { setter(target, Variant(value)); } const string name; const TypeInfo type; const Variant function(Object target) getter; const void function(Object target, Variant value) setter; this( string name, TypeInfo type, Variant function(Object target) getter, void function(Object target, Variant value) setter = null) { this.name = name; this.type = type; this.getter = getter; this.setter = setter; } } =
Re: templated overloaded operator problem.. :~
Ho thanks, even better than the work around I just found! :) David Nadlinger wrote in message news:itcvbj$1td2$1...@digitalmars.com... Add a pair of parentheses to the first overload to add an empty template argument list – currently, template and non-template functions can't be overloaded. David
smarter reflection issue
I have a MemberDesc class which describe a class's members. I fill it with a template method like that (with GETTER and SETTER some other templated method I wrote) = MemberDesc MEMBER(T, string memberName)() { TypeInfo ti = typeid( typeof(__traits(getMember, T, memberName)) ); Variant function(Object target) getter = null; getter = GETTER!(T, memberName); void function(Object target, Variant value) setter = null; setter = SETTER!(T, memberName); return new MemberDesc(memberName, ti , getter, setter); } = And it works except that I don't do any check that the setter / getter method exist! I tried something like that static if( __traits(compiles, __traits(getMember, T, member)) ) { getter = GETTER!(T, memberName); } but this always fail... mm.. how could I check for the getter? and i guess it's even harder for the setter! how about something like that (how to fix it?) = static if( __traits(compiles, __traits(getMember, T, member) = typeof(__traits(getMember, T, memberName)).init) ) { setter = SETTER!(T, memberName); } =
Re: smarter reflection issue
Hi Jesse, this won't work! It's my fault in not explaining my problem well though... I forget to mention something... I'm using property syntax and try to call the method Say I have = private int _foo; @property public int Foo() { return _foo; } @property public void Foo(int value) { _foo = value; } = if I call MEMBER(MyClass, Foo) I'd like to do some static test for int Foo() and void Foo(int) So... how will I go on solving that? Jesse Phillips wrote in message news:itdqs4$mv0$1...@digitalmars.com... MemberDesc MEMBER(T, string memberName)() if(std.traits.hasMember!(T, memberName)) { ... } Lloyd Dupont Wrote: I have a MemberDesc class which describe a class's members. I fill it with a template method like that (with GETTER and SETTER some other templated method I wrote) = MemberDesc MEMBER(T, string memberName)() { TypeInfo ti = typeid( typeof(__traits(getMember, T, memberName)) ); Variant function(Object target) getter = null; getter = GETTER!(T, memberName); void function(Object target, Variant value) setter = null; setter = SETTER!(T, memberName); return new MemberDesc(memberName, ti , getter, setter); } = And it works except that I don't do any check that the setter / getter method exist! I tried something like that static if( __traits(compiles, __traits(getMember, T, member)) ) { getter = GETTER!(T, memberName); } but this always fail... mm.. how could I check for the getter? and i guess it's even harder for the setter! how about something like that (how to fix it?) = static if( __traits(compiles, __traits(getMember, T, member) = typeof(__traits(getMember, T, memberName)).init) ) { setter = SETTER!(T, memberName); } =
Re: introspection experiment
Thanks for that! It'll need some digesting... but it's already giving me some idea! :) Adam D. Ruppe wrote in message news:it7rlo$2ql3$1...@digitalmars.com... While my code is ugly as sin, it might be useful to look at the prepareReflection function in my web.d http://arsdnet.net/dcode/web.d End result is you can do: reflection.objects[Foo].functions[ABC].dispatcher(...);
Re: enum sstring problem
Yes indeed, I'm using Visual D Ho... good to know, thanks! :) mm.. well hopefully it'll be fixed in the next release... and I should pay a close look at the build script! Johann MacDonagh wrote in message news:itbp22$28l2$1...@digitalmars.com... On 6/15/2011 5:32 PM, Jos van Uden wrote: Using 2.053 on win32 (XP), compiles and runs. Ah! I found the problem. If you're using VisualD it compiles with the -g flag (add symbolic debug info), which fails: main.d(4): Error: Integer constant expression expected instead of hello main.d(5): Error: Integer constant expression expected instead of betty main.d(4): Error: Integer constant expression expected instead of hello main.d(5): Error: Integer constant expression expected instead of betty If you compile with just dmd main.d in the command line it works. It's a bug. Anyone know if it's submitted yet?
Re: Is it reasonable to learn D
Too late! :P I have been inspired by the simplicity of D and DGui. Never happened before with earlier C++ experiments... my loss! Jose Armando Garcia wrote in message news:mailman.906.1308016642.14074.digitalmars-d-le...@puremagic.com... On Mon, Jun 13, 2011 at 6:33 AM, Lloyd Dupont ld-rem...@galador.net wrote: Let's learn together then! :P http://galador.net/codeblog/?tag=/D While my blog post are only about setting up the environment so far.. I have delved in the code for 2 weeks now! (Although I had some day off (work and programing) in Darwin) I'm right into it now, should have a new blog post soon! About programing this time! My verdict: it's frustrating yes. But D has a couple of advantages and 2 that you might like: - D has event / delegate, just like C# (and unlike C++, or maybe C++ has them, (it has method pointer, right!?) but it's not taken advantage of!) - the above point is probably what makes the C++ GUI so... difficult. Whereas I found a GUI API for D just like WinForm! (DGui!) Boost, GTK+ and QT have signals. E.g. http://www.boost.org/doc/libs/1_46_1/doc/html/signals.html
need some template help!
I'm writing some manual reflection (a bit more automatism will come later, thanks to __traits and mixin)(hopefully) There are a few problems with my implementation so far... - First the implementation: system.reflection.member.d = module system.reflection.member; public: public enum MemberType { Bool, Int, Object = 100, } class MemberDesc { MemberType mtype; string name; union { bool delegate() getbool; byte delegate() getyte; int delegate() getint; Object delegate() getobject; } this(string name, bool delegate() getbool) { this.name = name; this.mtype = MemberType.Bool; this.getbool = getbool; } this(string name, int delegate() getint) { this.name = name; this.mtype = MemberType.Int; this.getint = getint; } this(string name, Object delegate() getobject) { this.name = name; this.mtype = MemberType.Object; this.getobject = getobject; } } = test.d = module test; import system.reflection.property; class Foo { private int _abc; @property public int ABC() { return _abc; } @property public void ABC(int value) { _abc = value; } private Foo _foo; @property public Foo FOO() { return _foo; } @property public void FOO(Foo value) { _foo = value; } MemberDesc[string] getmembers; this() { getmembers[ABC] = new MemberDesc(ABC, ABC); getmembers[FOO] = new MemberDesc(FOO, delegate Object() { return FOO(); }); } override string toString() { return format(Foo(%s, %s), ABC, FOO); } } - now the problems: 1./ getmembers is an instance variable (i.e. not static) because.. it contains delegate! ideally it should be static! how could I have this working with a static getmembers? 2./ the very different syntax for the constructor of MemberDesc for ABC and FOO (ABC, and delegate Object() { return FOO(); }) how could I automate that (with mixin, __traits and foreach) 3./ I'd like the getmembers declaration and / or initialization being in a (mixin?) template. is that possible? how? Thanks for any tip(S)! :)
strange compiler (linker) error
I have DMD2.053, on Windows. I just moved my folder around. I compile with the following command line: == dmd -lib -g -unittest -debug -w -wi -X -XfDebug\dinstall.json -ofDebug\dinstall.lib -deps=Debug\dinstall.dep -map Debug\dinstall.map -L/NOMAP @Debug\dinstall.build.rsp == I got the following error, what the heck that could mean? == Error: multiple definition of format_b8_a15: _D10format.18412__ModuleInfoZ and format: _D10format.18412__ModuleInfoZ Building Debug\dinstall.lib failed! ==
introspection woes...
Trying to play with introspection. trying o, for a given object, to check its property by name. Experimenting with the function below. 1. it doesn't compile! mi.name() seems to be a problem? 2. match is always null! even though I pass the name of an existing property and / or field! === Object getelement(Object o, string aname) { if (!o) return null; auto ci = o.classinfo; writefln(class: %s, ci.name); auto match = ci.getMembers(aname); foreach(mi ; ci.getMembers(null)) { writefln(%s . %s, ci.name, mi.name()); } //writefln(match: %s, match); return o; } ==
Re: Object
I see mm Thanks for the info! Jonathan M Davis wrote in message news:mailman.866.1307943671.14074.digitalmars-d-le...@puremagic.com... Object is not currently const-correct: http://d.puremagic.com/issues/show_bug.cgi?id=1824 As a result, a number of basic functions do not currently work with const objects. So, making opEquals const means that it's not going to work. It sucks, but until Object is fixed to be const-correct, that's the way it goes.
Re: Is it reasonable to learn D
Let's learn together then! :P http://galador.net/codeblog/?tag=/D While my blog post are only about setting up the environment so far.. I have delved in the code for 2 weeks now! (Although I had some day off (work and programing) in Darwin) I'm right into it now, should have a new blog post soon! About programing this time! My verdict: it's frustrating yes. But D has a couple of advantages and 2 that you might like: - D has event / delegate, just like C# (and unlike C++, or maybe C++ has them, (it has method pointer, right!?) but it's not taken advantage of!) - the above point is probably what makes the C++ GUI so... difficult. Whereas I found a GUI API for D just like WinForm! (DGui!) In short summary I found these cool things: VisualD 0.3.24 (plugin for programing from Visual Studio) http://www.dsource.org/projects/visuald VisualD NOTE: (system tweaks)(required) : edit sc.ini http://www.dsource.org/projects/visuald/wiki/KnownIssues#Librarysearchpathnotpassedtolinker DGui 02052011 (WinForm like API) http://code.google.com/p/dgui/ Doost (r88) (serialization) http://www.dsource.org/projects/doost Windows API r371 http://dsource.org/projects/bindings/wiki/WindowsApi Fabian wrote in message news:islvgf$1b61$1...@digitalmars.com... Dear D Community, is it reasonable to learn D? I've found a lot of good points for D but I've found a lot of negative points too. I believe that I needn't to list all the point for D but I want to give a few examples against learning D I've read in some German and English boards: - The D compiler has only bad code optimization - There are no maintained GUI libraries - The development of the compiler is very slow - Only a small community = no real German community So I ask you - Is it reasonable to learn D? I'm looking forward to your answers. Greetings Fabian PS: If you want to contact me you are allowed to write an Email to me. contact-...@freemail.de
introspection woes (2)
trying to learn introspection, I have this simple test method: === static void dumpelement(Object o) { if (!o) return; auto ci = o.classinfo; foreach(mi ; ci.getMembers(null)) { writefln(%s . %s, ci.name, mi.name()); } } == However it fails to compile with the following error: (any ideas?) === main.d(57): Error: function object.MemberInfo.name () is not callable using argument types () const Building Debug\dtest.exe failed!
simple syntax issue with template
I'm trying to create 2 extra method for arrays (range would be better, though I don't quite understand what is a range) Although I have some indecipherable (to me) compiler error... What's wrong with the code below? == import std.algorithm; public: void remove(T)(ref T[] array, T element) { auto index = array.countUntil!(a == b, T[], T)(array, element); removeAt(index); } void removeAt(T)(ref T[] array, sizediff_t index) { if(index 0 || index = array.length) return; array.replaceInPlace(index, index + 1, []); } unittest { auto a = [1, 3, 4]; a.remove(3); assert(a == [1, 4]); } ==
Re: introspection woes (2)
Interesting... I think I understand... Thanks! :) However an other problem arise with getMembers() it always returns null! Looking at the code it seems (from my beginner's perspective) that getMembers() rely on the member field (function) xgetMembers which is always null, as far as I can tell (didn't see any assignment...) Anyway of ... making the runtime update xgetMembers? Johannes Pfau wrote in message news:20110613140030.70c8d27b@jpf-Satellite-A100... Lloyd Dupont wrote: trying to learn introspection, I have this simple test method: === static void dumpelement(Object o) { if (!o) return; auto ci = o.classinfo; foreach(mi ; ci.getMembers(null)) { writefln(%s . %s, ci.name, mi.name()); } } == Looks like getMembers() returns 'const MemberInfo' but name() is not declared as const. That's likely a bug in druntime, but as a workaround you can try this: == writefln(%s . %s, ci.name, (cast(MemberInfo)mi).name()); ==
Re: simple syntax issue with template
removed some obvious error, still stumped on the templated syntax ... so.. why is it not compiling? (error: Error: template std.algorithm.countUntil(alias pred = a == b,R1,R2) if (is(typeof(startsWith!(pred)(haystack,needle does not match any function template declaration ) = import std.algorithm; public: void remove(T)(ref T[] array, T element) { sizediff_t index = array.countUntil!(a == b, T[], T)(array, element); removeAt(array, index); } void removeAt(T)(ref T[] array, sizediff_t index) { if(index 0 || index = array.length) return; array.replaceInPlace(index, index + 1, []); } unittest { auto a = [1, 3, 4]; a.remove(3); assert(a == [1, 4]); } =
Re: simple syntax issue with template
ho.. plenty of silly mistake indeed.. thanks for spotting them! (maybe I should take a break and play the witcher 2 hey!?!? :) however I still have a problem with removeAt now! :( === void removeAt(T)(ref T[] array, int index) { if(index 0 || index = array.length) return; array.replaceInPlace(index, index + 1, []); } === will produce the following errors: === Error: template std.array.replaceInPlace(T,Range) if (isDynamicArray!(Range) is(ElementEncodingType!(Range) : T) !is(T == const(T)) !is(T == immutable(T))) does not match any function template declaration Error: template std.array.replaceInPlace(T,Range) if (isDynamicArray!(Range) is(ElementEncodingType!(Range) : T) !is(T == const(T)) !is(T == immutable(T))) cannot deduce template function from argument types !()(int[],int,int,void[]) === mmm.. strangely enough the code below succeed! void removeAt(T)(ref T[] array, int index) { if(index 0 || index = array.length) return; T[] empty; array.replaceInPlace(index, index + 1, empty); } but T[].init didn't work either?! ho well, thanks! :)
Re: introspection woes (2)
Thanks Robert! Mm.. can you (per chance!) share some code? I'm a newbie and compile time reflection is something which eludes me (so far...)! Robert Clipsham wrote in message news:it4vp1$1n5q$1...@digitalmars.com... Anyway of ... making the runtime update xgetMembers? My understanding is that xgetMembers is never filled in due to the overhead it would add. You can recompile dmd to support it, but that's a pain. The work around I use is to put a mixin in every class I want to use which uses compile time reflection to build an array which I can access at runtime. Not the most elegant solution. Perhap's a bug report needs opening for this if one isn't already open.
Re: introspection woes (2)
Works a treat! Thanks for your detailed sample! :) Robert Clipsham wrote in message news:it5395$2028$1...@digitalmars.com... See: http://www.digitalmars.com/d/2.0/traits.html class MyClass { void method1(){} void method2(){} } import std.stdio; void main() { foreach (member; __traits(allMembers, MyClass)) writefln(member: %s, member); foreach (member; __traits(derivedMembers, MyClass)) writefln(derived member: %s, member); } Instead of writefln() you can append to an array. You can also make this a bit more generic with: class MyClass { mixin memberArray!MyClass; void method1(){} void method2(){} } import std.stdio; mixin template memberArray(T) { immutable static members = [__traits(derivedMembers, T)]; } void main() { foreach (member; MyClass.members) writefln(member: %s, member); } Hope this helps :) -- Robert http://octarineparrot.com/
about attribute... (trying to implement a DataContractSerializer functionality)
From the book I was under the impression that there could be user defined attribute. I wonder if this has been implemented? My problem: I try to implement a simplistic DataContractSerializer (as in http://msdn.microsoft.com/en-us/library/SYSTEM.RUNTIME.SERIALIZATION.DATACONTRACTSERIALIZER(v=vs.100,d=lightweight).aspx ) Which, basically, use reflection / introspection to save on a permanent format whatever properties / fields has been marked as being important. I.e. attribute driven serialization if I might say... Is there such a thing? Any tip on how to go on implementing something.. similar?
format()
Apparently std.string.format() is not implemented / does not compile! :( Is there any sort of replacement? Something which works like writefln() but output a string!
Re: format()
mm... ok. but why the line below doesn't compile? mixin(format(class %s {}, A)); bearophile wrote in message news:it2pf5$1qh6$1...@digitalmars.com... Apparently std.string.format() is not implemented / does not compile! :( This works for me, DMD 2.053:
enum sstring problem
I'm using 2.053 this compile fine: enum : string { A = hello, B = betty, } this doesn't! enum AA : string { A = hello, B = betty, } Am I missing something? Named enum can't be typed? known bug?
string manipulation performance
I have a method like that: === public string repeat(string s, int num) { string result = s; for (int i=1; inum; i++) result ~= s; return result; } === basically it will create num string, each a little longer... is there a more efficient way to go about that? thanks! :)
Re: enum sstring problem
do you have DMD 2.053 on Windows? Your code fail for me with: main.d(10): Error: Integer constant expression expected instead of hello main.d(11): Error: Integer constant expression expected instead of betty main.d(10): Error: Integer constant expression expected instead of hello main.d(11): Error: Integer constant expression expected instead of betty = Timon Gehr wrote in message news:it3k0u$15s6$1...@digitalmars.com... Lloyd Dupont wrote: I'm using 2.053 this compile fine: enum : string { A = hello, B = betty, } this doesn't! enum AA : string { A = hello, B = betty, } Am I missing something? Named enum can't be typed? known bug? It works just fine for me. How I test: import std.stdio; enum AA : string { A = hello, B = betty, } void main(){ writeln(AA.A); writeln(AA.B); } Compiles and runs. Timon
Re: format()
yep, the example is simple because it is an example! Thanks for your suggestion! :) Jonathan M Davis wrote in message news:mailman.850.1307909499.14074.digitalmars-d-le...@puremagic.com... On 2011-06-12 10:30, David Nadlinger wrote: On 6/12/11 6:37 PM, Lloyd Dupont wrote: mm... ok. but why the line below doesn't compile? mixin(format(class %s {}, A)); Because format presumably can't be interpreted at compile time (yet) – not all functions are necessarily CTFEable. Yeah. format can only be used at runtime. If you want a version which works at compile time, then you std.metastrings.Format, which is an eponymous template. e.g. mixin(Format!(class %s {}, A)); should work. Of course, in this particular case, you might as well just give the whole string to the mixin directly, but I assume that the example is so simple simply because it's an example. - Jonathan M Davis
Re: string manipulation performance
But... string being immutable I don't see the point of allocating some space for one.. Am I missing something? Steven Schveighoffer wrote in message news:op.vwy503w4eav7ka@localhost.localdomain... On Sun, 12 Jun 2011 12:49:25 -0400, Lloyd Dupont ld-rem...@galador.net wrote: I have a method like that: === public string repeat(string s, int num) { string result = s; for (int i=1; inum; i++) result ~= s; return result; } === basically it will create num string, each a little longer... is there a more efficient way to go about that? thanks! :) The runtime tries its best to avoid allocating a new string on each append. Please read the manual on appending, and you also might want to check out an article I wrote about slices that deals with appending. The runtime also provides functions to pre-allocate an array for appending. For example: public string repeat(string s, int num) { string result = s; result.reserve(s.length * num); // ensure result can append all the repeated data without reallocating for (int i=1; inum; i++) result ~= s; return result; } http://www.digitalmars.com/d/2.0/arrays.html#resize http://www.digitalmars.com/d/2.0/phobos/object.html#reserve http://www.dsource.org/projects/dcollections/wiki/ArrayArticle -Steve
Re: string manipulation performance
Thanks! Jonathan M Davis wrote in message news:mailman.851.1307909610.14074.digitalmars-d- Also, std.string.repeat has been scheduled for deprecation. You should use std.array.replicate instead. It does the same thing but for all arrays instead of just strings. - Jonathan M Davis
Re: string manipulation performance
Thanks Steven, that was very informative! Steven Schveighoffer wrote in message news:op.vwzrwdmteav7ka@localhost.localdomain... On Sun, 12 Jun 2011 21:02:05 -0400, Lloyd Dupont ld-rem...@galador.net wrote: But... string being immutable I don't see the point of allocating some space for one.. Am I missing something? Reserving space for appending does not make that space immutable, yet. As far as the runtime is concerned, that space is unallocated. Although it can only ever be allocated to have immutable string data, it's not allocated yet, so it can be modified in the future. Observe: string s; assert(s.ptr is null); // string is unallocated s.reserve(100); assert(s.length == 0); // reserve doesn't alter the actual string, it just sets up space for it to grow into assert(s.ptr !is null); // but now it points to a memory block! auto sptr = s.ptr; // save pointer for later proof... for(i; 0..20) s ~= hello; // make a bunch of hellos assert(s.length == 100); // yep, we added some data, but assert(s.ptr is sptr); // it didn't move, so essentially, it grew into the existing memory block, that was previously unused. The reason it works is because the unused space in the block has no references, therefore, even though it is potentially immutable, it doesn't matter that we change it because nobody else knows about it yet. Note that without the reserve call, s.ptr would not be equal to sptr at the end of the operation, because the runtime would have chosen smaller memory blocks to begin with to store the string. -Steve
Object
I have problem with Object for example this doesn't compile: === Object o; o = ; === with error: cannot implicitly convert expression () of type string to object.Object or this also failed to compile: === class Foo { public: Object foo, bar, snafu; override const bool opEquals(Object t) { auto other = cast(Foo)t; if (!other) return false; return other.foo == foo other.bar == bar other.snafu == snafu ; } } with error such as: function object.opEquals (Object lhs, Object rhs) is not callable using argument types (Object,const(Object)) Any tip?
.lib problem
what if the Win32 function I'm interested in don't seem to be in .lib provide by dmd... (for example vista up windows function) Can I just use the .lib which come from the windows SDK?
Re: very newbie question (sring confusion)
I did the following, what do you think of my implementation? (checking if my string and array usage could be improved / powered up!!!) string[] _locales = [en-AU, fr-FR]; string getCurrentLocal() { return fr-BE; } string[] getCandidates() { auto local = getCurrentLocal(); string match = null; for (int i = _locales.length; i--0;) { if(_locales[i] == local) { match = _locales[i]; break; } } string partial = null; if(local.length = 2 match == null) { for (int i = _locales.length; i--0;) { auto tmpl = _locales[i]; if (tmpl.length 2 tmpl[0] == local[0] tmpl[1] == local[1]) { partial = tmpl; break; } } } string[] result; if(match) { result.length = result.length + 1; result[result.length-1] = match; } if(partial partial != match) { result.length = result.length + 1; result[result.length-1] = partial; } if(match != _locales[0] partial != _locales[0]) { result.length = result.length + 1; result[result.length-1] = _locales[0]; } return result; }
Re: .lib problem
Thanks I'll try tomorrow! :) (now I should really go to bed...) Andrej Mitrovic wrote in message news:mailman.565.1307117174.14074.digitalmars-d-le...@puremagic.com... If you have coffimplib (which isn't free), then you could just convert the windows sdk import lib to OMF format. Otherwise, you can create an import library from a DLL. Find the DLL (e.g. kernel32.dll), and run: implib /s kernel32.lib kernel32.dll Then link with the new import lib. I think that should work.
Re: very newbie question (sring confusion)
std.algorithm! will have a look, thanks! bearophile wrote in message news:isb5ql$1i23$1...@digitalmars.com... Lloyd Dupont: I did the following, what do you think of my implementation? Those for loops seem better as foreach ones, or even reverse foreach ones. Probably in std.algorithm there is stuff to shorten your code. Bye, bearophile
Re: .lib problem
Where can I find this implib tool you mentioned? I have the latest Windows SDK and Visual Studio 2010. Yet when I perform a search in program files I can't find it!! :( Andrej Mitrovic wrote in message news:mailman.565.1307117174.14074.digitalmars-d-le...@puremagic.com... If you have coffimplib (which isn't free), then you could just convert the windows sdk import lib to OMF format. Otherwise, you can create an import library from a DLL. Find the DLL (e.g. kernel32.dll), and run: implib /s kernel32.lib kernel32.dll Then link with the new import lib. I think that should work.
Re: .lib problem
Sweet, thanks you very much! :) Andrej Mitrovic wrote in message news:mailman.573.1307123755.14074.digitalmars-d-le...@puremagic.com... http://ftp.digitalmars.com/bup.zip Docs here: http://www.digitalmars.com/ctg/implib.html
Re: how to get the local?
Yes and no! On one hand I'm a fervent believer of all things Windows 7! :P On the other hand my (learning) D project is about writing an installer. Which should just work with no unexpected dependencies! I was telling to myself earlier today too that I should not use this function, just in case! :) Nick Sabalausky wrote in message news:is770e$1a00$1...@digitalmars.com... Andrej Mitrovic andrej.mitrov...@gmail.com wrote in message news:mailman.521.1306960464.14074.digitalmars-d-le...@puremagic.com... From my understanding of this page http://msdn.microsoft.com/en-us/library/dd318136%28v=vs.85%29.aspx : Lloyd, if the program you're writing is designed to be sold or distributed to the public then I'd highly recommend against doing anything that requires at least Vista. From what I've heard, the adoption rates of Vista and Win7 haven't been very good and about half of the Windows systems out there are still XP and pretty much holding there. A *lot* of Windows users are deliberately sticking with XP, and you'll be loosing a lot of people. Of course, if your software is only designed to be used internally by some company, or just for you own use, etc., then obviously it doesn't matter...
from .h to .d
let say there is a .h in the windows SDK I'm interested in (namely msi.h), is there a way to automatically translate it to a .d? I think I read about such a thing once... Thanks!
array of constants?
I'm trying to define an array of constant like: === immutable string[int] MyDict = [ 1: monday, 2: tuesday, ]; And I keep having compiler error: Error1Error: non-constant expression [1:monday,2:tuesday] C:\Dev\DTest\DTest1\Dexperiment\LCIDs.d9 what can I do? how do I do that?
2 question: internationalization and serialization
Hi I'm a newbie with big ambitions! (Sorry, got spoiled by C#) Anyhow I'm toying with a D learning project and there are 2 .NET feature that will be welcome in this D project: 1. internationalization. the app will contains a bunch of simple UIs and I was wondering how I would go on internationalizing the application. I.e. embed multiple resource for different languages in the EXE and show the appropriate ones for the target / running computer 2. I'd like a part of my library (in progress) to read / write some arbitrary settings. I was thing to use something akin to the DataContractSerialization we have in .NET where I could define a few classes with attribute [DataContract] class Root { [DataMember] public int Prop1 { get; set; } [DataMember] public B PropB { get; set; } } [DataContract] class B { [DataMember] public string Name { get; set; } } a reader / writer class can turn this class (using the atributes) into text (XML, JSON, I don't care) and back from text into object instance How would I implement something similar in D? Is there already a library doing it?
how to get the local?
I'm on a windows PC in Australia I'd like to get the string en-AU and en from Windows How do I do that please?
Re: how to get the local?
I tried to add that to my D file === public import std.c.windows.windows; extern(Windows) { int GetUserDefaultLocaleName(LPWSTR lpLocaleName, int cchLocaleName); } === and compile and link to kernel32.lib But I got the following compile error: Error1Error 42: Symbol Undefined _GetUserDefaultLocaleName@8 C:\Dev\DTest\DTest1\Dexperiment\ Any clues? Lloyd Dupont wrote in message news:is5gm7$1a8u$1...@digitalmars.com... I'm on a windows PC in Australia I'd like to get the string en-AU and en from Windows How do I do that please?
Re: how to get the local?
Thanks for the link hey! :) Otherwise I still get the same linking error with the W :( Andrej Mitrovic wrote in message news:mailman.518.1306939098.14074.digitalmars-d-le...@puremagic.com... From what I can tell you're using the wide version, so try prototyping it as GetUserDefaultLocaleNameW - note the W Otherwise you should really get http://dsource.org/projects/bindings/wiki/WindowsApi , which has prototypes for many windows functions. You just have to build and use it with --version=Unicode if you want GetUserDefaultLocaleName to alias itself to GetUserDefaultLocaleNameW.
Re: 2 question: internationalization and serialization
Awesome! WIll take a look at it tonight! Thanks for the link! :) Jacob Carlborg wrote in message news:is5msf$1lt0$1...@digitalmars.com... On 2011-06-01 14:51, Lloyd Dupont wrote: Hi I'm a newbie with big ambitions! (Sorry, got spoiled by C#) Anyhow I'm toying with a D learning project and there are 2 .NET feature that will be welcome in this D project: 1. internationalization. the app will contains a bunch of simple UIs and I was wondering how I would go on internationalizing the application. I.e. embed multiple resource for different languages in the EXE and show the appropriate ones for the target / running computer 2. I'd like a part of my library (in progress) to read / write some arbitrary settings. I was thing to use something akin to the DataContractSerialization we have in .NET where I could define a few classes with attribute [DataContract] class Root { [DataMember] public int Prop1 { get; set; } [DataMember] public B PropB { get; set; } } [DataContract] class B { [DataMember] public string Name { get; set; } } a reader / writer class can turn this class (using the atributes) into text (XML, JSON, I don't care) and back from text into object instance How would I implement something similar in D? Is there already a library doing it? For the serialization you could have a look at Orange: http://www.dsource.org/projects/orange Don't know if it works with the latest compilers, it's been a while since I updated the code. I'm also in the middle of complete rewrite of the library. At lease you can perhaps find some ideas. -- /Jacob Carlborg
Re: 2 question: internationalization and serialization
I'm looking! mm... how do I download the repository!?! :~ Jacob Carlborg wrote in message news:is5msf$1lt0$1...@digitalmars.com... For the serialization you could have a look at Orange: http://www.dsource.org/projects/orange Don't know if it works with the latest compilers, it's been a while since I updated the code. I'm also in the middle of complete rewrite of the library. At lease you can perhaps find some ideas. -- /Jacob Carlborg
Re: how to get the local?
Thanks for the quick answers hey! Another quick one (it's time to go to work for me!) Does this lib contains the MSI function? Andrej Mitrovic wrote in message news:mailman.518.1306939098.14074.digitalmars-d-le...@puremagic.com... From what I can tell you're using the wide version, so try prototyping it as GetUserDefaultLocaleNameW - note the W Otherwise you should really get http://dsource.org/projects/bindings/wiki/WindowsApi , which has prototypes for many windows functions. You just have to build and use it with --version=Unicode if you want GetUserDefaultLocaleName to alias itself to GetUserDefaultLocaleNameW.
Re: how to get the local?
Thanks, I'll have a look tonight! Steven Schveighoffer wrote in message news:op.vwezfbqmeav7ka@localhost.localdomain... On Wed, 01 Jun 2011 16:13:44 -0400, Lloyd Dupont ld-rem...@galador.net wrote: Here is my new theory -- note that the function is only defined on Vista or later. DMD does not use the same object format as Windows (i.e. Visual C++), so all libraries have to be converted to a form that dmd can link with. Most of the relevant Windows lib files are already pre-converted and included in the dmd distribution under windows/lib. I'd bet that the version of kernel32.lib that was used to generate this file is an XP version, which would not contain this function. I'd recommend investigating how to replace that kernel32.lib with the Vista (or later) version (I'm sure someone will tell you here ;) or try using the predecessor function, which should be universally compatible (See the above noted documentation).
Re: import problem
Well.. I'm using Visual D, so I have to find out how to set up the compiler! At any rates, I gave up on DFL, as it requires to overwrite the runtime library. I don't feel quite ready for it It'll be OK if I had any clue as to which file are going to be overwritten.. but now I'm confused.. why does the compiler need my D file for when it has the .lib file? Anyway, I'm struggling with DGui now. I added the import, to the source of DGui. Should be enough, right? No! I have this error when trying to compile (still with Visual D) Error1Error 42: Symbol Undefined _D4dgui3all12__ModuleInfoZ C:\Dev\DTest\DTest1\ for info here is the build log: == Building Debug\DTest1.exe Command Line set PATH=C:\D\dmd2\windows\bin;C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\\bin;%PATH% set DMD_LIB=;C:\D\dgui\lib dmd -g -debug -X -XfDebug\DTest1.json -IC:\D\dgui -ofDebug\DTest1.exe_cv -deps=Debug\DTest1.dep -map Debug\DTest1.map -L/NOMAP hello.d if errorlevel 1 goto reportError if not exist Debug\DTest1.exe_cv (echo Debug\DTest1.exe_cv not created! goto reportError) echo Converting debug information... C:\Program Files (x86)\VisualD\cv2pdb\cv2pdb.exe -D2 Debug\DTest1.exe_cv Debug\DTest1.exe if errorlevel 1 goto reportError if not exist Debug\DTest1.exe (echo Debug\DTest1.exe not created! goto reportError) goto noError :reportError echo Building Debug\DTest1.exe failed! :noError Output OPTLINK (R) for Win32 Release 8.00.12 Copyright (C) Digital Mars 1989-2010 All rights reserved. http://www.digitalmars.com/ctg/optlink.html Debug\DTest1.obj(DTest1) Error 42: Symbol Undefined _D4dgui3all12__ModuleInfoZ --- errorlevel 1 Building Debug\DTest1.exe failed! === Jesse Phillips wrote in message news:ir3pl3$1df4$1...@digitalmars.com... Jesse Phillips Wrote: Lloyd Dupont Wrote: so I copied the Entice generated UI code in Visual D, and tried to compile. I got 1 error: Error1Error: module all is in file 'dfl\all.d' which cannot be read C:\Dev\DTest\DTest1\myform.d7 On import dfl.all; For info I do have dfl.all in C:\D\dmd2\windows\import\dfl dmd myform.d -IC:\D\dmd2\windows\import\dfl Forgot DFL requires some more switches, maybe using dfl.exe to compile: http://wiki.dprogramming.com/Dfl/Tutorial The simplest way to compile with DFL is to use the dfl.exe command. Simply open a command prompt, cd to the directory containing the source files you wish to compile, and type dfl sourcefile.d you can add -gui switch and any other source files to include in the compilation Finally, the least appealing choice is to call the compiler directly. You must follow strict rules when doing this or things may behave erratically and even crash. The details can be found on the old setup instructions page; look for the use DMD directly section.
Re: (Windows) beginner woes....
Thanks Jesse! Before I was in the dark! :( Now I'm in.. errr... dawn! Simple questions and answers but it has clarified important stumbling starting block for me! :) Jesse Phillips wrote in message news:ir3imc$rhs$1...@digitalmars.com... Lloyd Dupont Wrote: 1]. ok, I unzipped dmd.zip and dm.zip. what's this dm.zip for? You shouldn't need dm.zip anymore. It used to be contain Digital Mars programs for dmd, Optlink I believe. But they are inculded in the dmd.zip now. It complain that all.d is missing. Why does it need a source file? I though the .lib file contained all necessary info and gone were the headers file! + how can I fix that? No. The .lib file is justly like every other .lib. Header files are gone, you just use the source files (no need for separation of declaration and implementation). But the contents of the lib must be known at compile time and that is provided either by a .d file or a .di file. To summarize I'm quite confused by the directory structure, where do I install .lib file, why do I need an import directory .lib goes in a location that the linker can find, the include directory is source files for the compiler to know what symbols your program will be using. Also, lastly, how do I compile 32bit or 64bits? I want to target 32 bits for sure! (even though I'm on a 64 bits machine!) No 64bit for windows yet.
(Windows) beginner woes....
1]. ok, I unzipped dmd.zip and dm.zip. what's this dm.zip for? 2]. I install Visual D, I had to point it to the DMD folder. And it did compile my 1st D program fine... doubly wondering what's dm for? 3]. I try installed DFL. Actuall it unzipped in the worng forlder, so I moved whateve in unpacked i the right folder. Made a form with entice designer, copied the code in Visual D (i.e. Visual studio with support for D) and tried to compile. It complain that all.d is missing. Why does it need a source file? I though the .lib file contained all necessary info and gone were the headers file! + how can I fix that? To summarize I'm quite confused by the directory structure, where do I install .lib file, why do I need an import directory Also, lastly, how do I compile 32bit or 64bits? I want to target 32 bits for sure! (even though I'm on a 64 bits machine!)
import problem
so I copied the Entice generated UI code in Visual D, and tried to compile. I got 1 error: Error1Error: module all is in file 'dfl\all.d' which cannot be read C:\Dev\DTest\DTest1\myform.d7 On import dfl.all; For info I do have dfl.all in C:\D\dmd2\windows\import\dfl