Re: Given a TypeInfo_Class, instance a new object of its type

2020-10-26 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 26 October 2020 at 21:57:18 UTC, Not A Rectangle wrote:

Is this possible to do?


Only if you know the type ahead of time, then you can cast it.

Normally you'd probably just know an interface or base class it 
implements then you can cast to that, with the exact derived type 
being only known at runtime.


Re: More elaborate asserts in unittests?

2020-10-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 21 October 2020 at 22:30:11 UTC, IGotD- wrote:
When an assert fails in a unittest, I only get which line that 
failed. However, it would be very useful to see what the values 
are on either side of the unary boolean expression. Is this 
possible?


try compiling with dmd -checkaction=context


Re: Best way to confine project to 64 bit builds only?

2020-10-17 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 17 October 2020 at 14:50:47 UTC, NonNull wrote:
I have inherited an open source C project that assumes that the 
size of a long and the size of a pointer are the same


static assert(long.sizeof == void*.sizeof);


Re: Packing of Struct Fields

2020-10-17 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 17 October 2020 at 13:00:59 UTC, Per Nordlöw wrote:
I understand that. I don't want the alignment of `S` to change. 
I want the padding after `s`


That padding is part of S. It is at the end, after its fields, 
but still part of it.


S's layout doesn't depend on what else is around it.


in `T` to be avoided and have `c` start at byte-offset 7.


Use a union.

struct S
{
int i;  // 4 bytes
short s;// 2 byte
bool b; // 1 byte
}
static assert(S.sizeof == 8);
static assert(S.alignof == 4);

struct T {
   union {
   S s;
   struct {
   align(1):
   ubyte[7] _ignore_me;
   char c;
   }
   }
}

static assert(T.alignof == 4);
static assert(T.sizeof == 8);
static assert(T.c.offsetof == 7);



Re: Packing of Struct Fields

2020-10-17 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 17 October 2020 at 12:44:44 UTC, Per Nordlöw wrote:
Can `align`s be inserted in S or/and T so that T is packed to 8 
bytes but still aligned to 8 bytes?


Yes. Put an align on the OUTSIDE of the struct you are nesting, 
then put one INSIDE the struct you want the contents packed.



I don't see why this shouldn't be the default behaviour...


It is generally slower.


Re: Forward referencing functions in D

2020-10-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 16 October 2020 at 19:55:53 UTC, wilcro wrote:
Evidently, I am misunderstanding something very elemental here; 
thanks for any enlightenment regarding this.


Inside a function things happen in order, top to bottom, 
including declarations (you can only access local variables after 
they are declared, and nested functions work like local 
variables).


In a declaration, order is less important.

For recursive nested functions it can sometimes help to put a 
declaration inside a function:


void main() {
  // order matters here, in function
   struct Holder {
   // order doesn't matter in here, in decl
}
  // order matters again since functions run in sequence
}


Re: How can I use class and wasm?

2020-10-15 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 16 October 2020 at 03:04:25 UTC, Jack wrote:

How can I allocate memory for this class?


It is possible but not easy without druntime.

If you are using -betterC, you can use extern(C++) classes with 
extern(D) members. The compiler will let you declare that. But 
then you need to allocate it. `__traits(classInstanceSize, 
Whatever)` will tell you the size to malloc, but you also need to 
copy an initializer over before you call the constructor.


I have a technique here that works on dmd...

http://dpldocs.info/this-week-in-d/Blog.Posted_2020_07_27.html#zero-runtime-classes

but ldc is more strict about the type definition and I don't know 
the magic it expects there... like it should be doable but idk 
how so this might not be of much use.


Personally, I prefer to just not use betterC and make my own mini 
runtime:


http://dpldocs.info/this-week-in-d/Blog.Posted_2020_08_10.html

in particular

https://github.com/adamdruppe/webassembly/blob/master/arsd-webassembly/object.d#L74


But that's also not easy, lots of unfinished cases in my thing, 
but I did manage to make it work... for my specific case.


Re: How do I make this function from module public?

2020-10-13 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 14 October 2020 at 01:46:11 UTC, Jack wrote:

extern(C):
int mul(int a, int b) { return a *  b;}


mark it `export` as well

and then be sure you are compiling in this module as well, it 
must be included on the ldc command line along with wasm.d


Re: Range format specifiers in other languages?

2020-10-11 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 12 October 2020 at 00:46:37 UTC, Imperatorn wrote:
To people trying to learn, why is that % before ( needed in the 
format string?


The %( ... %) stuff is expanded and repeated for each element 
inside the given array.


Re: Win32Api GetDlgItemText How make buffer with no fixed size?

2020-10-10 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 10 October 2020 at 10:15:03 UTC, Marcone wrote:

wchar[100] buffer; // I don't want fixed size :(


wchar[] buffer; // no fixed size

buffer.length = GetWindowTextLength(hwn); // set it to the text 
length of the window


// now get the text
GetDlgItemText(hwn, widget, buffer.ptr, buffer.length);



Use buffer.length instead of buffer.sizeof in D.



Re: Taking arguments by value or by reference

2020-10-04 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 4 October 2020 at 15:30:48 UTC, IGotD- wrote:
I don't agree with this, especially if the struct is 432 bytes. 
It takes time and memory to copy such structure.


If the compiler chooses to inline the function (which happens 
quite frequently with optimizations turned on), no copy takes 
place regardless of how you write it if the compiler can see it 
is unnecessary.


Returning a struct by value rarely means a copy either since the 
compiler actually passed a pointer to where it wants it up front, 
so it is constructed in-place.


So like "pass by value" in the language is not necessarily big 
copies in the generated binary. That's why the irc folks were 
advising to not worry about it unless you see a problem coming up 
that the profiles points here.


Re: Getting Field Names of a specific UDA in compile time.

2020-10-03 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 3 October 2020 at 13:10:31 UTC, realhet wrote:
I only managed to get the string[] by making a static foreach, 
but I don't know how to put that in an enum xxx = ...; 
statement.


There's always other ways but general rule: if you can get it one 
way, just wrap that up in a function and call that function for 
your enum initializer.


string[] your_function() {
 // implementation here you already have
 return it;
}

enum NodeNames = your_function();


Though with arrays btw `static immutable` tends to give better 
results than `enum` since it avoids extra allocations.


Re: Whats going on with this?

2020-10-03 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 2 October 2020 at 23:28:04 UTC, claptrap wrote:
I cant see anything in the struct docs explaining why that 
array on the right hand side is automatically converted to a 
constructor call.


I'm not sure exactly where it is in the docs but that's perfectly 
normal.


Any declaration with initialization of a struct is turned into a 
construction call if it can. If not, it tries to treat it as a 
struct literal.


I guess this is as close as it comes:
https://dlang.org/spec/struct.html#struct-constructor

"Struct constructors are used to initialize an instance of a 
struct when a more complex construction is needed than is allowed 
by static initialization or a struct literal. "


Which sends you back up here:
https://dlang.org/spec/struct.html#static_struct_init

showing the = syntax.


opAssign is only used AFTER the struct has already been declared.


Re: vibe.de multiple ports.

2020-09-30 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 30 September 2020 at 11:23:59 UTC, seany wrote:


auto router = new URLRouter;
router.post("/archive", );
router.get("/archive", );

auto settings = new HTTPServerSettings;
settings.port = port;
settings.bindAddresses = ["::1", "0.0.0.0"];
listenHTTP(settings, router);


If you loop this section it should listen to each port. This is 
just a setup loop, it wouldn't actually be wasteful once it is 
running.


(I think, I don't really know vibe super well)


Re: How to write a counterpart to C++ std::invoke that works with both free functions and methods?

2020-09-28 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 27 September 2020 at 05:22:36 UTC, 60rntogo wrote:

How would I check if it is actually a free function?

but this doesn't even compile since I defined add inside my 
main function


ah that's not a free function!!

That's a nested function and thus actually has a hidden argument. 
Of course, you could add `static` to it if it doesn't use other 
local variables, then it will work again.


But to handle nested functions, you can simply add a check for 
isNested too.



Bringing me to this:

-
auto invoke(alias fun, Args...)(Args args)
{
  static if(__traits(isStaticFunction, fun) || __traits(isNested, 
fun))

return fun(args);
  else
return __traits(child, args[0], fun)(args[1 .. $]);
}

// I think the above covers all the cases, what follows
// are just some tests of various situations.

struct Foo
{
  bool isValid(int a)
  {
return a > 0;
  }

  struct Bar {
void bar() {}
}

Bar bar;
}

int add3(int a, int b)
{
  return a + b;
}

class A {
void test() {}

int item;

class B {
void other(int arg) { import std.stdio; 
writeln(item, " nested ", arg); }

}

static class C {
void cool(string) {}
}
}

void main() {

auto a = new A;
a.item = 30;
invoke!(A.C.cool)(new A.C, "ok");
invoke!(A.B.other)(a.new B, 6);
invoke!(A.test)(a);
invoke!(Foo.Bar.bar)(Foo.Bar.init);

int add(int a, int b)
{
  return a + b;
}
int add2(int a, int b)
{
  return a + b;
}


assert(invoke!add(1, 2) == 3);
assert(invoke!add2(1, 2) == 3);
assert(invoke!add3(1, 2) == 3);

auto foo = Foo();
assert(invoke!(Foo.isValid)(foo, 3));
}
---


Re: assert format of a string before a mixin

2020-09-27 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 27 September 2020 at 21:38:43 UTC, ddcovery wrote:

i.e. checking this Regex expression
`^[a-zA-Z_]*[a-zA-Z0-9_]*[a-zA-Z][a-zA-Z0-9_]*$`



Is there any way to check a regular expression at compile time?


Not really and I'd actually suggest not trying because even if it 
did work, it'd probably be very slow.


But that regex there is pretty easy to translate to a little 
hand-written loop function that would do the job runtime, ctfe 
both and do it quickly.


Re: How to write a counterpart to C++ std::invoke that works with both free functions and methods?

2020-09-26 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 26 September 2020 at 22:58:44 UTC, 60rntogo wrote:
I get the error "undefined identifier isValid". How can I make 
this work?


This part is easy, you need to give the name like

assert(invoke!(Foo.isValid)(foo, 3));


Now, the other part is tricky, and a new feature just released 
this week is there to help:


https://dlang.org/changelog/2.094.0.html#add_traits_child

So you use this to branch on static vs non-static functions:

auto invoke(alias fun, Args...)(Args args)
{
  static if(__traits(isStaticFunction, fun))
return fun(args);
  else
return __traits(child, args[0], fun)(args[1 .. $]);
}


So, for static functions, you won't be passing a `this`, so it 
just sends the args straight in.


But for non-static functions, you use the now trait to attach 
`this` to the given function, then pass the rest of the arguments 
normally.


As a result, you `add` works fine, and 
`assert(invoke!(Foo.isValid)(foo, 3));` now works too!


Re: How create Win32api Thread in Dlang?

2020-09-25 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 26 September 2020 at 03:08:56 UTC, Marcone wrote:

#include 


import core.sys.windows.windows


WINAPI


extern(Windows)


int main(int argc, char *argv[]) {


int main(string[] args)


  CreateThread(NULL, 0, threadFunc, NULL, 0, NULL);


   CreateThread(null, 0, , null, 0, null);



Maybe minor compile errors like required casts but this is really 
about it. You can almost literally copy/paste most C examples to 
D.


Re: uda pattern foo and foo(val)

2020-09-22 Thread Adam D. Ruppe via Digitalmars-d-learn
On Wednesday, 23 September 2020 at 02:07:04 UTC, Steven 
Schveighoffer wrote:

I just said pragma(msg, __traits(getAttributes, z))


Ah, ok, this is weird, `pragma(msg, __traits(getAttributes, 
z)[0])` works just fine!


But that might be adequate for you - just loop over the 
attributes and use them one by one. Which you'd do anyway.


I suspect this is overload resolution not happening yet when you 
getAttributes but then it happens when it is forced evaluated 
with the index. (prolly one of those order-of-semantic bugs in 
dmd)




Re: uda pattern foo and foo(val)

2020-09-22 Thread Adam D. Ruppe via Digitalmars-d-learn
On Wednesday, 23 September 2020 at 01:45:46 UTC, Steven 
Schveighoffer wrote:
@foo int z; // Error: cannot interpret foo(T)(T val) at compile 
time


Where do you get that error? Is it from phobos' thing? cuz I 
copy/pasted your code and it compiled.


You can also just use a struct as the uda if your detection 
function checks for both the type and a value of the type, so it 
really depends on which search method you using.


Re: Why private methods cant be virtual?

2020-09-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 21 September 2020 at 23:30:30 UTC, H. S. Teoh wrote:

It looks like a bug to me.


No, it is by design:

https://dlang.org/spec/function.html#virtual-functions

see point 2.


Re: vibe.d: How to get the conent of a file upload ?

2020-09-19 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 20 September 2020 at 01:51:22 UTC, wjoe wrote:
Would even be more awesome if it provided a function which 
could be called from a custom main on top of the FancyMain.
I find e.g. custom parsing of command line arguments incredibly 
useful.


Yea, the version 2.0 stuff inside cgi.d does that. You can call 
`cgiMainImpl` from your own main thing (that's all the mixin does 
anyway) and disaggregate it as much as you want.


I was improving that this week when the baby decided to come, so 
the rest will be coming a little later. But on my copy right now 
you can even break up cgiMainImpl because its implementation is:


---
void requestHandler(Cgi cgi) {
   // if you call cgi.dispatcher in here, it does basically
   // what the old FancyMain would do, going to a class.
}

void main(string[] args) {
alias CustomCgi = Cgi; // just normal class w/o more 
custom

if(tryAddonServers(args))
return;

if(trySimulatedRequest!(requestHandler, CustomCgi)(args))
return;

RequestServer rs;
rs.listeningPort = 3000; // if you want to change default
rs.configureFromCommandLineArguments(args);
rs.handleRequests!(requestHandler, CustomCgi)(); // this 
may never return

}
---


But I haven't pushed this live yet. Probably will write about it 
in the blog next week or the week after depending on how 
everything else irl goes. Still not 100% happy with it, but a big 
goal with my version 2.0 implementation here is to make more 
pick-and-choose customization possible while still using the 
automation in the places you want that.


Re: vibe.d: How to get the conent of a file upload ?

2020-09-19 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 19 September 2020 at 20:17:06 UTC, aberba wrote:
Arsd cgi.d might be what you want if you want to it your way as 
its more low-level interface-wise.


Eh, it depends. My lib lets you do as much or as little as you 
want.


About ten years ago, I wrote a framework on top that 
automatically generates javascript/json interfaces as well as 
html form and output UI just given an ordinary D class. Had full 
interop with PHP too... all with no UDAs since they didn't exist 
yet!


I never really documented how to use it. Wrote a few examples on 
the forum but nothing formal. I kinda regret that; I've *still* 
never seen anyone else, anywhere, automate as much as it did.


old demo I posted in May 2011: 
http://arsdnet.net/cgi-bin/apidemo/javascript


I can't find the source to that anymore but it would be something 
like:


---
import arsd.web;

class CoolApi : WebApi {
   enum Color { red, green, etc }
   struct Person { int id; string first; string last; }

   Element getABox(Color c) {
 auto div = Element.make("div");
 div.style.color = to!string(c);
 return div;
   }

   int addSomeNumbers(int a, int b) { return a + b; }

   Person[] getPeople(int startingId) { return [Person(...)]; }
}
mixin FancyMain!CoolApi;
---

That's it - all the html and javascript are all auto-generated.


Nowadays I'm merging all those ideas into cgi.d and actually 
writing about it in my blog. There's a lot in my old 
implementation I didn't like but now that D's reflection is 
better than it was, I have techniques to make it even better.


My new dwidder website is the only public example of the new code 
so far 
https://github.com/adamdruppe/dupdates/blob/master/main.d#L157


Still a bunch more I'm slowly bringing together. D has unique 
strengths for web that javascript, ruby, and python can just 
*never* do and we should be pushing the edges to go as cool as we 
can.




Re: Cannot call @system funciton (stdout)

2020-09-19 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 19 September 2020 at 13:56:53 UTC, Anonymouse wrote:
Is there a way to detect programmatically if I'm in an 
environment where I need to manually set line buffering?


Part of the problem is the IDE console and cygwin too I believe 
both *look* like a pipe to the program instead of like an 
interactive terminal, thus why it gets block instead of line 
buffered.


Someone once told me of a trick to detect cygwin specifically but 
I can't access it right now and I'm not sure it would work 
reliably anyway


Just yeah set your expectations low because if it was easy to 
tell programmatically the libc would already do it right.


Re: Building LDC runtime for a microcontroller

2020-09-18 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 17 September 2020 at 09:53:57 UTC, Remi wrote:
My problem here is mostly understanding the __initZ symbol and 
where it comes from.


The compiler generates that when it spits out something that uses 
TypeInfo, which is a lot of things: ~= and ~ operators on built 
in arrays, the new operator, class dynamic casting, exception 
catching, and more. Annoyingly, even having a class member of a 
type will trigger a TypeInfo dependency too. Why? idk, probably 
to do with precise GC hook support.


The error you mentioned in your other message about the order of 
files is interesting.. I suspect that is because the compiler 
creates these symbols when it first sees a need... then tries to 
reuse it, and that must have made the conflict here since it made 
it in the wrong context... or something.


The error says something about constness being different, well, 
why the eff would an init symbol ever be mutable? And ldc is so 
strict about this stuff too where dmd just doesn't care and that 
can be annoying too.


idk this probably doesn't help you much since I don't know why it 
is generating it this way either. It is possible it is actually 
pulling the definition from the original druntime or something.


(on my webassembly.arsdnet.net site btw I made my own little 
on-demand build web service to pass the right args. p convenient 
but also specialized for me and prolly not too general purpose)


I'll keep investigating as I have time, but I do kinda prefer th 
idea of improving the system rather than hacking around it lol


I'll probably try what you describe in your "Zero-runtime 
classes" actually, and hopefully I can get away without the 
string manipulation or replace it with my own version of it.


oh the string manip there is just looking up the symbol, it isn't 
too bad.


The betterC thing also kinda sorta works with classes btw if you 
combine this with extern(C++) class definitions.


Re: vibe.d: How to get the conent of a file upload ?

2020-09-18 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 18 September 2020 at 22:02:07 UTC, aberba wrote:
In this case you want to get the file(s) in memory...in the 
form of bytes (or buffer) and probably set a file size limit. 
Its all doable through a library but such a library doesn't 
exist in D yet. At least not that I know of.


I actually added *exactly* this to cgi.d in... 2010 if I remember 
right. I even kinda documented it: 
http://dpldocs.info/experimental-docs/arsd.cgi.Cgi.UploadedFile.contentInMemory.html


The threshold where it goes to a file is right now 10 MB and not 
configurable, but I've been meaning to go back and clean up this 
api a little. The max file size it accepts is configurable 
 
but the threshold where it goes from memory to file is not.


Though I should note that if vibe is putting it in a temporary 
file it probably realistically stays in memory anyway this 
whole thing might be about nothing since the OS is pretty good 
about optimizing temp files.


Just I have bigger things to take care of right now (or should I 
say smaller things?!)


Re: Building LDC runtime for a microcontroller

2020-09-17 Thread Adam D. Ruppe via Digitalmars-d-learn
fyi my baby was just born i'll come back to this but it might be 
a day or two


Re: What kind of mangling has the LDC2 -X JsonFile "deco" field?

2020-09-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 17 September 2020 at 03:06:45 UTC, realhet wrote:

Anyone can help me telling how to decode these please?


so here's a cool trick to get hte other demanglers to help.

Just prepend

_D4name

to the string. so like:


$ ./ddemangle
_D4nameFAyaZE3het8keywords10KeywordCat
het.keywords.KeywordCat name(immutable(char)[])


so then the demangler will recognize it and use your placeholder 
name while spitting out the rest.


of course you can change that 4name to whatever you want.


Re: What kind of mangling has the LDC2 -X JsonFile "deco" field?

2020-09-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 17 September 2020 at 03:06:45 UTC, realhet wrote:
I'm trying to get information from the JsonFile produced by 
LDC2, but having no clue how to decode this:


For example:
header: KeywordCat kwCatOf(int k)
  "deco" : "FAyaZE3het8keywords10KeywordCat",


That's a D mangle but just of one individual variable, without an 
attached name. std.demangle looks for the _D prefix and the name 
so it prolly can't read it.


https://dlang.org/spec/abi.html#name_mangling

But from eyeball it is a extern(D) function taking a string 
argument and returning a KeywordCat enum..


The "F" means extern(D). After this are the argument list. "Aya" 
you'll get to recognize as "string", but formally it means "Array 
(A) of immutable (y) chars (a)". Then "Z" means non-variadic 
function and this ends the argument list, so the next thing is 
the return type. "E" means enum, then the name comes with a count 
of chars in this name piece, then the chars.




Re: Building LDC runtime for a microcontroller

2020-09-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 16 September 2020 at 17:59:41 UTC, Remi wrote:
I tried to modify the hello.d example from your blog post. It 
works without changes but when I tried to do a string 
concatenation


Yeah, concatenation is one of the features that uses druntime, 
and specifically, it is done through TypeInfo. I would actually 
personally skip it if you are doing a minimal custom thing.


If you skip it, you can implement your own type instead of using 
the built-in array concat. You can make a struct with an operator 
overload to look basically the same, and it can give a slice to 
pass to other functions. This is much easier here - no druntime 
code needed and the user code will be clearer that they might 
have to manage the memory. Typical code with normal append tends 
to just assume there's no stomping, that the GC takes care of it, 
etc.



I'm hitting linker errors related to TypeInfo:


But if you do implement it, as of right now, you have to define 
TypeInfo. Which suckss because it is super tedious. There's a 
WIP pull request up there with dmd to templatize this which would 
help a lot. But right now it means implementing at least some of 
it.


You'd need the base class TypeInfo, then TypeInfo_a (a == 
"char"), TypeInfo_Array, TypeInfo_Aa (which means "array of 
char"), then finally, TypeInfo_Aya, which is "array of immutable 
char", aka, string.


Once you get enough of that up - and the compiler is picky about 
those right now - then the append operation is 
`_d_arrayappendcTX`, which takes TypeInfo as a param.


Search these names in the druntime source to see their official 
implementations... it is a bit of a beast, which is why I 
recommend actually skipping them if you can. It quickly explodes 
in size and by the time you follow it to its final conclusion, 
you've reimplemented 3/4 of full druntime anyway and might as 
well have just done a port.




Re: enum and const or immutable ‘variable’ whose value is known at compile time

2020-09-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 16 September 2020 at 17:12:47 UTC, Cecil Ward wrote:

then is there any downside to just using enum all the time?


For a non-string array, enum may give runtime allocations that 
static immutable won't.


Generally think of enum as being replaced with the literal 
representation and array literals actually make a new array.


This may or may not matter to you.


Re: importing a symbol without specifying a subpackage name

2020-09-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 16 September 2020 at 13:36:22 UTC, 60rntogo wrote:
except that I tried doing this in foo.d and then the compiler 
yelled at me.


Yeah, this is the one case where the compiler is picky about the 
directory structure and filename. It *must* be package.d. 
(blargh.)


Re: importing a symbol without specifying a subpackage name

2020-09-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 16 September 2020 at 13:30:57 UTC, 60rntogo wrote:
I'm curious, how is this behavior achieved in the standard 
library?


They define an additional file

std/package.d

(and std/algorithm/package.d btw)

that lists off

module std;

public import std.algorithm;
public import std.everything;
public import std.else;

you get the idea.

So then teh compiler sees import std and finds that package.d, 
then follows its public imports the rest of the way down.


Re: Newbie question: Return a locally allocated variable

2020-09-14 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 14 September 2020 at 16:29:11 UTC, Fitz wrote:
I expect the following code below to create 10 items with 10 
different addresses, instead they all have the same address?


You are taking the address of the local variable holding 
reference, not the reference itself.



class Bob {
}

Bob *bobFactory() {
Bob bob = new Bob;
Bob *pBob = 

return pBob;
}


This is a common mistake with people coming from C++. A D class 
is more like a Java class - it is automatically a reference.


So your class Bob here in D would actually be represented as 
`Bob*` in C++.


Thus when you define `Bob*` in D, that's like a `Bob**` in C++... 
a pointer to a pointer. Thus you're getting the address on the 
stack of the local, not at all what you want.


Your factory should really just be:

Bob bobFactory() { return new Bob; }

Then to compare addresses, do:

writeln(cast(void*) bob); // convert the reference itself to a 
pointer


Re: Why does a directly defined constructor hide a mixed-in constructor?

2020-09-13 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 13 September 2020 at 12:34:06 UTC, 60rntogo wrote:
However, if I directly insert the contents of X into Bar 
instead of mixing it in, it compiles just fine. What's going on 
here?


You can override members from mixin templates by giving a member 
with the same *name* (not the same signature!) directly.


mixin template foo() { int a; }

class Thing { mixin foo; string a; /* this a overrides foo's a */ 
}



This is pretty useful in a lot of cases but kinda annoying with 
overloading. To overload, you must use `alias` to merge the 
overload sets. For constructors, you need to use the name 
`__ctor` instead of `this` to make it compile:


```
struct Bar
{
  mixin X some_name; // notice the addition of a name

  this(Foo foo)
  {
this.x = [0, 0];
  }

  alias __ctor = some_name.__ctor; // merge the overloads
}
```

Read more here:

http://dpldocs.info/this-week-in-d/Blog.Posted_2020_01_20.html#understanding-mixin-templates

and here too:

https://stackoverflow.com/a/57712459/1457000


Re: Passing string array to C

2020-09-10 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 10 September 2020 at 14:31:41 UTC, Andre Pany wrote:

Why does it crash?


You messed up the pointers.

A string is one star.

An array of strings is two stars.

A pointer to an array of strings is /three/ stars.

---
import std;

void main()
{
size_t* i; // this need not be a pointer either btw
const(wchar)** r; // array of strings
sample(, ); // pass pointer to array of strings

// Try to read the 2 string values
auto arr = r[0..*i]; // slice array of strings
writeln(to!string(arr[0])); // Works
writeln(to!string(arr[1])); // all good
}

// taking a pointer to an array of strings so 3 stars
extern(C) export void sample(const(wchar)*** r, size_t** c)
{
string[] arr = ["foo¤", "bar"];
auto z = new const(wchar)*[arr.length];
foreach(i, ref p; z)
{
p = toUTF16z(arr[i]);
}

// previously you were sending the first string
// but not the pointer to the array
// so then when you index above, arr[1] is bad math
*r = [0];

*c = new size_t();
**c = arr.length;
}
---


Re: UDA inheritance

2020-09-10 Thread Adam D. Ruppe via Digitalmars-d-learn
On Thursday, 10 September 2020 at 13:06:41 UTC, Joseph Rushton 
Wakeling wrote:

`hasUDA!(T, AnotherUDA)`


...do you have to use hasUDA?

The language works with class UDAs, but hasUDA doesn't support it.

If you write your own test function though you can:

``import std.traits;

class BaseUDA {
static BaseUDA opCall(string a) {
return new BaseUDA(a);
}

string a_;
string a() { return a_; }

this(string a) {
this.a_ = a;
}
}


class DerivedUDA : BaseUDA {
static DerivedUDA opCall(string a) { return new 
DerivedUDA(a); }

this(string a) { super(a); }
}


@DerivedUDA("test") struct Test {}

BaseUDA hasOurUda(T)() {
BaseUDA found = null;
foreach(uda; __traits(getAttributes, T)) {
static if(is(typeof(uda) : BaseUDA))
found = uda;
}
return found;
}

pragma(msg, hasOurUda!Test);

```

Or, of course, if you are making your own function, you can still 
do a plain type == a || b, but the class is fairly natural for 
more user extension.


the opCall there is not necessary, it just saves the `new`. This 
is equally valid:


@(new DerivedUDA("test")) struct Test {}


You could also use static immutable class instances kinda like 
enum instances:



---

import std.traits;

class BaseUDA {
string a_;
string a() const { return a_; }

this(string a) immutable {
this.a_ = a;
}


static immutable A = new immutable BaseUDA("A");
static immutable B = new immutable BaseUDA("B");
}


class DerivedUDA : BaseUDA {
this(string a) immutable { super(a); }

static immutable C = new immutable DerivedUDA("C");
}

// or use B or C or wahtever
@(DerivedUDA.A) struct Test {}

pragma(msg, __traits(getAttributes, Test));

immutable(BaseUDA) hasOurUda(T)() {
   // awkward to work around unreachable code warning
BaseUDA found = null;
foreach(uda; __traits(getAttributes, T)) {
static if(is(typeof(uda) : const BaseUDA))
found = cast() uda;
}
return cast(immutable) found;
}

pragma(msg, hasOurUda!Test);

---



so if you are willing to write your own test function there's a 
lot of options to consider.


But if you're stuck with Phobos... well, back to the drawing bard.


Re: GC.LDC2 on Android

2020-09-08 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 8 September 2020 at 12:47:11 UTC, Danny Arends wrote:
How can I figure out which linker is used ? When performing a 
dub build, it just mentions that ldc2 is used for linking


If you are using the d_android setup thing, it actually edits 
ldc2.conf so it uses the linker from the NDK. Did you do that 
step?


Re: Are @safe unittests actually checked for safety?

2020-09-07 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 7 September 2020 at 20:33:26 UTC, 0xEAB wrote:

Are unittests that are marked @safe actually checked for safety?


https://github.com/dlang/phobos/blob/v2.093.1/std/file.d#L4937
How comes this unittest is @safe when `dirEntries` appears to 
be @system?


I see what happened now: those nested functions are defined, but 
never actually called.


The definition did NOT inherit the @safe from the unittest, but 
since they were never called, it never actually mattered; the 
check happens on call, not on definition.


Re: Building LDC runtime for a microcontroller

2020-09-07 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 7 September 2020 at 20:55:54 UTC, IGotD- wrote:

I guess this was written before betterC existed.


Well, -betterC existed even then, but it was *completely* 
useless. It didn't become useful until 2016 or 2017.


But around that same time, going minimal runtime got even easier, 
so I never really got on the betterC train anyway. On my tetris 
webassembly thing last month, I went with a minimal druntime 
http://dpldocs.info/this-week-in-d/Blog.Posted_2020_08_10.html#druntime


And it has some class support too in not a lot of code: 
https://github.com/adamdruppe/webassembly/blob/master/arsd-webassembly/object.d


(and if you aren't doing classes and built-in arrays, you can cut 
a bunch of that out too).


To be honest I like this approach better as it opens up for 
gradually adding functionality.


Yes, indeed.

betterC is nice that it gives a library community a shared target 
to rally around, but for your own custom application it is 
probably better to do your own thing (though betterC might work 
for you too, worth considering at least).


Re: Bug in import(...) on Windows?

2020-09-02 Thread Adam D. Ruppe via Digitalmars-d-learn
On Wednesday, 2 September 2020 at 18:40:55 UTC, Andrey Zherikov 
wrote:
If I provide -Jfoo to dmd, doesn't it mean my consent to use 
the contents of directory foo?


Yeah, but dmd has been inconsistent on platforms about if it 
allows subdirectories. Right now I think it just strips all 
slashes out so your .\ path there just gets caught in the filter.


Re: Bug in import(...) on Windows?

2020-09-02 Thread Adam D. Ruppe via Digitalmars-d-learn
On Wednesday, 2 September 2020 at 17:39:04 UTC, Andrey Zherikov 
wrote:

Is this a bug in dmd?


I think it is an old bug filed (I can't find it though) about 
inconsistent platform behavior but it is allowed by spec for the 
compiler to reject any path components.


import("") is supposed to just give a filename, no directory path.

See: https://dlang.org/spec/expression.html#import_expressions

"Implementations may restrict the file name in order to avoid 
directory traversal security vulnerabilities. A possible 
restriction might be to disallow any path components in the file 
name."


Re: I think Associative Array should throw Exception

2020-09-01 Thread Adam D. Ruppe via Digitalmars-d-learn
On Tuesday, 1 September 2020 at 18:55:20 UTC, Steven 
Schveighoffer wrote:
This is the big sticking point -- code that is nothrow would no 
longer be able to use AAs. It makes the idea, unfortunately, a 
non-starter.


You could always catch it though.

But I kinda like things the way they are exactly because you can 
check with the in operator ahead of time. Or the .get helper 
method is pretty convenient too.


Re: How to create compile-time container?

2020-08-31 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 31 August 2020 at 20:39:10 UTC, Andrey Zherikov wrote:

How can I do that?


You can use a normal string[] BUT it is only allowed to be 
modified inside its own function.


Then you assign that function to an enum or whatever.


string[] ctGenerate() {
   string[] list;
   list ~= "stuff";
   return list;
}

enum list = ctGenerate();


That's all allowed. But CTFE is now allowed to read or modify 
anything outside its own function; you can't have two separate 
function calls build up a shared list (unless you can somehow 
call them both together like `enum list = ctGenerate() ~ 
other_thing();`


Re: what's this Error: corrupt MS Coff object module

2020-08-24 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 25 August 2020 at 01:08:49 UTC, mw wrote:

Is it safe to just delete all the:


yup. I have to do this every other week on my work box to keep 
its hard drive from filling up lol


Re: what's this Error: corrupt MS Coff object module

2020-08-24 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 25 August 2020 at 00:41:27 UTC, mw wrote:

How to fix this Coff object issues?


there's two library formats: coff and omf. omf is the old one 
that dmd assumes without arguments. coff is the new one with `dmd 
-m32mscoff` or `dmd -m64`.


I would guess one of those libs was built with plain old dmd and 
the other with the other switch.


Might help to just delete the old directories and let it 
redownload and recompile fresh with all the new settings.


Re: Introspecting a package for submodules

2020-08-24 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 24 August 2020 at 22:32:52 UTC, Anonymouse wrote:

How do I do this? (Is there some other way?)


Not really a way. A package doesn't quite exist in D; there is no 
formal construct that is a package and has a defined list if 
stuff.


It is just whatever modules are compiled in that happen to have 
the same starting bits in their name.


If you made a file and put `module std.algorithm.mystuff;`, the 
language would treat it exactly the same way as if it was the 
Phobos authors did... the two files have no connection beside 
name, and need not even be compiled together, so no compile-time 
introspection could ever list it all.


What some people do is have a pre-build step that scans the files 
and pulls the module names out ahead of time, then you can 
organize them by name too and sort it that way. But the compiler 
isn't really of any help.


Re: opIndex for type list

2020-08-24 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 24 August 2020 at 14:19:14 UTC, data pulverizer wrote:
I am trying to implement `opIndex` (e.g. T[i]) for types in a 
struct. So for I have `length`:


Can't really do that, the operator overloads work on instances 
instead of static types.


AliasSeq is magical because it just gives a name to something 
built-into the compiler.


Re: __FILE__ and __LINE__ in case of import expression

2020-08-23 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 23 August 2020 at 12:50:36 UTC, Andrey Zherikov wrote:
Even this approach can lead to unclear result if you move 
'q{...}' outside of mixin:


Yes, that's why I write it very specifically the way I do, with 
q{ and mixin on the same line.


Re: __FILE__ and __LINE__ in case of import expression

2020-08-21 Thread Adam D. Ruppe via Digitalmars-d-learn
On Friday, 21 August 2020 at 22:12:48 UTC, Steven Schveighoffer 
wrote:

Who does that though?


An incompetent coder:

http://dpldocs.info/experimental-docs/source/arsd.cgi.d.html#L5713
http://dpldocs.info/experimental-docs/source/arsd.cgi.d.html#L5943
http://dpldocs.info/experimental-docs/source/arsd.cgi.d.html#L6018
http://dpldocs.info/experimental-docs/source/arsd.cgi.d.html#L6058

I actually do kinda a lot. It is kinda useful for adding 
declarations with mixed in names (the whole declaration must be 
mixed in even if the only unique part is the name), or the first 
instance there is to version out features where the compiler's 
parser worked (I maintain compatibility with 2+ year old 
compilers too and if the parser changes, version alone will not 
work).


And honestly, if it says the source is "mixin-50, line 1", I 
think people will get it.


I could probably live with that too, but the status quo is pretty 
useful as-is.


Re: __FILE__ and __LINE__ in case of import expression

2020-08-21 Thread Adam D. Ruppe via Digitalmars-d-learn
On Friday, 21 August 2020 at 21:42:21 UTC, Steven Schveighoffer 
wrote:

While not necessarily a "bug", it's not very useful.


Maybe not in this case, but it is perfectly accurate for cases 
like:


mixin(q{
   some code here
});

Where it will actually line back up to the original file's line 
number perfectly.





Re: __FILE__ and __LINE__ in case of import expression

2020-08-21 Thread Adam D. Ruppe via Digitalmars-d-learn
On Friday, 21 August 2020 at 21:06:11 UTC, Steven Schveighoffer 
wrote:
The hybrid line number (original source line number + mixin 
line number) seems like a bug to me.


I'm not so sure without seeing all the code. Remember to the 
compiler, the mixin thing is just a big string literal at the 
location of the import statement.


So it adds the number of \n's in the string literal to the 
original line number to get the mixin line number.


Re: __FILE__ and __LINE__ in case of import expression

2020-08-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 21 August 2020 at 14:01:24 UTC, Andrey Zherikov wrote:

mixin(import("foo.d"));  // line #17(2)


Why are you doing this? This kind of thing is almost never an 
ideal solution in D.


See, the compiler just sees a big string literal there. It isn't 
a separate file at that point, the import expression just pastes 
in the file contents as a string, and then mixin makes a chunk of 
code from it.


These two features are not really meant to be used together, at 
least not without some custom translation code in the middle.


Re: BetterC + WASM Update

2020-08-19 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 19 August 2020 at 21:24:23 UTC, Mike Brown wrote:
I can see that LDC supports WASM output, and I believe this 
requires BetterC to be enabled?


Not really but anything beyond -betterC is still kinda diy right 
now.


So I happened to do port my little tetris game in D to wasm just 
last week, you can read about it here:

http://dpldocs.info/this-week-in-d/Blog.Posted_2020_08_10.html

And it uses classes! But... I cheated. I did a minimal custom 
druntime and library port that has just enough to make that 
little game work. This is a viable approach and can lead to 
reasonably small compiled binaries, but it is kinda immature.


For a full druntime, the author of spasm 
 is working on a port. See his 
fork here:


https://github.com/skoppe/druntime/tree/wasm

I say "full" but it will most likely leave some things out. 
Classes, GC (at least of D memory), and other features all should 
work already if you brave building it yourself, but threads do 
not work and exceptions are only partially supported. Read more 
here: 
https://gist.github.com/skoppe/7617ceba6afd67b2e20c6be4f922725d


That may change in the future as wasm gets more standardized 
capabilities.


Other libraries, including interop with javascript, are not 
covered by the druntime goal, but they will probably get easier 
with this.


I have done some tests, and it appears that classes are 
supported (LDC 1.22.0)? Is it possible to get an update on what 
is and still isn't supported in BetterC?


How did you compile it? You can definitely make classes work but 
as far as I knew it didn't "just work" but maybe that changed 
with the recent release.


After a stable experience, so if you can also let me know if 
these features are beta etc too?


but yeah stability is probably a ways out still. Sebastiaan has 
been busy lately so his druntime work is on pause and mine was 
just one weekend so I'd have something to show off on the blog; I 
have no concrete plans of continuing right now.


Good chance we'll get it all working eventually, but I wouldn't 
expect even beta stability - aside from the diy betterC stuff - 
any time soon. Maybe beta quality by the end of the year. Maybe.


Re: Creating a pointer array

2020-08-19 Thread Adam D. Ruppe via Digitalmars-d-learn
On Wednesday, 19 August 2020 at 13:03:54 UTC, data pulverizer 
wrote:
How do you create an array of pointers in D? I tried something 
like


```
double* []y;
```


I'd write it

double*[] y;

but yeah that's it.


Error: only one index allowed to index double[]


That must be at the usage point where you prolly just need parens 
or something.


Re: Types of lambda args

2020-08-16 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 17 August 2020 at 00:20:24 UTC, Cecil Ward wrote:
In a lambda, how do we know what types the arguments are? In 
something like

(x) => x * x


In that the compiler figures it out from usage context. So if you 
pass it to a int delegate(int), it will figure x must be int.



- there I just don’t get it at all. Can you write
(uint x) => x * x


yeah you can always add more info if you like.


Re: Leaving a pointer to it on the stack

2020-08-13 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 13 August 2020 at 20:04:59 UTC, Andre Pany wrote:

Hi,

in the specification 
https://dlang.org/spec/interfaceToC.html#storage_allocation 
there is this paragraph:
"Leaving a pointer to it on the stack (as a parameter or 
automatic variable), as the garbage collector will scan the 
stack."


I have some trouble to understand what does this mean. Given 
this example:


```
import std;

void main()
{
int* i;
sample();
writeln(*i);
}

extern(C) export void sample(int** i)
{
*i = new int();
**i = 42;
}
```

Int variable is created on the heap. How do I leave a pointer 
on the stack?


You just did - the `int* i` is a pointer left on the stack for 
the duration of `main` so the GC won't collect it until after 
main returns.


But after main returns, even if `sample` kept a copy of it 
somewhere in some other location, the GC might reap it...


Re: dpldocs not update

2020-08-07 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 7 August 2020 at 21:58:10 UTC, Per Nordlöw wrote:

https://phobos-next.dpldocs.info/index.html

aren't updated. For instance the file


dpldocs never auto-updates. You must either link to a specific 
tagged version like this:


https://phobos-next.dpldocs.info/v0.3.9/index.html

Or go to the page manually and click the little tiny "clear 
cache" button at the page bottom center.


Maybe someday we can link in dub's update to click that button 
for you but for the foreseeable future you need to hit it 
yourself to update the docs.


Re: How does D's templated functions implementation differ from generics in C#/Java?

2020-08-07 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 7 August 2020 at 21:03:47 UTC, aberba wrote:
Syntactically they look the same (although D's can do more 
things) so I'm trying to understand how why in D it's called 
template but in languages like C#/Java they're generics.


In D, a copy of the function is created for each new template 
argument type. In Java (and I assume C# but I don't know for 
sure), there's just one copy of the function and the types are 
erased to call it.


So let's take a D template `sort(T)(T list)`. The compiler 
generates nothing until you pass it arguments; it is just a 
template in its memory. Pass it int[] and it generates a whole 
new function sort(int[] list). Pass it float[] and it generates 
another, totally separate function sort(float[] list).


Now, take a Java generic function `sort(List list)`. The 
compiler will generate a function `sort(List list)`. Pass it a 
List and the compiler actually will just cast it back to 
the List interface and pass it into the one function it already 
generated; this creates no new code. At runtime, you cannot tell 
it was a List, only the compiler knew that*.


Pass it a List and again, the compiler will just cast it 
back to the interface and give it to the same `sort(List list)` 
function. The actual generic type is known only to the Java 
compiler and at runtime it is basically a bunch of hidden casts 
to make it work.


* the java runtime is free to optimize a bit more based on usage 
with its jit compiler but that doesn't change much in the concept.


you can read some more here 
https://en.wikipedia.org/wiki/Generics_in_Java#Problems_with_type_erasure


A cool thing with Java's thing though is since they are just 
special kinds of interface methods you can access generics 
through runtime reflection in it, whereas D's templates cease to 
exist at runtime. Only the generated instances of them are around 
by then since the template itself only lives in the compiler's 
memory for it to make copies of to generate instances.




Re: Non-recursive maxSizeOf

2020-08-06 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 6 August 2020 at 13:18:40 UTC, Per Nordlöw wrote:

mixin(T.stringof ~ " _store" ~ T.mangleof ~


Never ever use mixin(T.stringof). Always just use mixin("T") 
instead.


mixin("T _store", T.mangleof /* or just idx is gonna be better 
*/,";");


Though I doubt this is going to win a benchmark anyway getting 
this complicated.


Re: Non-recursive maxSizeOf

2020-08-05 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 6 August 2020 at 01:23:33 UTC, Per Nordlöw wrote:
How does the memory usage and speed of this code compare to the 
variant that uses template instantiations?


I haven't tested this specifically, but similar tests have come 
in at like 1/10th the memory and compile time cost.


There is one template instance here per argument list though, and 
that template includes the implementation function. The eponymous 
version Ali posted will perform a bit better than my version 
because the compiler can see it will never need code generation.


Still for small argument lists the Phobos one might do better, 
but for larger ones, the ctfe version should be much better. So 
on average Ali's version is almost certain to win in my 
experience.


Re: Non-recursive maxSizeOf

2020-08-05 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 6 August 2020 at 01:17:51 UTC, lithium iodate wrote:

more love for phobos pls


That would add a lot to the cost and bring no real benefit


Re: Non-recursive maxSizeOf

2020-08-05 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 6 August 2020 at 00:58:39 UTC, Per Nordlöw wrote:

Is it possible to implement

in a non-recursive way?


It is very easy too... just write an ordinary function:

size_t maxSizeOf(T...)() {
size_t max = 0;
foreach(t; T)
if(t.sizeof > max)
max = t.sizeof;
return max;
}

pragma(msg, maxSizeOf!(int, char, long));


Re: Template functions inside interface

2020-08-04 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 4 August 2020 at 13:36:15 UTC, Zans wrote:
Is there any way to declare template functions inside interface 
and then override them in a class?


No, the templates in the interface are automatically considered 
`final`. So the body must be in the interface too to avoid that 
undefined reference error.


You can have them forward to normal methods in the interface 
though, just there needs to be a fixed number of them with 
concrete types.


Re: Are function literals deprecated?

2020-08-03 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 3 August 2020 at 14:23:56 UTC, Victor L Porton wrote:
Are function literals considered deprecated in regard of using 
delegates instead?


No, they both work well for different purposes.


Re: Question about UDAs

2020-08-02 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 3 August 2020 at 03:00:08 UTC, Cecil Ward wrote:
When practically speaking would you use UDAs? A real-world 
use-case?


They are useful when you want to attach some kind of metadata to 
the declarations for a library to read. For example, my script.d 
looks for `@scriptable` for methods that it should expose to the 
script user. My cgi.d uses things like `@URLName("foo")` and/or 
`@DisplayName("whatever")` if you want to override the 
auto-wrapper's default strings.


My day job work project uses it for user-visible documentation of 
their functions too, accessible from a command line interface.



I’ve seen them in use already for core language features 
instead of keywords like "pure"


i wouldn't call those UDAs because they aren't user-defined... 
but yeah it is the same syntax there basically too.


Re: Equivalent of C++ #__VA_ARGS__

2020-08-02 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 2 August 2020 at 16:05:07 UTC, Ronoroa wrote:
That doesn't seem to stringize the args part like in 
#__VA_ARGS__


oh yeah i missed that part.

D basically can't do that exactly, but if you pass the args as 
template things directly you can do this:


---
void main(string[] args) {
int a;
int b = 34;
dbg!(a, b); // notice the !
}

void dbg(Args...)(size_t line = __LINE__) {
import std.stdio;

write("#", line, ": ");
foreach(idx, alias arg; Args) {
if(idx) write(", ");
write(arg.stringof, " = ", arg);
}
writeln();
}
---

#4: a = 0, b = 34


Or reformat the output however you want.



Re: Equivalent of C++ #__VA_ARGS__

2020-08-02 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 2 August 2020 at 15:30:27 UTC, Ronoroa wrote:

How do I achieve equivalent semantics of following C++ code?

```
#define dbg(...) std::cout << __LINE__ << #__VA_ARGS__ << " = " 
<< print_func(__VA_ARGS__) << std::endl;

```


You probably just want


void dbg(Args...)(Args args, size_t line = __LINE__) {
 writeln(line, args, " = ", print_func(args));
}


Re: How do I convert a Base64 image url string to a png/jpg image file?

2020-07-30 Thread Adam D. Ruppe via Digitalmars-d-learn

On Thursday, 30 July 2020 at 12:22:46 UTC, aberba wrote:
I'm able to decode it to a buffer but the trouble is getting it 
from buffer to an actual image file. Any library function 
combination I can use?


I don't think I wrote it as a library yet, but the idea is pretty 
simple: they all start with "data:" so you look for that.


Then there's a type after that, so you read the string until the 
next ; character. It will be like image/png or image/jpeg.


Then there's the semicolon and the string "base64,".

After that, the rest of the string is base64 data.

```
import std.base64;
ubyte[] data = Base64.decode(rest_of_string);
```

And now that you have the data you can write it to a file:

```
import std.file;
std.file.write("filename.png", data);
```

And that should make the file you want.


Re: miscellaneous array questions...

2020-07-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 21 July 2020 at 19:20:28 UTC, Simen Kjærås wrote:
Walter gives some justification in the post immediately 
following:


whelp proves my memory wrong!


Re: miscellaneous array questions...

2020-07-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 21 July 2020 at 13:16:44 UTC, IGotD- wrote:
Either the array will hit that page during initialization or 
something else during the execution.


But the array isn't initialized in the justification scenario. It 
is accessed through a null pointer and the type system thinks it 
is fine because it is still inside the static limit.


At run time, the cpu just sees access to memory address 0 + x, 
and if x is sufficient large, it can bypass those guard pages.


Re: std/process.d: nothrow functions which throw (in struct ProcessPipes)

2020-07-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 21 July 2020 at 12:44:23 UTC, Drone1h wrote:

Would it be possible to explain this, please ?


nothrow only applies to Exception and its children. Error is a 
different branch.


Error means you have a programming error and cannot be caught and 
recovered (though the compiler allows it anyway, it reserves the 
right to just abort the program instead of actually going through 
the try/catch system), so it doesn't count as a normal exception, 
even though it is still thrown.


You are supposed to prevent Errors by fixing the bugs in your 
code, so in a final build they never happen.


Re: miscellaneous array questions...

2020-07-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 20 July 2020 at 22:05:35 UTC, WhatMeWorry wrote:

How does that pertain to an array?


C arrays work as pointers to the first element and D can use that 
style too.


2) "The total size of a static array cannot exceed 16Mb" What 
limits this?


The others aren't wrong about stack size limits playing some 
role, but the primary reason is that it is a weird hack for 
@safe, believe it or not.


The idea is:

---
class A {
ubyte[4_000_000_000] whole_system;
}

@safe void lol() {
A a;
a.whole_system[any_address] = whatever;
}
---


With the null `a`, the offset to the static array is just 0 + 
whatever and the @safe mechanism can't trace that.


So the arbitrary limit was put in place to make it more likely 
that such a situation will hit a protected page and segfault 
instead of carrying on. (most low addresses are not actually 
allocated by the OS... though there's no reason why they 
couldn't, it just usually doesn't, so that 16 MB limit makes the 
odds of something like this actually happening a lot lower)


I don't recall exactly when this was discussed but it came up in 
the earlier days of @safe, I'm pretty sure it worked before then.


Re: Is there a compiler option to list all functions executed at compile time when compiling a file?

2020-07-20 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 20 July 2020 at 16:01:53 UTC, blizzard wrote:
I am trying to learn D and knowing when code is run at compile 
time would be good for learning what functions can be used 
without thinking much about performance.


No function is ever run at compile time unless you specifically 
request it with some kind of static context, like top-level in a 
module or class declaration, putting the static keyword on the 
variable, passing it to a !() template argument, or using the 
enum keyword.


Re: Good way to send/receive UDP packets?

2020-07-18 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 18 July 2020 at 16:00:09 UTC, Dukc wrote:
I have a project where I need to take and send UDP packets over 
the Internet. Only raw UDP


I wrote an example using phobos on my blog a while ago that might 
help you get started:


http://dpldocs.info/this-week-in-d/Blog.Posted_2019_11_11.html#communication-by-datagram


Re: Bind C++ class to DLang : undefined reference to `Canvas::Foo()'

2020-07-13 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 13 July 2020 at 09:34:35 UTC, zoujiaqing wrote:

# dmd source/main.d Canvas.o -L-lstdc++ && ./main
[1]49078 segmentation fault  ./main


On my computer I got this warning out of the compiler:

libstdc++ std::__cxx11::basic_string is not yet supported; the 
struct contains an interior pointer which breaks D move semantics!



sounds like it might be a known limitation.


Re: GDC and DMD incompatability, can both be used?

2020-07-11 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 11 July 2020 at 04:28:32 UTC, cy wrote:
  125 | static foreach (string member; 
FieldNameTuple!T) {


The word "static" there can probably be removed and have it work 
exactly the same way. Worth a try.



Does gdc not support static foreach at all?


only the newest gdc does, version 10. version 9, in most package 
managers, doesn't include it.


but if it is inside a function, normal foreach does the same 
thing anyway.


Re: Catching OS Exceptions in Windows using LDC

2020-07-04 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 4 July 2020 at 12:45:50 UTC, realhet wrote:
It was not a problem on other systems like: MSVC or Delphi, but 
on LDC these events are completely ignored.


use dmd with -m32 or -m32mscoff and it works correctly 
automatically.


For whatever reason, dmd 64 bit and ldc decided to do their own 
thing instead of following the Windows standard and thus have no 
interop with OS exceptions.


Alas not much help if you must use those other builds


Re: Print only part of a stack trace

2020-07-01 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 1 July 2020 at 17:44:45 UTC, Dennis wrote:
On assertion failure, the default error handler prints a stack 
trace that looks like this



My cgi.d does something just like that. It just does 
`exception.toString()` then `splitLines` on that string.




Element exceptionToElement(Throwable t) {
auto div = Element.make("div");
div.addClass("exception-display");

div.addChild("p", t.msg);
div.addChild("p", "Inner code origin: " ~ 
typeid(t).name ~ "@" ~ t.file ~ ":" ~ to!string(t.line));


auto pre = div.addChild("pre");
string s;
s = t.toString();
Element currentBox;
bool on = false;
foreach(line; s.splitLines) {
if(!on && line.startsWith("-"))
on = true;
if(!on) continue;
if(line.indexOf("arsd/") != -1) {
if(currentBox is null) {
currentBox = 
pre.addChild("details");

currentBox.addChild("summary", "Framework code");

}
currentBox.addChild("span", line 
~ "\n");

} else {
pre.addChild("span", line ~ "\n");
currentBox = null;
}
}

return div;
}





Re: Why is this allowed

2020-06-30 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 30 June 2020 at 16:41:50 UTC, JN wrote:
I like my code to be explicit, even at a cost of some extra 
typing, rather than get bitten by some unexpected implicit 
behavior.


I agree, I think ALL implicit slicing of static arrays are 
problematic and should be removed. If you want to set it all or 
slice it for any other reason, just put on the [].


Re: mixin template compile-time compute declared name

2020-06-27 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 27 June 2020 at 21:10:59 UTC, NonNull wrote:
Is it possible to use a template to declare something whose 
name is computed at compile time?


You'd have to string mixin the contents inside the mixin template.


Re: Recursive delegate inside template?

2020-06-26 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 26 June 2020 at 14:12:00 UTC, drathier wrote:

I'm trying to get this to compile, without much luck:


You might be able to make it a function:


bool foo()
{
auto fn(A)()
{
A delegate(A) fn;
fn = delegate A(A a)
{
return fn(a);
};
return fn;
}

return fn!(bool)()(true);
}

but I need the function to be polymorphic, so I need the 
template.


I don't really understand your need though, can you post more 
context?


Re: Downloading files over TLS

2020-06-26 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 26 June 2020 at 10:12:09 UTC, Jacob Carlborg wrote:

* Arsd [4]. Relies on OpenSSL


Yeah, I've been wanting to change that and use the native apis 
for years but like I just haven't been able to figure out the 
documentation of them.


Though for plain download, on Windows there's a high level 
function you can just call that's relatively easy... just the 
rest of the module needs low level access so it isn't super 
useful.


And of course Mac does it differently, I don't know much about 
there.



The main problem is that it has been deprecated.


That's the problem of everything Apple makes. Kinda drives me 
nuts trying to keep up with their endless churn and constantly 
Think Different campaigns.


* Are there any high level APIs, like NSURLSession, on Windows 
that can be used to download files?


https://docs.microsoft.com/en-us/windows/win32/winhttp/winhttp-sessions-overview

I guess that is more middle level but it isn't too hard to use. I 
think there's a flat out url -> bytes function too but I don't 
remember what it is.


Regardless, the Windows functions may look familiar if you have 
done AJAX - that was based on an IE object which was based on the 
Windows API.


Re: figure out where a particular template function is located

2020-06-24 Thread Adam D. Ruppe via Digitalmars-d-learn
On Wednesday, 24 June 2020 at 20:28:24 UTC, Steven Schveighoffer 
wrote:

Is there a way to figure this out from the call?


The .mangleof the instance might help track it down since it 
should give you the module name as part of that mangle. Then go 
in there and start breaking things (or use the __FILE__, __LINE__ 
default args) to narrow it down.


not a great answer but sould at least get you started.


Re: Some questions about strings

2020-06-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 22 June 2020 at 03:43:58 UTC, Denis wrote:
My code reads a UTF-8 encoded file into a buffer and validates, 
byte by byte, the UTF-8 encoding along with some additional 
validation. If I simply return the UTF-8 encoded string, there 
won't be another decoding/encoding done -- correct?


Yeah D doesn't do extra work when you are just passing stuff 
around, only when you specifically ask for it by calling a 
function or maybe doing foreach (depends on if you ask for char 
or dchar in the foreach type)


Re: Some questions about strings

2020-06-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 22 June 2020 at 03:17:54 UTC, Denis wrote:
- First, is there any difference between string, wstring and 
dstring?


Yes, they encode the same content differently in the bytes. If 
you cast it to ubyte[] and print that out you can see the 
difference.


- Are the characters of a string stored in memory by their 
Unicode codepoint(s), as opposed to some other encoding?


no, they are encoded in utf-8, 16, or 32 for string, wstring, and 
dstring respectively.


- Can a series of codepoints, appropriately padded to the 
required width, and terminated by a null character, be directly 
assigned to a string WITHOUT GOING THROUGH A DECODING / 
ENCODING TRANSLATION?


no, they must be encoded. Unicode code points are an abstract 
concept that must be encoded somehow to exist in memory (similar 
to the idea of a number).


Re: Passing a variable number of slices into a function

2020-06-21 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 22 June 2020 at 02:04:06 UTC, user1234 wrote:

Maybe each slice has different type ?


in some cases T[][]... will work better too. depends on the 
details here


Re: why cannot spawn function defined in unittest block {}?

2020-06-20 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 20 June 2020 at 17:43:42 UTC, mw wrote:
the function defined in unittest become a delegate? how to 
work-around this?


just add the keyword static to the functions


Re: Should a parser type be a struct or class?

2020-06-17 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 17 June 2020 at 14:24:01 UTC, Stefan Koch wrote:

Parser in dmd does even inherit from Lexer.


why would a parser ever inherit from a lexer?


Re: Weird behavior with UDAs

2020-06-13 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 13 June 2020 at 12:55:36 UTC, realhet wrote:
My first question is, how to avoid that error with A.i4?  Why 
is there a difference between @UNIFORM and @UNIFORM(), do the 
first returns a type and the later returns a value?


Basically yeah. a UDA in D is just whatever you write gets 
directly attached - it does no additional processing. So if you 
give it a type, it keeps a type. If a value, it keeps the value.


The simplest answer is probably "don't do that"; if it is meant 
to be a value, always give it a value.


But you could also write your own get UDA thing that recognizes 
the type (the check: static if(is(attribute)) for a type vs 
static if(is(typeof(attribute))) for the value) and returns the 
init value if you want in your code.


My second quertion is, why the UNIFORM struct with 
uninitialized string producing UNIFORM(null).
How can be a difference when I say name="", and it's just the 
same as the default string initializer, and then it produce 
UNIFORM("")?


null and "" can be used interchangeably and sometimes yield the 
same thing, but they aren't exactly the same.


Since you specified it there in the definition as a default value 
in a struct the compiler used that distinction. I'd suggest you 
write what you mean even in cases where it is the same so you 
cover the bases.


If you specifically want null, check `str is null` and use ` = 
null`. If either is fine, just use `str.length == 0`.


Re: What is the current stage of @property ?

2020-06-10 Thread Adam D. Ruppe via Digitalmars-d-learn

On Wednesday, 10 June 2020 at 22:50:17 UTC, Paul Backus wrote:

static assert(isInputRange!S); // passes


isInputRange doesn't check it but others do. 
std.random.isSeedable requires @property on front for example.


Some apparently test incorrectly too, like 
std.range.primitives.moveFront seems to incorrectly reject front 
variables.


@property is done wrong and I wish they would fix it but right 
now it is... often ignorable but sometimes will do mysterious 
inconsistency due to library use.


Re: Metaprogramming with D

2020-06-08 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 8 June 2020 at 14:41:55 UTC, Jan Hönig wrote:

What is the name of this `q` thing?


It is just a string that looks like code.


Re: Mixin and imports

2020-06-08 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 8 June 2020 at 02:55:25 UTC, jmh530 wrote:
In the code below, foo!fabs compiles without issue, but 
foo!"fabs" does not because the import is not available in the 
string mixin.


Why do you even want foo!"fabs"? Usually when I see people having 
this problem it is actually a misunderstanding of what is 
possible with the foo!fabs style - which is better in basically 
every way and can be used in most the same places.


So what's your bigger goal?


Re: Control flushing to stdout... core.osthread.Thread + arsd.terminal

2020-06-05 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 5 June 2020 at 20:11:16 UTC, aberba wrote:
Didn't come to mind to lookup from terminal docs. Thought it 
was a Dlang/OS problem.


Yeah, the OS by itself rarely buffers output like this, but both 
the C library (on which std.stdio is built) and my Terminal 
object do (they do separately btw, which is why I suggest you 
avoid mixing together terminal.writeln and regular 
stdout.writeln, since they can intermix unpredictably as they 
flush at different calls).


The C one tends to auto-flush on newline, unless it is piped to 
another program... which confuses poor users on IDEs, since from 
the program's perspective, the IDE console is another program! So 
your output can be delayed differently there vs direct to the 
user's screen. (My terminal.d will actually throw an exception if 
you try to use it in such an environment. You need to check 
Terminal.stdoutIsTerminal() if you want to handle that case 
differently. This is another decision I semi-regret and might 
change in the future, since a lot of things do work fine in that 
environment, you just can't move the cursor around in it.)


Anyway the point is just that output functions often pretend to 
succeed while actually just buffering it internally. Unless the 
docs say otherwise when using one of these, there's no guarantee 
it will actually display until you call the library's flush 
function (in std.stdio btw it is `stdout.flush();`, in C it is 
`fflush(stdio);`) or close the file.


Re: Control flushing to stdout... core.osthread.Thread + arsd.terminal

2020-06-05 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 5 June 2020 at 20:05:28 UTC, aberba wrote:
Why was the initial decision to handle buffering that way in 
terminal?


More buffering = more speed, it actually makes a surprisingly big 
difference sometimes, like you can notice the lag with your eyes 
alone as it prints in the more extreme cases, seeing the cursor 
bounce around the screen and such when doing a full screen update.


So I have it internally gathering everything together into one 
big buffer, all your moveTo, color, and writeln calls gather it. 
Then the flush updates as much of the screen as possible in one 
go.


Since it auto-flushes when you get input or when the program 
exits, it works pretty well a lot of the time... but when you are 
like "working..." then the program pauses, it doesn't help at all.


If I was doing it again today, I think I'd probably make it flush 
a little more often automatically, at least with the linear 
output mode.


Re: Control flushing to stdout... core.osthread.Thread + arsd.terminal

2020-06-05 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 5 June 2020 at 11:45:31 UTC, aberba wrote:
How can I make Thread.sleep() only run AFTER "Wait, signing you 
in ..." is written (force flushed) to stdout?


just use explicit `terminal.flush();` any time you want the 
output to appear immediately.


Terminal does its own aggressive buffering internally (which I 
kinda regret) and only flushes with 1) it is full or 2) you ask 
for input, unless you call that flush function.


Re: How to get the pointer of "this" ?

2020-05-26 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 26 May 2020 at 11:35:23 UTC, Vinod K Chandran wrote:

Okay, but uint is working perfectly.


It won't if you use -m64.


Re: How to get the pointer of "this" ?

2020-05-25 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 25 May 2020 at 22:32:52 UTC, Vinod K Chandran wrote:

What is an opCast ?


operator overload of the cast function. if you didn't write one, 
you don't have to worry about this.


Re: How to get the pointer of "this" ?

2020-05-25 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 25 May 2020 at 22:31:00 UTC, Vinod K Chandran wrote:
A dword is an unsigned, 32-bit unit of data. We can use uint in 
D. I have tried that too, but no luck.


A DWORD_PTR is *not* the same as a uint. It is more like a size_t 
or void* depending on context.


Re: How to get the pointer of "this" ?

2020-05-25 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 25 May 2020 at 21:45:39 UTC, welkam wrote:

Where is DWORD_PTR defined?


it is a win32 thing. should be able to directly cast to it most 
the time


if there is opCast on the class it needs another layer of helper 
function but without opCast it should just work


  1   2   3   4   5   6   7   8   9   10   >