Re: Selective unittesting in DUB

2020-12-01 Thread Johannes Loher via Digitalmars-d-learn
Am 01.12.20 um 08:11 schrieb ryuukk_:
> Running .\dawn-test-application.exe
> 2 modules passed unittests
> 
> 
> Wich ones? it should print
> 
> 
> ```
> Running tests for target X
> 
> - src/module_a.d Tests: OK   <-- line in green
> - src/module_b.d Tests: OK
> - src/module_c.d Tests: OK
> - src/module_e.d Tests: FAIL <-- line in red
> 
> 3 modules passed, 1 failed
> 
> ```
> 
> 

>From what I understand, the default test runner is intentionally being
kept quite simple. There are some libraries that provide test runners
that do what you expect (e.g. [1], [2], [3], there is probably more).

[1] https://code.dlang.org/packages/silly
[2] https://code.dlang.org/packages/unit-threaded
[3] https://code.dlang.org/packages/trial


Re: Running unit tests from DUB single file packages

2020-12-01 Thread Johannes Loher via Digitalmars-d-learn
Am 01.12.20 um 14:55 schrieb drug:
> On 12/1/20 2:40 PM, Johannes Loher wrote:
>> ...
>> However, I am having trouble running the unit tests when using the
>> ...
> 
> This can be one of solution https://github.com/dlang/dub/pull/2050
> 

Thanks! Let's see if it gets merged or if a slightly more involved
solution is needed.


Re: Running unit tests from DUB single file packages

2020-12-01 Thread Johannes Loher via Digitalmars-d-learn
Am 01.12.20 um 14:52 schrieb jmh530:
> On Tuesday, 1 December 2020 at 13:52:35 UTC, jmh530 wrote:
>> On Tuesday, 1 December 2020 at 11:40:38 UTC, Johannes Loher wrote:
>>> [snip]
>>>
>>> Any hints on how to execute unit tests from single file DUB packages?
>>> Is it even possible at the moment? Thanks in advance for any help!
>>>
>>>
>>> [1] https://adventofcode.com/
>>
>> Have you tried it without the imports?
> 
> Or rather, without the dependency.

The point of using DUB (and the single file package format) is easy
access to libraries from the DUB registry. If I didn't want to use a
dependency, I would not be using DUB at all. That said, leaving out the
dependency does not solve the issue, it also occurs with the following
source file:

```
#!/usr/bin/env dub
/+ dub.sdl:
name "main"
+/

void main() {}

unittest {
assert(true);
}
```

```
johannesloher@saiph:~> dub test --single main.d

Package main (configuration "application") defines no import paths, use
{"importPaths": [...]} or the default package directory structure to fix
this.

Generating test runner configuration 'main-test-application' for
'application' (executable).

Source file '/home/johannesloher/main.d' not found in any import path.
```


Running unit tests from DUB single file packages

2020-12-01 Thread Johannes Loher via Digitalmars-d-learn
Hello everybody,

when solving today's problem for the adventofcode [1], I decided to try
out DUB's single file package feature, in order to keep things short.

When doing the adventofcode, I always use the given examples as unit
tests in order to verify that my solutions are actually correct.
However, I am having trouble running the unit tests when using the
single file package format:

```
johannesloher@saiph:..020/day1/part1-mir(master)> dub test --single
main.d

Package main (configuration "application") defines no import paths, use
{"importPaths": [...]} or the default package directory structure to fix
this.

Generating test runner configuration 'main-test-application' for
'application' (executable).

Source file
'/home/johannesloher/Development/aoc2020/day1/part1-mir/main.d' not
found in any import path.
```

I tried defining `importPaths` as suggested in the error message but
apparently that's not possible for single file packages:

```
Single-file packages are not allowed to specify import paths.
```

WARNING: Spoilers for day 1 of the adventofcode, please stop reading if
you have not solved it yet and want to do so by yourself.

Here is the source for my main.d file:

```
#!/usr/bin/env dub
/+ dub.sdl:
name "main"
dependency "mir-algorithm" version="~>3.10.12"
+/

import std;
import mir.combinatorics;

void main()
{
File("input",
"r").byLine.map!(to!int).array.multiplyNEntriesThatSumTo(2, 2020).writeln;
}

alias product = partial!(reverseArgs!(fold!((a, b) => a * b)), 1);

int multiplyNEntriesThatSumTo(int[] input, int n, int requiredSum)
{
return input.combinations(n).filter!(combination => combination.sum
== requiredSum)
.map!(combination => combination.product)
.front;
}

unittest
{
auto input = [1721, 979, 366, 299, 675, 1456];

assert(input.multiplyNEntriesThatSumTo(2, 2020) == 514_579);
}
```

Any hints on how to execute unit tests from single file DUB packages? Is
it even possible at the moment? Thanks in advance for any help!


[1] https://adventofcode.com/


Re: isInputRange not satisfied even if all individual conditions are satisfied

2020-06-26 Thread Johannes Loher via Digitalmars-d-learn
Am 26.06.20 um 15:35 schrieb ag0aep6g:
> `isInputRange!R` fails because it has no knowledge of your free `empty`
> function. Without `empty`, `R` is obviously not a range.

Ah, OK, that makes sense. It's kind of sad though because it really
limits the extensibility of existing types with UFCS. Do you know if
there is a way around this?


isInputRange not satisfied even if all individual conditions are satisfied

2020-06-26 Thread Johannes Loher via Digitalmars-d-learn
Recently, I read about problems regarding the API design of ranges (not
being able to make them const, differences between class and struct
based ranges etc.).

One of the issues that came up what the fact that sometimes it is useful
to use the class wrappers `InputRangeObject` etc. if you need to decide
at runtime which range you want to use. I ran into this into a personal
project in the past and this also was how I solved the issue.

Another suggestion in that thread was to simply use choose, which I
guess should work, but I had trouble getting it to work in my particular
case.

However, a third option came to my mind: Why not simply use a sumtype to
return either one range or the other? In order to make it more
convenient to use afterwards, it would be useful if we could regard a
sumtype of ranges as a range itself. That should be no problem because
we just need to delegate all function calls to the range api to the
actual range that sits inside the sumtype.

So I tried to implement this and it kind of seems to work (I can call
the individual functions on the sumtype using UFCS) but for some reason,
`isInputRange` evaluates to `false`. What makes it even weirder is the
fact that all individual conditions that are part of `isInputRange` seem
to be fulfilled. Could somebody explain to me what is going on? Here is
the code:

https://run.dlang.io/gist/93bcc196f73b0a7c7aa1851beef59c22 (currently
give me a 502 though)

```
#!/usr/bin/env dub
/+ dub.sdl:
name "sumtype-range"
dependency "sumtype" version="~>0.9.4"
+/

module sumtype_range;

import std.meta : allSatisfy, staticMap;
import std.traits : allSameType;
import std.range : isInputRange, ElementType, empty;

import sumtype;

private template EmptyLambda(T) if (isInputRange!T)
{
alias EmptyLambda = (ref T t) => t.empty;
}

@property bool empty(TypeArgs...)(auto ref scope SumType!(TypeArgs) r)
if (allSatisfy!(isInputRange, TypeArgs) && TypeArgs.length > 0)
{
return r.match!(staticMap!(EmptyLambda, TypeArgs));
}

private template FrontLambda(T) if (isInputRange!T)
{
alias FrontLambda = (ref T t) => t.front;
}

@property ElementType!(TypeArgs[0]) front(TypeArgs...)(auto ref scope
SumType!(TypeArgs) r)
if (allSatisfy!(isInputRange, TypeArgs)
&& allSameType!(staticMap!(ElementType, TypeArgs)) &&
TypeArgs.length > 0)
{
return r.match!(staticMap!(FrontLambda, TypeArgs));
}

private template PopFrontLambda(T) if (isInputRange!T)
{
alias PopFrontLambda = (ref T t) => t.popFront();
}

void popFront(TypeArgs...)(auto ref scope SumType!(TypeArgs) r)
if (allSatisfy!(isInputRange, TypeArgs) && TypeArgs.length > 0)
{
return r.match!(staticMap!(PopFrontLambda, TypeArgs));
}

enum bool myIsInputRange(R) =
is(typeof(R.init) == R)
&& is(ReturnType!((R r) => r.empty) == bool)
&& is(typeof((return ref R r) => r.front))
&& !is(ReturnType!((R r) => r.front) == void)
&& is(typeof((R r) => r.popFront));

void main() {
import std.range : iota, only;
import std.stdio : writeln;
import std.traits : ReturnType;

auto i = iota(4);
auto o = only(1);
alias R = SumType!(typeof(i), typeof(o));

// all individual conditions of `isInputRange` are satisfied
static assert(is(typeof(R.init) == R));
static assert(is(ReturnType!((R r) => r.empty) == bool));
static assert(is(typeof((return ref R r) => r.front)));
static assert(!is(ReturnType!((R r) => r.front) == void));
static assert(is(typeof((R r) => r.popFront)));

// but `isInputRange` is not satisfied
static assert(!isInputRange!(R));

// and neither is a local copy
static assert(!myIsInputRange!(R));
}
```


Re: Why is it possible to call non-const member functions of rvalues but a compile error to modify members or rvalues directly?

2020-06-14 Thread Johannes Loher via Digitalmars-d-learn

On Saturday, 13 June 2020 at 12:47:31 UTC, Stanislav Blinov wrote:

[...]
The temporary exists until the end of full expression, or until 
the end of enclosing statement. It is simply not an lvalue for 
the caller, but it certainly exists, and so its interface must 
function.


So public data members are not part of the interface? I 
understand that it probably doesn't make much sense to mutate 
data members of an rvalue but this just looks very inconsistent 
to me, in particular if you consider the fact that you can also 
call member functions with the = syntax:

```
struct A
{

auto a(int _a)
{
return this._a = _a;
}

int _a = 0;
}

void main
{
static assert(__traits(compiles, { A().a = 2; })); // this is 
ok but looks like it shouldn’t be

}
```


Why is it possible to call non-const member functions of rvalues but a compile error to modify members or rvalues directly?

2020-06-13 Thread Johannes Loher via Digitalmars-d-learn
Consider the following example:

```
struct A
{

auto a(int _a)
{
return this._a = _a;
}

int _a = 0;
}

void main()
{
static assert(!__traits(compiles, { A()._a = 2; }));
static assert(__traits(compiles, { A().a(2); }));
}
```
(https://run.dlang.io/is/GkmpA8)

Why is it a compile error to set `_a` directly but calling `a` just
works fine?

If we prevent modifying members of rvalues directly, I would also expect
calling non-const member functions of rvalues to be prevented.


Re: I want Sublime 3 D auto import !

2020-06-01 Thread Johannes Loher via Digitalmars-d-learn

On Monday, 1 June 2020 at 16:18:44 UTC, Виталий Фадеев wrote:

I want Sublime D auto import !

When typing code like this:


class Uno : IStylable
{
//
}


I want will be auto added "import IStylable" at begin of file. 
Like this:



import ui.istylable : IStylable;

class Uno : IStylable
{
//
}


1. I want for plugin will scan all files in project, and grep 
for "module ".

2. Then "module " replaced to "import ".
3. Then "import " inserted in text. At top. After line 
"module ..." if it exist, else just at top.

4. Check for "module " not exists before insert.


Demanding stuff usually doesn't work in this community. The usual 
answer is something like this: If you care about this, implement 
it yourself or pay somebody to do it.




Re: how to achieve C's Token Pasting (##) Operator to generate variable name in D?

2020-05-30 Thread Johannes Loher via Digitalmars-d-learn

On Saturday, 30 May 2020 at 23:39:31 UTC, mw wrote:

On Saturday, 30 May 2020 at 22:21:14 UTC, Paul Backus wrote:

[...]



Thank you all for the reply.

I hate to write boilerplate code:

[...]


import std.stdio : writeln;

mixin template f(T, string name, T value = T.init)
{
mixin("T _" ~ name ~ " = value;");
}

void main()
{
mixin f!(int, "x", 3);
_x.writeln; // prints 3
mixin f!(float, "y", 1.23f);
_y.writeln; // prints 1.23
mixin f!(string, "z");
_z.writeln; // prints an empty string (== string.init)
}



Re: Determining @trusted-status

2020-05-28 Thread Johannes Loher via Digitalmars-d-learn

On Friday, 29 May 2020 at 00:09:56 UTC, Clarice wrote:
It seems that @safe will be de jure, whether by the current 
state of DIP1028 or otherwise. However, I'm unsure how to 
responsibly determine whether a FFI may be @trusted: the type 
signature and the body. Should I run, for example, a C library 
through valgrind to observe any memory leaks/corruption? Is it 
enough to trust the authors of a library (e.g. SDL and OpenAL) 
where applying @trusted is acceptable?
There's probably no one right answer, but I'd be very thankful 
for some clarity, regardless.


In theory, you should probably actually verify the code of the 
library you are using by any means. That can be very broad and 
range from looking at the code, using static analysis tools, 
valgrind to fuzzing.


In practice, it really depends on how certain you need to be that 
your code is free of memory corruption errors and how much you 
trust the authors of the library (however, if they don't claim to 
have a safe interface, don't assume anything ;)).


Re: A custom name for variables

2020-05-28 Thread Johannes Loher via Digitalmars-d-learn

On Thursday, 28 May 2020 at 20:26:55 UTC, Quantium wrote:

I need to create a variable with custom name, like this
import std;
void main()
{
string name;
readf(" %s", );
// some code that generates a variable of type integer and 
value 0

}
Could you help me with that?


Do you want to create a variable with the name read with readf? 
If yes, that is not possible. Variable names need to be known at 
compile time.


Re: What's the best way to find out which exceptions may be thrown ?

2020-05-27 Thread Johannes Loher via Digitalmars-d-learn
Am 27.05.20 um 12:30 schrieb wjoe:
> 
> Could you please elaborate why checked exceptions are more annoying?
> 
> The only exposure to checked exceptions I had was with Java and I always
> liked and appreciated them.
> It's super annoying the fiddle around with catch(Exception) all over the
> place and log unhandled Exceptions and never be sure that all exceptions
> are properly taken care of.
>
There are several reasons. Walter elaborates on some of them in the
thread regarding the acceptance of DIP1028 in the announce section.
Another example is the fact that they don't work with functional
interfaces in Java: You cannot pass a function that throws checked
exceptions to map etc.


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

2020-05-27 Thread Johannes Loher via Digitalmars-d-learn

On Tuesday, 26 May 2020 at 22:23:19 UTC, bauss wrote:

On Tuesday, 26 May 2020 at 12:08:29 UTC, Johannes Loher wrote:

[...]

You can just do this to get around it:

 auto button = this;
 log();


True, somebody else posted the same idea already. But as 
explained, it doesn't do the correct thing.


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

2020-05-26 Thread Johannes Loher via Digitalmars-d-learn
Am 26.05.20 um 16:17 schrieb Vinod K Chandran:
> On Tuesday, 26 May 2020 at 13:48:52 UTC, ag0aep6g wrote:
>> On 26.05.20 15:43, Vinod K Chandran wrote:
>>> So far now, two solutions are very clear for this problem.
>>> 1. As per John Chapman's suggestion - use
>>> cast(DWORD_PTR)cast(void*)this).
>>> 2. Use another varibale to use as an lvalue. -
>>>   Button dummyBtn = this;
>>>   cast(DWORD_PTR)
>>> Among these two, i think 2nd option is good. Am i right ?
>>
>> No. Use option 1.
> 
> Could you please tell me why ?
With option 2, you will not actually get a pointer to the object but a
pointer to the local variable which is a reference to the object. `this`
and the local variable both are references to the object, so internally
they already are pointers. Their usage is just restricted in regular D
code. This is also why simply casting it to a pointer works. You need to
cast to void* in between because that's just the way to tell the
compiler to ignore the restrictions you usually have for references.


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

2020-05-26 Thread Johannes Loher via Digitalmars-d-learn

On Tuesday, 26 May 2020 at 12:08:29 UTC, Johannes Loher wrote:

[...]


Small correction: I said that this is an lvalue and that you 
cannot take the address of lvalues. Of course that is incorrect, 
I meant to say that rvalues (this is an rvalue and you cannot 
take the address of rvalues).


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

2020-05-26 Thread Johannes Loher via Digitalmars-d-learn

On Tuesday, 26 May 2020 at 11:44:58 UTC, Vinod K Chandran wrote:

On Monday, 25 May 2020 at 16:39:30 UTC, Mike Parker wrote:

On Monday, 25 May 2020 at 08:39:23 UTC, John Burton wrote:


I believe that in D *this* is a reference to the
object and not a pointer like in C++.
So I think that writing  might be what you need?


No. A class reference is a pointer under the hood. Getting its 
address will result in a pointer to the reference variable 
itself, not to the class instance. When passing a reference to 
a C API, casting it directly to the C type is correct.


Try this code. This will reproduce the same error.
import std.stdio : log = writeln;



void main() {
 log("Let's check whether 'this' is an lvalue or not.");
 Button btn = new Button("A button");
}

class Button {
this(string btntext){
mtext = btntext;
log("button created with the name , ", btntext);
log();
}
private:
string mt
}

It doesn't compile, the line

string mt

should be

string mtext;

instead. Indeed, we get a compiler error:

Error: this is not an lvalue and cannot be modified.

The problem is in line 11: You are trying to get the address of 
`this`. But `this` is an lvalue, so it does not have an address 
you could take. It becomes mir clear that this doesn’t work if 
you consider other lvalues, like literals:


int* = &1; // doesn’t compile, can’t take the address of an 
lvalue.


In this code example, the correct thing to do is to simply not 
take the address but pass `this` to `writeln`. That compiles and 
results in the following output:


Let's check whether 'this' is an lvalue or not.
button created with the name , A button
onlineapp.Button

(The module is onlineapp because I ran it in run.dlang.io)

I don't know what the correct thing would be in your original 
code though.




Re: Unexpectedly nice case of auto return type

2019-12-06 Thread Johannes Loher via Digitalmars-d-learn

On Tuesday, 3 December 2019 at 10:06:22 UTC, Mike Parker wrote:

On Tuesday, 3 December 2019 at 10:03:22 UTC, Basile B. wrote:



That's interesting details of D developement. Since you reply 
to the first message I think you have not followed but in the 
last reply I told that maybe we should be able to name the 
type of null. I think this relates to TBottom too a bit.


https://github.com/dlang/DIPs/blob/40352337053998885fbd0fe2718c300a322d3996/DIPs/DIP1NNN-DK.md


This is everything I wished for. It basically exactly resembles 
the results of the lengthy discussion H. S. Theo and I had in the 
review thread for Walter‘s original bottom type suggestion. And 
it even covers a few additional details we had not thought about. 
I can’t wait for this DIP to go into review. Thanks a lot to the 
DIP author. You have my biggest respect for writing a fleshed out 
proposal of this!




Re: Throwing from a lambda isn't supported by the compiler

2019-09-09 Thread Johannes Loher via Digitalmars-d-learn

On Monday, 9 September 2019 at 10:46:10 UTC, Dennis wrote:
Such a shame it got rejected in favor of ugly 'no return' 
annotations [...]


This is incorrect. It was rejected because the proposal was not 
solid enough. While it is true that a lot of people seemed to 
prefer an annotation based solution during the discussion, no 
such solution has been accepted into the language yet (at least 
as far as I know). Personally, I favor the bottom type solution 
and the problems described in this thread could be part of a good 
rationale for a new DIP proposing a bottom type. It just needs 
somebody to come up with a solid proposal.


Re: How should I sort a doubly linked list the D way?

2019-08-13 Thread Johannes Loher via Digitalmars-d-learn
Am 13.08.19 um 11:48 schrieb Mirjam Akkersdijk:
> Hello there,
> If I had a DLL, how would I sort it judging by the node contents, the D
> way?
> 
> In C if I were to sort a piece of malloc'd memory pointing to node
> pointers, I would write my compare function and let qsort sort it out.
> In D, I tried to use std.algorithm's sort functionality to no avail,
> because my guess would be it only operates on arrays. This opens up
> another can of worms as I am not fond of VLAs and D desperately wants to
> know what the size is at compile time.
> 
> Let's say we this trivial implementation:
> 
> Node* get_node(DLL* list, uint index);
> 
> struct Node {
>   int x;
>   Node* prev, next;
> };
> 
> struct DLL {
>   Node* head;
>   uint size;
> };
> 
> Node** nodes = cast(Node**) malloc(DLL.size * (Node*).sizeof);
> 
> and I would like to sort based on Node.t, how should I tackle it,
> preferably without resorting to C libraries?

I'd do something along the lines of this:

```
import std;

struct Node(T)
{
private:
typeof(this)* prev, next;
public:
T data;
}

struct DoublyLinkedList(T)
{
private:
Node!T* head = null;
Node!T* tail = null;

public:
void pushFront(T t)
{
auto n = new Node!T;
if (head != null)
{
head.prev = n;
}
else
{
tail = n;
}
n.data = t;
n.next = head;
head = n;
}

T front() const @property
{
return head.data;
}

void popFront()
{
head = head.next;
if (head != null)
{
head.prev = null;
}
else
{
tail = null;
}
}

void pushBack(T t)
{
auto n = new Node!T;
if (tail != null)
{
tail.next = n;
}
else
{
head = n;
}
n.data = t;
n.prev = tail;
tail = n;
}

T back() const @property
{
return tail.data;
}

void popBack()
{
tail = tail.prev;
if (tail != null)
{
tail.next = null;
}
else
{
head = null;
}
}

size_t empty() const @property
{
return head == null;
}

auto nodes() @property
{
static struct NodePointerRange
{
private:
Node!T* head;

public:
Node!T* front() @property
{
return head;
}

void popFront()
{
head = head.next;
}

bool empty() const @property
{
return head == null;
}
}

return NodePointerRange(head);
}
}

auto doublyLinkedList(R)(R r) if (isInputRange!R)
{
DoublyLinkedList!(ElementType!R) list;

foreach (e; r)
{
list.pushBack(e);
}
return list;
}

auto doublyLinkedListFromNodePointerRange(R)(R r)
if (isInputRange!R && isPointer!(ElementType!R)
&& isInstanceOf!(Node, PointerTarget!(ElementType!R)))
{
DoublyLinkedList!(TemplateArgsOf!(PointerTarget!(ElementType!R))) list;
foreach (n; r)
{
n.prev = list.tail;
if (list.tail != null)
{
list.tail.next = n;
}
else
{
list.head = n;
}
list.tail = n;
}
list.tail.next = null;
return list;
}

void main()
{
auto list = doublyLinkedList([5, 3, 7, 24, 1]);
// looks natural but allocates new nodes
auto sortedList = list.array.sort.doublyLinkedList;
sortedList.each!writeln;

writeln;

auto anotherList = doublyLinkedList([54, 23, 8]);
// looks a bit uglier but reuses the already allocated nodes
auto anotherSortedList = anotherList.nodes
.array
.sort!((n1, n2) => n1.data < n2.data)
.doublyLinkedListFromNodePointerRange;
anotherSortedList.each!writeln;
}
```

Modulo bugs of course ;)

This uses the GC. If you want to avoid it in favor of malloc (or
std.experimental.allocator), you need to add `free`s (and possibly
referece counting) accordingly.




Re: Why is Throwable.TraceInfo.toString not @safe?

2019-07-22 Thread Johannes Loher via Digitalmars-d-learn
Am 22.07.19 um 20:38 schrieb Jonathan M Davis:
> On Monday, July 22, 2019 1:29:21 AM MDT Johannes Loher via Digitalmars-d-
> learn wrote:
>> Am 22.07.19 um 05:16 schrieb Paul Backus:
>>> On Sunday, 21 July 2019 at 18:03:33 UTC, Johannes Loher wrote:
>>>> I'd like to log stacktraces of caught exceptions in an @safe manner.
>>>> However, Throwable.TraceInfo.toString is not @safe (or @trusted), so
>>>> this is not possible. Why is it not @safe? Can it be @trusted?
>>>>
>>>> Thanks for your help!
>>>
>>> Seems like it's because it uses the form of toString that accepts a
>>> delegate [1], and that delegate parameter is not marked as @safe.
>>>
>>> [1] https://dlang.org/phobos/object.html#.Throwable.toString.2
>>
>> I'm not talking about Throwable's toString method, but about
>> Throwable.TraceInfo's. Throwable.TraceInfo is an Interface inside
>> Throwable:
>>
>> interface TraceInfo
>> {
>> int opApply(scope int delegate(ref const(char[]))) const;
>> int opApply(scope int delegate(ref size_t, ref const(char[]))) const;
>> string toString() const;
>> }
>>
>> Throwable has a member info of type TraceInfo. It is never explicitly
>> set, so I assume it is automatically set by runtime magic. This is the
>> constructor of Throwable:
>>
>> @nogc @safe pure nothrow this(string msg, Throwable nextInChain = null)
>> {
>> this.msg = msg;
>> this.nextInChain = nextInChain;
>> //this.info = _d_traceContext();
>> }
>>
>> In theory people could define their own exception classes which provide
>> their own implementation of TraceInfo, but I never heard of anybody
>> doing this. So the real question is if the toString method of of the
>> DRuntime implementations (I assume there might be different
>> implementations for different platforms) are actually @safe (or
>> @trusted) and why we do not mark the interface to be @safe then.
> 
> All of that stuff predates @safe and most if not all attributes. @safe and
> the like have been added to some of that stuff, but in some cases, doing so
> would break code. I'd have to look at TraceInfo in more detail to know
> whether it can reasonably be marked @safe, but if it might end up calling
> anything that isn't guaranteed to be @safe, then it probably can't be (e.g.
> if it calls Object's toString). Also, TraceInfo is really more for
> druntime's use than for your typical programmer to use it directly in their
> program. So, I wouldn't be surprised in the least if not much effort was
> ever put in to making it @safe-friendly even if it could be. In general,
> stuff like @safe has tended to be applied to stuff in druntime and Phobos an
> a case-by-case basis, so it's really not surprising when an attribute is
> missing when it arguably should be there (though it frequently can't be
> there due to stuff like template arguments).
> 
> You _do_ need to be very careful with attributes and interfaces/classes
> though, because once an attribute is or isn't there, that can lock every
> derived class into a particular set of attributes. So, it's not always
> straightforward whether an attribute should be present or not. There are
> plenty of cases where ideally it would be present, but it can't be (e.g. a
> number of functions on TimeZone aren't pure even though they could be for
> _most_ derived classes, because they can't be pure for LocalTime), and there
> are cases where an attribute should be present but was simply never added. I
> don't know where TraceInfo sits, since I haven't dug into it.
> 
> - Jonathan M Davis
> 
> 
> 

Thanks for your insights, I already guessed that it is simply too old
for @safe and friends...

I understand that we have to be careful with adding attributes to
interfaces / classes, but in this particular case, I really cannot
imagine a usecase where we would not want it to be @safe (and the
situation here is better than with your example of TimeZone because we
have the @trusted escape hatch). Also I cannot imagine anybody
implementing their own version of TraceInfo.

The thing is that it can actually be quite useful to access TraceInfo in
user code, exactly for the example I gave in the beginning: Logging the
stacktrace. For long running programs, it is common practice in the
industry to log the stacktraces of caught exceptions in error cases
which do not mandate a program crash, simply to make a postmortem
analysis even possible. And in my opinion, user code should be @safe as
much as possible. If we cannot mark this @trusted, it means that a whole
lot of user code cannot be @safe, simply because of logging which would
be really weird...

I had a quick look at

Re: Why is Throwable.TraceInfo.toString not @safe?

2019-07-22 Thread Johannes Loher via Digitalmars-d-learn
Am 22.07.19 um 05:16 schrieb Paul Backus:
> On Sunday, 21 July 2019 at 18:03:33 UTC, Johannes Loher wrote:
>> I'd like to log stacktraces of caught exceptions in an @safe manner.
>> However, Throwable.TraceInfo.toString is not @safe (or @trusted), so
>> this is not possible. Why is it not @safe? Can it be @trusted?
>>
>> Thanks for your help!
> 
> Seems like it's because it uses the form of toString that accepts a
> delegate [1], and that delegate parameter is not marked as @safe.
> 
> [1] https://dlang.org/phobos/object.html#.Throwable.toString.2

I'm not talking about Throwable's toString method, but about
Throwable.TraceInfo's. Throwable.TraceInfo is an Interface inside Throwable:

interface TraceInfo
{
int opApply(scope int delegate(ref const(char[]))) const;
int opApply(scope int delegate(ref size_t, ref const(char[]))) const;
string toString() const;
}

Throwable has a member info of type TraceInfo. It is never explicitly
set, so I assume it is automatically set by runtime magic. This is the
constructor of Throwable:

@nogc @safe pure nothrow this(string msg, Throwable nextInChain = null)
{
this.msg = msg;
this.nextInChain = nextInChain;
//this.info = _d_traceContext();
}

In theory people could define their own exception classes which provide
their own implementation of TraceInfo, but I never heard of anybody
doing this. So the real question is if the toString method of of the
DRuntime implementations (I assume there might be different
implementations for different platforms) are actually @safe (or
@trusted) and why we do not mark the interface to be @safe then.


Why is Throwable.TraceInfo.toString not @safe?

2019-07-21 Thread Johannes Loher via Digitalmars-d-learn
I'd like to log stacktraces of caught exceptions in an @safe manner.
However, Throwable.TraceInfo.toString is not @safe (or @trusted), so
this is not possible. Why is it not @safe? Can it be @trusted?

Thanks for your help!


Re: Why after writeln the binaryHeap become empty?

2019-06-18 Thread Johannes Loher via Digitalmars-d-learn
Am 18.06.19 um 17:45 schrieb lili:
> Hi Guys:
>    see this code
> ~~~
>     int[] ar = [1,2,3,4,52,34,22];
>     auto h = heapify(ar);
>     assert(h.length() == ar.length);
>     writeln("h:",h);
>     assert(h.empty());
> ~~~
> dmd v2.086.0  run all assert passed. Why?

The result of heapify is a BinaryHeap, which is a range. writeln
basically prints ranges by iterating over them and printing each element
(except for the types which are special cased, such as dynamic arrays
etc.). However, ranges are consumed by iterating over them, which
explains the behavior because writeln is not special cased for BinaryHeaps.

In order to avoid this, you can make a copy of the BinaryHeap before
printing it:

```
import std;

void main()
{
int[] ar = [1, 2, 3, 4, 52, 34, 22];
auto h = heapify(ar);
assert(h.length() == ar.length);
writeln("h:", h.dup);
assert(!h.empty());
}
```

Funnily enough, BinaryHeap does not implement a "save" method, which is
the usual way of making ranges copiable, i.e. making them ForwardRanges.
In this case I believe save could even simply be an alias to dup.


Re: Function parameters UDAs

2019-06-10 Thread Johannes Loher via Digitalmars-d-learn
On Wednesday, 14 November 2018 at 18:05:55 UTC, Adam D. Ruppe 
wrote:

On Wednesday, 14 November 2018 at 16:28:19 UTC, Radu wrote:
Looks like that there is no easy way to extract a function 
parameters UDA list.


Indeed, the only way I can find is kinda crazy:

---
void foo(int f, @("test") string s) {}

void main() {
static if(is(typeof(foo) Params == __parameters))
pragma(msg, __traits(getAttributes, 
Params[1..2])); // get the second param

}
---


So, the process is:

1) alias the params with the static if + is() statement (this 
is what std.traits.Parameters does internally)


2) slice the params! using params[0] will not work, but 
params[0 .. 1] will.


3) get the attributes using the language function


Has anybody come up with a better solution yet? And why does 
__traits(getAttributes, Parameters!foo[0]) not work in the first 
place?


I am asking because I ran into a problem which does not seem 
solvable to me using the above workaround:


I would like to iterate over all parameters of a function using 
static foreach and then process each parameter's UDAs. But by 
using static foreach on the parameter tuple, slicing it is not 
possible anymore, so the suggested workaround does not work in 
this case :(


The error does not appear if all parameters of the function are 
symbols (e.g. structs), but it still does not work as expected 
because the UDAs simply get dropped when iterating over the 
parameter tuple. Here is an example:


import std;

struct Test
{}

void foo(@(1) Test x)
{
}

void main()
{
alias Params = Parameters!foo;
pragma(msg, Params);
static foreach(P; Params)
{
pragma(msg, P);
static foreach(uda; __traits(getAttributes, P))
{
pragma(msg, uda);
}
}
}

This prints

(@(1) Test)
Test

but I would expect it to print something like

(@(1) Test)
@(1) Test
@(1)



Re: Meson build system user learning D.

2019-05-20 Thread Johannes Loher via Digitalmars-d-learn

On Sunday, 19 May 2019 at 16:47:39 UTC, Mike Brockus wrote:

On Sunday, 19 May 2019 at 07:46:11 UTC, Johannes Loher wrote:

Am 18.05.19 um 08:20 schrieb Mike Brockus:

[...]


Hey there,

I already tried to answer your questions on reddit.

You can post links here by simply pasting the URL (the link 
will not be highlighted in the editor, but it will be when it 
is posted).


Regarding your problem: Could you please describe what you are 
actually trying to do? Are you trying to use D in an exisiting 
Meson project (as an addition to the existing code)? Why are 
you trying to use the Unity test framework (I only had a quick 
look at it, but from what I saw it uses a lot of preprocessor 
macros which will make it difficult to get it wotk work 
properly with D). Why not use the built-in unittests or one of 
the many already existing unit testing frameworks for D ([1], 
[2], [3], [4], [5])?


[1] https://code.dlang.org/packages/unit-threaded
[2] https://code.dlang.org/packages/dunit
[3] https://code.dlang.org/packages/d-unit
[4] https://code.dlang.org/packages/fluent-asserts
[5] https://code.dlang.org/packages/trial


I am trying to do two things one being able to turn a pure C 
project into a pure D project without destroying the existing 
file structure.

The project (https://github.com/squidfarts/c-project.git)

The other is to make a new Arduino UNO board project that 
leverages existing C and C++ code so I can spend small amounts 
of time writing new D code as I update all of my Arduino 
applications.


I would like to use the Unity test framework for that Arduino 
UNO based project that uses D, C, C++ and both Meson build 
system and Conan package manager.  The part with C and C++ are 
just for linking with the Arduino libraries, including exiting 
classes while I write new D code to replace the existing C and 
C++ code where ever it makes since.  Conan is used to get both 
the Unity and CMock from GitHub.


For the pure D project I would like to use whatever D provides 
me.  Since you provided this list I would start with 
unit-threaded and see if it can help with this main function 
problem.


Hey again, does my answer from reddit not solve your first 
problem (keeping the existing file structure)? As mentioned, 
using Unity for the tests does not really make sense with D, 
though it might be possible to use it with dpp ([1]).


Regarding your second problem: The Arduino UNO is based on the 
ATmega328P, which is an AVR chip. There is currently no D 
compiler available, that targets AVR, so you won‘t be able to use 
D for programming your Arduino UNO for now. There have been 
discussions about this ([2], [3]), but for now it is simply not 
possible.


[1] https://github.com/atilaneves/dpp
[2] 
https://forum.dlang.org/thread/1328258826.2142.4.camel@ububox?page=1
[3] 
https://forum.dlang.org/thread/zvderukicijcuxgqg...@forum.dlang.org


Re: Meson build system user learning D.

2019-05-19 Thread Johannes Loher via Digitalmars-d-learn
Am 18.05.19 um 08:20 schrieb Mike Brockus:
> Hello there this is your hometown Meson build system user here just
> happen to have a
> question related to unit testing in D.
> 
> So is there a way to run the unit-test in the test main as a costume
> test runner in
> "test/test.d", and run the executable program in "src/main.d", with this
> resulting in two
> executable binaries one for test and one for the program?
> 
> I was considering using Unity test framework so I would know that if I
> was running the test runner that it was definitely the custom test
> runner returning the value of all test cases ran and not a mistake of
> running the main executable program.  But I am not sure if that would
> insulate the D programming community by not using the provided unit
> testing functionality in D.
> 
> I am mostly trying to make a version based on an existing C template but
> with D language
> syntax using whatever tools D provides along side Meson build system.  I
> would give you
> the link(s) but I haven't figured out how to add links here on the D
> forum, and I just
> registered.
> 
> Thanks...

Hey there,

I already tried to answer your questions on reddit.

You can post links here by simply pasting the URL (the link will not be
highlighted in the editor, but it will be when it is posted).

Regarding your problem: Could you please describe what you are actually
trying to do? Are you trying to use D in an exisiting Meson project (as
an addition to the existing code)? Why are you trying to use the Unity
test framework (I only had a quick look at it, but from what I saw it
uses a lot of preprocessor macros which will make it difficult to get it
wotk work properly with D). Why not use the built-in unittests or one of
the many already existing unit testing frameworks for D ([1], [2], [3],
[4], [5])?

[1] https://code.dlang.org/packages/unit-threaded
[2] https://code.dlang.org/packages/dunit
[3] https://code.dlang.org/packages/d-unit
[4] https://code.dlang.org/packages/fluent-asserts
[5] https://code.dlang.org/packages/trial


Re: How to mixin finction name?

2019-04-14 Thread Johannes Loher via Digitalmars-d-learn
Am 14.04.19 um 15:22 schrieb Adam D. Ruppe:
> [...]
> Though, I'd point out the mixin code doesn't have to be too ugly.
> Consider this:
> 
> void main()
> {
>     enum letters = ['A', 'B', 'C'];
> 
>     static foreach(ch; letters)
>     {
>     mixin(q{
>     void print}~ch~q{(int i) {
>     import std.stdio;
>     writeln(ch, " - ", i);
>     }
> });
>     }
> 
>     printB(6);
> }
> 
> 
> Well, the name part is a big ugly, but the rest of it looks perfectly
> normal, and the compiler error message still give reasonable results.
At first I was very confused that this example even worked. Why does
`ch` get expanded in the call to writeln? It is part of the mixed in
string, so why does the string not simply include "writeln(ch, ...)" on
every iteration?

If you do not care about your code being compatible with -betterC, you
can use std.format to make the code even more readable (at least in my
opinion):

void main()
{
import std.format : format;

enum letters = ['A', 'B', 'C'];

static foreach (ch; letters)
{
mixin(q{
void print%s(int i) {
import std.stdio;
writeln(ch, " - ", i);
}
}.format(ch));
}

printB(6);
}


Re: Aliasing a mixin (or alternative ways to profile a scope)

2019-03-07 Thread Johannes Loher via Digitalmars-d-learn
Am 07.03.19 um 22:50 schrieb Johannes Loher:
> [...]

As a small addition, if you always want to pass the function name as a
parameter, you can simplify this to the following:

```
enum profile_scope(string name = __FUNCTION__) = "import core.stdc.stdio
: printf; printf(\""
~ name ~ "\n\"); scope(exit) printf(\"" ~ name ~ "\n\");";

extern (C) void main()
{
mixin(profile_scope!());
foo();
}

extern (C) void foo() {
mixin(profile_scope!());
}
```
This will print
```
main.main
main.foo
main.foo
main.main
```
to the commandline.



Re: Aliasing a mixin (or alternative ways to profile a scope)

2019-03-07 Thread Johannes Loher via Digitalmars-d-learn
Am 07.03.19 um 22:21 schrieb Simon:
> 
> Is there a way to achieve this while compiling with -betterC? I use a
> custom string struct right now, and your version needs TypeInfo,
> concatening using ~ needs the garbage collector. I have the feeling D is
> really not agreeing with the way I want to do things. If this is not
> possible, I will just roll with the Adam's struct solution.
> 

Using Adams struct solution is perfectly fine. I believe it is probably
the cleaner solution overall.

My solution depends on TypeInfo because format does. I used format
because it makes the string more readable. You can avoid this and use
string concatenation in combination with providing the function name as
template parameter instead:

```
enum profile_scope(string name) = "import core.stdc.stdio : printf;
printf(\""
~ name ~ "\n\"); scope(exit) printf(\"" ~ name ~ "\n\");";

extern (C) void main()
{
mixin(profile_scope!"func1");
}

```
This uses string concatenation only at compile time and not during run
time, so it does not require the garbage collector and is compatible
with betterC :)


Re: Aliasing a mixin (or alternative ways to profile a scope)

2019-03-07 Thread Johannes Loher via Digitalmars-d-learn
Am 07.03.19 um 21:07 schrieb Simon:
> Hello,
> 
> I am currently porting the frontend of my instrumenting profiler to D.
> It features a C++-makro that profiles the time between entering and
> leaving a scope (achieved with con-/destructors in C++). Since D has
> scopeguards, I hoped to achieve this by creating a mixin that generates
> the following code:
> 
> measure("func1");
> scope(exit) measure("func1");
> 
> Since I of course don't want to type a mixin for that everytime I want
> to use it, I tried to alias it:
> 
> import std.meta : Alias;
> alias profile_scope(string name) = Alias!(mixin("measure(\"" ~ name ~
> "\"); scope(exit) measure(\"" ~ name ~ "\");"));
> 
> I expected this to generate the code above by typing
> profile_scope("func1") in my programm. However the compiler (dmd) gives
> me the following error:
> 
> source\main.d(24): Error: template plattform.profile_scope cannot deduce
> function from argument types !()(string), candidates are:
> source\plattform.d(262):    plattform.profile_scope(string name)
> 
> This looks like a deduction/overload kind of error, which has me
> completly confused since there is no other identifier of the name
> "profile_scope" in my programm and the error message shows only one
> candidate.
> 
> Is there any way I can achive generating those two statements using only
> something that effectively looks like a function call/C-macro with an
> argument?
The error you are seeing is due to the fact that you pass "func1" as
runtime parameter instead of as a teamplate parameter. You would need to
do `profile_scope!("func1");`. However, this will still not work and
you'll get an error message similar to this:
```
main.d(4): Error: incomplete mixin expression writeln("func1");
scope(exit) writeln("func1");
main.d(8): Error: template instance `main.profile_scope!"func1"` error
instantiating
```

The underlying problem is that you can only alias expressions, i.e. you
cannot use alias to generate macro like functionality.

`measure("func1"); scope(exit) measure("func1");` is not an expression,
it is simply a statement, so the alias cannot work.

If you want to inject code directly at some place, basically your only
option is to use a string mixin. I understand that you do not want to
write `mixin` all the time, but to me, this does not look that bad:
```
auto profile_scope(string name)
{
import std.format : format;
return q{import std.stdio : writeln; writeln("%1$s"); scope(exit)
writeln("%1$s");}.format(name);
}

void main()
{
mixin(profile_scope("func1"));
}
```
(replace writeln with your appropriate function call, "measure" in your
example).



Re: 2 class issues

2019-03-07 Thread Johannes Loher via Digitalmars-d-learn
Am 07.03.19 um 11:38 schrieb spir:
> Hello,
> 
> First, I am not very experimented with the combination of static lang
> (alloc & typing) and OO (class-based). I'm implementing a library for
> lexical analysis (lexing), with 2 minor issues:
> 
> -1- How to enforce that subclasses implement given methods without using
> "abstract", which seems to make the whole class abstract? (no info found
> in doc, actually, the page on classes [1] does not seem to even mention
> abstract classes)
> 
> -2- How to have "constant" (predefined) class instances at the
> module-level? The compiler requires a "static this ()". What does this
> actually mean (for a constructor)? What are the consequences, for either
> my code or client code? (The doc on the topic [2] is rather obscure for
> me, and I could not find better elsewhere.)
> 
> I'm also bluffed by "Static constructors have empty parameter lists."
> Does this mean I should manually fill the fields? (not a big deal, but
> why???) This may give:
>     // Predefined pseudo-pattern "End-of-Text":
>     auto EoT = new Pattern() ;   // ???
>     EoT.name = "EoT" ;
> 
>     // Unique lexeme "end-of-text":
>     auto eot = new Lexeme() ;   // ???
>     eot.patname = "EoT" ;
>     eot.slice = null ;
>     eot.index = uint.max ;
> Then, why have a constructor at all? This would also prevent me from
> making classes immutable, while conceptually all are immutable... (no
> reason for a pattern or a lexeme to change)
> 
> Thank you,
> diniz
> 
> [1] https://dlang.org/spec/class.html
> [2] https://dlang.org/spec/class.html#static-constructor

Regarding your first point: I don't think it is currently possible to
force derived classes to override functions from the base class while
also implementing these functions in the base class. What would the
usecase of this be anyways?

Regarding your second point: What excatly do you mean by '"constant"
(predefined) class'? Do you mean that you want to provide an instant
from that class? You can achieve this like the following:

```
class Test
{
}

Test testInstance;

static this() {
testInstance = new Test();
}
```
If you want the testInstance to be shared across threads:
```
class Test
{
}

shared Test testInstance;

shared static this() {
testInstance = new Test();
}
```

You seem to be misunderstanding how static class constructors work: They
are not invoked when you try to instanciate the class, but when the
module in which the class is located is loaded. This also explains why
they need to have empty parameter lists: You cannot pass arguments when
loading a module  static constructors are usually used to initialize
static class variables. Consider the following example:

```
import core.thread: Thread;

class Test
{

private static ulong i;

static this() {
i = Thread.getThis.id;
}
}
```
You cannot initialize `i` directly in its declaration because
`Thread.getThis.id` is only available at runtime (i.e. `private static
ulong i = Thread.getThis.id;` does not compile). To get around this, you
can use static constructors.



Re: Should I prefix package names with the name of my program?

2019-01-29 Thread Johannes Loher via Digitalmars-d-learn
Am 28.01.19 um 18:29 schrieb H. S. Teoh:
> On Mon, Jan 28, 2019 at 04:59:22PM +, Victor Porton via 
> Digitalmars-d-learn wrote:
>> Should I prefix all module names with `xmlboiler.` (where XML Boiler
>> is the name of my program). These packages are expected to be used
>> internally by my program, not as an exported API (however there are
>> some little chances that in the future I will make a public API)
> 
> I won't pretend to speak for anyone else, but personally, I don't even
> bother with packages until my code has grown past a certain size. It's
> just useless cruft and needless complexity for small to medium sized
> projects. It's only when you're planning to export a public API, or when
> your code has grown past a certain size, that it becomes useful to
> segregate the code into different packages.
> 
> So IMO you don't need to bother.  You can always refactor the code later
> to have a package name when you make a public API.
> 
> 
> T
> 

This is basically the same thing I do: Start with toplevel modules and
reorder them into packages once things get more complicated. Mostly I
only include a top level package named like my project when writing a
project which might be used by other projects (i.e. library code). So
far this has worked very well for me.

If you expect name clashes with other modules you import, prefixing your
own modules with a top level package is a valid solution.


Re: Understanding SIGSEGV issues

2019-01-09 Thread Johannes Loher via Digitalmars-d-learn

On Wednesday, 9 January 2019 at 16:48:47 UTC, Russel Winder wrote:
On Tue, 2019-01-08 at 11:51 +, Nicholas Wilson via 
Digitalmars-d-learn wrote:

[...]

[…]

[...]


[...]


If debugger integration is that important to you, you might want 
to try out visual studio code with the corresponding plugins (you 
need a separate plugin for debugger support). I found it to work 
quite decently.


Re: typeof function literals which define the types of its parameters but do not give their parameters names

2018-12-27 Thread Johannes Loher via Digitalmars-d-learn
On Thursday, 27 December 2018 at 08:53:30 UTC, Johannes Loher 
wrote:
On Thursday, 27 December 2018 at 04:27:03 UTC, Steven 
Schveighoffer wrote:

[...]


As a side note:

During last DConf I talked to Walter and Andrei about the fact 
that `typeof(SomeTemplate) == void` and they agreed that it 
probably should be a compiler error instead (see also 
https://issues.dlang.org/show_bug.cgi?id=15437). It would be 
pretty hard to do this right now, as it breaks existing code 
(quite a lot of phobos code depends on this in template 
constraints). But if this was indeed some day changed to be a 
compiler error, it would make things even weirder.


Re: typeof function literals which define the types of its parameters but do not give their parameters names

2018-12-27 Thread Johannes Loher via Digitalmars-d-learn
On Thursday, 27 December 2018 at 04:27:03 UTC, Steven 
Schveighoffer wrote:

On 12/26/18 10:52 PM, Johannes Loher wrote:

Hey all,

I am a bit confused about the inferred types of function 
literals which do not name their parameters (something like 
`(int) {}`). The confusion arises from the fact that the 
inferred type sometimes is `void` (might be the case, because 
the function literal is inferred to be a template) and 
sometimes it is something like `void function(bool _param_0) 
pure nothrow @nogc @safe`. What is really weir is that seems 
to depend on the type of the parameter. Here is small example 
showing what happens for different parameter types: 
https://run.dlang.io/is/xSMZZu


Also note that this only happens for function literals. For 
regular functions and member functions, `void` is never 
inferred, but only types like `pure nothrow @nogc @safe 
void(MyClass _param_0)`.


Has anybody any idea what is going on here? Is this a bug?


This is pretty funny actually.

Note the difference between the ones that print something other 
than "void" is that the parameters are all keywords!


The ones that do print "void" have a normal symbol name as 
their parameter. This could be a parameter name or a parameter 
type, and the compiler is choosing the latter.


In other words, you are expecting:

alias f = (string) {}

to evaluate to something like:

void f(string) {}

but in fact, it evaluates to:

void f(T)(T string) {}

because string is not a keyword, it's an alias. So you are free 
to redefine it inside your lambda (in this case, as a template 
parameter *name*).


As proof, you can try calling it like this:

f(1)

and it works.

To fix, just give all your lambda parameters names.

-Steve


Thanks for the insight, this is indeed actually very funny. You 
can even force the compiler to interpret the parameters as types 
in several ways:


```
alias j = (typeof(string.init)) { };

alias identity(T) = T;
alias k = (identity!size_t) { };

```

or if the type is defined at module level, this works, too:

```
alias l = (.MyStruct) { };
```

There are probably a lot more. You just need to use some 
expression which evaluates to the actual type but cannot be 
interpreted as an identifier (".", "!", "(" and ")" are not 
allowed inside identifiers, which is how I suppose the above 
examples work).


However, this still leaves the question whether this behavior is 
intentional or not. It is at least very surprising and 
inconsistent in my opinion. For example consider some generic 
code using `std.traits.isSomeFunction` (which is actually how I 
found out about this):


```
static assert(isSomeFunction!((long) {});
static assert(!isSomeFunction!((size_t) {});
```

If this behavior is indeed intentional, it should at least be 
covered in the spec.




typeof function literals which define the types of its parameters but do not give their parameters names

2018-12-26 Thread Johannes Loher via Digitalmars-d-learn

Hey all,

I am a bit confused about the inferred types of function literals 
which do not name their parameters (something like `(int) {}`). 
The confusion arises from the fact that the inferred type 
sometimes is `void` (might be the case, because the function 
literal is inferred to be a template) and sometimes it is 
something like `void function(bool _param_0) pure nothrow @nogc 
@safe`. What is really weir is that seems to depend on the type 
of the parameter. Here is small example showing what happens for 
different parameter types: https://run.dlang.io/is/xSMZZu


Also note that this only happens for function literals. For 
regular functions and member functions, `void` is never inferred, 
but only types like `pure nothrow @nogc @safe void(MyClass 
_param_0)`.


Has anybody any idea what is going on here? Is this a bug?


Re: cas and interfaces

2018-12-25 Thread Johannes Loher via Digitalmars-d-learn

On Monday, 24 December 2018 at 11:23:32 UTC, Johan Engelen wrote:
On Sunday, 23 December 2018 at 14:07:04 UTC, Johannes Loher 
wrote:

[...]


The types of the 2nd and 3rd arguments of `cas` do not have to 
be the same, and aren't in your case. I think what's happening 
is that you are overwriting `testInterface` with a pointer to a 
TestClass which is not a valid TestInterface pointer. And then 
the program does something invalid because, well, you enter UB 
land.

Fixed by:
```
cas(, testInterface, cast(shared(TestInterface)) 
new shared TestClass).writeln;

```
Note the cast!

Whether this is a bug in `cas` or not, I don't know. The `cas` 
template checks whether the 3rd can be assigned to the 1st 
argument (`*here = writeThis;`) which indeed compiles _with_ an 
automatic conversion. But then the implementation of `cas` does 
not do any automatic conversions (casts to `void*`). Hence the 
problem you are seeing.


-Johan


Thanks a lot for the info, that clarifies things a bit. But it 
still leaves the question, why it works correctly when inheriting 
from an abstract class instead of implementing an interface... 
Any idea about why that?


cas and interfaces

2018-12-23 Thread Johannes Loher via Digitalmars-d-learn
I recently played around with atomic operations. While doing so, 
I noticed a problem with the interaction of interfaces and cas. 
Consider the following program:


```
import core.atomic;
import std.stdio;

interface TestInterface
{
}

class TestClass : TestInterface
{
}

void main()
{
shared TestInterface testInterface = new shared TestClass;
cas(, testInterface, new shared 
TestClass).writeln;

writeln(typeid(testInterface));
}
```
(https://run.dlang.io/is/9P7PAb)

This program compiles successfully and outputs

```
true
Error: program killed by signal 11
```

i.e. a segmentation fault happens.

When replacing "interface" with "abstract class" 
(https://run.dlang.io/is/sFaO1k), everything works as expected 
and the program outputs


```
true
onlineapp.TestClass
```

Is this actually a bug or a fundamental limitation of cas and 
interfaces? Did I do anything wrong?


Re: Why do ints defined in template mixins have garbage values?

2018-12-12 Thread Johannes Loher via Digitalmars-d-learn
On Tuesday, 11 December 2018 at 21:09:55 UTC, Johannes Riecken 
wrote:

Code:

import std.conv;
import std.stdio;

mixin template genInts()
{
  enum arr = [0,1];
  static foreach (t; arr) {
mixin("int i" ~ to!string(t) ~ " = 5;");
  }
}

void main() {
  mixin genInts!();
  writeln(i0);
  writeln(i1);
}


Expected output:
5
5

Actual output is two garbage integer values.


Definitely a compiler bug.

According to 
https://run.dlang.io/gist/1e6e7574a8762d7fed5a3aa22390493d?compiler=dreg

Garbage values are printed since 2.078.1.

compiling with ldc results in a segmentation fault when running 
the program: 
https://run.dlang.io/gist/02780bfe33a2bfd000aa5718a3fe6505?compiler=ldc


Re: vibe.d: Finding out if currently in webinterface request

2018-08-10 Thread Johannes Loher via Digitalmars-d-learn

On Friday, 10 August 2018 at 09:33:34 UTC, Timoses wrote:
On Thursday, 9 August 2018 at 21:59:24 UTC, Johannes Loher 
wrote:
I already posted this in the vibe.d forums 
(https://forum.rejectedsoftware.com/groups/rejectedsoftware.vibed/thread/58891/), but it seems, there is not a lot of activity over there, so I am cross posting this here:


[...]


Do you have some code segments boiled down to the problem?

Are you using vibe.core.log?


Yes, I am using vibe.core.log, but as mentioned, I want to 
implement my own logger. The gist of what I am trying to do is 
this:


https://run.dlang.io/is/7qpJ6J

This actually works the way it is, but it involves catch 
Throwable (actually AssertError would be enough) and this is bad. 
I would like to find a different solution.


vibe.d: Finding out if currently in webinterface request

2018-08-09 Thread Johannes Loher via Digitalmars-d-learn
I already posted this in the vibe.d forums 
(https://forum.rejectedsoftware.com/groups/rejectedsoftware.vibed/thread/58891/), but it seems, there is not a lot of activity over there, so I am cross posting this here:


Is there a way to find out, if we are currently in a webinterface 
request?


My usecase is the following:

I want to implement a logger, which in addition to the actual log 
message also logs information about the request which is 
currently being handled (if any). For this I would like to call 
request(), which gives me the current HTTPServerRequest. However, 
this results in an AssertError, whenever logging appears outside 
of a webinterface request (so basically immediately after 
starting the application, because vibe.d logs some things 
automatically). So I would need to check, if we are currently 
processing a webinterface request.


Another usecase which would be interesting to me and which has 
the exact same problem is the following:


Suppose in my received request, there is an HTTP header 
X-Correlation-Id: . Now whenever during processing of this 
request I start an HTTP request to some other service (e.g. via 
requestHTTP()), I also want to include this header in the new 
request I send. Of course, you could implement this by always 
passing the header manually, but I'd prefer to implement this 
using a generalized wrapper around requestHTTP(). But then in 
this wrapper, I would also need to call request(), which makes it 
impossible to call it from outside of webinterface request (e.g. 
it could be triggered by a timer, or something like this). But it 
would be nice, to be able to just use a single function for all 
my requests (to keep things uniform).


Re: Question about template argument matching with alias this

2018-07-29 Thread Johannes Loher via Digitalmars-d-learn

On Sunday, 29 July 2018 at 20:51:45 UTC, Alex wrote:

Do you mean something like this?
[...]


Yeah, I know that it possible to implement the template like 
this, but that is not the point here. I would like to know why it 
does not work the way I described it. To me it seems very 
strange, that `S : T` has different semantics in `is` expressions 
and as template parameters.


My actual problem is the following: I would like to use the 
dependency injection framework poodinis [1] in conjuction with 
the mocking capabilities from unit-threaded [2]. My code would 
look something like the following:


```
import poodinis : DependencyContainer;
import unit_threaded.mock : mock;

interface SomeInterface
{
}

unittest
{
auto myMock = mock!SomeInterface;
alias MockedType = typeof(myMock)
auto container = new shared DependencyContainer;

container.register!(SomeInterface, 
MockedType)().existingInstance(myMock);

/* ... */
}
```

The problem with this is that register has the signature 
described above, i.e. register(T, S : T)() and that the mock 
template from unit-threaded is actually implemented by a struct 
which is "alias this"ed (how do you call that...? :D) to a class 
which is derived from the mocked interface. This means I run 
exactly into the problem I described in the first post.


Now I could ask the author of poodinis to remove the restriction 
on the template parameters for register, but it actually 
perfectly makes sense to have that restriction, because we are 
registering a concrete type as an abstract type.


I also had a quick look at the implementation of mock, which 
seems to be quite complicated already. So I fear that changing 
this implementation to using a derived class directly is unlikely 
to happen.


So I am back to my question: Why do we have this strange 
behavior? All compiler version on run.dlang.io behave like that, 
so I suppose there is some reason for this...?


[0] https://github.com/mbierlee/poodinis
[1] https://github.com/atilaneves/unit-threaded


Question about template argument matching with alias this

2018-07-29 Thread Johannes Loher via Digitalmars-d-learn
I have a question about template argument matching in combination 
with implicit conversion and alias this. Consider the following 
code:



interface SomeInterface
{
}

class SomeClass : SomeInterface
{
}

struct SomeStruct
{
SomeClass someClass;
alias someClass this;
}

template isSuperType(T, S : T)
{
enum isSuperType = is(SomeStruct : SomeInterface);
}

void main()
{
static assert(is(SomeStruct : SomeInterface));
static assert(isSuperType!(SomeInterface, SomeStruct)); // 
why does the template not match?

}


The question is, why does the template declaration not match? 
Thanks for your help!


Re: Request scoped information in Vibe.d

2018-07-29 Thread Johannes Loher via Digitalmars-d-learn

On Sunday, 22 July 2018 at 18:21:21 UTC, Venkat wrote:

On Sunday, 22 July 2018 at 08:43:23 UTC, Johannes Loher wrote:

On Sunday, 22 July 2018 at 06:21:40 UTC, Venkat wrote:

[...]


What is your usecase? If you simply want to pass a variable to 
a diet template, just pass it as a template parameter to 
render:


/* ... */

int myVar = 42;
render!("mytemplate.dt", myVar);

/* ... */

Then in mytemplate.dt, you can do something like:

p The best number ever is #{ myVar }


That is what I want to do. But what if I am redirecting the 
user with some form errors ? In that case I am not using 
render!.


Could you give a short example of what you are trying to do?


Re: Request scoped information in Vibe.d

2018-07-22 Thread Johannes Loher via Digitalmars-d-learn

On Sunday, 22 July 2018 at 06:21:40 UTC, Venkat wrote:
How do I make variables available to diet templates ? Java has 
request.setAttribute. Vibe.d's HTTPServerRequest has params and 
queryString. But by the looks of it, neither one of them is 
created for the purpose of temporary storage in the request. 
Where do I store request scoped information ?


What is your usecase? If you simply want to pass a variable to a 
diet template, just pass it as a template parameter to render:


/* ... */

int myVar = 42;
render!("mytemplate.dt", myVar);

/* ... */

Then in mytemplate.dt, you can do something like:

p The best number ever is #{ myVar }


Re: making a struct an inputRange with free functions

2018-04-16 Thread Johannes Loher via Digitalmars-d-learn
Am 16.04.2018 um 21:27 schrieb Jonathan M Davis:
> On Monday, April 16, 2018 21:10:03 Johannes Loher via Digitalmars-d-learn 
> wrote:
>> Is there a way to do this? Here is a naive implementation:
>> https://run.dlang.io/is/JKvL80 .
>>
>> It does not pass `isInputRange` (I think, because the free functions are
>> not visible in the scope of `isInputRange`).
>>
>> Trying to iterate over it with a foreach loop results in a compile error:
>> Error: invalid foreach aggregate NoRange(0, 0).this(5), define
>> opApply(), range primitives, or use .tupleof
>>
>> Thanks for your help!
> 
> It doesn't work unless the module using the range either contains the free
> functions or imports them. So, I believe that that would mean that for
> isInputRange to pass, std.range.primitives would have to have access to the
> functions, which isn't going to happen for anything but dynamic arrays. It's
> a limitation of UFCS in general (it's similar to why using string lambdas
> with std.functional has become fairly rare - you can only use functions in
> them that std.functional already knows about). The only way for the
> functions to be associated with the type and thus always be available is if
> they're member functions. So, if you want a type to be a range, you have to
> declare the range functions as member functions.
> 
> - Jonathan M Davis
> 
Yeah, that's what I guessed, too. Thanks for the clarification.


making a struct an inputRange with free functions

2018-04-16 Thread Johannes Loher via Digitalmars-d-learn
Is there a way to do this? Here is a naive implementation:
https://run.dlang.io/is/JKvL80 .

It does not pass `isInputRange` (I think, because the free functions are
not visible in the scope of `isInputRange`).

Trying to iterate over it with a foreach loop results in a compile error:
Error: invalid foreach aggregate NoRange(0, 0).this(5), define
opApply(), range primitives, or use .tupleof

Thanks for your help!


Re: VibeD Rest Interface Generator

2018-03-03 Thread Johannes Loher via Digitalmars-d-learn

On Saturday, 3 March 2018 at 02:32:11 UTC, Mario wrote:
So I've been learning D since the day 11 (I posted for first 
time here) and now I've decided to try Vibe.D to make my 
company API.


The fact is that I've achieved to do it (according to the 
provided code) and it works! But it shows a default message and 
on the startup. So I'd like to know how can I set it to receive 
the HTTP(s) request, analyze the body and get the data through 
a database (we will probably use MongoDB).


If you can help me with this, I'd be grateful. Best regards, 
Mario :-)


These are quite a lot of questions at once and it is difficult, 
to answer them all here, because they are so general. I suggest 
you take a look at the excelent book D Web Development 
(https://www.packtpub.com/web-development/d-web-development) 
which covers everything you asked. Be aware  though that  new 
vibe.d Versions have been released since the Book has been 
published and so some of its information is outdated. so if you 
use a recent Version of vibe.d, be sure to also Check out the 
documentation.


vibed.web.auth framework and redirection

2017-08-07 Thread Johannes Loher via Digitalmars-d-learn

Hello

I'd like to use the vibed.web.auth framework for authentication 
in my vibe.d app. If a user is not authorized to access a certain 
page, he should be redirected to another page (a custom error 
page for example, or the login page in my case). At the moment, 
I'm using the following authenticate method to achieve this:


@noRoute AuthInfo authenticate(scope HTTPServerRequest req, scope 
HTTPServerResponse res)

{
if (!req.session || !req.session.isKeySet("auth"))
{
redirect("/login");
throw new HTTPStatusException(HTTPStatus.forbidden, "Du 
musst dich erst einloggen");

}
return req.session.get!AuthInfo("auth");
}

If you need a full working example, the complete sourcecode can 
be found at 
https://git.f3l.de/fsimphy/calendar-webapp/tree/poodinis-mongo. 
The authenticate method is in the file source/calendarwebapp.d.


While this method seems to work, there are a few issues:
1. Nothing at all seems to happen with the thrown exception 
(well, something got to happen, what is it?). I'd like to somehow 
use and display the Exception msg.
2. Using authenticate methods, which are not @safe or @trusted is 
deprecated as of vibed 0.8.0. The redirect function is neither 
@safe nor @trusted, so my authenticate method can not be @safe. I 
don't know if it is safe to mark it as @trusted.


To me, it seems as if redirecting is not really intended. This 
leads me to the question: Is there any better way to do this?


Thanks in advance for your help!


Re: Manually calling postblots recursively

2017-06-22 Thread Johannes Loher via Digitalmars-d-learn

On Sunday, 18 June 2017 at 14:16:03 UTC, Basile B. wrote:

On Sunday, 18 June 2017 at 09:41:01 UTC, Johannes Loher wrote:
Hey, I'm trying to work on 
https://issues.dlang.org/show_bug.cgi?id=15708 so I decided it 
might be interesting to find a way to (recursively) call all 
postblits that belong to certain struct or static array. This 
is what I came up with so far:


[...]


"@disable" postblits are detected as valid postblits.
I think that you have to AndAnd the detection with 
std.traits.isCopyable


Here is my new version. Additionally to taking care of @disable 
this(this); I added compile time checks if the underlying fields 
have an "elaborate copy constructor" so that I only call 
callPostblits on them if needed. Is this reasonable? It increases 
compiletime, but could possibly decrease runtime a little. On the 
other hand, the empty function calls should probably just get 
optimized away...?


While doing all that I realized that hasElaborateCopyConstructor 
is true for structs with @disable this(this). Is that intended? 
It looks a bit weird to me...




import std.traits;

void callPostblits(S)(ref S s)
{
static if (isStaticArray!S && S.length && 
hasElaborateCopyConstructor!(ElementType!S))

{
foreach (ref elem; s)
callPostblits(elem);
}
else static if (is(S == struct))
{
foreach (field; FieldNameTuple!S)
{
static if 
(hasElaborateCopyConstructor!(typeof(__traits(getMember, s, 
field

{
callPostblits(__traits(getMember, s, field));
}
}

static if (hasMember!(S, "__postblit") && isCopyable!S)
{
s.__postblit();
}
}
}

unittest
{

struct AnotherTestStruct
{
int b = 0;

this(this)
{
b = 1;
}
}

struct TestStruct
{
int a = 0;

this(this)
{
a = 1;
}

AnotherTestStruct anotherTestStruct;
}


TestStruct[2] testStructs;

assert(testStructs[0].a == 0 && 
testStructs[0].anotherTestStruct.b == 0);
assert(testStructs[1].a == 0 && 
testStructs[1].anotherTestStruct.b == 0);


callPostblits(testStructs);

assert(testStructs[0].a == 1 && 
testStructs[0].anotherTestStruct.b == 1);
assert(testStructs[1].a == 1 && 
testStructs[1].anotherTestStruct.b == 1);


struct YetAnotherTestStruct
{
@disable this(this);
}

YetAnotherTestStruct yetAnotherTestStruct;
callPostblits(yetAnotherTestStruct); // This will also compile
}


Manually calling postblots recursively

2017-06-18 Thread Johannes Loher via Digitalmars-d-learn
Hey, I'm trying to work on 
https://issues.dlang.org/show_bug.cgi?id=15708 so I decided it 
might be interesting to find a way to (recursively) call all 
postblits that belong to certain struct or static array. This is 
what I came up with so far:


import std.traits;

void callPostblits(S)(ref S s)
{
static if (isStaticArray!S && S.length)
{
foreach (ref elem; s)
callPostblits(elem);
}
else static if (is(S == struct))
{
foreach (field; FieldNameTuple!S)
{
callPostblits(__traits(getMember, s, field));
}

static if (hasMember!(S, "__postblit"))
{
s.__postblit();
}
}
}

@safe unittest
{

struct AnotherTestStruct
{
int b = 0;

this(this)
{
b = 1;
}
}

struct TestStruct
{
int a = 0;

this(this)
{
a = 1;
}

AnotherTestStruct anotherTestStruct;
}


TestStruct[2] testStructs;

assert(testStructs[0].a == 0 && 
testStructs[0].anotherTestStruct.b == 0);
assert(testStructs[1].a == 0 && 
testStructs[1].anotherTestStruct.b == 0);


callPostblits(testStructs);

assert(testStructs[0].a == 1 && 
testStructs[0].anotherTestStruct.b == 1);
assert(testStructs[1].a == 1 && 
testStructs[1].anotherTestStruct.b == 1);

}

Any suggestions for improvement or cases where this fails?


forwarding build type to dependencies with dub

2016-09-07 Thread Johannes Loher via Digitalmars-d-learn
Is it possible to forward the build type to the dependencies of a dub
project? For example, if I build my project with

dub build -b unittest

is it possible to make dub build the dependencies of my project also
with the unittest build type? Even better would be a way to specify for
which dependencies this should happen.

This would be useful for using dunit
(http://code.dlang.org/packages/dunit). When built with the unittest
build type, it replaces the default unittest handler to give nicer
output about which unittests failed and why etc. If I simply add dunit
as a dependency to my project and build my project as described above,
dunit is not built with the unittest build type and thus the unittest
handler is not replaced and I got the usual assertion error output for
failing unittests.

I tried removing the version(unittest) from the part of dunit, which
replaces the handler, but it always outputs some text, even if no
unittests are being run (if we don't compile with -unittest). Of course
I do not want this ouput when not testing and especially not in release
code...


Re: Getting the superclass of a type?

2016-09-05 Thread Johannes Loher via Digitalmars-d-learn
Am 05.09.2016 um 17:43 schrieb Lodovico Giaretta:
> On Monday, 5 September 2016 at 15:20:10 UTC, pineapple wrote:
>> I'd like to be able to write something like this, but I haven't been
>> able to find anything in the docs
>>
>> class Base{}
>> class Sub: Base{}
>> static assert(is(SuperClassOf!Sub == Base));
> 
> https://dlang.org/phobos/std_traits.html#.BaseClassesTuple

Another option would be to use the following:

class Base {}
class Sub: Base {}
class Other {}

static assert(is(Sub : Base));
static assert(!is(Other : Base));

However, the ":" syntax also works for automatic conversion (see
http://ddili.org/ders/d.en/is_expr.html and search for "is (T : OtherT)").


Re: Question regarding Base64 decoding

2016-08-08 Thread Johannes Loher via Digitalmars-d-learn
Am 02.08.2016 um 00:47 schrieb Seb:
> On Monday, 1 August 2016 at 08:53:30 UTC, Kagamin wrote:
>> A bug.
> 
> ... which should be filled at Bugzilla and/or fixed. Thanks! :)

I created a pullrequest: https://github.com/dlang/phobos/pull/4720


Re: Converting int to dchar?

2016-07-31 Thread Johannes Loher via Digitalmars-d-learn
Am 31.07.2016 um 23:46 schrieb Seb:
> On Sunday, 31 July 2016 at 21:31:52 UTC, Darren wrote:
>> Hey, all.
>>
>> I'm pretty much a programming novice, so I hope you can bear with me. 
>> Does anyone know how I can change an int into a char equivalent?
>>
>> e.g.
>> int i = 5;
>> dchar value;
>> ?
>> assert(value == '5');
>>
>> If I try and cast it to dchar, I get messed up output, and I'm not
>> sure how to use toChars (if that can accomplish this).
>>
>> I can copy+paste the little exercise I'm working on if that helps?
>>
>> Thanks in advance!
> 
> Ehm how do you you want to represent 1_000 in one dchar?
> You need to format it, like here.
> 
> import std.format : format;
> assert("%d".format(1_000) == "1000");
> 
> Note that you get an array of dchars (=string), not a single one.

An immutable array of dchars is a dstring, not a string (which is an
immutable array of chars). It is true however, that you should not
convert to dchar, but to string (or dstring, if you want utf32, but i
see no real reason for this, if you are only dealing with numbers),
because of the reason mentioned above. Another solution for this would
be using "to":

import std.conv : to;

void main()
{
int i = 5;
string value = i.to!string;
assert(value == "5");
}

If you know that your int only has one digit, and you really want to get
it as char, you can always use value[0].



Question regarding Base64 decoding

2016-07-31 Thread Johannes Loher via Digitalmars-d-learn
Currently, the function Base64.decode for decoding char[] to ubyte[] has
an in contract, that should ensure that the supplied buffer is large
enough. However, it uses the function decodeLength, which does not give
the accurate decodeLength, but instead an upper bound (decodeLength can
be up to 2 bigger than realDecodeLength).

I understand, that this is useful for the cases when one wants to decode
an imputRange, becuase the it is (in general) not possible to use
realDecodeLength, because it needs random access and opDollar. But it
would be possible to use realDecodeLength when decoding an array (in
fact it is used in the out contract in this case).

My problem with this is, that I read base64 encoded data from a file,
and I know, that the data needs to be exactly 32 byte when decoded,
otherwise the data is faulty and an exception should be raised. So
naively, I would just supply a 32 byte buffer to the decode function.
But the decodeLength function returns 33 for the encoded data, so when
calling decode with a 32 byte buffer, the in contract fails. The funny
thing is, when using a release build (and thus removing all contracts)
everything works as expected.

So my question is the following: Is there any specific reason for this
behaviour (which I can't see), or is this simply a "bug" and
realDecodeLength should be used in the in contract?


Re: Initializing static array with contents of (static and dynamic) arrays

2016-07-05 Thread Johannes Loher via Digitalmars-d-learn
Am 05.07.2016 um 17:22 schrieb Marc Schütz:
> auto concat(T : E[n], E, size_t n)(const E[][] args...) @nogc
> {
> size_t offset = 0;
> T result = void;
> foreach(arr; args) {
> result[offset .. offset+arr.length] = arr;
> offset += arr.length;
> }
> assert(offset == result.length);
> return result;
> }
> 
> static immutable ubyte[4] sigma0 = [101, 120, 112,  97];
> static immutable ubyte[4] sigma1 = [110, 100,  32,  51];
> static immutable ubyte[4] sigma2 = [ 50,  45,  98, 121];
> static immutable ubyte[4] sigma3 = [116, 101,  32, 107];
> 
> void func(in ref ubyte[32] key, in ref ubyte[16] n) @nogc
> {
> ubyte[64] buf;
> buf[0..4] = sigma0;
> buf[4..20] = key[0..16];
> buf[20..24] = sigma1;
> buf[24..40] = n;
> buf[40..44] = sigma2;
> buf[44..60] = key[16..$];
> buf[60..64] = sigma3;
> 
> auto buf2 = concat!(ubyte[64])(sigma0, key[0..16], sigma1, n,
> sigma2, key[16..$], sigma3);
> 
> assert(buf == buf2);
> }
> 
> void main() {
> ubyte[32] key =
> [0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1];
> ubyte[16] n   = key[0..16];
> func(key, n);
> }
> 
> 
> Some remarks:
> 
> * I added `ref` to `func`'s parameters, because the arrays are
> relatively large, so passing them by value might be costly (you should
> measure it if you care).
> 
> * The `void` initialization in `concat` is an optimization that is valid
> only for POD types.
> 
> * Returning the array is cheap because of NRVO.

This seems to be exactly what I was looking for. Thanks a lot!



Re: Initializing static array with contents of (static and dynamic) arrays

2016-07-05 Thread Johannes Loher via Digitalmars-d-learn
Am 05.07.2016 um 17:12 schrieb Johannes Loher:
> Am 05.07.2016 um 16:39 schrieb Rene Zwanenburg:
>> On Tuesday, 5 July 2016 at 12:34:20 UTC, Johannes Loher wrote:
>>> I tried this, but it does not work correctly with slices.
>>
>> The length of a slice is a runtime value, which is why it can't be used
>> to set static array size. What were you trying to achieve? Avoid copying
>> the input arrays, or accepting any slice?
>>
>> In case of the first, you can put ref in front of the Args:
>> auto combineArrays(Args...)(ref Args args)
>>
>> The second case will be a bit harder to solve nicely..
> 
> I would like to be able, to accept any slice. In the example in my first
> post, I need this for key[0..16] and key[16..$] (which are slices).
> Strangely enough, the solution I am leaning towards at the moment also
> uses length, but it does work for slices of static arrays (i.e. key[0..16]):
> 
> template expand(alias A)
> {
> auto ref M(alias I)() @property { return A[I]; }
> mixin(q{alias expand = TypeTuple!(}
> ~ iota(A.length).map!(a => "M!" ~ a.to!string).join(",")
> ~ q{);});
> }
> 
> ubyte[64] buf = [expand!sigma0,
>  expand!key[0..16],
>  expand!sigma1,
>  expand!n,
>  expand!sigma2,
>  expand!key[16..$],
>  expand!sigma3];
> 
> I suppose this is because the length of those slices is actually known
> at copiletime, but it looks a bit strange to me...
> 
> I was trying to write another template that takes several arrays and
> expands all of them:
> 
> template expand(Args...)
> {
> mixin(q{alias expand = TypeTuple!(}
> ~ iota(Args.length).map!(a => "expand!(Args[" ~ a.to!string ~
> "])").join(",")
> ~ q{);});
> }
> 
> It works for static arrays, but not for slices, because the template
> parameters are not alias parameters, so the length is then not "known"
> at compile time (at least that's what I think why it fails). Is there a
> way to specify variadic templates taking any number of alias template
> parameters?
> 

Well, I just realized my method does not work in the case that I want to
use expand on static arrays, which are returned from template functions...



Re: Initializing static array with contents of (static and dynamic) arrays

2016-07-05 Thread Johannes Loher via Digitalmars-d-learn
Am 05.07.2016 um 16:39 schrieb Rene Zwanenburg:
> On Tuesday, 5 July 2016 at 12:34:20 UTC, Johannes Loher wrote:
>> I tried this, but it does not work correctly with slices.
> 
> The length of a slice is a runtime value, which is why it can't be used
> to set static array size. What were you trying to achieve? Avoid copying
> the input arrays, or accepting any slice?
> 
> In case of the first, you can put ref in front of the Args:
> auto combineArrays(Args...)(ref Args args)
> 
> The second case will be a bit harder to solve nicely..

I would like to be able, to accept any slice. In the example in my first
post, I need this for key[0..16] and key[16..$] (which are slices).
Strangely enough, the solution I am leaning towards at the moment also
uses length, but it does work for slices of static arrays (i.e. key[0..16]):

template expand(alias A)
{
auto ref M(alias I)() @property { return A[I]; }
mixin(q{alias expand = TypeTuple!(}
~ iota(A.length).map!(a => "M!" ~ a.to!string).join(",")
~ q{);});
}

ubyte[64] buf = [expand!sigma0,
 expand!key[0..16],
 expand!sigma1,
 expand!n,
 expand!sigma2,
 expand!key[16..$],
 expand!sigma3];

I suppose this is because the length of those slices is actually known
at copiletime, but it looks a bit strange to me...

I was trying to write another template that takes several arrays and
expands all of them:

template expand(Args...)
{
mixin(q{alias expand = TypeTuple!(}
~ iota(Args.length).map!(a => "expand!(Args[" ~ a.to!string ~
"])").join(",")
~ q{);});
}

It works for static arrays, but not for slices, because the template
parameters are not alias parameters, so the length is then not "known"
at compile time (at least that's what I think why it fails). Is there a
way to specify variadic templates taking any number of alias template
parameters?



Re: Initializing static array with contents of (static and dynamic) arrays

2016-07-05 Thread Johannes Loher via Digitalmars-d-learn
Am 05.07.2016 um 00:41 schrieb Rene Zwanenburg:
> On Monday, 4 July 2016 at 19:22:52 UTC, Johannes Loher wrote:
>> This looks really nice, but I have several occurences of this, with
>> different arrays (and lengths), so i would need to create several of
>> those structs. But it looks really clean :)
> 
> You can use a template to remove the boilerplate. Here's a quick example:
> 
> https://dpaste.dzfl.pl/43b379992648

I tried this, but it does not work correctly with slices.


Re: Initializing static array with contents of (static and dynamic) arrays

2016-07-04 Thread Johannes Loher via Digitalmars-d-learn
Am 04.07.2016 um 19:24 schrieb ZombineDev:
> On Monday, 4 July 2016 at 14:31:41 UTC, Johannes Loher wrote:
>> In a project I am currently working on, I have lot's of code of the
>> following form:
>>
>> static immutable ubyte[4] sigma0 = [101, 120, 112,  97]; static
>> immutable ubyte[4] sigma1 = [110, 100,  32,  51]; static immutable
>> ubyte[4] sigma2 = [ 50,  45,  98, 121]; static immutable ubyte[4]
>> sigma3 = [116, 101,  32, 107];
>>
>> void func(in ubyte[32] key, in ubyte[16] n)
>> {
>> ubyte[64] buf;
>> buf[0..4] = sigma0;
>> buf[4..20] = key[0..16];
>> buf[20..24] = sigma1;
>> buf[24..40] = n;
>> buf[40..44] = sigma2;
>> buf[44..60] = key[16..$];
>> buf[60..64] = sigma3;
>>
>>/* do something with buf */
>> }
>>
>> This looks really bad to me. I would like to initialize buf with the
>> corresponding values (the way it's done now, it is impossible to make
>> buf immutable...).
>>
>> One option for this would be to use ~ to concatenate the arrays. But
>> this obviously results in GC allocations, which I want to avoid here,
>> because the functions get called very often.
>>
>> Another option would be to to manually expand the arrays and
>> initialize buf with that:
>>
>> ubyte[64] buf = [sigma0[0], sigma0[1], /* ... */, sigma3[3]];
>>
>> This is obviously very annoying and error prone.
>>
>> Whe searching for a solution, I found this thread about automatic
>> expanding of arrays:
>>
>> http://forum.dlang.org/thread/hwellpcaomwbpnpof...@forum.dlang.org?page=1
>>
>> This would result in the following code for me:
>>
>> ubyte[64] buf = [
>> expand!sigma0,
>> expand!key[0..16],
>> expand!sigma1,
>> expand!n,
>> expand!sigma2,
>> expand!key[16..$],
>> expand!sigma3
>> ];
>>
>> Is this the suggested solution (is it robust)? Is there anything like
>> this in Phobos?
>>
>> Thanks for your help!
> 
> You should be able to use
> http://dlang.org/phobos-prerelease/std_meta#aliasSeqOf for this.
> 
> I think it should work with the same syntax as expand, but with added
> bonus that it also handles ranges like those in std.range and
> std.algorithm.
I just tried that, but it does not work for arrays, which can not be
read at compile time.


Re: Initializing static array with contents of (static and dynamic) arrays

2016-07-04 Thread Johannes Loher via Digitalmars-d-learn
Am 04.07.2016 um 20:33 schrieb Ali Çehreli:
> On 07/04/2016 07:31 AM, Johannes Loher wrote:
>> In a project I am currently working on, I have lot's of code of the
>> following form:
>>
>> static immutable ubyte[4] sigma0 = [101, 120, 112,  97];
>> static immutable ubyte[4] sigma1 = [110, 100,  32,  51];
>> static immutable ubyte[4] sigma2 = [ 50,  45,  98, 121];
>> static immutable ubyte[4] sigma3 = [116, 101,  32, 107];
>>
>> void func(in ubyte[32] key, in ubyte[16] n)
>> {
>>  ubyte[64] buf;
>>  buf[0..4] = sigma0;
>>  buf[4..20] = key[0..16];
>>  buf[20..24] = sigma1;
>>  buf[24..40] = n;
>>  buf[40..44] = sigma2;
>>  buf[44..60] = key[16..$];
>>  buf[60..64] = sigma3;
>>
>> /* do something with buf */
>> }
> 
> Here's an option that overlays a struct on top of the bytes:
> 
> struct Buf {
> union {
> struct {
> ubyte[4] sigma0 = [101, 120, 112,  97];
> ubyte[16] keyBeg;
> ubyte[4] sigma1 = [110, 100,  32,  51];
> ubyte[16] n;
> ubyte[4] sigma2 = [ 50,  45,  98, 121];
> ubyte[16] keyEnd;
> ubyte[4] sigma3 = [116, 101,  32, 107];
> }
> 
> ubyte[64] bytes;
> }
> 
> this(const ubyte[] key, const ubyte[] n) {
> this.keyBeg = key[0..16];
> this.keyEnd = key[16..$];
> this.n = n;
> }
> }
> 
> static assert(Buf.sizeof == 64);
> 
> void func(in ubyte[] key, in ubyte[] n) {
> auto buf = Buf(key, n);
> writeln(buf.bytes);
> }
> 
> import std.stdio;
> import std.range;
> import std.array;
> 
> void main() {
> func(ubyte(32).iota.array,
>  ubyte(16).iota.array);
> }
> 
> Prints:
> 
> [101, 120, 112, 97, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
> 15, 110, 100, 32, 51, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
> 15, 50, 45, 98, 121, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
> 29, 30, 31, 116, 101, 32, 107]
> 
> Ali
> 
This looks really nice, but I have several occurences of this, with
different arrays (and lengths), so i would need to create several of
those structs. But it looks really clean :)


Initializing static array with contents of (static and dynamic) arrays

2016-07-04 Thread Johannes Loher via Digitalmars-d-learn
In a project I am currently working on, I have lot's of code of the
following form:

static immutable ubyte[4] sigma0 = [101, 120, 112,  97];
static immutable ubyte[4] sigma1 = [110, 100,  32,  51];
static immutable ubyte[4] sigma2 = [ 50,  45,  98, 121];
static immutable ubyte[4] sigma3 = [116, 101,  32, 107];

void func(in ubyte[32] key, in ubyte[16] n)
{
ubyte[64] buf;
buf[0..4] = sigma0;
buf[4..20] = key[0..16];
buf[20..24] = sigma1;
buf[24..40] = n;
buf[40..44] = sigma2;
buf[44..60] = key[16..$];
buf[60..64] = sigma3;

   /* do something with buf */
}

This looks really bad to me. I would like to initialize buf with the
corresponding values (the way it's done now, it is impossible to make
buf immutable...).

One option for this would be to use ~ to concatenate the arrays. But
this obviously results in GC allocations, which I want to avoid here,
because the functions get called very often.

Another option would be to to manually expand the arrays and initialize
buf with that:

ubyte[64] buf = [sigma0[0], sigma0[1], /* ... */, sigma3[3]];

This is obviously very annoying and error prone.

Whe searching for a solution, I found this thread about automatic
expanding of arrays:

http://forum.dlang.org/thread/hwellpcaomwbpnpof...@forum.dlang.org?page=1

This would result in the following code for me:

ubyte[64] buf = [
expand!sigma0,
expand!key[0..16],
expand!sigma1,
expand!n,
expand!sigma2,
expand!key[16..$],
expand!sigma3
];

Is this the suggested solution (is it robust)? Is there anything like
this in Phobos?

Thanks for your help!



Re: problem with std.range.choose()

2016-02-20 Thread Johannes Loher via Digitalmars-d-learn
On Wednesday, 17 February 2016 at 01:35:34 UTC, Johannes Loher 
wrote:

Hello, I have a problem with using std.range.choose():

When using std.range.choose() on a range R, for which 
hasElaborateCopyConstructor!R is true, then a postblit for the 
result of std.range.choose() is created, which includes a call 
to R.__postblit(). However, hasElaborateCopyConstructor!R may 
be true, even if R does not define this(this), for example in 
the case that one of the members of R does so.


[...]


Well, has anybody got an idea if this behaviour is intended? Is 
it a bug?


problem with std.range.choose()

2016-02-16 Thread Johannes Loher via Digitalmars-d-learn

Hello, I have a problem with using std.range.choose():

When using std.range.choose() on a range R, for which 
hasElaborateCopyConstructor!R is true, then a postblit for the 
result of std.range.choose() is created, which includes a call to 
R.__postblit(). However, hasElaborateCopyConstructor!R may be 
true, even if R does not define this(this), for example in the 
case that one of the members of R does so.


The example that I encountered (reduced to a minimum) was the the 
following:


import std.stdio : stdin;
import std.range: choose;

void main()
{
ubyte[1][] secondRange;
choose(true, stdin.byChunk(1), secondRange);
}

In this case File defines this(this), but ByChunk does not, so 
the above code does not compile.


I think what std.range.choose() does here is completely 
unnecessary: When the result of std.range.choose() gets copied, 
the underyling range gets copied, and if it implements postblit, 
it is automatically called. No need to call it explicitly, right?.


Re: Mac IDE with Intellisense

2015-09-27 Thread Johannes Loher via Digitalmars-d-learn

On Saturday, 26 September 2015 at 18:27:52 UTC, Mike McKee wrote:

On Saturday, 26 September 2015 at 10:31:13 UTC, wobbles wrote:

Have you installed dkit for sublime?


As in?

https://github.com/yazd/DKit

Looks like it's alpha and doesn't run on Mac? No homebrew 
install?


I'm using this and it works great. It uses dcd, so you need to 
install that first (via homebrew). As DKit it is a sublime text 
plugin, you don't install it via homebrew. Usually you'd install 
sublime packages via Package Control, but sadly DKit is not in 
the repositories yet. There is an issue about that already 
(https://github.com/yazd/DKit/issues/18). So instead, you install 
the package manually (just follow the instrcutions in the readme).


I don't know where you got the idea it doesn't work on OS X, it 
works like a charm for me.