www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - learn some d those days, can't understand the code here

reply Junfeng <jackfeng.jia gmail.com> writes:
Hi,

Come here for help. what I doing is setup vim and use dcd for 
goto define, but sometimes dcd-server got crash, issue is here: 
https://github.com/Hackerpilot/DCD/issues/294

Then I build the debug version, and an assert error comes out:

https://github.com/Hackerpilot/libdparse/blob/master/src/dparse/parser.d#L6654

paste here:

     T[] ownArray(T)(T[] from)
     {
         if (allocator is null)
             return from;
         if (from.length == 0)
             return null;
         T[] to = cast(T[]) allocator.allocate(T.sizeof * 
from.length);
         assert (to.length == from.length, format("from.length = 
%d, to.length = %d", from.length, to.length));
         to[] = from[];
         return to;
     }

For my limited d knowledge, T[] is an array has abi layout:

0: size
size_t: ptr

seems the code try to allocate an array with size from.length, 
but after cast, the length at offset 0 will be 0, so assert 
fail(why dmd allow this cast here? I try use GC.malloc and cast 
in my small test app, dmd will error "Error: cannot cast 
expression malloc(400LU, 0u, null) of type void* to Node[]").

a quick search, seem we should write it like:

t[] to = (cast(T*)allocator.allocate(T.sizeof * from.length))[0 
.. from.length]);

but after this modify, it will crash at
          to[] = from[];
Feb 12 2016
next sibling parent Adam D. Ruppe <destructionator gmail.com> writes:
On Friday, 12 February 2016 at 20:13:16 UTC, Junfeng wrote:
 seems the code try to allocate an array with size from.length, 
 but after cast, the length at offset 0 will be 0, so assert 
 fail(why dmd allow this cast here? I try use GC.malloc and cast 
 in my small test app, dmd will error "Error: cannot cast 
 expression malloc(400LU, 0u, null) of type void* to Node[]").
I'm pretty sure that allocator.allocate returns a void[] or ubyte[] rather than a pointer. Which allocator is being used here? When I played with the dcd backend libraries I found it worked best with the Mallocator it includes and other things were kinda unreliable.
Feb 13 2016
prev sibling parent sigod <sigod.mail gmail.com> writes:
On Friday, 12 February 2016 at 20:13:16 UTC, Junfeng wrote:
 a quick search, seem we should write it like:

 t[] to = (cast(T*)allocator.allocate(T.sizeof * from.length))[0 
 .. from.length]);

 but after this modify, it will crash at
          to[] = from[];
Shouldn't you use [`makeArray`][0] in this case? [0]: http://dlang.org/phobos/std_experimental_allocator.html#.makeArray
Feb 13 2016