Re: String "dequote" in phobos?

2021-05-13 Thread Anonymouse via Digitalmars-d-learn

On Thursday, 13 May 2021 at 14:10:08 UTC, cc wrote:
Does something to dequote (unquote? or what would you call it?) 
a string exist in the standard library?  I didn't see one in 
std.string, just wondering before reinventing the wheel.


Something like:
```d
assert(dequote(`"foo"`) == "foo");
assert(dequote(`'foo'`) == "foo");
assert(dequote(`"foo's"`) == "foo's");
assert(dequote(`'foo "bar"'`) == `foo "bar"`);
assert(dequote(`"fo\"o"`) == `fo"o`);
dequote(`"fo"o"`); // bad quoting, maybe throw an exception 
here or something?

```


I called mine `unquoted`[1] and `unsinglequoted`. Not very 
imaginative, I concede.


I also assumed ASCII and fearlessly sliced `line[1..$-1]`, which 
you may or may not be able to do.


```d
private T unenclosed(char token = '"', T)(const T line) pure 
nothrow @nogc

if (isSomeString!T)
{
enum escaped = "\\" ~ token;

if (line.length < 2)
{
return line;
}
else if ((line[0] == token) && (line[$-1] == token))
{
if ((line.length >= 3) && (line[$-2..$] == escaped))
{
// End quote is escaped
return line;
}

return line[1..$-1].unenclosed!token;
}
else
{
return line;
}
}


pragma(inline, true)
T unquoted(T)(const T line) pure nothrow @nogc
{
return unenclosed!'"'(line);
}

unittest
{
assert(`"Lorem ipsum sit amet"`.unquoted == "Lorem ipsum sit 
amet");
assert(`"Lorem ipsum sit amet"`.unquoted == "Lorem 
ipsum sit amet");

// Unbalanced quotes are left untouched
assert(`"Lorem ipsum sit amet`.unquoted == `"Lorem ipsum sit 
amet`);

assert(`"Lorem \"`.unquoted == `"Lorem \"`);
assert("\"Lorem \\\"".unquoted == "\"Lorem \\\"");
assert(`"\"`.unquoted == `"\"`);
}


pragma(inline, true)
T unsinglequoted(T)(const T line) pure nothrow @nogc
{
return unenclosed!'\''(line);
}

// ...
```

I'm not sure it's quite correct for all valid inputs but it 
worked well enough for my purposes.


[1]: http://lu.dpldocs.info/lu.string.unquoted.html


Re: Creating std.format.format warpper

2021-05-01 Thread Anonymouse via Digitalmars-d-learn

On Saturday, 1 May 2021 at 09:10:09 UTC, novice2 wrote:

Hello.

Can please anybody help me create template format2 like 
std.format.format,

so it can access to format string (change it for example)
then instantiate std.format.format template in 
compile-time-checkable way


Since `std.format.format` already does this, just create 
templates that simply pass on their arguments to it and let it 
validate them. "Prefixing" the format pattern is trivially done 
(in a separate template) before deferring to `format`.


https://run.dlang.io/is/QsYCkq

If you're not familiar with templates and the difference between 
compile-time and runtime parameters, there are several good 
write-ups, such as the template chapter of Ali Çehreli's book 
(which is available online at 
http://ddili.org/ders/d.en/templates.html).


Re: is it posible to compile individual module separately?

2021-02-17 Thread Anonymouse via Digitalmars-d-learn

On Tuesday, 16 February 2021 at 18:54:08 UTC, Paul Backus wrote:
I stand corrected. Shouldn't have trusted the documentation so 
much, I guess.


It makes perfect sense to intuit that --single should be related 
to --build-mode=singleFile. As it is the build modes aren't 
explained in the documentation at all[1], so there's no way of 
knowing, short of running it to see what happens. Not ideal, 
perhaps.



--build-mode=
  Specifies the way the compiler and linker are invoked. Valid 
values:

separate (default), allAtOnce, singleFile

(Nothing about what they do.)

[1]: https://dub.pm/commandline


Re: is it posible to compile individual module separately?

2021-02-16 Thread Anonymouse via Digitalmars-d-learn

On Tuesday, 16 February 2021 at 17:26:06 UTC, Paul Backus wrote:

On Tuesday, 16 February 2021 at 17:15:25 UTC, Anonymouse wrote:
You can also use dub build --build-mode=singleFile, and it 
will compile one file at a time. It'll be slow but slow is 
better than OOM.


singleFile is for single-file packages [1]. The option you're 
thinking of is --build-mode=separate.


[1] https://dub.pm/advanced_usage.html#single-file


No, I do mean singleFile.

$ dub build --build-mode=singleFile --force
Performing "debug" build using /usr/local/bin/ldc2 for x86_64.
arsd-official:characterencodings 9.1.2: building configuration 
"library"...
Compiling 
../../.dub/packages/arsd-official-9.1.2/arsd-official/characterencodings.d...

Linking...
arsd-official:dom 9.1.2: building configuration "library"...
Compiling 
../../.dub/packages/arsd-official-9.1.2/arsd-official/dom.d...

Linking...
lu 1.1.2: building configuration "library"...
Compiling ../../.dub/packages/lu-1.1.2/lu/source/lu/common.d...
Compiling ../../.dub/packages/lu-1.1.2/lu/source/lu/container.d...
Compiling ../../.dub/packages/lu-1.1.2/lu/source/lu/conv.d...
Compiling 
../../.dub/packages/lu-1.1.2/lu/source/lu/deltastrings.d...

Compiling ../../.dub/packages/lu-1.1.2/lu/source/lu/json.d...
Compiling ../../.dub/packages/lu-1.1.2/lu/source/lu/meld.d...
Compiling ../../.dub/packages/lu-1.1.2/lu/source/lu/numeric.d...
Compiling ../../.dub/packages/lu-1.1.2/lu/source/lu/objmanip.d...
Compiling ../../.dub/packages/lu-1.1.2/lu/source/lu/package.d...
Compiling ../../.dub/packages/lu-1.1.2/lu/source/lu/semver.d...
Compiling 
../../.dub/packages/lu-1.1.2/lu/source/lu/serialisation.d...

Compiling ../../.dub/packages/lu-1.1.2/lu/source/lu/string.d...
Compiling ../../.dub/packages/lu-1.1.2/lu/source/lu/traits.d...
Compiling ../../.dub/packages/lu-1.1.2/lu/source/lu/typecons.d...
Compiling ../../.dub/packages/lu-1.1.2/lu/source/lu/uda.d...
Linking...
dialect 1.1.1: building configuration "library"...
Compiling 
../../.dub/packages/dialect-1.1.1/dialect/source/dialect/common.d...
Compiling 
../../.dub/packages/dialect-1.1.1/dialect/source/dialect/defs.d...
Compiling 
../../.dub/packages/dialect-1.1.1/dialect/source/dialect/package.d...
Compiling 
../../.dub/packages/dialect-1.1.1/dialect/source/dialect/parsing.d...
Compiling 
../../.dub/packages/dialect-1.1.1/dialect/source/dialect/postprocessors/package.d...
Compiling 
../../.dub/packages/dialect-1.1.1/dialect/source/dialect/postprocessors/twitch.d...
Compiling 
../../.dub/packages/dialect-1.1.1/dialect/source/dialect/semver.d...

Linking...
cachetools 0.3.1: building configuration "library"...
Compiling 
../../.dub/packages/cachetools-0.3.1/cachetools/source/cachetools/cache.d...
Compiling 
../../.dub/packages/cachetools-0.3.1/cachetools/source/cachetools/cache2q.d...
Compiling 
../../.dub/packages/cachetools-0.3.1/cachetools/source/cachetools/cachelru.d...
Compiling 
../../.dub/packages/cachetools-0.3.1/cachetools/source/cachetools/containers/hashmap.d...

^C


Re: is it posible to compile individual module separately?

2021-02-16 Thread Anonymouse via Digitalmars-d-learn

On Tuesday, 16 February 2021 at 17:06:21 UTC, evilrat wrote:

On Tuesday, 16 February 2021 at 07:01:53 UTC, bokuno_D wrote:

i run "dub build" on it. but OOM kill the compiler.
-
is there a way to reduce memory consumtion of the compiler?
or maybe third party tool? alternative to dub?


Assuming you are using DMD, there is -lowmem switch to enable 
garbage collection (it is off by default for faster builds)


open dub.json, add dflags array with -lowmem, something like 
this line:


   "dflags": [ "-lowmem" ],


Ideally this would work, but 
https://issues.dlang.org/show_bug.cgi?id=20699. Does work with 
ldc though.


You can also use dub build --build-mode=singleFile, and it will 
compile one file at a time. It'll be slow but slow is better than 
OOM.


Re: std.net.curl and HTTP.responseHeaders

2021-02-04 Thread Anonymouse via Digitalmars-d-learn

On Wednesday, 3 February 2021 at 19:25:18 UTC, Vindex wrote:

Output:
```
std.net.curl.HTTPStatusException@/usr/include/dmd/phobos/std/net/curl.d(1097): 
HTTP request returned status code 405 ()
```

Perhaps some special HTTP configuration is needed?


Is this closer to what you want?

import std.stdio, std.net.curl;

void main() {
enum url = "https://en.wikipedia.org/wiki/Passenger_pigeon;;
auto http = HTTP(url);
http.perform();
writeln(http.responseHeaders);
}


Re: How to profile compile times of a source code?

2021-01-31 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 31 January 2021 at 12:31:59 UTC, Johan Engelen wrote:
Try LDC 1.25 (now in beta testing) with --ftime-trace. Clang 
has the same option, so you can read more about it online in 
that context. Be sure to check out the related commandline 
flags.
I recommend the Tracy UI to look at traces, because it is by 
far the fastest viewer of large traces. 
https://github.com/wolfpld/tracy


-Johan


Does ldc produce traces in a format that Tracy supports? I can't 
seem to open the generated *.time-trace files with it. (tracy 
0.7.5-1 installed from Arch Linux AUR.)


Re: using dub and -checkaction=context

2021-01-17 Thread Anonymouse via Digitalmars-d-learn
On Sunday, 17 January 2021 at 15:41:45 UTC, Steven Schveighoffer 
wrote:
I'm trying to run unittests using `dub test`, and I wanted to 
use the new -checkaction=context feature to avoid having to 
instrument my unittests to print out the string comparison 
failure that's happening.


But I tried adding this to my dub.sdl file:

dflags "-checkaction=context" platform="dmd"

But now I get linker errors:

/home/steves/.dub/packages/vibe-core-1.10.1/vibe-core/source/vibe/appmain.d:(.text._D3std8typecons__T10RefCountedTSQBe9container5array__T5ArrayTS4vibe4core4sync18LocalTaskSemaphore12ThreadWaiterZQCg7PayloadVEQEtQEs24RefCountedAutoInitializei0ZQFm6__dtorMFNaNbNiZv[_D3std8typecons__T10RefCountedTSQBe9container5array__T5ArrayTS4vibe4core4sync18LocalTaskSemaphore12ThreadWaiterZQCg7PayloadVEQEtQEs24RefCountedAutoInitializei0ZQFm6__dtorMFNaNbNiZv]+0x5c):
 undefined reference to 
`_D4core8internal7dassert__T14_d_assert_failVAyaa1_3eTmTiZQBeFNaNbNiNfKxmxiZQBf'


https://issues.dlang.org/show_bug.cgi?id=19937 ? Slightly 
different error message though.


Re: Why doesn't this work when the function is a static method?

2021-01-14 Thread Anonymouse via Digitalmars-d-learn

On Thursday, 14 January 2021 at 15:20:54 UTC, Jack wrote:

On Thursday, 14 January 2021 at 09:13:27 UTC, evilrat wrote:

On Thursday, 14 January 2021 at 05:44:43 UTC, Jack wrote:
On Wednesday, 13 January 2021 at 17:21:23 UTC, Paul Backus 
wrote:


Member functions (including static ones) can't be called 
with UFCS.



 is this documented somewhere? Is this going to change?


It will stay as is.
It is somewhat vaguely described in p.7 under UFCS section in 
functions


https://dlang.org/spec/function.html#pseudo-member


I see, thanks


If it's really important you can make a module-level alias to the 
static method.


https://run.dlang.io/is/4IFsjr


Re: dirEntries: How get "." and ".."?

2021-01-10 Thread Anonymouse via Digitalmars-d-learn

On Saturday, 9 January 2021 at 18:44:10 UTC, kdevel wrote:
There seems to be no switch to disable the skip of "."  and 
"..".

So the original position of these dir entries is lost. ☹


I imagine dirEntries returning an entry for ".." would make for a 
lot of confusion.


Don't you already know "." as the path you passed to dirEntries? 
What exactly are you trying to do?


Re: How can I set Timeout of Socket?

2020-11-15 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 15 November 2020 at 00:05:08 UTC, Marcone wrote:

Socket s = new Socket(AddressFamily.INET, SocketType.STREAM);
s.connect(new InternetAddress("domain.com", 80));

I want that program raise an error if reach for example 30 
seconds of timeout.


My program does something like this. (untested)

Socket s = new TcpSocket;
s.setOption(SocketOptionLevel.SOCKET, SocketOption.RCVTIMEO, 
30.seconds);
s.setOption(SocketOptionLevel.SOCKET, SocketOption.SNDTIMEO, 
30.seconds);


auto addresses = getAddress("domain.com", 80);
bool isConnected;

foreach (address; addresses)
{
try
{
s.connect(address);
isConnected = true;
break;
}
catch (SocketException e)
{
// Failed, try next address
writeln(e.msg);
}
}

if (!isConnected) return false;  // failed to connect

// Connected

You can tell whether a read timed out by looking at the amount of 
bytes read (when `Socket.receive` returns `Socket.ERROR`) and the 
value of `std.socket.lastSocketError` (and/or 
`core.stdc.errno.errno` equaling EAGAIN).


Re: How format UnixTime to "%Hh:%Mm:%Ss" ?

2020-11-15 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 15 November 2020 at 03:14:07 UTC, Marcone wrote:

I want to convert seconds to hour, minut and second.


Do you want to convert a *duration* into hours/minutes/seconds, 
or format a UNIX *timestamp* to hours/minutes/seconds? These are 
conceptually two different things.


`Clock.currTime` will return a `SysTime` (a point in time) in 
your local timezone. If you want to get the hour/minute/second 
parts of a duration of time (for instance, in seconds), use a 
`Duration` and `split`.


// Função strftime()
string strftime(string fmt, int tempo){
long H, M, S;
tempo.seconds.split!("hours", "minutes", "seconds")(H, M, S);
	return fmt.replace("%H", H.text).replace("%M", 
M.text).replace("%S", S.text);

}

writeln(strftime("%H:%M:%S", 4783));  // 1:19:43

https://run.dlang.io/is/0L5yqP

https://dlang.org/articles/intro-to-datetime.html


Re: How format UnixTime to "%Hh:%Mm:%Ss" ?

2020-11-14 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 15 November 2020 at 03:08:48 UTC, Marcone wrote:

On Sunday, 15 November 2020 at 02:29:20 UTC, Anonymouse wrote:

On Sunday, 15 November 2020 at 01:04:41 UTC, Marcone wrote:

auto mytime = Clock.currTime().toUnixTime()

writeln(strftime("%Hh:%Mm:%Ss", mytime)); How can I make some 
like this in D?


auto mytime = Clock.currTime;
writefln("%02dh:%02dm:%02ds", mytime.hour, mytime.minute, 
mytime.second);


auto mytimeFromUnix = SysTime.fromUnixTime(1234567890);
writefln("%02dh:%02dm:%02ds", mytimeFromUnix.hour, 
mytimeFromUnix.minute, mytimeFromUnix.second);


https://run.dlang.io/is/TAO6Q9


Your code get wrong hour result: 21hours, only minuts and 
seconds correct.


If you're looking at the run.dlang.io output, the server is 
probably in a different timezone than yours.


Tested locally at 04:14 instead of sleeping:

$ dmd -run mytime.d
04h:14m:06s
00h:31m:30s


Re: How format UnixTime to "%Hh:%Mm:%Ss" ?

2020-11-14 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 15 November 2020 at 01:04:41 UTC, Marcone wrote:

auto mytime = Clock.currTime().toUnixTime()

writeln(strftime("%Hh:%Mm:%Ss", mytime)); How can I make some 
like this in D?


auto mytime = Clock.currTime;
writefln("%02dh:%02dm:%02ds", mytime.hour, mytime.minute, 
mytime.second);


auto mytimeFromUnix = SysTime.fromUnixTime(1234567890);
writefln("%02dh:%02dm:%02ds", mytimeFromUnix.hour, 
mytimeFromUnix.minute, mytimeFromUnix.second);


https://run.dlang.io/is/TAO6Q9


Re: Switch between two structs with csvreader

2020-11-05 Thread Anonymouse via Digitalmars-d-learn

On Thursday, 5 November 2020 at 21:18:52 UTC, Selim Ozel wrote:

auto records = rawtext.csvReader!struct_type1(';');


D is statically typed and `auto` means "deduce this type for me 
based on this one function's return value". It is not like 
JavaScript's `var` whose type may change.


If I'm not mistaken the `csvReader` function returns a range 
struct, and the full type is something long and unwieldy like 
`CsvReader!(struct_type1, cast(Malformed)1, string, dchar, 
string[])`. So just think of `records` as being that.


(You can tell what type it is at compilation with `pragma(msg, 
typeof(records).stringof)`.)



if(aControlCondition) {
records = rawtext.csvReader!struct_type2(';');


Here `csvReader!struct_type2(';')` returns a value of type 
`CsvReader!(struct_type2, ...)`, which is a different type from 
that of `records` (and they're not implicitly convertible). So 
the error message is right. If `auto` worked like `var` your code 
would work, but it doesn't.


You need two different variables and two different `foreach`es. 
For the same code to work on both types, the easy solution is 
templates. Perhaps make the `foreach` part after the reads a 
templated function that accepts any type passed to it?




Re: I need a most simple and easy example to understand UDA.

2020-11-01 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 1 November 2020 at 20:33:15 UTC, Marcone wrote:

I need a most simple and easy example to understand UDA.


https://ddili.org/ders/d.en/uda.html


Re: Removind duplicates for JSON string

2020-11-01 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 1 November 2020 at 09:14:35 UTC, Vino wrote:

[
 Tuple!(string, string)("DEV", "D1"),
 Tuple!(string, string)("DEV", "default"),
 Tuple!(string, string)("DEV", "D1"),
 Tuple!(string, string)("QAS", "Q1"),
 Tuple!(string, string)("QAS", "Q1"),
 Tuple!(string, string)("QAS", "default"),
 Tuple!(string, string)("PRD", "P1"),
 Tuple!(string, string)("PRD", "P1"),
 Tuple!(string, string)("PRD", "default")
]

Required Output
[
 Tuple!(string, string)("DEV", "D1"),
 Tuple!(string, string)("QAS", "Q1"),
 Tuple!(string, string)("PRD", "P1"),
]

From,
Vino.B


I can only test with Phobos (no asdf on run.dlang.io), but isn't 
just normal sort and uniq what you want?


data[]
.array
.sort
.uniq!((tup1, tup2) => tup1[0] == tup2[0]);

https://run.dlang.io/is/a3KHaE

Sorting "default" values can be tricky but they conveniently cede 
to explicit D1/Q1/P1 values because of ASCII. Otherwise you would 
have to provide different sort and uniq predicates.


Re: dub fetching dependencies for wrong configuration(s)

2020-10-28 Thread Anonymouse via Digitalmars-d-learn

On Wednesday, 28 October 2020 at 19:34:43 UTC, ikod wrote:
To make this transition as painless as possible I'll create new 
package with major version "2" if you confirm that everything 
works as expected.


I tried cloning requests from git and added it as a dub package, 
and it seems to work.



~/src $ rm -rf ~/.dub/packages



~/src $ git clone https://github.com/ikod/dlang-requests.git
~/src $ dub add-local dlang-requests
Registered package: requests (version: 1.1.7+commit.4.g8e1c308)



~/src $ cd kameloso
~/src/kameloso $ dub upgrade
Upgrading project in /home/zorael/src/kameloso
Fetching lu 0.5.0 (getting selected version)...
Fetching cachetools 0.3.1 (getting selected version)...
Fetching dialect 0.9.0 (getting selected version)...
Fetching arsd-official 8.5.2 (getting selected version)


No vibe-d downloaded!


Re: dub fetching dependencies for wrong configuration(s)

2020-10-27 Thread Anonymouse via Digitalmars-d-learn

On Tuesday, 27 October 2020 at 21:15:35 UTC, ikod wrote:

On Tuesday, 27 October 2020 at 17:01:23 UTC, Anonymouse wrote:

On Sunday, 4 October 2020 at 21:00:49 UTC, ikod wrote:

Thanks, Andre!
I'll split requests as you suggested (increasing minor 
version, so that this change will not hurt anybody who build 
current requests package for vibe-d).


Will you make a requests-core?


I plan to clean requests package dependency from vibe, and make 
separate requests-vibe with vibe enabled config.


Is it urgent?


Not very, just following with interest!


Re: dub fetching dependencies for wrong configuration(s)

2020-10-27 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 4 October 2020 at 21:00:49 UTC, ikod wrote:

Thanks, Andre!
I'll split requests as you suggested (increasing minor version, 
so that this change will not hurt anybody who build current 
requests package for vibe-d).


Will you make a requests-core?


Re: How Stop Worker Thread if Owner Thread is Finished?

2020-10-27 Thread Anonymouse via Digitalmars-d-learn

On Tuesday, 27 October 2020 at 08:33:36 UTC, Johann Lermer wrote:
or you could use the fact, that receiveTimeout throws an 
exception, when main ends (although I don't know if this is the 
intended behaviour; the manual just says that it throws an 
exception when the sending thread was terminated):


If you're receiving you can listen for an OwnerTerminated message.

bool shouldExit = receiveTimeout((-1).seconds,
(OwnerTerminated o) {}
);

https://run.dlang.io/is/2t50yS


Re: `unittest` placement in code?

2020-10-26 Thread Anonymouse via Digitalmars-d-learn
On Monday, 26 October 2020 at 13:16:32 UTC, Vladimirs Nordholm 
wrote:

Hello.
[...]


Additionally, if you care about generating documentation, then 
placing them after whatever is being tested can make them end up 
as examples (of how to use them). Handy if your unittests shows 
how they're used and not only tests that they work; not so much 
otherwise.


class Foo
{
/// asdf
int multiplier;

/++
Multiplies stuff by `multiplier`.

Params:
n = Number to multiply.

Returns:
The integer passed, multiplied by `multiplier`.
 +/
int mul(int n)
{
return multiplier * n;
}

///
unittest
{
// Will end up in examples section, provided /// is 
placed above unittest

Foo foo = new Foo;
foo.multiplier = 2;

int four = foo.mul(2);
int six = foo.mul(3);
int eight = foo.mul(4);
int ten = foo.mul(5);
}
}

https://i.imgur.com/zjuJQkR.jpg

Even so I keep my larger test suite in a separate tests/ 
directory next to source/, but mostly because they'd swamp the 
original source files. You also lose the ability to unittest 
private stuff this way.


Re: Docs generation example

2020-10-09 Thread Anonymouse via Digitalmars-d-learn
On Saturday, 10 October 2020 at 02:07:02 UTC, Виталий Фадеев 
wrote:

Wanted!
Docs generation example.

I have dub project, sources/*.d.
I want html-index with all classes/functions.

Is exists simple, hi-level, one-line command line solution ?


dub run adrdox -- -i sources

Files will be in generated-docs/


Re: Taking arguments by value or by reference

2020-10-04 Thread Anonymouse via Digitalmars-d-learn

On Saturday, 3 October 2020 at 23:47:32 UTC, Max Haughton wrote:
The guiding principle to your function parameters should be 
correctness - if I am passing a big struct around, if I want to 
take ownership of it I probably want to take it by value but if 
I want to modify it I should take it by reference (or by 
pointer but don't overcomplicate, notice in the previous 
example they lower to the same thing). If I just want to look 
at it, it should be taken by const ref if possible (D const 
isn't the same as C++ const, this may catch you out).


Const-correctness is a rule to live by especially with an big 
unwieldy struct.


I would avoid the new in for now, but I would go with const ref 
from what you've described so far.


I mostly really only want a read-only view of the struct, and 
whether a copy was done or not is academic. However, profiling 
showed (what I interpret as) a lot of copying being done in 
release builds specifically.


https://i.imgur.com/JJzh4Zc.jpg

Naturally a situation where I need ref I'd use ref, and in the 
rare cases where it actually helps to have a mutable copy 
directly I take it mutable. But if I understand what you're 
saying, and ignoring --preview=in, you'd recommend I use const 
ref where I would otherwise use const?


Is there some criteria I can go by when making this decision, or 
does it always reduce to looking at the disassembly?


dub fetching dependencies for wrong configuration(s)

2020-10-04 Thread Anonymouse via Digitalmars-d-learn
My project depends on the requests dub package, which has two 
build configurations; one with an extra vibe-d dependency, one 
without (default).


"configurations": [
{
"name": "std"
},
{
"name": "vibed",
"versions": ["vibeD"],
"dependencies": {
"vibe-d": ">=0.8.0"
}
}
],

I only ever use the default "std" configuration, but dub always 
pulls the additional multiple vibe-d dependencies, regardless of 
what I pick. Adding a subConfiguration restriction does not seem 
to help.


$ dub upgrade
Upgrading project in /home/zorael/src/kameloso
Fetching vibe-core 1.10.2 (getting selected version)...
Fetching memutils 1.0.4 (getting selected version)...
Fetching taggedalgebraic 0.11.18 (getting selected version)...
Fetching vibe-d 0.9.2 (getting selected version)...
Fetching botan-math 1.0.3 (getting selected version)...
Fetching stdx-allocator 2.77.5 (getting selected version)...
Fetching botan 1.12.18 (getting selected version)...
Fetching diet-ng 1.7.4 (getting selected version)...
Fetching openssl 1.1.6+1.0.1g (getting selected version)...
Fetching eventcore 0.9.9 (getting selected version)...
Fetching mir-linux-kernel 1.0.1 (getting selected version)...
Fetching libasync 0.8.6 (getting selected version)...

Is there any way to stop this?


Taking arguments by value or by reference

2020-10-03 Thread Anonymouse via Digitalmars-d-learn
I'm passing structs around (collections of strings) whose .sizeof 
returns 432.


The readme for 2.094.0 includes the following:

This release reworks the meaning of in to properly support all 
those use cases. in parameters will now be passed by reference 
when optimal, [...]


* Otherwise, if the type's size requires it, it will be passed 
by reference.
Currently, types which are over twice the machine word size 
will be passed by
reference, however this is controlled by the backend and can be 
changed based

on the platform's ABI.


However, I asked in #d a while ago and was told to always pass by 
value until it breaks, and only then resort to ref.


[18:32:16]  at what point should I start passing my 
structs by ref rather than by value? some are nested in others, 
so sizeofs range between 120 and 620UL

[18:33:43]  when you start getting stack overflows
[18:39:09]  so if I don't need ref for the references, 
there's no inherent merit to it unless I get in trouble without 
it?

[18:39:20]  pretty much
[18:40:16]  in many cases the copying is merely 
theoretical and doesn't actually happen when optimized


I've so far just been using const parameters. What should I be 
using?


Re: Safe to remove AA elements while iterating over it via .byKeyValue?

2020-09-27 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 27 September 2020 at 13:02:04 UTC, Per Nordlöw wrote:
Is it safe to remove AA-elements from an `aa` I'm iterating 
over via aa.byKeyValue?


I'm currently doing this:

foreach (ref kv; aa.byKeyValue)
{
if (pred(kv.key))
aa.remove(kv.key); // ok?
}
if (aa.length == 0)
aa = null;

Is there a better way?


The boring way is to store an array of the spent keys and remove 
afterwards.


KeyType!(typeof(aa))[] garbage;
garbage.reserve(aa.length);

foreach (ref kv; aa.byKeyValue)
{
if (pred(kv.key))
garbage ~= kv.key;
}

foreach (const key; garbage)
{
aa.remove(key);
}

This works with normal arrays too (and 
std.algorithm.mutation.remove), if you foreach_reverse the 
garbage array.


Re: Struct initializer in UDA

2020-09-27 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 27 September 2020 at 10:17:39 UTC, realhet wrote:
On Saturday, 26 September 2020 at 17:13:17 UTC, Anonymouse 
wrote:

On Saturday, 26 September 2020 at 16:05:58 UTC, realhet wrote:
The closest I can get is @(S.init.c(9).f(42)) with use of 
opDispatch, which is easier to read but still ugly.


All I can get is that the
- an identifier of a member is stronger than the opDispatch. -> 
Error: function expected before (), not S(0, 0).c of type int
- and if I prefix it with '_' it ruins toString. -> Error: no 
property toString for type onlineapp.S



import std.stdio, std.range, std.algorithm, std.traits, 
std.meta, std.conv, std.string, std.uni, std.meta, 
std.functional, std.exception;


struct S{
int a, b;

auto opDispatch(string name, T)(T value)
if(name.startsWith("_"))
{
mixin(name[1..$], "= value;");
return this;
}
}

void main(){
S.init._a(5).writeln;
}


Now I'm more confused, as the compiler completely ignores the 
if(name.startsWith("_")) constraint o.O


It works if you specialise opDispatch to take an int parameter 
instead of a type T. It smells like a bug but I don't know enough 
to say.


I used two opDispatches to be able to avoid having to use _a and 
_b, and std.algorithm.comparison.among to constrain them.


struct S{
private int _a, _b;

auto opDispatch(string name)(int value)
if (name.among("a", "b"))
{
mixin("_", name, "= value;");
return this;
}

auto opDispatch(string name)()
if (name.among("a", "b"))
{
mixin("return _", name, ";");
}
}

void main(){
S.init.a(123).b(456).writeln;
S().b(456).a(123).writeln;  // Alternative syntax, may not 
work if opCall is defined

}

It's brittle in that you have to update and sync the two 
among("a", "b") constraints every time you add or remove a field, 
but I can't seem to get the names by introspection without it 
endlessly recursing over opDispatch again.


Re: Struct initializer in UDA

2020-09-26 Thread Anonymouse via Digitalmars-d-learn

On Saturday, 26 September 2020 at 16:05:58 UTC, realhet wrote:

Hi,

  struct S{int a, b, c=9, d, e, f;}

Is there a way or a trick to declare an UDA by using a nice 
struct initializer?


It would be nice to be able to use the form:

  @S{f:42} int a;  //or something similar to this.

instead of this longer and error-prone way:

  @S(0, 0, 0, 9, 0, 42) int a;


I don't think you can currently, no, but I'd be happy to be 
proven wrong.


The closest I can get is @(S.init.c(9).f(42)) with use of 
opDispatch, which is easier to read but still ugly.


Re: Cannot call @system funciton (stdout)

2020-09-19 Thread Anonymouse via Digitalmars-d-learn
On Saturday, 19 September 2020 at 14:08:39 UTC, Adam D. Ruppe 
wrote:
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.


Also makes sense, thanks. I already expose the option to force 
flushing with a --flush command-line argument, so I guess I'll 
keep that around (but use setvbuf when the TERM/uname thing 
detects a whitelisted environment).


Re: Cannot call @system funciton (stdout)

2020-09-19 Thread Anonymouse via Digitalmars-d-learn

On Saturday, 19 September 2020 at 14:14:46 UTC, Paul Backus wrote:
You can check the TERM environment variable [2], or you can use 
the POSIX uname() function [3] to see if you're running under 
Cygwin specifically. If there are any other environments where 
you need to manually set line-buffering, you'll probably have 
to check for those individually as well.


All right, thanks. Yes, currently I'm doing the TERM and uname 
thing on program start and flushing manually after every writeln 
if I detected Cygwin or vscode.


I think I can work with this.



Re: Cannot call @system funciton (stdout)

2020-09-19 Thread Anonymouse via Digitalmars-d-learn

On Saturday, 19 September 2020 at 13:32:07 UTC, Paul Backus wrote:
On Saturday, 19 September 2020 at 13:23:29 UTC, Anonymouse 
wrote:

On Tuesday, 18 August 2020 at 06:25:31 UTC, Kagamin wrote:

On Sunday, 16 August 2020 at 18:13:07 UTC, Anonymouse wrote:
Just as a drive-by comment, the main stdio thing I came 
across that I couldn't do from within @safe was 
stdout.flush(), which I need to call manually for Cygwin 
terminals and some terminals embedded in editors (vscode). 
If someone knows why, please tell me.


Cygwin terminals are not recognized as terminals, you should 
set line buffered mode, then it will flush every line.


How do I do this?


http://dpldocs.info/experimental-docs/std.stdio.File.setvbuf.1.html


Thanks.

I don't have a clone of druntime/Phobos available to me right 
now, so some follow-up questions.


It looks like full buffering _IOFBF is the default setting, but 
"normal" non-Cygwin stdio certainly seems to do line buffering. 
Is it getting set to line buffering _IOLBF during initialisation 
of stdout? (Why then is Cygwin exempt?)


Is there a way to detect programmatically if I'm in an 
environment where I need to manually set line buffering?




Re: Cannot call @system funciton (stdout)

2020-09-19 Thread Anonymouse via Digitalmars-d-learn

On Tuesday, 18 August 2020 at 06:25:31 UTC, Kagamin wrote:

On Sunday, 16 August 2020 at 18:13:07 UTC, Anonymouse wrote:
Just as a drive-by comment, the main stdio thing I came across 
that I couldn't do from within @safe was stdout.flush(), which 
I need to call manually for Cygwin terminals and some 
terminals embedded in editors (vscode). If someone knows why, 
please tell me.


Cygwin terminals are not recognized as terminals, you should 
set line buffered mode, then it will flush every line.


How do I do this?


Re: Introspecting a package for submodules

2020-08-24 Thread Anonymouse via Digitalmars-d-learn

On Monday, 24 August 2020 at 22:32:52 UTC, Anonymouse wrote:
`__traits(allMembers, std.algorithm)` evaluates to nothing, but 
replace it with `std.algorithm.searching` and it does.


`std.algorithm` makes for a bad example as it is actually empty 
save for imports. Just read it as `std.datetime` please, which 
has struct members.


`__traits(allMembers, std.datetime)` evaluates to nothing, but 
replace it with `std.datetime.systime` and it does.


This makes everything really difficult. Is it intentional?

https://run.dlang.io/is/UAHiAo


Introspecting a package for submodules

2020-08-24 Thread Anonymouse via Digitalmars-d-learn
I have some modules, and then one `package.d` file that publicly 
imports them all. I have reason to access them individually 
however, with hopes of being able to enumerate them and 
introspect with `__traits(allMembers, someModule)`. Concretely, I 
want to express "find all module-level classes in all submodules 
of this package".


As an analogy, I have `std.algorithm` and I want to 
programmatically get `std.algorithm.comparison`, 
`std.algorithm.iteration`, `std.algorithm.mutation`, etc -- 
either as symbols or as strings.


`__traits(allMembers, std.algorithm)` evaluates to nothing, but 
replace it with `std.algorithm.searching` and it does.


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


Re: Cannot call @system funciton (stdout)

2020-08-16 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 16 August 2020 at 10:07:02 UTC, Simen Kjærås wrote:

On Saturday, 15 August 2020 at 23:59:36 UTC, Joel wrote:
../../JMiscLib/source/jmisc/base.d(176,2): Error: @safe 
function jmisc.base.upDateStatus!string.upDateStatus cannot 
call @system function 
std.stdio.makeGlobal!"core.stdc.stdio.stdout".makeGlobal
/Library/D/dmd/src/phobos/std/stdio.d(4837,20):
std.stdio.makeGlobal!"core.stdc.stdio.stdout".makeGlobal is 
declared here


I got around it by avoiding 'stdout'.


First, what's wrong with using writeln and friends instead of 
directly mucking about with stdout? :p


Just as a drive-by comment, the main stdio thing I came across 
that I couldn't do from within @safe was stdout.flush(), which I 
need to call manually for Cygwin terminals and some terminals 
embedded in editors (vscode). If someone knows why, please tell 
me.





Re: My RPN calculator code review?

2020-07-18 Thread Anonymouse via Digitalmars-d-learn

On Friday, 17 July 2020 at 21:37:46 UTC, AB wrote:
Hello, inspired by the "Tiny RPN calculator" example seen on 
the dlang homepage, I wanted to create my own version.


I'd appreciate your opinions regarding style, mistakes/code 
smell/bad practice. Thank you.


I generally don't know what I'm talking about, but nothing stands 
out as outright wrong. Style is unique from person to person.


valid_ops is a compile-time constant and can be made an enum.

I'm not happy about the looping and allocating replacements of 
spaced_args, but it's an easy solution where alternatives quickly 
become tricky or involve regular expressions (something like 
`spaced_args.matchAll("[0-9]+|[+*/-]".regex)`). Regex is neat but 
heavy.


You can use std.algorithm.iteration.splitter instead of 
std.array.split to lazily foreach spaced_args.


I don't know enough to say if `case [o]` will allocate at 
runtime. If so, it could be replaced with `case to!string(o)`, 
but maybe the compiler is smart enough to not consider [o] a 
runtime literal. For a program this short it doesn't really 
matter, but for a longer one it might be worth looking up.


You're not checking for array size before slicing stack, and as 
such the program range errors out on operator-operand count 
mismatch.


The rest is micro-optimisation and nit-picking. If valid_ops is 
an enum, you could foreach over it as an AliasSeq with a normal 
foreach (`foreach (o; aliasSeqOf!valid_ops)`; see std.meta). You 
could use std.array.Appender instead of appending to a real[]. 
etc.


Re: getopt: How does arraySep work?

2020-07-14 Thread Anonymouse via Digitalmars-d-learn

On Tuesday, 14 July 2020 at 11:12:06 UTC, Andre Pany wrote:

[...]


Steven Schveighoffer already answered while I was composing this, 
so discarding top half.


As far as I can tell the default arraySep of "" splitting the 
argument by whitespace is simply not the case.



https://github.com/dlang/phobos/blob/master/std/getopt.d#L923


// ...
else static if (isArray!(typeof(*receiver)))
{
// array receiver
import std.range : ElementEncodingType;
alias E = ElementEncodingType!(typeof(*receiver));

if (arraySep == "")
{
*receiver ~= to!E(val);
}
else
{
foreach (elem; val.splitter(arraySep).map!(a => 
to!E(a))())

*receiver ~= elem;
}
}

So you will probably want an arraySep of " " if you want 
--modelicalibs "a b".


Re: Send empty assoc array to function

2020-07-09 Thread Anonymouse via Digitalmars-d-learn

On Thursday, 9 July 2020 at 19:53:42 UTC, JN wrote:

void foo(int[int] bar)
{
// ...
}



Is it possible to send an empty array literal?

foo( [ 0 : 2 ] ) works
foo( [] ) doesn't

int[int] empty;
foo(empty);
works but it's two lines


I always did foo((int[int]).init);


Re: std.concurrency.receive and shared const(char)[]?

2020-06-28 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 28 June 2020 at 16:11:50 UTC, BakedPineapple wrote:

import std.stdio;
import std.concurrency;

void main()
{
auto t = spawn((){
receive((shared const(char)[] char_arr) {
ownerTid.send(true);
});
});
shared const(char)[] char_arr = "cut my code into pieces";
t.send(char_arr);
assert(receiveOnly!(bool) == true);
}

When I run this program, it blocks on the receive() inside the 
spawned thread. What am I doing wrong?


Make the parameter shared(const(char))[] and it will work. I'll 
leave it to someone who knows more to explain why it behaves that 
way.


Re: Dub platform probes

2020-05-25 Thread Anonymouse via Digitalmars-d-learn

On Monday, 25 May 2020 at 22:58:54 UTC, Tim wrote:

[...]


Same here, but /tmp.

$ ls /tmp/dub* | wc -l
174




Re: Is there a way to tell if an auto ref parameter is by ref or by value?

2020-05-09 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 10 May 2020 at 00:33:07 UTC, NaN wrote:

Ie something like..


auto Foo(T)(auto ref T x)
{
static if (isByRef(x))
{
}
else
{
}
}


__traits(isRef, x)


Compilation memory use

2020-05-04 Thread Anonymouse via Digitalmars-d-learn
TL;DR: Is there a way to tell what module or other section of a 
codebase is eating memory when compiling?


I'm keeping track of compilation memory use using zsh `time` with 
some environmental variables. It typically looks like this.


```
$ time dub build -c dev
Performing "debug" build using /usr/bin/dmd for x86_64.
[...]
Linking...
To force a rebuild of up-to-date targets, run again with --force.
dub build -c dev   9.47s  user 1.53s system 105% cpu 10.438 total
avg shared (code): 0 KB
avg unshared (data/stack): 0 KB
total (sum):   0 KB
max memory:4533 MB
page faults from disk: 1
other page faults: 1237356
```

So it tells me the maximum memory that was required to compile it 
all. However, it only tells me just that; there's no way to know 
what part of the code is expensive and what part isn't.


I can copy dub's dmd command and run it with `-v` and try to 
infer that the modules that are slow to pass semantic3 are also 
the hungry ones. But are they?


Is there a better metric?


Re: Can't get dub dustmite to work

2020-04-27 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 26 April 2020 at 22:05:20 UTC, aliak wrote:

On Saturday, 25 April 2020 at 19:00:55 UTC, Anonymouse wrote:

On Saturday, 25 April 2020 at 09:38:59 UTC, aliak wrote:

Then I run this dub dustmite command:

dub dustmite -b unittest ../dubdust --compiler-regex="never 
matches"


I have had zero luck with dustmite via dub. I would honestly 
recommend that you create a shell script that does `dub test 
2>&1 | grep "never matches"`, and just use that as a tester 
with dustmite directly.


Ok I got it working with that but it resulted in the wrong 
output (it was a bad test case basically" But expanding the 
shell script to


dub test 2>&1 | grep 'Error: static assert:  \"handler #0 of 
type `Optional!(Exception) function(FailureContainer container) 
pure nothrow @nogc @safe` never matches\"'


now results in

...
Loading ./source/result/failure.d
Loading ./source/result/package.d
Loading ./source/result/result.d
Loading ./tests/result.d
None => No
Hint: use --no-redirect to see test script output
Hint: read 
https://github.com/CyberShadow/DustMite/wiki#initial-test-fails
object.Exception@DustMite/dustmite.d(295): Initial test fails: 
Test script "dub test 2>&1 | grep 'Error: static assert:  
\"handler #0 of type  never matches\"'" exited with exit code 1 
(failure)


??:? _Dmain [0x10c56cf5e]


This is the full dustmite command:

dustmite --force . "dub test 2>&1 | grep 'Error: static assert:
 \"handler #0 of type `Optional!(Exception) 
function(FailureContainer container) pure nothrow @nogc @safe` 
never matches\"'"


I'm not at the computer but I expect what's happening is backtick 
command substitution. It's difficult to get right since you want 
to nest quotes here, but you may be able to get around it by just 
escaping the backticks too. The easy solution is a shell script. 
I'll test it some more once I have something better to type on 
than the phone.


Re: Can't get dub dustmite to work

2020-04-25 Thread Anonymouse via Digitalmars-d-learn

On Saturday, 25 April 2020 at 09:38:59 UTC, aliak wrote:

Then I run this dub dustmite command:

dub dustmite -b unittest ../dubdust --compiler-regex="never 
matches"


I have had zero luck with dustmite via dub. I would honestly 
recommend that you create a shell script that does `dub test 2>&1 
| grep "never matches"`, and just use that as a tester with 
dustmite directly.


Re: Bug in std.json or my problem

2020-04-22 Thread Anonymouse via Digitalmars-d-learn
On Wednesday, 22 April 2020 at 17:48:18 UTC, Craig Dillabaugh 
wrote:

The crash is caused because the 'income' field with value 0.0 is
output as 0 (rather than 0.0) and when it is read this is 
interpreted

as an integer.

Shouldn't this work?


Yes, it's just buggy.

Giving it a value of an even 1.0 will make it throw the same 
exception (js["income"].type is JSONType.integer), but a value of 
1.1 will make it pass (.type properly becomes JSONType.float_).


I don't know of a solution other than to check js["income"].type 
beforehand and use .floating or .integer as befits, or simply use 
an alternative JSON library (asdf?).


File an issue if you have the time, maybe it will get attention. 
Unreported bugs can only be fixed by accident.


Re: docs.json is incomplete

2020-04-11 Thread Anonymouse via Digitalmars-d-learn

On Saturday, 11 April 2020 at 13:13:45 UTC, Adam D. Ruppe wrote:

On Saturday, 11 April 2020 at 06:49:21 UTC, Anonymouse wrote:
(TL;DR: the module contains one public class and (private) two 
structs, three free functions and one module-level mixin, but 
only the class is shown.


It is all under a `private:` thing for this file.

http://kameloso.dpldocs.info/source/kameloso.plugins.sedreplace.d.html#L34

Then there's a `public:` directly above the class. My doc 
generator skips private members unless you run the generator 
yourself and pass `-p` to the command line.


This makes sense.

I have more elaborate examples where some free functions make 
it and some don't, showing that public/private visibility is 
not the cause.)


Have an example there? My parser has been known to get off 
track before on things and just give up on the rest of the 
file. The D parser I have is pretty hacky.


Yes, http://kameloso.dpldocs.info/kameloso.plugins.seen.html. 
onBusMessage is private like the other functions, but it shows 
up. (Additionally the public imports are private.)


In http://kameloso.dpldocs.info/kameloso.plugins.admin.html, 
http://kameloso.dpldocs.info/kameloso.plugins.automode.html, 
http://kameloso.dpldocs.info/kameloso.plugins.chatbot.html, 
http://kameloso.dpldocs.info/kameloso.plugins.connect.html, 
http://kameloso.dpldocs.info/kameloso.plugins.notes.html, ...; in 
nearly all modules listed in 
http://kameloso.dpldocs.info/kameloso.plugins.html private 
members are partly included.


The idea is for every plugin module to only expose the public 
IRCPlugin class and hide the rest. Some, correctly then, only 
show the plugin (e.g. 
http://kameloso.dpldocs.info/kameloso.plugins.ctcp.html).


The fact that it is listed four times seems to have to do with 
the use of `version(Something):` at the top of the module, to 
allow for opt-in enabling it based on dub build configuration. 
Commenting them out does not bring the missing stuff back.


Is there a syntax error somewhere? I can't see it. Is the 
docs.json generator at fault?


That repetition sounds like a bug in the other thing. Their 
weird handling of `version` is why I actually decided to write 
my own parser!


my version at least shows it kinda sanely:

version(WithSedReplacePlugin)
class SedReplacePlugin : IRCPlugin {}


Yeah, I like yours more, I just imagined it used docs.json too.


docs.json is incomplete

2020-04-11 Thread Anonymouse via Digitalmars-d-learn
I'm trying to get docs for my project hosted, and everything 
works, except there are entries missing. Looking at the generated 
docs.json there's simply a lot of omitted stuff.


Example:

http://kameloso.dpldocs.info/kameloso.plugins.sedreplace.html
http://kameloso.dpldocs.info/source/kameloso.plugins.sedreplace.d.html
https://zorael.github.io/kameloso/kameloso/plugins/sedreplace/SedReplacePlugin.html

(TL;DR: the module contains one public class and (private) two 
structs, three free functions and one module-level mixin, but 
only the class is shown. I have more elaborate examples where 
some free functions make it and some don't, showing that 
public/private visibility is not the cause.)


```json
{
"kind": "module",
"file": "source/kameloso/plugins/sedreplace.d",
"members": [
{
"line": 449,
"kind": "class",
"char": 7,
"members": [],
"name": "SedReplacePlugin",
"interfaces": [
"kameloso.plugins.ircplugin.IRCPlugin"
],
"comment": "[...]"
},
{
"line": 449,
"kind": "class",
"char": 7,
"members": [],
"name": "SedReplacePlugin",
"interfaces": [
"kameloso.plugins.ircplugin.IRCPlugin"
],
"comment": "[...]"
},
{
"line": 449,
"kind": "class",
"char": 7,
"members": [],
"name": "SedReplacePlugin",
"interfaces": [
"kameloso.plugins.ircplugin.IRCPlugin"
],
"comment": "[...]"
},
{
"line": 449,
"kind": "class",
"char": 7,
"members": [],
"name": "SedReplacePlugin",
"interfaces": [
"kameloso.plugins.ircplugin.IRCPlugin"
],
"comment": "[...]"
}
],
"comment": "[module ddoc ...]",
"name": "kameloso.plugins.sedreplace"
},

```

The fact that it is listed four times seems to have to do with 
the use of `version(Something):` at the top of the module, to 
allow for opt-in enabling it based on dub build configuration. 
Commenting them out does not bring the missing stuff back.


Is there a syntax error somewhere? I can't see it. Is the 
docs.json generator at fault?


Re: @safe function with __gshared as default parameter value

2020-04-08 Thread Anonymouse via Digitalmars-d-learn

On Wednesday, 8 April 2020 at 19:53:03 UTC, jmh530 wrote:
Well that definitely shouldn't happen. I would file a bug 
report.


Filed as https://issues.dlang.org/show_bug.cgi?id=20726


Re: @safe function with __gshared as default parameter value

2020-04-08 Thread Anonymouse via Digitalmars-d-learn

On Wednesday, 8 April 2020 at 19:22:11 UTC, jmh530 wrote:
On Wednesday, 8 April 2020 at 18:50:16 UTC, data pulverizer 
wrote:

On Wednesday, 8 April 2020 at 16:53:05 UTC, Anonymouse wrote:

```
import std.stdio;

@safe:

__gshared int gshared = 42;

void foo(int i = gshared)
{
writeln(i);
}

void main()
{
foo();
}
```

This currently works; `foo` is `@safe` and prints the value 
of `gshared`. Changing the call in main to `foo(gshared)` 
errors.


Should it work, and can I expect it to keep working?


According to the manual it shouldn't work at all 
https://dlang.org/spec/function.html#function-safety where it 
says Safe Functions: "Cannot access __gshared variables.", I 
don't know why calling as `foo()` works.


You still wouldn't be able to manipulate gshared within the 
function. Though it may still be a problem for @safe...


It works with `ref int` too.


```
__gshared int gshared = 42;

void foo(ref int i = gshared) @safe
{
++i;
}
void main()
{
assert(gshared == 42);
foo();
assert(gshared == 43);
}
```


@safe function with __gshared as default parameter value

2020-04-08 Thread Anonymouse via Digitalmars-d-learn

```
import std.stdio;

@safe:

__gshared int gshared = 42;

void foo(int i = gshared)
{
writeln(i);
}

void main()
{
foo();
}
```

This currently works; `foo` is `@safe` and prints the value of 
`gshared`. Changing the call in main to `foo(gshared)` errors.


Should it work, and can I expect it to keep working?


dub sourceFiles

2020-03-31 Thread Anonymouse via Digitalmars-d-learn
I have a library package that I split up into subpackages, but 
I'm having to do mental gymnastics to make it only compile the 
files I want.


The problem is that even if you specify some `sourceFiles`, it 
will build everything under the sun inside `sourcePaths`, which 
defaults to "source" or "src" depending on availability. There's 
no way to set it to an empty string, or something that doesn't 
exist.


```sdl
name "stuff"
targetType "library"

subPackage {
name "foo"

sourceFiles \
"source/foo.d"
}

subPackage {
name "bar"

sourceFiles \
"source/bar.d" \
"source/common.d"
}
```


$ dub build -v :foo
[...]
/usr/bin/dmd -Isource source/foo.d source/bar.d source/common.d


Since I didn't specify any `sourcePaths`, it here defaults to 
"source" and my subpackage only asking for "foo.d" was handed all 
of the files anyway.


What is the preferred solution here?

1. Use `excludedSourceFiles` and exclude files not to be 
compiled. Mental gymnastics needed when you have 12 files (the 
actual case).
2a. Keep source tree in something that isn't named "source" or 
"src", but keep an empty one around for dub to auto-include 
nothing from. I kind of want to avoid this.
2b. Keep real source files in "source", but declare `sourcePaths` 
to point to a dummy empty "ignoreme" directory.  Crude but 
technically works.

3. Something else? Surely I'm not the first to run into this.

I could set up the subpackages to each have its own directory 
(2a), but I'd end up with twelve, not including the empty 
"source" acting as bait for dub.


Re: How to create an array with custom length?

2020-03-27 Thread Anonymouse via Digitalmars-d-learn

On Friday, 27 March 2020 at 19:30:39 UTC, Quantium wrote:

Code
int n=0;
readf(" %d", );
int[n] m;
generated an error (DMD compiler):
Cannot read n at compile time.
How to create an array with custom length?


The tour has a page for this: 
https://tour.dlang.org/tour/en/basics/arrays


int n=0;
readf(" %d", );
int[] m = new int[n];


Re: dub and -lowmem: does nothing

2020-03-21 Thread Anonymouse via Digitalmars-d-learn

On Saturday, 21 March 2020 at 00:17:37 UTC, kinke wrote:
Most likely because dub doesn't actually invoke the listed 
command, but uses a response file to work around cmdline length 
limits. -lowmem in response files is ignored by DMD (needs to 
be parsed and set before druntime initialization, but response 
file parsing needs druntime + GC). It works for LDC though.


So there is no way to do -lowmem with dub and dmd?

I'm not having out-of-memory problems with ldc, luckily.


dub and -lowmem: does nothing

2020-03-20 Thread Anonymouse via Digitalmars-d-learn

Manjaro/Arch x86_64, dmd v2.091.0, dub 1.19.0.

I have a project which dmd on Windows fails to compile, throwing 
an OutOfMemoryError[1]. Up until recently it could be worked 
around by using `--build-mode=singleFile`, but now that's no 
longer enough and errors out too (on AppVeyor).


The obvious solution is to set `-lowmem` in dub.sdl, but it seems 
to do nothing, as measured *in Linux* by the amount of memory 
used with zsh's `time` shell built-in.


If using zsh time, you may need the following environmental 
variable to get the required output:


```
TIMEFMT='%J   %U  user %S system %P cpu %*E total
avg shared (code): %X KB
avg unshared (data/stack): %D KB
total (sum):   %K KB
max memory:%M MB
page faults from disk: %F
other page faults: %R'
```

A gutted test branch: (has two dependencies)

git clone https://github.com/zorael/tests.git -b lowmem


1. `dub build` on a default configuration without -lowmem defined 
shows some ~2011 Mb used.
2. If I run dub with -v, then copy the dmd command it runs and 
execute it manually, I get the same ~2012 Mb used. Close enough, 
makes sense.
3. `dub build -c lowmem` for an identical configuration but with 
dflags "-lowmem" added, nothing changes and I still get ~2011 Mb 
used.
4. If I run dub with -v on the lowmem configuration and 
copy/paste *the same command it ran*, unmodified, I suddenly get 
the more expected ~1183 Mb used.


Log: https://pastebin.com/raw/yDnCj1KJ

-lowmem is visibly present in the dmd command listed with -v, but 
it seems to do nothing through dub.


How? Why?



dub remove lu --version="*"
dub remove dialect --version="*"


[1]: https://issues.dlang.org/show_bug.cgi?id=20562


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

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

On Sunday, 16 February 2020 at 09:13:54 UTC, ikod wrote:

Just a note - this is not a bug, server really send empty body:

< HTTP/1.1 500 Internal Server Error
< cache-control: private
< server: Microsoft-IIS/10.0
< x-aspnetmvc-version: 5.1
< access-control-allow-origin: *
< x-aspnet-version: 4.0.30319
< request-context: 
appId=cid-v1:7585021b-2db7-4da6-abff-2cf23005f0a9

< access-control-expose-headers: Request-Context
< x-powered-by: ASP.NET
< date: Sat, 15 Feb 2020 20:44:03 GMT
< content-length: 0
< 0 bytes of body received


Yes, my bad. I was assuming curl's output was what was sent.


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

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

On Saturday, 15 February 2020 at 16:25:42 UTC, Gregor Mückl wrote:
Unfortunately, this is not true. The msg only contains the text 
information in the status line of the HTTP reply. If I'm not 
mistaken, the exception is created in this line in 
std/net/curl.d:


enforce(statusLine.code / 100 == 2, new 
HTTPStatusException(statusLine.code,
format("HTTP request returned status code %d (%s)", 
statusLine.code, statusLine.reason)));


If anything is wrong, the server I'm interested in tends to 
reply with a status code 500 and a generic status line text and 
a bloated XML body containing the actual error message.


Not that it answers your question but requests[1] can do this, if 
you don't mind adding some dependencies.


Request req;
Response res = req.get(urlRespondingWith500);
assert(res.code == 500);
writeln(res.responseBody);  // Buffer!ubyte; use .to!string to 
get a string


When testing to confirm I ran into a bug[2] where the body is 
sometimes empty, but outside of fringe cases it should work.


[1]: https://code.dlang.org/packages/requests
[2]: https://github.com/ikod/dlang-requests/issues/115


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: Some impressions/notes from a new D programmer

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

On Wednesday, 12 February 2020 at 13:36:13 UTC, mark wrote:
Some cargo packages are applications. If I do 'cargo install 
someapp' it will be installed in $HOME/.cargo/bin. So by simply 
adding that to my PATH, I can easily use all installed rust 
apps. But dub doesn't appear to have an equivalent of this.


There is 'dub run someapp', which is good enough for some cases, 
like digger[1]. But no 'dub install someapp', no.


Maybe there are some hard design decisions again $HOME/.dub/bin, 
unsure. It might be difficult to globally pull off if programs 
expect the binary to be placed in the source tree (for resources).


[1]: https://github.com/CyberShadow/Digger


Re: digger: Failed to spawn new process (The system cannot find the file specified.)

2020-02-03 Thread Anonymouse via Digitalmars-d-learn
On Monday, 3 February 2020 at 22:08:50 UTC, Vladimir Panteleev 
wrote:

On Monday, 3 February 2020 at 22:01:18 UTC, Anonymouse wrote:

No, C:\Temp\work\dl\git does not exist. :o


OK, that makes sense.

Please try the latest Digger version 
(24cd4168956dad382d05984b4b8d37d9e8ebe3ae).


Works great. Thanks for your help!


Re: digger: Failed to spawn new process (The system cannot find the file specified.)

2020-02-03 Thread Anonymouse via Digitalmars-d-learn
On Monday, 3 February 2020 at 21:58:31 UTC, Vladimir Panteleev 
wrote:

On Monday, 3 February 2020 at 21:44:20 UTC, Anonymouse wrote:

New log: https://pastebin.com/raw/uUMNQjEN


It looks like it fails to execute git (to get the current 
version for the build).


I don't know why that fails, as I see C:\Temp\work\dl\git\cmd 
is in PATH in the environment that build.exe is invoked with. I 
assume that that directory does contain a git.exe?


You may have some luck further debugging the cause of the error 
with a strace-like tool such as Process Monitor.


No, C:\Temp\work\dl\git does not exist. :o

```
 Directory of C:\Temp\work\dl

03/02/2020  22:20  .
03/02/2020  22:20  ..
03/02/2020  22:20  7z
03/02/2020  22:20   384,846 7za920.zip
03/02/2020  22:20  dm857-snn2074-optlink80017
03/02/2020  22:19 3,057,337 dm857c.zip
03/02/2020  22:20  dmd-2.079.0
03/02/2020  22:2020,614,650 dmd.2.074.0.windows.7z
03/02/2020  22:2041,903,965 dmd.2.079.0.windows.zip
   4 File(s) 65,960,798 bytes
   5 Dir(s)  42,867,355,648 bytes free
```


Re: digger: Failed to spawn new process (The system cannot find the file specified.)

2020-02-03 Thread Anonymouse via Digitalmars-d-learn
On Monday, 3 February 2020 at 21:33:09 UTC, Vladimir Panteleev 
wrote:

On Monday, 3 February 2020 at 21:30:57 UTC, Anonymouse wrote:
I was on beta 8. I forced dub to download the latest now 
(3.0.0-alpha-9), wiped the work directory and retried, but to 
similar results.


The latest is v3.0.0-alpha-11.

Oh, I guess that's not how semantic versioning works. Probably 
I should make a normal stable release.


For now you can clone and build from source.


New log: https://pastebin.com/raw/uUMNQjEN


```
..\generated\build.exe --called-from-make OS=windows 
BUILD=release MODEL=32 HOST_DMD= 
HOST_DC=C:\Temp\work\dl\dmd-2.079.0\dmd2/windows/bin\dmd.exe 
..\generated\windows\release\32\lexer.lib

(TX) VERSION

std.process.ProcessException@std\process.d(752): Failed to spawn 
new process (The system cannot find the file specified.)


0x00448EDC in @trusted std.process.Pid 
std.process.spawnProcessImpl(const(char[]), std.stdio.File, 
std.stdio.File, std.stdio.File, 
const(immutable(char)[][immutable(char)[]]), std.process.Config, 
const(char[]))
0x0044D6AA in @trusted std.process.Pid 
std.process.spawnProcess(const(char[][]), std.stdio.File, 
std.stdio.File, std.stdio.File, 
const(immutable(char)[][immutable(char)[]]), std.process.Config, 
const(char[]))
0x0046E114 in @trusted std.process.ProcessPipes 
std.process.pipeProcessImpl!(std.process.spawnProcess, 
const(char[])[]).pipeProcessImpl(const(char[])[], 
std.process.Redirect, 
const(immutable(char)[][immutable(char)[]]), std.process.Config, 
const(char[]))
0x004555A4 in @safe std.process.ProcessPipes 
std.process.pipeProcess(const(char[][]), std.process.Redirect, 
const(immutable(char)[][immutable(char)[]]), std.process.Config, 
const(char[]))
0x0043B160 in @trusted std.typecons.Tuple!(int, "status", 
immutable(char)[], "output").Tuple 
std.process.execute(const(char[][]), 
const(immutable(char)[][immutable(char)[]]), std.process.Config, 
uint, const(char[]))
0x0041DEAF in void build.__funcliteral51().__lambda1() at 
C:\Temp\work\repo\dmd\src\build.d(278)
0x00406D0B in void build.DependencyRef.runSynchronized() at 
C:\Temp\work\repo\dmd\src\build.d(1092)
0x0040347F in void build.DependencyRef.run() at 
C:\Temp\work\repo\dmd\src\build.d(1065)
0x00406C1D in void build.DependencyRef.runSynchronized() at 
C:\Temp\work\repo\dmd\src\build.d(1078)
0x0040347F in void build.DependencyRef.run() at 
C:\Temp\work\repo\dmd\src\build.d(1065)

0x00402783 in _Dmain at C:\Temp\work\repo\dmd\src\build.d(138)
0x004375B3 in void rt.dmain2._d_run_main(int, char**, extern (C) 
int function(char[][])*).runAll().__lambda1()
0x00437535 in void rt.dmain2._d_run_main(int, char**, extern (C) 
int function(char[][])*).runAll()

0x004373D0 in _d_run_main
0x004371C8 in main at C:\Temp\work\repo\dmd\src\build.d(7)
0x004B4B91 in mainCRTStartup
0x74D36359 in BaseThreadInitThunk
0x77337B74 in RtlGetAppContainerNamedObjectPath
0x77337B44 in RtlGetAppContainerNamedObjectPath
```


Re: digger: Failed to spawn new process (The system cannot find the file specified.)

2020-02-03 Thread Anonymouse via Digitalmars-d-learn
On Monday, 3 February 2020 at 20:54:46 UTC, Vladimir Panteleev 
wrote:

On Monday, 3 February 2020 at 20:41:00 UTC, Anonymouse wrote:

It doesn't seem to include debugging symbols.


Is your Digger version up-to-date?

https://github.com/CyberShadow/ae/commit/48ee31a3b0d47e52769ee87b0e673034abe4add5


I was on beta 8. I forced dub to download the latest now 
(3.0.0-alpha-9), wiped the work directory and retried, but to 
similar results.


https://pastebin.com/raw/zF39VKzc


Re: digger: Failed to spawn new process (The system cannot find the file specified.)

2020-02-03 Thread Anonymouse via Digitalmars-d-learn
On Monday, 3 February 2020 at 20:09:43 UTC, MoonlightSentinel 
wrote:

On Monday, 3 February 2020 at 16:54:20 UTC, Anonymouse wrote:
It does a `dmd.exe -of..\generated\build.exe`, but then the 
immediately following call to `..\generated\build.exe` fails? 
What am I doing wrong?


The executable was launched because make would yield a 
different error message otherwise.
This seems to be an error during the environment processing of 
build.d, could you provide the full stack trace for this 
exception?


std.process.ProcessException@std\process.d(752): Failed to 
spawn new process (The system cannot find the file specified.)


It doesn't seem to include debugging symbols. Does digger not 
build its dmds with -g?


```
std.process.ProcessException@std\process.d(752): Failed to spawn 
new process (The system cannot find the file specified.)


0x004386D0
0x00441132
0x00454B5C
0x00444994
0x0042C808
0x004039BD
0x0040257D
0x004353FB
0x0043537D
0x00435218
0x0042948B
0x76C96359 in BaseThreadInitThunk
0x77457B74 in RtlGetAppContainerNamedObjectPath
0x77457B44 in RtlGetAppContainerNamedObjectPath
```

Here's the full log: https://pastebin.com/raw/6MyVDFPc



digger: Failed to spawn new process (The system cannot find the file specified.)

2020-02-03 Thread Anonymouse via Digitalmars-d-learn
I'm trying to bisect a dmd compilation error on Windows 10 and I 
can't get digger to do more than one initial test. When preparing 
to compile the next dmd build (the BAD revision) it errors out. 
This is in a normal cmd console.


The bisect ini has nothing weird in it:

```
bad = v2.088.1
good = v2.087.1
reverse = false

tester = cd C:\Temp\init2 && C:\D\dmd2\windows\bin\dub.exe build 
2>&1 | findstr /C:"Memory allocation failed"

```


Console log excerpt:

```
[...]
digger: -- Running test command... 
---
core.exception.OutOfMemoryError@src\core\exception.d(647): Memory 
allocation failed
digger: - Test command exited with status 0 (GOOD). 
--
digger: Sanity-check, testing BAD revision 
b7a303005afce50f317c768311b71bc21d47090d...

digger: Testing revision: b7a303005afce50f317c768311b71bc21d47090d
digger: Starting at meta repository commit 
b7a303005afce50f317c768311b71bc21d47090d
digger: Building components dmd, druntime, phobos-includes, 
phobos, rdmd
digger: needInstalled: 
dmd-8a2067c4bd9c720098c8acb5429f189b12b32ab6-07d4846ed48eb28d158e52488e305015

digger: Cache miss.
digger: needBuild: 
dmd-8a2067c4bd9c720098c8acb5429f189b12b32ab6-07d4846ed48eb28d158e52488e305015

digger: Cleaning repository dmd...
HEAD is now at 758722e42 bump VERSION to v2.087.1
digger: Checking out dmd commit 
8a2067c4bd9c720098c8acb5429f189b12b32ab6...

Previous HEAD position was 758722e42 bump VERSION to v2.087.1
HEAD is now at 8a2067c4b bump VERSION to v2.088.1
digger: Building 
dmd-8a2067c4bd9c720098c8acb5429f189b12b32ab6-07d4846ed48eb28d158e52488e305015

digger: DMC=C:\Temp\work\dl\dm857-snn2074-optlink80017\bin
digger: Preparing DMD v2.079.0
digger: 
hostDC=C:\Temp\work\dl\dmd-2.079.0\dmd2/windows/bin\dmd.exe

digger: Cleaning repository dmd...
HEAD is now at 8a2067c4b bump VERSION to v2.088.1
digger: Environment: SystemDrive=C:
digger: Environment: TMPDIR=C:\Temp\work\tmp
digger: Environment: HOME=C:\Temp\work\home
digger: Environment: SystemRoot=C:\WINDOWS
digger: Environment: 
PATH=C:\Temp\work\dl\dm857-snn2074-optlink80017\bin;C:\WINDOWS\system32;C:\WINDOWS

digger: Environment: TEMP=C:\Temp\work\tmp
digger: Environment: TMP=C:\Temp\work\tmp
digger: Environment: 
DMC=C:\Temp\work\dl\dm857-snn2074-optlink80017\bin

digger: Working directory: C:\Temp\work\repo\dmd\src
digger: Running: "make" -f win32.mak ^"MODEL=32^" 
HOST_DC=C:\Temp\work\dl\dmd-2.079.0\dmd2/windows/bin\dmd.exe dmd
if not exist "..\generated\windows\release\32" mkdir 
..\generated\windows\release\32


make -fwin32.mak C=dmd\backend ROOT=dmd\root MAKE="make" 
HOST_DC="C:\Temp\work\dl\dmd-2.079.0\dmd2/windows/bin\dmd.exe" 
MODEL=32 CC="" LIB="lib" OBJ_MSVC="" "OPT=-o" "DEBUG=" "DDEBUG=" 
"DOPT=-O -release -inline" "LFLAGS=-L/delexe/la" 
..\generated\windows\release\32\dmd.exe


[...]

Digital Mars Librarian Version 8.02n
Copyright (C) Digital Mars 2000-2007 All Rights Reserved
http://www.digitalmars.com/ctg/lib.html
Digital Mars Librarian complete.

C:\Temp\work\dl\dmd-2.079.0\dmd2/windows/bin\dmd.exe 
-of..\generated\build.exe -debug build.d


..\generated\build.exe --called-from-make OS=windows 
BUILD=release MODEL=32 HOST_DMD= 
HOST_DC=C:\Temp\work\dl\dmd-2.079.0\dmd2/windows/bin\dmd.exe 
..\generated\windows\release\32\lexer.lib


std.process.ProcessException@std\process.d(752): Failed to spawn 
new process (The system cannot find the file specified.)


[...]

--- errorlevel 1

--- errorlevel 1
digger: Saving to cache.
digger: Clearing temporary cache
digger: Build failed: 
object.Exception@C:\Users\zorael\AppData\Local\dub\packages\ae-0.0.2413\ae\sys\d\manager.d(850): Command ["make", "-f", "win32.mak", "MODEL=32", "HOST_DC=C:\\Temp\\work\\dl\\dmd-2.079.0\\dmd2/windows/bin\\dmd.exe", "dmd"] failed with status 1


[...]

object.Exception@C:\Users\zorael\AppData\Local\dub\packages\digger-3.0.0-alpha-8\digger\bisect.d(89):
 BAD revision b7a303005afce50f317c768311b71bc21d47090d is not testable

[...]

Program exited with code 1
```


It does a `dmd.exe -of..\generated\build.exe`, but then the 
immediately following call to `..\generated\build.exe` fails? 
What am I doing wrong?


Re: list of all defined items in a D file

2020-01-23 Thread Anonymouse via Digitalmars-d-learn

On Thursday, 23 January 2020 at 17:10:29 UTC, berni44 wrote:
I'd like to get a list of all items (public, package, private) 
that are defined in a D file. Is there a simple way, to get 
them?


__traits(allMembers, mixin(__MODULE__))?

Replace with a full module name if not the current one. You'll 
only get their string names with that though, not aliases to the 
symbols themselves (as you would have with .tupleof). I imagine 
you could get those with __traits(getMember, moduleName, 
stringName).


Re: How to Unqual an array?

2019-11-16 Thread Anonymouse via Digitalmars-d-learn
On Saturday, 16 November 2019 at 15:20:26 UTC, James Blachly 
wrote:

On 11/16/19 9:48 AM, James Blachly wrote:
I am trying to write templated code that will take a character 
array -- mutable, const, or immutable (string).


I am aware of isSomeString, but I am still curious about Unqual 
array from a learning perspective.


https://pastebin.com/f2FUAYQT is what I use, assuming I 
understand what you want. (run.dlang.io shortening seems to be 
down.)





Re: Inspecting __traits(isDeprecated) and deprecation warnings

2019-09-26 Thread Anonymouse via Digitalmars-d-learn
On Wednesday, 25 September 2019 at 20:35:55 UTC, Boris Carvajal 
wrote:
On Wednesday, 25 September 2019 at 14:20:00 UTC, Anonymouse 
wrote:
I added some deprecations in my project and am going through 
my templates trying to silence the warnings that suddenly 
popped up. This template works, but it triggers deprecation 
warnings when I am actively trying to avoid them.


This code seems to work for classes too and even with DMD "-de" 
compiler switch.


template isMemberDeprecated(T, string name)
{
enum isMemberDeprecated = mixin(q{__traits(isDeprecated, }, 
T, ".", name, q{)});

}

https://run.dlang.io/is/iQbxOC


I think I can work with this, thanks!


Re: Inspecting __traits(isDeprecated) and deprecation warnings

2019-09-25 Thread Anonymouse via Digitalmars-d-learn
On Wednesday, 25 September 2019 at 05:57:19 UTC, Tobias Pankrath 
wrote:
Does your code work or does it not? I don't seem to unterstand 
neither what the question here is nor what the desired result 
is. Is the problem that the static reflections triggers the 
deprecation warning?


I added some deprecations in my project and am going through my 
templates trying to silence the warnings that suddenly popped up. 
This template works, but it triggers deprecation warnings when I 
am actively trying to avoid them.


getMember in _traits(isDeprecated, __traits(getMember, T, name)) 
causes a warning on deprecated symbols, which I wanted to avoid 
with isDeprecated, but I couldn't without first calling getMember 
to get the symbol to evaluate it. There's no way to combine 
isDeprecated with getMember without getting a warning.


I worked around the issue by using .tupleof instead of getMember, 
which breaks it for classes (.tupleof needs a `this` and 
SomeClass.init can't be it) but silences warnings for structs.


https://run.dlang.io/is/TVR8Cb

import std;

void main()
{
static assert(longestMemberName!Foo == "bbb".length);
}

struct Foo
{
string s;
int ii;
bool bbb;

deprecated("Use `s`")
string ;
}

template longestMemberName(T)
if (is(T == struct))
{
enum longestMemberName = ()
{
size_t maxLength;
T thing;  // need a `this`

foreach (immutable i, member; thing.tupleof)
{
static if (!__traits(isDeprecated, thing.tupleof[i]) 
&&

   !isType!(thing.tupleof[i]))
{
enum name = __traits(identifier, 
thing.tupleof[i]);

maxLength = max(maxLength, name.length);
}
}

return maxLength;
}();
}


Inspecting __traits(isDeprecated) and deprecation warnings

2019-09-24 Thread Anonymouse via Digitalmars-d-learn
I want to write a piece of code that reflects on the names of 
members of a passed struct, where some are depreacted.


https://run.dlang.io/is/P9EtRG

struct Foo
{
string s;
int ii;
bool bbb;

deprecated("Use `s`")
string ;
}

template longestMemberLength(T)
{
enum longestMemberLength = ()
{
size_t maxLength;

foreach (immutable i, immutable name; 
__traits(allMembers, T))

{
static if (!__traits(isDeprecated, 
__traits(getMember, T, name)))

{
maxLength = max(maxLength, name.length);
}
}

return maxLength;
}();
}

static assert (longestMemberLength!Foo == "bbb".length);

onlineapp.d(23): Deprecation: variable `onlineapp.Foo.` is 
deprecated - Use s


Is there any way to inspect the deprecated-ness of a member this 
way? I only have what __traits(allMembers) gives me.


Re: Deprecation message sources

2019-09-17 Thread Anonymouse via Digitalmars-d-learn
On Tuesday, 17 September 2019 at 19:31:53 UTC, Steven 
Schveighoffer wrote:
I'd hate to say the answer is to special case Nullable for so 
many functions, but what other alternative is there?


-Steve


Nullable isn't alone, std.json.JSONType causes a literal wall of 
text of deprecation warnings.


import std.stdio;
import std.json;

void main()
{
writeln(JSONValue.init.type);
}

https://run.dlang.io/is/J0UDay


Interdependent dub subpackages

2019-08-30 Thread Anonymouse via Digitalmars-d-learn
I have a project where the source is mixed library, mixed 
application, and I'd like to separate the two. The code is fairly 
decoupled as is, but the files are all next to each other in the 
same namespace.


I moved out the library parts and made a new dub package, and it 
alone compiles fine. Ideally I'd like to separate it further into 
subpackages in a tree-like structure where some depend on others 
(but not the other way around).



/dub.sdl

---
name "lu"
targetType "none"
dependency "lu:base" version="*"
dependency "lu:utils" version="*"
subPackage {
name "base"
targetType "library"
sourcePaths "base"
}
subPackage {
name "utils"
targetType "library"
sourcePaths "utils"
}
---


/base/dub.sdl

---
name "base"
targetType "library"
sourcePaths "source"
---


/utils/dub.sdl

---
name "utils"
targetType "library"
sourcePaths "source"
dependency "lu:base" version="*"
---

$ dub build
Performing "debug" build using /usr/bin/dmd for x86_64.
lu:base ~master: building configuration "library"...
lu:utils ~master: building configuration "library"...
utils/source/config.d(35,12): Error: module `common` is in file 
'lu/base/common.d' which cannot be read

import path[0] = /usr/include/dlang/dmd
/usr/bin/dmd failed with exit code 1.

The offending line is naturally `import lu.base.common;`.

Is what I'm trying to do not possible? I thought lu:utils would 
just use the generated liblu_base.a. Am I not understanding it 
right? I tried adding importPaths "." to the subPackages section 
in /dub.sdl in hope it would see it but it did nothing. 
importPaths "base" does nothing either.


Do I need to add the source paths for "upstream" subpackages 
after all? Is that kind of downward dependency tree not possible?


Re: Use std.string.lineSplitter with std.array.Appender!string

2019-08-28 Thread Anonymouse via Digitalmars-d-learn

On Wednesday, 28 August 2019 at 15:52:18 UTC, NonNull wrote:


Disambiguate how ?

```
import std.string, std.array;
auto s = appender!string;
// ...
auto a = s.lineSplitter;
```


auto a = s.data.lineSplitter;

On mobile, can't test.


Re: How to check that import module will succeed?

2019-07-26 Thread Anonymouse via Digitalmars-d-learn

On Friday, 26 July 2019 at 06:24:18 UTC, evilrat wrote:

On Friday, 26 July 2019 at 03:42:58 UTC, Andrey Zherikov wrote:
bool isModuleAvailable(alias modName)() {
mixin("import " ~ modName ~ ";");
static if (__traits(compiles, mixin(modName).stringof))
return true;
else
return false;
}

// use like this
static if (__traits(compiles, isModuleAvailable!"mymod" ))
import mymod;


I forgot the exact details but I ran into troubles with this 
where __traits(compiles, moduleName) would evaluate to false even 
if the module was available, if there were top-level errors in it.


I use __traits(compiles, __traits(identifier, moduleName)) now 
instead and it seems to work.


Re: OPTLINK : Warning 9: Unknown Option : OUT

2019-07-17 Thread Anonymouse via Digitalmars-d-learn

On Wednesday, 17 July 2019 at 17:43:53 UTC, Anonymouse wrote:

[...]


Ignore this, Logger is a class and the error is to be expected. 
Will retry dustmite.




Re: OPTLINK : Warning 9: Unknown Option : OUT

2019-07-17 Thread Anonymouse via Digitalmars-d-learn

On Tuesday, 16 July 2019 at 13:33:01 UTC, Anonymouse wrote:
I started a dustmite process, with some luck it should produce 
something smaller by tonight or tomorrow.


Reduced:

import std.experimental.logger : Logger;

void main()
{
Logger logger;
logger.error();
}


git clone https://github.com/zorael/tests -b loggererror


$ dub run
Performing "debug" build using C:\D\dmd2\windows\bin\dmd.exe for 
x86_64.

tests ~loggererror: building configuration "application"...
Linking...
Running .\tests.exe
Program exited with code -1073741819

$ dmd -oftests.exe source/app.d && ./tests.exe

object.Error@(0): Access Violation

0x00402381
0x00402357
0x00409055
0x00408EF0
0x004075A7
0x76358494 in BaseThreadInitThunk
0x775341C8 in RtlAreBitsSet
0x77534198 in RtlAreBitsSet




Re: OPTLINK : Warning 9: Unknown Option : OUT

2019-07-16 Thread Anonymouse via Digitalmars-d-learn

On Tuesday, 16 July 2019 at 13:33:01 UTC, Anonymouse wrote:

IRCParser.init.chantypes even has a default value of "#".


IRCParser.init.client.server.chantypes.


Re: OPTLINK : Warning 9: Unknown Option : OUT

2019-07-16 Thread Anonymouse via Digitalmars-d-learn

On Tuesday, 16 July 2019 at 11:20:49 UTC, Boris Carvajal wrote:


The debugger exposes a crash in memchr from C runtime.

In file messaging.d line 216 called from the unittest just below


if (emoteTarget.beginsWithOneOf(state.client.server.chantypes))


chantypes.ptr is null. However chantypes.length is 1 so you are 
assigning something invalid to it.



grep -nr "chantypes = " kameloso/


shows this place as something to care about
kameloso/source/kameloso/irc/parsing.d:1983:   chantypes = 
value;


Again, thank you for your immense help!

This is weird, chantypes should refer to a slice of immutables (a 
string). Simplified:


void onISUPPORT(ref IRCParser parser, ref string slice)
{
import std.algorithm.iteration : splitter;

foreach (string value; slice.splitter(' '))
{
// ...
parser.client.server.chantypes = value;
}
}

IRCParser.init.chantypes even has a default value of "#".

I get the same error even if I try to work around it with .idup. 
The only thing that does seem to help is checking for .ptr !is 
null at the unittest location you mention.


if (state.client.server.chantypes.ptr && 
emoteTarget.beginsWithOneOf(state.client.server.chantypes))


I started a dustmite process, with some luck it should produce 
something smaller by tonight or tomorrow.


Re: OPTLINK : Warning 9: Unknown Option : OUT

2019-07-16 Thread Anonymouse via Digitalmars-d-learn

On Monday, 15 July 2019 at 12:40:57 UTC, Boris Carvajal wrote:

On Monday, 15 July 2019 at 11:48:13 UTC, Anonymouse wrote:

I built it with:

dub fetch digger
dub run digger -- build "stable + druntime#2675"


I have not touched any digger.ini. The only one I can find is 
digger.ini.sample.


sc.ini and dub output at:

https://pastebin.com/jPnh4yEA


dub test was invoked with:
dub test 
--compiler=C:/cygwin/home/zorael/work/result/bin/dmd.exe -v


I seem to get the same errors from a Cygwin terminal as from a 
cmd one.


I'll give you another option if you just need that fix.
Patch your phobos64.lib in the original dmd install directory 
using cygwin and sed, just run this exact command on cygwin 
prompt, editing the path to your case:


sed -bi 's/%zu): /%llu):/' /c/d/dmd2/windows/lib64/phobos64.lib

you can patch the 32bit libs if you need them.
Then just run dub without "--compiler=" option to use your 
original dmd.


This works for the reduced test program but not for my whole 
project. If you wouldn't mind trying it:


git clone https://github.com/zorael/kameloso.git && cd kameloso 
&& dub test


(Windows 10, dmd 2.087 with your sed substitution)

I'll try dustmiting it later tonight.


Re: OPTLINK : Warning 9: Unknown Option : OUT

2019-07-15 Thread Anonymouse via Digitalmars-d-learn

On Monday, 15 July 2019 at 11:12:41 UTC, Vladimir Panteleev wrote:

On Monday, 15 July 2019 at 10:27:49 UTC, Anonymouse wrote:

OPTLINK : Warning 9: Unknown Option : OUT


It looks like it's trying to use MS link command-line syntax 
with DM OPTLINK.


I'm not sure why that would happen, as Digger creates a 
complete sc.ini file containing full paths to all relevant 
linkers (OPTLINK, and 32-bit / 64-bit MS link). Perhaps Dub or 
the CygWin environment is interfering somehow?


Could you please post the following:

- The Digger command-line and digger.ini you used to build D
- The contents of ...\Digger\work\result\bin\sc.ini
- Also if you could please run the Dub command with -v, and 
post the full dmd.exe command line that Dub generates and runs.


I built it with:

dub fetch digger
dub run digger -- build "stable + druntime#2675"


I have not touched any digger.ini. The only one I can find is 
digger.ini.sample.


sc.ini and dub output at:

https://pastebin.com/jPnh4yEA


dub test was invoked with:
dub test 
--compiler=C:/cygwin/home/zorael/work/result/bin/dmd.exe -v


I seem to get the same errors from a Cygwin terminal as from a 
cmd one.


OPTLINK : Warning 9: Unknown Option : OUT

2019-07-15 Thread Anonymouse via Digitalmars-d-learn
I wanted to try out druntime + a specific pull request with 
digger on Windows, and dmd and everything builds, except my 
program itself fails to link when compiled with it.


$ dub test 
--compiler=C:/cygwin/home/zorael/work/result/bin/dmd.exe

[...]
Linking...
OPTLINK (R) for Win32  Release 8.00.17
Copyright (C) Digital Mars 1989-2013  All rights reserved.
http://www.digitalmars.com/ctg/optlink.html
OPTLINK : Warning 9: Unknown Option : OUT
.dub\build\unittest-unittest-windows-x86_64-dmd_2087-54F51FF76286807F6977B498DED6593D\kameloso.obj
 Offset 0H Record Type 0064
 Error 138: Module or Dictionary corrupt
Error: linker exited with status 1
C:/cygwin/home/zorael/work/result/bin/dmd.exe failed with exit 
code 1.


If I run it from a Cygwin terminal and I comment the LINKCMD 
entry from the sc.ini by the digger dmd.exe, it defaults to its 
/usr/bin/link, which throws a similar error.


[...]
Linking...
/usr/bin/link: extra operand 
‘/OUT:.dub\\build\\unittest-unittest-windows-x86_64-dmd_2087-54F51FF76286807F6977B498DED6593D\\kameloso.exe’

Try '/usr/bin/link --help' for more information.
Error: linker exited with status 1
C:/cygwin/home/zorael/work/result/bin/dmd.exe failed with exit 
code 1.


The normally-installed dmd 2.087 works fine. What am I missing?


Re: Windows segfault, need brief help

2019-07-15 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 14 July 2019 at 08:49:43 UTC, Boris Carvajal wrote:

On Saturday, 13 July 2019 at 16:39:51 UTC, Anonymouse wrote:


Thank you!

Filed as https://issues.dlang.org/show_bug.cgi?id=20048.


https://github.com/dlang/druntime/pull/2675


Excellent, thanks!

I got OPTLINK errors while trying to confirm that it worked with 
digger, so I'll just trust it and wait for 2.088.


Re: Windows segfault, need brief help

2019-07-13 Thread Anonymouse via Digitalmars-d-learn

On Saturday, 13 July 2019 at 06:36:06 UTC, Boris Carvajal wrote:

On Friday, 12 July 2019 at 22:46:11 UTC, Anonymouse wrote:
I'm suddenly getting segfaults when running tests on Windows. 
It works fine on Linux. I reduced it to a few lines (plus a 
dependency) with dustmite, but they don't really make 
sense[1]. Nevertheless they do trigger the segfault.


Can someone with Windows 10 and dmd 2.087.0 try the following 
and see if it crashes please?


git clone https://github.com/zorael/tests -b wintestcrash && 
cd tests && dub test


I can reproduce it on Win10/x64 (qemu).
But it's really hard to debug on windows (at least with dmd and 
no V.Studio), I could only get a readable backtrace with 
"WinDbg Preview" debugger:


Thank you!

Filed as https://issues.dlang.org/show_bug.cgi?id=20048.



Re: Windows segfault, need brief help

2019-07-13 Thread Anonymouse via Digitalmars-d-learn

On Friday, 12 July 2019 at 23:05:41 UTC, Stefan Koch wrote:
[1]: 
https://github.com/zorael/tests/blob/wintestcrash/source/app.dx


maybe you haven't pushed?
I can't see it.


Sorry, typo in the link.

https://github.com/zorael/tests/blob/wintestcrash/source/app.d


Windows segfault, need brief help

2019-07-12 Thread Anonymouse via Digitalmars-d-learn
I'm suddenly getting segfaults when running tests on Windows. It 
works fine on Linux. I reduced it to a few lines (plus a 
dependency) with dustmite, but they don't really make sense[1]. 
Nevertheless they do trigger the segfault.


Can someone with Windows 10 and dmd 2.087.0 try the following and 
see if it crashes please?


git clone https://github.com/zorael/tests -b wintestcrash && cd 
tests && dub test


If it ends with an assertion failure, okay, darn. If it "exited 
with code -1073741819" I'll have confirmed it happens for more 
than just me and AppVeyor, and thus can go ahead and file a bug 
report.



Running custom 'unittest' configuration.
Performing "unittest" build using C:\D\dmd2\windows\bin\dmd.exe 
for x86_64.
cachetools 0.1.2: target for configuration "library" is up to 
date.

requests 1.0.9: target for configuration "std" is up to date.
test ~wintestcrash: building configuration "unittest"...
Linking...
To force a rebuild of up-to-date targets, run again with 
--force.

Running .\test.exe
Program exited with code -1073741819


[1]: 
https://github.com/zorael/tests/blob/wintestcrash/source/app.dx


Closures and memory allocation

2019-06-22 Thread Anonymouse via Digitalmars-d-learn
I'm looking into why my thing does so many memory allocations. 
Profiling with kcachegrind shows _d_allocmemory being called upon 
entering a certain function, lots and lots of times.


It's a function that receives concurrency messages, so it 
contains nested functions that close over local variables. Think 
receiveTimeout(0.seconds, , , , ...) with 
13 pointers to nested functions passed.


When entering the following function, does it allocate:

1. 0 times, because while there are closures defined, none is 
ever called?

2. 2 times, because there are closures over two variables?
3. 20 times, because there are 20 unique closures?

void foo()
{
int i;
long l;

void foo01(bool b_) { i += 1; }
void foo02(string s) { i += 2; }
void foo03(int n) { i += 3; }
void foo04(float f) { i += 4; }
void foo05(double d) { i += 5; }
void foo06() { i += 6; }
void foo07() { i += 7; }
void foo08() { i += 8; }
void foo09() { i += 9; }
void foo10() { i += 10; }
void foo11() { l += 11; }
void foo12() { l += 12; }
void foo13() { l += 13; }
void foo14() { l += 14; }
void foo15() { l += 15; }
void foo16() { l += 16; }
void foo17() { l += 17; }
void foo18() { l += 18; }
void foo19() { l += 19; }
void foo20() { l += 20; }

auto f01 = 
auto f02 = 
auto f03 = 
auto f04 = 
auto f05 = 
auto f06 = 
auto f07 = 
auto f08 = 
auto f09 = 
auto f10 = 
auto f11 = 
auto f12 = 
auto f13 = 
auto f14 = 
auto f15 = 
auto f16 = 
auto f17 = 
auto f18 = 
auto f19 = 
auto f20 = 
}


Re: Delegate / Error: cannot implicitly convert expression...

2019-06-15 Thread Anonymouse via Digitalmars-d-learn

On Saturday, 15 June 2019 at 15:54:00 UTC, Robert M. Münch wrote:
Why does the follwing code give: Error: cannot implicitly 
convert expression & myFunc of type void function(int a) to 
void delegate(int)



void myFunc(int a){return;}

void main()
{
   void delegate(int) dg;
   dg = 
}

See: https://run.dlang.io/is/iTYo2L


By design, I think.

"delegate and function objects cannot be mixed. But the standard 
function std.functional.toDelegate converts a function to a 
delegate."


Your example compiles if the assignment is changed to dg = 
toDelegate(); (given appropriate imports).


https://tour.dlang.org/tour/en/basics/delegates

https://dlang.org/phobos/std_functional.html#.toDelegate


Re: How to walk over two arrays by ref in beautyfull way?

2019-06-10 Thread Anonymouse via Digitalmars-d-learn

On Monday, 10 June 2019 at 08:02:18 UTC, vitalfadeev wrote:

On Monday, 10 June 2019 at 07:45:42 UTC, vitalfadeev wrote:

On Monday, 10 June 2019 at 07:41:40 UTC, vitalfadeev wrote:

How to?

I plan scan First array with checkers:
[checker, checker, checker]

...and store result to Second array:
[0, 0, 1]

In next code 'r' not reference. But expected ref.

import std.range : zip;

foreach(checker, ref r; zip(checkers, result.set)) {
   r = checker();
}


Replace zip with lockstep and your example works.

"zip is similar to lockstep, but lockstep doesn't bundle its 
elements and uses the opApply protocol. lockstep allows reference 
access to the elements in foreach iterations."


https://dlang.org/library/std/range/zip.html

"Function lockstep

Iterate multiple ranges in lockstep using a foreach loop. In 
contrast to zip it allows reference access to its elements."


https://dlang.org/library/std/range/lockstep.html


Re: 'version'-based code selection

2019-06-02 Thread Anonymouse via Digitalmars-d-learn

On Saturday, 1 June 2019 at 07:46:40 UTC, Jonathan M Davis wrote:
For the most part though, you don't declare your own version 
identifiers. It sometimes makes sense, but usually, version 
identifiers are used for versioning code based on the platform 
or architecture that it's compiled on. They're really only 
intended to be a saner version of #ifdefs, and if you're doing 
anything fancy with them, you're really not using them as 
intended and are probably going to have problems.


I use versioning pervasively to make features opt-in/opt-out at 
compile-time.


Like so, from dub.json:

"versions":
[
"AsAnApplication",
"WithAdminPlugin",
"WithAutomodePlugin",
"WithBashQuotesPlugin",
"WithChanQueriesService",
"WithChatbotPlugin",
"WithConnectService",
"WithCTCPService",
"WithHelpPlugin",
"WithNotesPlugin",
"WithPersistenceService",
"WithPipelinePlugin",
"WithPrinterPlugin",
"WithQuotesPlugin",
"WithSedReplacePlugin",
"WithSeenPlugin",
"WithWebtitlesPlugin"
],

---

module foo;

version(WithFoo):

// ...

Is this recommended against? It's a very convenient way of 
enabling and disabling modules outright, since (by default) dub 
eagerly compiles everything it sees. I haven't had any problems 
with it as of yet, at the very least.




Re: [dub] Passing --DRT-gcopt to dmd

2019-05-31 Thread Anonymouse via Digitalmars-d-learn

On Friday, 31 May 2019 at 13:50:57 UTC, Andre Pany wrote:

You can specify the parameters also in code. See example here

https://dlang.org/changelog/2.085.0.html#gc_cleanup


I need it to apply to dmd though, I'm exceeding memory limits 
when compiling. Once done the program doesn't need a whole lot of 
it, but dmd -lowmem does.


Re: [dub] Passing --DRT-gcopt to dmd

2019-05-31 Thread Anonymouse via Digitalmars-d-learn

On Friday, 31 May 2019 at 15:31:13 UTC, kinke wrote:

On Friday, 31 May 2019 at 10:27:44 UTC, Anonymouse wrote:

$ grep dflags dub.json
"dflags": [ "-lowmem", "--DRT-gcopt=profile:1" ],


This should work indeed. I guess it doesn't because dub 
probably uses a response file containing all cmdline options, 
whereas -lowmem definitely [and --DRT-* probably] need to be 
direct cmdline args.


Is this something I can/should report? (Where do dub issues go?)


Re: [dub] Passing --DRT-gcopt to dmd

2019-05-31 Thread Anonymouse via Digitalmars-d-learn

On Friday, 31 May 2019 at 10:47:20 UTC, Mike Parker wrote:

On Friday, 31 May 2019 at 10:27:44 UTC, Anonymouse wrote:


What is the correct way?


--DRT flags are for run time, not compile time. They're 
intended to be passed to your executable and not the compiler. 
From the docs [1]:


"By default, GC options can only be passed on the command line 
of the program to run"


My use-case is limiting the amount of memory dmd will allocate 
before -lowmem kicks in and collects (by use of 
--DRT-gcopt=heapSizeFactor on dmd), to accomodate for limited 
available memory. As pasted in the original post I seem to be 
able to do this manually.


So there is no way to set up a dub build configuration that 
automates this?


[dub] Passing --DRT-gcopt to dmd

2019-05-31 Thread Anonymouse via Digitalmars-d-learn
I'm trying to tweak the GC when compiling with dub, starting with 
something easy like profile:1.



$ grep dflags dub.json
"dflags": [ "-lowmem", "--DRT-gcopt=profile:1" ],
$ dub test


Doesn't work, doesn't give any extra output. Entering bogus flags 
like --DRT-gcopt=banana:1 doesn't evoke any error message either, 
making me doubt it's being passed on at all.



$ dmd -oftest -lowmem --DRT-gcopt=profile:1 source/**/*.d
Number of collections:  13
Total GC prep time:  7 milliseconds
Total mark time:  2110 milliseconds
Total sweep time:  270 milliseconds
Total page recovery time:  204 milliseconds
Max Pause Time:  472 milliseconds
Grand total GC time:  2592 milliseconds
GC summary: 1099 MB,   13 GC 2592 ms, Pauses 2117 ms <  472 ms


Manual dmd invocation does work, so it's not like dmd is ignoring 
--DRT-gcopt.



$ dub test --DRT-gcopt=profile:1
[...]
Number of collections:  10
Total GC prep time:  0 milliseconds
Total mark time:  4 milliseconds
Total sweep time:  7 milliseconds
Total page recovery time:  4 milliseconds
Max Pause Time:  0 milliseconds
Grand total GC time:  15 milliseconds
GC summary:   12 MB,   10 GC   15 ms, Pauses4 ms <0 ms


The totals should be in the ballpark of 1Gb+ (as above), not 
12Mb. Is it only profiling dub itself? (Incidentally this is 
roughly what dmd reports if called without -lowmem.)



$ export DRT_GCOPT=profile:1
$ dub test


Doesn't work either, I can't actually get the env var to affect 
dmd at all, even when manually running it.


What is the correct way?


Re: Tweakig -lowmem to be more eager

2019-05-21 Thread Anonymouse via Digitalmars-d-learn

On Monday, 20 May 2019 at 13:41:15 UTC, Boris-Barboris wrote:

On Sunday, 19 May 2019 at 23:54:27 UTC, Anonymouse wrote:

What makes it decide to collect? What triggers it?


You can try setting heapSizeFactor option to something lower 
than 2 to increase collection frequency:

https://github.com/dlang/druntime/blob/47b03c14a1097d28afcf22f645628ba4046377bd/src/core/gc/config.d#L26
https://dlang.org/spec/garbage.html#gc_config

dmd appears to respect DRT_GCOPT environment variable.


This does look like what I need. I'm having no luck with 
DRT_GCOPT though.


$ dmd "--DRT-gcopt=heapSizeFactor=1.5 profile:1" hello.d
Number of collections:  2
Total GC prep time:  0 milliseconds
Total mark time:  0 milliseconds
Total sweep time:  0 milliseconds
Total page recovery time:  0 milliseconds
Max Pause Time:  0 milliseconds
Grand total GC time:  0 milliseconds
GC summary:5 MB,2 GC0 ms, Pauses0 ms <0 ms

$ DRT_GCOPT="heapSizeFactor=1.5 profile:1" dmd hello.d
[no output]

Are you sure dmd honours it? I can't grep rt_envvars_enabled in 
the dmd sources.


How can I otherwise get dub to pass these onto dmd?


Re: Tweakig -lowmem to be more eager

2019-05-19 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 19 May 2019 at 23:54:27 UTC, Anonymouse wrote:

Tweakig


I'd edit the title if I could. Grumble mutter.


Tweakig -lowmem to be more eager

2019-05-19 Thread Anonymouse via Digitalmars-d-learn

I have CircleCI set up to test my project when I push to GitHub.

For a free user there the memory restriction is pretty severe (4 
Gb), and as such non-trivial programs cannot be compiled without 
separate compilation.


This sounded like a clear-cut case for -lowmem, but the process 
is still killed from allocating too much.


circleci@ab1d64fc40cf:~/project$ dub test
Running custom 'unittest' configuration.
Performing "unittest" build using /usr/bin/dmd for x86_64.
cachetools 0.1.2: building configuration "library"...
requests 1.0.8: building configuration "std"...
kameloso 1.1.3+commit.31.g11ba25fd: building configuration 
"unittest"...

Killed
/usr/bin/dmd failed with exit code 137.

dub test -v shows -lowmem being properly passed to dmd.

What makes it decide to collect? What triggers it?



Re: Nothing at all compiles with -m64 on Windows

2019-05-11 Thread Anonymouse via Digitalmars-d-learn

On Tuesday, 7 May 2019 at 17:33:22 UTC, Ron Tarrant wrote:
I've had this happen, too. I don't know for sure, but I think 
it may be because the installers aren't prepared to do updates, 
not on Windows, anyway.


My best success for updating has been to scrape D completely 
off my drive (ie. uninstall DMC and DMD using Control Panel > 
Programs and Features) then reinstall from scratch.


I only had DMD installed, but I uninstalled it and reinstalled to 
no effect.


Removing Visual Studio 2017 did fix it though, which is both a 
relief and to some dismay.


Nothing at all compiles with -m64 on Windows

2019-05-07 Thread Anonymouse via Digitalmars-d-learn
Everything, even an empty void main, fails to compile in -m64 on 
this machine running Windows. -m32 works. dmd was installed with 
the .exe installer. It used to work and I forget what version of 
dmd I had, but then I upgraded to 2.086 and now it doesn't. I've 
tried reverting as far back as 2.079 but the behaviour persists.


void main() {}


dmd -m64 main.d
libcmt.lib(utility_desktop.obj) : error LNK2019: unresolved 
external symbol __imp_RtlLookupFunctionEntry referenced in 
function __scrt_fastfail
libvcruntime.lib(risctrnsctrl.obj) : error LNK2001: unresolved 
external symbol __imp_RtlLookupFunctionEntry
libucrt.lib(invalid_parameter.obj) : error LNK2001: unresolved 
external symbol __imp_RtlLookupFunctionEntry
libcmt.lib(gs_report.obj) : error LNK2001: unresolved external 
symbol __imp_RtlLookupFunctionEntry
libcmt.lib(utility_desktop.obj) : error LNK2019: unresolved 
external symbol __imp_RtlVirtualUnwind referenced in function 
__scrt_fastfail
libucrt.lib(invalid_parameter.obj) : error LNK2001: unresolved 
external symbol __imp_RtlVirtualUnwind
libcmt.lib(gs_report.obj) : error LNK2001: unresolved external 
symbol __imp_RtlVirtualUnwind
libvcruntime.lib(_riscchandler_.obj) : error LNK2019: unresolved 
external symbol __imp_RtlUnwindEx referenced in function 
__C_specific_handler
libvcruntime.lib(risctrnsctrl.obj) : error LNK2001: unresolved 
external symbol __imp_RtlUnwindEx
libvcruntime.lib(throw.obj) : error LNK2019: unresolved external 
symbol __imp_RtlPcToFileHeader referenced in function 
_CxxThrowException

main.exe : fatal error LNK1120: 4 unresolved externals
Error: linker exited with status 1120


 adam_d_ruppe | looks like it didnt include the normal crt
alphaglosined | think so?
 adam_d_ruppe | well wait that IS the normal crt referencing 
something else

 adam_d_ruppe | weird
alphaglosined | yeah


Obviously something is wrong with the environment/setup. What can 
I do?


Setting process name

2019-05-01 Thread Anonymouse via Digitalmars-d-learn
Is there a way of setting the process/thread name that's neater 
than this?


import core.sys.posix.pthread;

extern(C) int pthread_setname_np(pthread_t, const char*);

void main()
{
import std.string : toStringz;
pthread_setname_np(pthread_self(), toStringz("thread_name"));
// ...
}

It seems to work, but it also seems peculiar that 
pthread_setname_np isn't in core.sys.posix.pthread with the rest. 
Why is this? Is there an easier way? Thread.getThis().name 
doesn't seem to be it.



https://forum.dlang.org/thread/gudwwmmdcqrfhbdux...@forum.dlang.org


Re: Trying to extract string from curl redirected URL

2019-02-10 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 10 February 2019 at 14:12:02 UTC, Josh wrote:
Is there something I'm missing? It it possible to access the 
private handle? Is there a better way to do what I'm trying to 
achieve?


Assuming I'm understanding your question (you want to get the 
path of a URL after redirects), if you're not adverse to 
dependencies you could use requests; 
https://code.dlang.org/packages/requests.


Create a Request, query an URL for a Response and then access its 
finalURI member. Then parse the path string normally to get the 
session ID, such as with std.algorithm.findSplit and friends or 
with regex.


import requests;

Request req;
Response res = req.get("https://website.com/;);

string id = res.finalURI.path
.findSplit("?s=")[2]
.findSplitBefore("&")[0];

if (!id.length) { /* no ID in URL */ }



  1   2   >