Re: How to use labeled break in static foreach?

2020-02-13 Thread cc via Digitalmars-d-learn
Here's a more involved example of what I'm trying to accomplish.  
Is there an easier/cleaner way to do this?  (This is still a bit 
reduced, what I'm actually trying to do is compare whether a 
given variadic typetuple passed to opDispatch is implicitly 
convertible to one of the parameter definitions of overloaded 
functions with the same name on another object).


import std.meta;
struct Test { int[3] x; }
enum A = Test([1, 3, 3]);
enum B = Test([5, 6, 7]);
enum C = Test([5, 6, 7]);
enum D = Test([8, 9, 0]);
enum ARRS = AliasSeq!(A, B, C, D);

enum TESTER = Test([5, 6, 7]);

static foreach (ai, af; ARRS) {
static if (!__traits(compiles, FOUND)) {
static foreach (idx, field; af.x) {
			// Have to declare a different MISMATCH enum for each inner 
loop iteration
			//   unless we enclose it in its own {} scope, but if we do 
that then FOUND

//   is not visible to the outer loop
			static if (!__traits(compiles, mixin(format("MISMATCH_%d", 
ai {

static if (TESTER.x[idx] != af.x[idx]) {
mixin(`enum bool 
`~format("MISMATCH_%d", ai)~` = true;`);
}
}
			static if (idx == af.x.length - 1 && !__traits(compiles, 
mixin(format("MISMATCH_%d", ai {

enum FOUND = ai;
}
}
}
}
static if (__traits(compiles, FOUND)) {
pragma(msg, format("entry #%d matches: %s", FOUND, ARRS[FOUND]));
} else {
static assert(0, "Got no match...");
}



How to use labeled break in static foreach?

2020-02-13 Thread cc via Digitalmars-d-learn

import std.meta;
enum A = AliasSeq!(1, 2, 3, 4);
THREELOOP: static foreach (idx, field; A) {
static if (field == 3) {
pragma(msg, "Got a 3!");
break THREELOOP;
}
static if (idx == A.length - 1) {
static assert(0, "Got no 3...");
}
}

What I'd like to achieve in this example is for compilation to 
fail if the given tuple doesn't contain a matching item.  Is 
there an easy way to do this?  Trying to break out of the static 
foreach gives me

Error:enclosing label `THREELOOP` for `break` not found

In this reduced example, I was able to accomplish this by setting 
some enum within the successful comparison body and then checking 
e.g. static if (!__traits(compiles, FOUND)) but this breaks down 
once I start dealing with multiple levels of scope.


How to get to body of HTTP 500 error with std.net.curl.get()?

2020-02-13 Thread Gregor Mückl via Digitalmars-d-learn

Hi!

I am trying to write a client for pretty... well... creatively 
designed web API. The server gives HTTP status 500 replies if the 
requests are malformed, but the actual error message is hidden in 
the body of the reply (an XML document!). std.net.curl.get() 
throws an exception in this case. But I would like to get the 
body to process the error message within. How can I do that?


Thanks in advance,
Gregor



Re: How do you find the struct types in a module? - getting Error: unknown

2020-02-13 Thread aliak via Digitalmars-d-learn
On Thursday, 13 February 2020 at 15:38:37 UTC, Steven 
Schveighoffer wrote:

On 2/13/20 9:47 AM, aliak wrote:

[...]


Not sure about your error, but here is a working version (don't 
use mixins, use __traits(getMember)):


import std.meta;
template ListOfStructs(alias mod)
{
enum isStruct(string m) = is(__traits(getMember, mod, m) == 
struct);

alias getMember(string m) = __traits(getMember, mod, m);
alias ListOfStructs = staticMap!(getMember, 
Filter!(isStruct, __traits(allMembers, mod)));

}

-Steve


It works without the mixin indeed! Thank you!


Re: Unpack Variadic Args?

2020-02-13 Thread H. S. Teoh via Digitalmars-d-learn
On Thu, Feb 13, 2020 at 12:32:01PM -0500, Steven Schveighoffer via 
Digitalmars-d-learn wrote:
[...]
> Some syntax like expr(someTuple)... would be really cool to have in D.
> 
> Or something like arg => expr syntax for templates might be useful:
> 
> f(staticMap!(!a => foo(a), args)); // look ma, anonymous template!
[...]

Yes, yes, and yes!  Anonymous templates would make std.traits and
std.meta *much* easier to use.


T

-- 
"I'm running Windows '98." "Yes." "My computer isn't working now." "Yes, you 
already said that." -- User-Friendly


Re: Unpack Variadic Args?

2020-02-13 Thread Steven Schveighoffer via Digitalmars-d-learn

On 2/13/20 12:24 PM, Steven Schveighoffer wrote:
But this means you have an additional function call (which could of 
course be inlined).


And I might add, an additional requirement to declare some other 
template (one of the huge drawbacks of std.meta, IMO).


Some syntax like expr(someTuple)... would be really cool to have in D.

Or something like arg => expr syntax for templates might be useful:

f(staticMap!(!a => foo(a), args)); // look ma, anonymous template!

-Steve


Re: Unpack Variadic Args?

2020-02-13 Thread Steven Schveighoffer via Digitalmars-d-learn

On 2/13/20 12:18 PM, Adam D. Ruppe wrote:

On Thursday, 13 February 2020 at 17:13:31 UTC, Steven Schveighoffer wrote:

the f(foo(args)...) syntax doesn't have a D equivalent.


It would be staticMap 



f(staticMap!(foo, args))


No, this does foo!(args[0]), foo!(args[1])...).

He wants a runtime call to each arg wrapped with foo.

One could do:

auto wrapFoo(alias arg)() { return foo(arg); }

and then f(staticMap!(wrapFoo, args));

But this means you have an additional function call (which could of 
course be inlined). It is a viable solution though (tested, and it does 
work).


-Steve


Re: Unpack Variadic Args?

2020-02-13 Thread Adam D. Ruppe via Digitalmars-d-learn
On Thursday, 13 February 2020 at 17:13:31 UTC, Steven 
Schveighoffer wrote:

the f(foo(args)...) syntax doesn't have a D equivalent.


It would be staticMap 



f(staticMap!(foo, args))

staticMap is a recursive template 
 so no mixin stuff


but it can get CT memory heavy in some cases due to all the 
instantiations. i say the compiler should just do this better. 
but really it works for the most part.


Dscanner: is it possible to switch off style checks case-by-case?

2020-02-13 Thread mark via Digitalmars-d-learn

I'm starting out with GtkD and have this function:

void main(string[] args) {
Main.init(args);
auto game = new GameWindow();
Main.run();
}

and this method:

void quit(Widget widget) {
Main.quit();
}

When I run dscanner --styleCheck it reports:

./src/app.d(10:10)[warn]: Variable game is never used.
./src/app.d(22:22)[warn]: Parameter widget is never used.

These are correct. However, is it possible to switch them off 
individually?


(In Python you can switch off lint checks using a special text in 
a comment at the end of the line.)


Re: Unpack Variadic Args?

2020-02-13 Thread Steven Schveighoffer via Digitalmars-d-learn

On 2/13/20 11:29 AM, Jeff wrote:

On Thursday, 13 February 2020 at 08:06:52 UTC, Paul Backus wrote:
Variadic template arguments unpack automatically in D, so you don't 
need to do anything special here:


    void g(Args...)(auto ref Args args) {
    import core.lifetime: forward; // like std::forward
    f(forward!args);
    }

You can read more about variadic template arguments in this article:

https://dlang.org/articles/ctarguments.html


That would result in the call:

     f( args[0], args[1], ... );

But the C++ version does the following:

     f( foo(args[0]), foo(args[1]), ... );

They are different.


the f(foo(args)...) syntax doesn't have a D equivalent.

I don't think it's possible to do without some form of mixin. While 
compile-time lists are available, they must be strictly made of things 
that are either CTFE expressions or symbols.


A possible mixin solution:

string doMixin(T...)(string formatspec)
{
   string result;
   import std.format: format;
   static foreach(i; 0 .. T.length)
  result ~= format(formatspec, __traits(identifier, T[i])) ~ ",";
   return result[0 .. $-1]; // trim last comma
}

void g(T...)(T args) {
   mixin("f(" ~ doMixin!args("foo(%s)") ~ ");");
}

-Steve


Re: Unpack Variadic Args?

2020-02-13 Thread Jeff via Digitalmars-d-learn

On Thursday, 13 February 2020 at 08:06:52 UTC, Paul Backus wrote:

On Thursday, 13 February 2020 at 07:06:49 UTC, Jeff wrote:

Hello,

Was wondering if there was a simple, efficient way to unpack a 
variadic template argument. It needs to be efficient at 
runtime, and hopefully not use too much excessive CTFE.


C++ has the "..." operator, is there something equivalent in D?

template
void g(Args... args) {
f(foo(args)...); // f(foo(args[0]), foo(args[1])); // 
etc

}

What would be a good way to write that in D, with it being as 
efficient (no copies or building structs etc) and not use too 
much CTFE. Needing to use `.map` or similar at CTFE would be 
an example of too much CTFE.


void g(Args...)(auto ref Args args) {
 // ?
}


Variadic template arguments unpack automatically in D, so you 
don't need to do anything special here:


void g(Args...)(auto ref Args args) {
import core.lifetime: forward; // like std::forward
f(forward!args);
}

You can read more about variadic template arguments in this 
article:


https://dlang.org/articles/ctarguments.html


That would result in the call:

f( args[0], args[1], ... );

But the C++ version does the following:

f( foo(args[0]), foo(args[1]), ... );

They are different.


Re: How do you find the struct types in a module? - getting Error: unknown

2020-02-13 Thread Steven Schveighoffer via Digitalmars-d-learn

On 2/13/20 9:47 AM, aliak wrote:

Hi,

I'm trying to get a typed list of structs in my current module that 
matches certain criteria. Something like:


module mod;

struct X {}
struct Y {}

alias allTypes = ListOfTypes!mod;

But I'm having a bit of trouble. I have this so far:

template ListOfTypes(alias T) {
     import std.meta;
     enum isStruct(string m) = is(mixin(m) == struct);
     enum types = Filter!(isStruct, __traits(allMembers, T));
     alias toType(string m) = mixin(m);
     alias all = staticMap!(toType, types);
     alias CommandGroupsOf = all;
}

pragma(msg, ListOfTypes!mod);

But that causes an error I've never seen before:

Error: unknown, please file report on issues.dlang.org
onlineapp.d(30,1):    while evaluating `pragma(msg, 
CommandGroupsOf!(mod))`



Any workarounds or maybe insight in to the error?




Not sure about your error, but here is a working version (don't use 
mixins, use __traits(getMember)):


import std.meta;
template ListOfStructs(alias mod)
{
enum isStruct(string m) = is(__traits(getMember, mod, m) == struct);
alias getMember(string m) = __traits(getMember, mod, m);
alias ListOfStructs = staticMap!(getMember, Filter!(isStruct, 
__traits(allMembers, mod)));

}

-Steve


Re: writeln() in static import std

2020-02-13 Thread Steven Schveighoffer via Digitalmars-d-learn

On 2/13/20 2:33 AM, Adnan wrote:
How can I reach stdout.writeln() using fully qualified name with static 
import?

I have tried:
std.stdio.stdout.writeln() -- fails
std.writeln() -- works
std.stdout.writeln -- works


How does static import with std work?

Hm..., this works:

static import std.stdio;

void main()
{
std.stdio.stdout.writeln("hi");
}

Did you do

static import std;

?

If so, this would explain your issues.

imports have some interesting behavior, but they are totally 
straightforward once you understand all the nuances.


static import imports the module as is, and provides all the symbols 
under the namespace named after the module. Thus, all the symbols 
imported with std are now available under in the namespace std.


What std does is import ALL MODULES in Phobos/druntime with public imports.

A public import imports all the symbols in the given module, and aliases 
all of them as if they were defined in the current module. Thus, you 
have the symbol std.stdout, but not the symbol std.stdio.stdout.


A selective import imports the given symbols and aliases them as if they 
were defined in the current module.


A renamed import imports the given module with the given alias 
substituting for the module imported.


So import io = std.stdio means you have io.stdio.writeln available.

Not sure if there's a good primer on how imports work, but the power 
available is quite good. You can make your namespace look like anything 
you want.


-Steve


Re: Type sequence concatenation / associative array implementation

2020-02-13 Thread Steven Schveighoffer via Digitalmars-d-learn

On 2/12/20 5:47 PM, Paul Backus wrote:

On Wednesday, 12 February 2020 at 20:58:49 UTC, Marcel wrote:
2- How is the builtin associative array implemented? I think I read 
somewhere it's implemented like C++'s std::unordered_map but with BSTs 
instead of DLists for handling collisions: is this correct?


It's an open-addressed hash table. If you want to see all the details, 
the source is here:


https://github.com/dlang/druntime/blob/v2.090.1/src/rt/aaA.d


For some background, collisions used to be handled via a BST, which 
required all AA keys to provide opCmp in addition to opEquals and toHash.


It was changed some time ago (maybe like 8 years ago? Can't remember) to 
be open addressed hash, thus removing the requirement for opCmp.


This is probably why you read something about the old implementation 
using BST.


-Steve


can't run D project on Visual studio

2020-02-13 Thread Akomire Samson via Digitalmars-d-learn
I am having this error on running D project using Visual studio 
2019 and Visual D



Build Log

Building Win32\Debug\LearningD.exe

Command Line

set PATH=C:\D\ldc2-1.19.0-windows-multilib\bin;C:\Program Files 
(x86)\Microsoft Visual 
Studio\2019\Community\VC\Tools\MSVC\14.24.28314\bin\HostX86\x64;C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE;C:\Program Files (x86)\Windows Kits\10\bin;%PATH%
set LIB=C:\Program Files (x86)\Microsoft Visual 
Studio\2019\Community\VC\Tools\MSVC\14.24.28314\lib\x86;C:\Program Files (x86)\Windows Kits\10\Lib\10.0.18362.0\ucrt\x86
set VCINSTALLDIR=C:\Program Files (x86)\Microsoft Visual 
Studio\2019\Community\VC\
set VCTOOLSINSTALLDIR=C:\Program Files (x86)\Microsoft Visual 
Studio\2019\Community\VC\Tools\MSVC\14.24.28314\
set VSINSTALLDIR=C:\Program Files (x86)\Microsoft Visual 
Studio\2019\Community\

set WindowsSdkDir=C:\Program Files (x86)\Windows Kits\10\
set WindowsSdkVersion=10.0.18362.0
set UniversalCRTSdkDir=C:\Program Files (x86)\Windows Kits\10\
set UCRTVersion=10.0.18362.0
"C:\Program Files (x86)\VisualD\pipedmd.exe" -deps 
Win32\Debug\LearningD.dep ldc2 -m32 -g -d-debug -X 
-Xf="Win32\Debug\LearningD.json" -of="Win32\Debug\LearningD.exe" 
-L/PDB:"Win32\Debug\LearningD.pdb" -L/SUBSYSTEM:CONSOLE 
-L/noopttls -od="Win32\Debug" LearningD.d

if %errorlevel% neq 0 goto reportError
if not exist "Win32\Debug\LearningD.exe" (echo 
"Win32\Debug\LearningD.exe" not created! && goto reportError)


goto noError

:reportError
echo Building Win32\Debug\LearningD.exe failed!

:noError
Output

LINK : fatal error LNK1181: cannot open input file 'kernel32.lib'
Error: C:\Program Files (x86)\Microsoft Visual 
Studio\2019\Community\VC\Tools\MSVC\14.24.28314\bin\HostX86\x64\link.exe failed with status: 1181

Building Win32\Debug\LearningD.exe failed!



I will appreciate any help.


How do you find the struct types in a module? - getting Error: unknown

2020-02-13 Thread aliak via Digitalmars-d-learn

Hi,

I'm trying to get a typed list of structs in my current module 
that matches certain criteria. Something like:


module mod;

struct X {}
struct Y {}

alias allTypes = ListOfTypes!mod;

But I'm having a bit of trouble. I have this so far:

template ListOfTypes(alias T) {
import std.meta;
enum isStruct(string m) = is(mixin(m) == struct);
enum types = Filter!(isStruct, __traits(allMembers, T));
alias toType(string m) = mixin(m);
alias all = staticMap!(toType, types);
alias CommandGroupsOf = all;
}

pragma(msg, ListOfTypes!mod);

But that causes an error I've never seen before:

Error: unknown, please file report on issues.dlang.org
onlineapp.d(30,1):while evaluating `pragma(msg, 
CommandGroupsOf!(mod))`



Any workarounds or maybe insight in to the error?




Re: Overfflow in Assert error messages

2020-02-13 Thread Anonymouse via Digitalmars-d-learn

On Thursday, 13 February 2020 at 07:49:13 UTC, Adnan wrote:

However my test fails saying something like:
source/binary_search.d(33): [unittest] 18446744073709551615 != 1
core.exception.AssertError@source/binary_search.d(33): 
18446744073709551615 != 1


What's causing this underflow?


It's ulong -1, which is the type idx is of on 64-bit systems. On 
32-bit systems it will be uint -1 and say "4294967295 != 0". 
indexOf is probably not doing what you think it's doing.


int indexOf(T)(const T[] list, const T key) {
return -1;
}

void main()
{
int[] arr = [ 0 ];
foreach (idx, i; arr)
assert(indexOf(arr, i) == idx);  // 18446744073709551615 
!= 0

}


Re: Unpack Variadic Args?

2020-02-13 Thread Paul Backus via Digitalmars-d-learn

On Thursday, 13 February 2020 at 07:06:49 UTC, Jeff wrote:

Hello,

Was wondering if there was a simple, efficient way to unpack a 
variadic template argument. It needs to be efficient at 
runtime, and hopefully not use too much excessive CTFE.


C++ has the "..." operator, is there something equivalent in D?

template
void g(Args... args) {
f(foo(args)...); // f(foo(args[0]), foo(args[1])); // 
etc

}

What would be a good way to write that in D, with it being as 
efficient (no copies or building structs etc) and not use too 
much CTFE. Needing to use `.map` or similar at CTFE would be an 
example of too much CTFE.


void g(Args...)(auto ref Args args) {
 // ?
}


Variadic template arguments unpack automatically in D, so you 
don't need to do anything special here:


void g(Args...)(auto ref Args args) {
import core.lifetime: forward; // like std::forward
f(forward!args);
}

You can read more about variadic template arguments in this 
article:


https://dlang.org/articles/ctarguments.html