Re: openssl 1.1 vs. 3.0 for vibe.d:tls on Ubuntu 22.04

2023-08-02 Thread Mathias LANG via Digitalmars-d-learn

On Friday, 28 July 2023 at 08:56:17 UTC, Guillaume Lathoud wrote:

Hello, some context first:

I recently updated a server to Ubuntu 22.04 which appears to 
have only openssl 3.0.2 installed. Dub could compile my 
project, but could not link it anymore, as the D code seemed to 
be expecting openssl 1.1 whereas only 3.0.2 was installed.


Do you compile directly on the server ? Or on an Ubuntu 22.04 
host?
The autodetection code happens by calling a D script: 
https://github.com/D-Programming-Deimos/openssl/blob/master/scripts/generate_version.d
Make sure you have `pkg-config` installed as that's what is used 
for autodetection, as well as the development libraries (the 
`-dev` package).


I've been using openssl 3 on Ubuntu 22.04 since it came out, so 
it should just work.


Re: Warning The package will no longer be detected starting from v1.42.0

2023-06-25 Thread Mathias LANG via Digitalmars-d-learn

On Sunday, 25 June 2023 at 04:50:42 UTC, Soulsbane wrote:


I'm guessing it's caused by this 
https://github.com/dlang/dub/pull/2610. What's the fix for this 
exactly? Thanks!


A fix would be to do the following:

```
for package in $($HOME/Projects/D/libs/*); do
  mv -v $package $package/master/$(basename $package)
done
```

Provided that all you have in your `libs` folder are folders that 
represent packages.
This would also allow you to use different versions of a library 
(I'm assuming you only have one, hence the `master`), and work 
with libraries like Cybershadow's `ae`.
However, I'm not sure we should expect our users to do this for a 
simple `add-path`.


Re: constant pointer failing to compile

2023-04-05 Thread Mathias LANG via Digitalmars-d-learn

immutable ubyte[4] data = [1, 2, 3, 4];


Using a static array instead of a slice will do the trick. You 
can leave the `__gshared` if you want, but it is redundant on a 
global, initialized `immutable` variable.


Re: Which TOML package, or SDLang?

2023-01-30 Thread Mathias LANG via Digitalmars-d-learn
On Monday, 30 January 2023 at 06:38:46 UTC, Daren Scot Wilson 
wrote:

So, which package do I use for TOML?

I find these three:

* toml-foolery  (Andrej Petrović)
* toml-d, or toml.d (oglu on github) at ver 0.3.0
* toml, (dlang community on github) at ver 2.0.1

I'm guessing from version numbers that the third one, toml, is 
officially good for real world use. But I wonder if there are 
good reasons to use the others.


I would go with the dlang-community one, whenever available.

Also, a low-effort search for TOML in the D world turned up 
SDLang, where the substring "DLang" has nothing to do with 
dlang, the common short name for D Language. SDLang looks nice. 
Should I ditch TOML for it?


I would not recommend it. SDL (Simple Declarative Language) is a 
language we have support for, but it's rather unknown - TOML will 
probably be simpler for end users.


I just realized - it's been ages since I've dealt with config 
files, beyond editing them as an end user. I work on existing 
software where someone else made the choiced and wrote the 
code, or it's a small specialized project not needing config. 
I'm a config caveman!


This is for a small fun personal project with potential 
show-off value, available on github but too primitive for now 
to mention. Controlling hardware, needing to store device info 
to recall for later runs. There are zero compatibility or 
standards issues to consider.  Whatever is simplest to 
implement and tinker with is the winner.


If I can allow a shameless self plug, and if you are willing to 
consider YAML:

https://github.com/dlang-community/configy

If you are willing to stick to a "simple" config where you 
essentially want some values to end up in a struct, and want 
decent error messages, this is for you.


Re: forgetting -betterC means no runtime bounds checking?

2023-01-05 Thread Mathias LANG via Digitalmars-d-learn
On Thursday, 5 January 2023 at 09:17:28 UTC, areYouSureAboutThat 
wrote:
core.exception.ArrayIndexError@test.d(25): index [5] exceeds 
array of length 5

Aborted (core dumped)


This is bounds checking happening.


Re: Makefiles and dub

2022-11-08 Thread Mathias LANG via Digitalmars-d-learn

On Friday, 4 November 2022 at 23:19:17 UTC, Anonymouse wrote:
[#20699](https://issues.dlang.org/show_bug.cgi?id=20699) must 
be non-trivial to fix, so I'm exploring makefiles. If possible 
I'd like to keep dub for dependency management though, just not 
for actual compilation.


That bug is fixed for the last 3 releases (not including the 
current one in progress), that is, since v1.26.0.


Is it at all possible (or even desireable) to construct a 
makefile that builds dependencies from outside of the source 
tree (namely 
`$HOME/.dub/packages/package_with_unknown_version-1.2.[0-9]+/`)?


Does anyone have an example `Makefile` I could dissect?

Thanks.


In the past, I used https://github.com/sociomantic-tsunami/makd 
for building D code.
But it doesn't do dependency management like dub, as it expected 
libraries to be in `submodules/`.


Re: Best practice for dub registry package and module names

2022-09-03 Thread Mathias LANG via Digitalmars-d-learn

On Sunday, 4 September 2022 at 01:52:11 UTC, Ali Çehreli wrote:
Should the package be the author's name: acehreli.a, 
acehreli.b, and acehreli.c?


I use this approach:
https://forum.dlang.org/thread/jdkmtgftmwtwaxxqh...@forum.dlang.org


Re: Constructors not working

2022-09-03 Thread Mathias LANG via Digitalmars-d-learn

On Friday, 2 September 2022 at 18:35:22 UTC, Svyat wrote:

I write this code in one directory:

```
module time;

struct Time {
public int hours, minutes, seconds;
this(int h, int m, int s) {
hours = h;
minutes = m;
seconds = s;
}
Time opBinary(string op : "=")(int secos) {
assert(secos <= 86_400);
return new Time(secos / 3600, (secos % 3600) / 60, 
secos % 60);

}
}
```

```
module testfortime;
import time;
import std.stdio;

void main() {
Time time = 360;
write(time.hours);
readln;
}
```

After execute 'dmd -run ./testfortime.d' i got this:
```
".\testfortime.d(6): Error: constructor `time.Time.this(int h, 
int m, int s)` is not callable using argument types `(int)`
.\testfortime.d(6):too few arguments, expected `3`, got 
`1`"

```

WTF? Why standart constructor isn`t callable? How it`s possible 
in a programming language?


First of all, the error message is telling you what is wrong: You 
are calling the constructor with only one argument, while your 
constructor is declared to take 3.
If you wanted your call to work, you should have declared the 
constructor as:

```
this(int h, int m = 0, int s = 0) { /* Magic */ }
```

But D will by default give you a default constructor that does 
exactly that. And the constructor will be properly attributed, 
because in your case, the constructor should actually be this:

```
this(int h, int m = 0, int s = 0) inout scope @safe pure nothrow 
@nogc { /* Magic */ }

```

So if you just remove the constructor, things will work. Note 
that in D, as soon as you define one constructor, the default one 
is no longer generated.


Second, your `opBinary` cannot compile, because `Time` is a 
`struct`, and if you are returning a `new Time` in `opBinary`, 
you should return a `Time*`. Currently it's working because you 
are not using it.


Finally, there is a module in druntime for time management, which 
provides a very nice API: `core.time : Duration`. It will allow 
you to do everything you want to do with your code, and more.
For example: `import core.time; auto time = 1.hour; 
writeln(time);`


Re: Comping a Musl-linked druntime & phobos?

2022-08-24 Thread Mathias LANG via Digitalmars-d-learn

On Thursday, 25 August 2022 at 01:45:50 UTC, TheGag96 wrote:
Hi, all. Has anyone had any success compiling a Musl-linked 
druntime and phobos? I haven't had any luck so far. I'm running 
Linux Mint x64.


Somewhat related - using `-target=x86_64-linux-musl` with dmd 
master doesn't even set the version `CRuntime_Musl`. I asked 
about this in the Discord, and I was told by Horo:


dmd 2.096 worked well for me. Same for gdc, haven't tried ldc. 
There is/was a bug that was introduced recently in druntime 
that broke musl but the older versions should work fine


2.096 doesn't have the `-target` option, and 2.097.0-2.098.0 
don't even build properly for me. Using LDC to build works of 
course, but only with `-betterC` (i.e. no druntime/phobos).


Hi!
Thinks should mostly work. There is some issues with stack 
traces, but I don't remember the details. Check what Alpine Linux 
is doing: 
https://gitlab.alpinelinux.org/alpine/aports/-/tree/master/community/dmd


Note that the `target` should not be required: 
https://github.com/dlang/dmd/blob/09d04945bdbc0cba36f7bb1e19d5bd009d4b0ff2/compiler/src/dmd/target.d#L1177-L1180


Re: Approach to Integration Testing in D

2022-02-04 Thread Mathias LANG via Digitalmars-d-learn

On Friday, 4 February 2022 at 12:38:08 UTC, Vijay Nayar wrote:

Greetings everyone,

## Question

What is your approach to integration testing in D? Do you use 
`unittest` blocks? Do you write stand-alone programs that 
interact with a running version of your program? Is there a 
library that makes certain kinds of testing easier?


For server nodes, I've built a library just for this:
https://github.com/Geod24/localrest

It required careful planning on the application side (e.g. we're 
not calling `runTask`, we have some classes for dependency 
injection), but allowed us to write "integration tests" in 
unittests block: 
https://github.com/bosagora/agora/tree/75967aac4f41272c6e5e8487c4066174825290e0/source/agora/test#agora-test-folder


Re: "need `this` for `s` of type `char*`" error message

2021-11-10 Thread Mathias LANG via Digitalmars-d-learn

On Thursday, 11 November 2021 at 07:10:39 UTC, Mathias LANG wrote:

[...]


Your type definition is wrong:
```D
struct toml_datum_t {
  int ok;
  union u {
toml_timestamp_t* ts; /* ts must be freed after use */
char*   s; /* string value. s must be freed after use */
int b; /* bool value */
int64_t i; /* int value */
double  d; /* double value */
  }
}
```

If you check the size of this struct, it's going to be 4,
because `u` is a type definition. What you want is either:

```D
struct toml_datum_t {
  int ok;
  union {
toml_timestamp_t* ts; /* ts must be freed after use */
char*   s; /* string value. s must be freed after use */
int b; /* bool value */
int64_t i; /* int value */
double  d; /* double value */
  }
}
```

Which you access via `host.s` or:

```D
struct toml_datum_t {
  int ok;
  /// This is the type definition
  union U {
toml_timestamp_t* ts; /* ts must be freed after use */
char*   s; /* string value. s must be freed after use */
int b; /* bool value */
int64_t i; /* int value */
double  d; /* double value */
  }
  /// This is the field
  U u;
}
```

Note that instead of doing this work yourself, I would highly 
recommend the excellent 
[dstep](https://github.com/jacob-carlborg/dstep).


Fixed formatting (so much for "Fix it for me").


Re: "need `this` for `s` of type `char*`" error message

2021-11-10 Thread Mathias LANG via Digitalmars-d-learn

On Thursday, 11 November 2021 at 07:04:57 UTC, rempas wrote:
After not being able to use ImportC to automatically compile a 
C library, now I'm trying to do it myself. The library I want 
to use is [tomlc99](https://github.com/cktan/tomlc99) which is 
a small C library to parse toml files. Now I compiled the 
library and I copied the "config.h" file and modified to make 
it a D file that will contain the declaration so D knows which 
symbols to call. I resulted with a "toml.d" file and a "main.d" 
file. The first one contains the decorations and the second one 
contains the code from the example in the 
[usage](https://github.com/cktan/tomlc99#usage) section. 
However, when I try to compile, I'm getting the following error 
message:


```
main.d(51): Error: need `this` for `s` of type `char*`
Deprecation: argument `__error` for format specification `"%s"` 
must be `char*`, not `_error_`

main.d(57): Error: need `this` for `i` of type `long`
main.d(63): Error: need `this` for `s` of type `char*`
```

I uploaded the modified files so someone is able to look at 
them and explain me what I'm doing wrong so I can properly 
learn. Links:


[toml.d](https://gist.github.com/rempas/8aaab43b71e3da720ce298ef472f0673)
[main.d](https://gist.github.com/rempas/07dfb15295c5f6142c6a8dfab669c40e)


Your type definition is wrong:
```D
struct toml_datum_t {
  int ok;
  union u {
toml_timestamp_t* ts; /* ts must be freed after use */
char*   s; /* string value. s must be freed after use */
int b; /* bool value */
int64_t i; /* int value */
double  d; /* double value */
  }
}
```

If you check the size of this struct, it's going to be 4, 
because `u` is a type definition. What you want is either:

```D
struct toml_datum_t {
  int ok;
  union {
toml_timestamp_t* ts; /* ts must be freed after use */
char*   s; /* string value. s must be freed after use */
int b; /* bool value */
int64_t i; /* int value */
double  d; /* double value */
  }
}
```

Which you access via `host.s` or:
```D
struct toml_datum_t {
  int ok;
  /// This is the type definition
  union U {
toml_timestamp_t* ts; /* ts must be freed after use */
char*   s; /* string value. s must be freed after use */
int b; /* bool value */
int64_t i; /* int value */
double  d; /* double value */
  }
  /// This is the field
  U u;
}
```

Note that instead of doing this work yourself, I would highly 
recommend the excellent 
[dstep](https://github.com/jacob-carlborg/dstep).


Re: A way to mixin during runtime?

2021-08-27 Thread Mathias LANG via Digitalmars-d-learn

On Friday, 27 August 2021 at 06:52:10 UTC, Kirill wrote:

Is there a way to do mixin or similar during runtime?

I'm trying to read a csv file and extract data types. Any ideas 
on how this should be approached in D are greatly appreciated.


You cannot mixin at runtime. However, it is fairly easy to map a 
finite and CT-know set of argument to runtime arguments via 
`static foreach`.
Could you give us example of the content of your CSV file and 
what you are trying to do ?


Re: Potential strategy for avoiding problems with copy of a struct (maybe??)

2021-08-22 Thread Mathias LANG via Digitalmars-d-learn

On Sunday, 22 August 2021 at 07:58:12 UTC, james.p.leblanc wrote:


Is there a better way?

Best Regards,
James


```
public mixin template NonMovableOrCopyable ()
{
@disable this ();
@disable this (this);
@disable ref typeof (this) opAssign () (auto ref typeof(this) 
rhs);

}
```

This will catch most mistakes at CT. However the language is 
technically free to copy / move structs at will (and interior 
pointers are forbidden).
A recent enough version of LDC (>= v1.20.0 IIRC, might be 
v1.22.0) will do a very good job at not needlessly moving things 
around.
See for example the discussion here: 
https://forum.dlang.org/thread/miuevyfxbujwrhghm...@forum.dlang.org


DMD on the other hand is much more likely to not perform NRVO / 
move things, so be wary of compiler differences.


Re: modules and mains

2021-08-22 Thread Mathias LANG via Digitalmars-d-learn

On Sunday, 22 August 2021 at 03:22:02 UTC, Brian Tiffin wrote:
Is this wrong thinking?  I'm ~~working on~~ playing with a 
first project.


Meant to be a suite of tools, each usable from the command 
line, i.e. with a `main`.  Then a manager program that accepts 
subcommands for dispatch *and other boss type things*.


boss.d wants to import command1.d command2.d etc.

Is there a way for `command1.d` to know it's an `import` versus 
a file named as part of a `gdc` compile?


I'd like to skip defining `main` during `import` (using a 
different name for boss dispatch), but do define `main` when 
it's a standalone compile.  Or is that a bad way of thinking 
about D program development interactions?


Cheers


IIUC, you want to generate multiple binaries, too ?
In which case, I think you need more of a build tool solution 
than a language solution.


Recent-ish versions of DUB (>= v1.24.0) support this out of the 
box.

Provided the following structure:
```
+ $(pwd)
+ - dub.json
+ - source/
+ - source/appname/
+ - source/appname/prog1.d
+ - source/appname/prog2.d
+ - source/appname/common.d
```

If your `dub.json` contains:
```
{
  "name": "swissarmyknife",
  "targetType": "executable",

  "configurations": [
{
  "name": "prog1",
  "targetName": "prog1",
  "mainSourceFile": "source/appname/prog1.d"
},
{
  "name": "prog2",
  "targetName": "prog2",
  "mainSourceFile": "source/appname/prog2.d"
}
}
```

It will build `prog1` by default, and `prog2` if you use `dub 
build -c prog2`.
Note that you might want to put a `library` configuration as 
first entry,
so that you can also use your code base as a library if you wish 
to extend your project later.


Re: Drawbacks of exceptions being globally allocated

2021-08-15 Thread Mathias LANG via Digitalmars-d-learn

On Monday, 16 August 2021 at 05:36:07 UTC, Tejas wrote:


That is why I was using heapAllocate, because using `new` on 
scope allocates exception on stack, and if you exit, then the 
exception is basically freed before it even gets caught. It 
fails even when you catch within the same function.


But allocate on heap and giving ownership to a `scope` 
qualified variable is no problem at all. No `signal 11` killing 
my process ^_^


You are relying on an accept-invalid though. The compiler *should 
not* accept that code, but currently erroneously does so.


Re: Drawbacks of exceptions being globally allocated

2021-08-14 Thread Mathias LANG via Digitalmars-d-learn

On Sunday, 15 August 2021 at 02:09:08 UTC, Tejas wrote:

On Sunday, 15 August 2021 at 00:15:32 UTC, Ali Çehreli wrote:

On 8/14/21 4:41 AM, Tejas wrote:

> [...]
exception
> [...]

So, there would be many exception objects one for each place 
that an exception can be thrown. Functions like enforce() 
would have to take a reference to the exception object that is 
associated with that local scope.


[...]


I just want ```@nogc``` exceptions ;_;

Please tell me that the ```GC.stats``` thing I posted is 
irrelevant so that I can go back to using ```emplace```.


I wanted to allocate a class on the heap without being forced 
to use templates... but I guess that simply isn't possible(I 
know I can use ```mixin```, but that's even worse).


You can't really have `@nogc` allocated Exception without 
circumventing the type system. Personally I gave up on `@nogc` 
just because of how inconvenient it is.


Regarding the broader topic, at Sociomantic, we had pre-allocated 
Exception. After years working there, I grew to see the `throw 
new Exception` you see everywhere as an anti-pattern.


Exceptions aren't convenient to use. At the very least, we should 
have a way to print a formatted message, however nothing 
currently offers this.


A simple way to achieve this is the following:
https://github.com/bosagora/agora/blob/113c89bd63048a7b98b8e9a2a664bd0eb08ebc84/source/agora/common/Ensure.d

The gist of it is a statically allocated Exception (via module 
ctor) that is thrown by our `ensure` method. This is not `pure` 
unfortunately (because accessing a global mutable is not pure), 
and not `@nogc` (because `snformat` / `formattedWrite` aren't 
`@nogc`), but it doesn't allocate.


As Ali mentioned, having a single Exception in the program breaks 
Exception chaining. But Exception chaining is one of the lowest 
ROI feature of D: It took a lot of effort to implement correctly, 
and is barely, if at all, used. There have even been talks 
(involving Walter) of deprecating it.


If your goal is to never *link* in the GC, then you can barely 
use Phobos. If your goal is to never use the GC, I would say, why 
? Using the GC for long-lived object and/or infrequent allocation 
doesn't hurt. GC collections are only triggered when you call 
new, so as long as you keep your critical path free of 
allocations, you're in the clear.


Another little piece of code you might find interesting: 
https://github.com/sociomantic-tsunami/ocean/blob/adb31c84baa2061d07aaa0cb7a7d14c3cc98309b/src/ocean/core/Test.d#L305-L340


This uses a built-in method (`gc_stats`) which predates 
`GC.stats` and doesn't work in D2, but I'm sure you'll easily 
figure out how to adapt it :)


Re: input range with non copyable element

2021-08-08 Thread Mathias LANG via Digitalmars-d-learn

On Sunday, 8 August 2021 at 18:36:02 UTC, vit wrote:
Hello, is there reason why elements of input range must be 
copyable?


By design, not that I can think of. But it is assumed all over 
the place, unfortunately. You can make your `front` method return 
by `ref`, but you're still going to get bitten as soon as you do 
any `std.algorithm`-based operation, as storage classes are not 
inferred (https://issues.dlang.org/show_bug.cgi?id=9423) and 
things get passed by value to your delegates by default. The 
problem can also show up when you `foreach` over a range 
(https://issues.dlang.org/show_bug.cgi?id=15413). And finally, 
`std.algorithm` need to support it.


So currently you'll have to jump through a lot of hops to get it 
to work. It'll be much easier to use your own `map` & co to get 
the job done for the time being. Hopefully at some point in the 
near future that won't be needed anymore.


Re: __FILE__

2021-08-04 Thread Mathias LANG via Digitalmars-d-learn

On Monday, 26 July 2021 at 11:43:56 UTC, workman wrote:

file test.d:

-
module test;
import abc;
void doTest(){
log!"test"();
}
---

file abc.d:
-
module abc;
import test;
void log(string fmt, int line = __LINE__, string path = 
__FILE__[0..$], A...)(A a) {

import core.stdc.stdio;
printf("[%s:%d] \n", path.ptr, line);
}
extern(C) int main() {
doTest();
return 0;
}

-

retult: [abc.d:4]

expect: [test.d:4]


It's a known bug: https://issues.dlang.org/show_bug.cgi?id=18919
If you remove the slicing from `__FILE__`, it'll work as expected.


Re: module search paths

2021-08-04 Thread Mathias LANG via Digitalmars-d-learn

On Wednesday, 4 August 2021 at 04:51:48 UTC, Brian Tiffin wrote:
With `import std.json` working for the other symbols like 
parseJSON?


`gdc-11 (Ubuntu 11.1.0-1ubuntu1~18.04.1) 11.1.0`

Have good.


You are using GDC 11, which has an older version of the frontend.
GDC is pretty great for targeting a variety of platform and 
having a very stable compiler, but it comes with the downside 
that it is updated less frequently (tied to GCC releases) and the 
docs may get outdated.


JSONType used to be named `JSON_TYPE`, and this was changed in 
v2.082.0. I think GDC-11 is somewhere around v2.076.0 (with a lot 
of backport for bugs, but no feature / Phobos backport). Since 
v2.082.0 was released 2018-09-02 (almost 3 years ago), the 
documentation has long moved.


TL;DR: Use `JSON_TYPE`.
Note that you can quickly get LDC / DMD setup with the install 
script, or d-apt (https://d-apt.sourceforge.io/).


Re: Name Mangling & its representation of D types

2021-08-03 Thread Mathias LANG via Digitalmars-d-learn

On Tuesday, 3 August 2021 at 20:29:10 UTC, NonNull wrote:

On Tuesday, 3 August 2021 at 17:01:38 UTC, Mike Parker wrote:

On Tuesday, 3 August 2021 at 16:43:52 UTC, NonNull wrote:
how does it work for recursive types like a struct containing 
a pointer to a struct of the same type


A struct `S` with a member of type `S*` is still just a struct 
`S`. The pointer doesn't change anything about the type.


Aha, so it just uses the name S, not an algebraic 
representation of the structure of S.


Yes, because D is a nominal type system, using the FQN of the 
symbol is enough.


Mangled names start with `_D` and then contain the encoding of 
the symbol being mangled (can be a variable, a function, etc...).


To avoid an explosion in the symbol length we have back reference 
(which the blog mentions IIRC). Not only are parameter types 
encoded, but so are function attributes (`@safe` and co), with 
the notable exception of inferred `scope`, to allow people to 
link `-dip1000` code with non-DIP1000 code.


`core.demangle` provides a programmatic way to demangle a symbol 
to its code representation. `ddemangle`, packed with DMD, allow 
to do it via the CLI (similar to `c++filt`). Newer binutils have 
support for D as well, so `nm --demangle=dlang` works (note that 
some older binutils support this, but don't support backref).


Mangling is altered by `extern(LANG)` (where LANG is one of `C`, 
`C++`, `Objective-C`, `System`, `D`), or `pragma(mangle)`.


Re: Exit before second main with -funittest

2021-07-29 Thread Mathias LANG via Digitalmars-d-learn

On Friday, 30 July 2021 at 03:45:21 UTC, Ali Çehreli wrote:

Almost all of my programs are in the following pattern:

```D
import std.stdio;

void main(string[] args) {
  version (unittest) {
// Don't execute the main program when unit testing
return;
  }
}
```


Are you aware that this isn't necessary since v2.090.0 ?
https://dlang.org/changelog/2.090.0.html#unittest-default


Re: Performance issue with fiber

2021-07-28 Thread Mathias LANG via Digitalmars-d-learn

On Wednesday, 21 July 2021 at 22:51:38 UTC, hanabi1224 wrote:
Hi, I'm new to D lang and encounter some performance issues 
with fiber, not sure if there's something obviously wrong with 
my code.


I took a quick look, and the first problem I saw was that you 
were using `spawnLinked` but not replacing the scheduler.
`std.concurrency` uses a global `scheduler` variable to do its 
job.

Hence doing:
```diff
- auto scheduler = new FiberScheduler();
+ scheduler = new FiberScheduler();
```

Will ensure that `spawnLinked` works as expected.
There are a few other things to consider, w.r.t. fibers:
- Our Fibers are 4 pages (on Linux) by default;
- We have an extra guard page, because we are a native language, 
so we can't do the same trick as Go to auto-grow the stack;
- Spawning fibers *is* expensive and other languages reuse fibers 
(Yes, Go recycle them);


The `FiberScheduler` implementation is unfortunately pretty bad: 
it [does not re-use 
fibers](https://github.com/dlang/phobos/blob/b48cca57e8ad2dc56872499836bfa1e70e390abb/std/concurrency.d#L1578-L1599). I believe this is the core of the issue.


Re: enum true, or 1

2021-07-21 Thread Mathias LANG via Digitalmars-d-learn

On Thursday, 22 July 2021 at 03:44:13 UTC, Brian Tiffin wrote:
What is the preferred syntax for simple on/off states?  Did I 
read that D was moving to strictly 1 and 0 literals instead of 
true/false on/off yes/no?


If so, is there an idiom for yes/no/maybe  -1,0,1  
less/equal/greater?


Excuse the noise.  For some backfill; getting used to DDoc.  
Frontmatter can be attached to the module declaration.  Great 
for setting up a page.  Wanted to do something similar for 
backmatter, in particular the without warranty disclaimer 
(instead of it taking up space on the first screen of a 
listing).  That means attaching backmatter doc comments to a 
declaration, something akin to `enum INDEMNITY = true;`.  Or is 
it `= 1`?


Opinions welcome, as this will end up being nothing more than a 
personal preference, but it would be nice to avoid dragging 
fingernails over anyone's mental chalkboard.


Have good, make well.


AFAIK, the usual wisdom is to use `true` or `false` over `1` and 
`0`.
However, it still might not be enough in a public API, so there 
is `std.typecons.Flag`: 
https://dlang.org/library/std/typecons/flag.html


Last but not least, `true` is defined as `1` per the spec, so the 
following is valid:

```
char[] myString = getString();
bool hasNullCharAtEnd = parseString(myString);
char[] copy = new char[](myString.length - hasNullCharAtEnd);
```

This is quite useful when needed to offset something by one: Just 
add or subtract your `bool` value.


Re: How to Fix Weird Build Failure with "-release" but OK with "-debug"?

2021-07-20 Thread Mathias LANG via Digitalmars-d-learn

On Wednesday, 21 July 2021 at 03:25:03 UTC, apz28 wrote:

with below error message:
..\..\pham\db\db_skdatabase.d(140): Error: null dereference in 
function 
_D4pham2db10fbdatabase7FbArray__T13readArrayImplTbZQsMFNfCQCeQCc8database12DbNameColumnZAb
..\..\pham\db\db_skdatabase.d(139): Error: null dereference in 
function 
_D4pham2db10fbdatabase7FbArray__T13readArrayImplTbZQsMFNfCQCeQCc8database12DbNameColumnZAb
Error: null dereference in function 
_D4pham2db10fbdatabase7FbArray__T13readArrayImplTbZQsMFNfCQCeQCc8database12DbNameColumnZAb
..\..\pham\db\db_skdatabase.d(138): Error: null dereference in 
function 
_D4pham2db10fbdatabase7FbArray__T13readArrayImplTbZQsMFNfCQCeQCc8database12DbNameColumnZAb


It seems the compiler is doing extra analysis and seeing that a 
null pointer is being dereferenced. Can you provide the code for 
"pham\db\db_skdatabase.d" at L138 through 140 ?


Re: How to parse a json node that contains children of different types?

2021-07-20 Thread Mathias LANG via Digitalmars-d-learn

On Tuesday, 20 July 2021 at 21:18:12 UTC, Bagomot wrote:


But there is a problem with different types. I understand that 
Object[] is not suitable here, but I don’t know how to do it.


I ask you to help me with this.


IIUC, the `arguments` are command line arguments passed to a Java 
program, and some of those might be passed to the JVM ?


So you probably will end up with something like:
```
struct Arguments{
JVMArgs jvm;
ProgramArgs program;
}
```

Of course, the question is, what's `JVMArgs` ?

Now, as you noticed, you can't represent an array of unrelated 
types in D (which makes sense). So what you can do is create a 
common type for it, by using an `union`.


```
union JVMArg
{
RuleValue ruleValue;
string str;
// Etc...
}
alias JVMArgs = JVMArg[];
```

However, \ might not support it directly, or 
might support it through its own type (you will need a tagged 
union, and not just a simple union, as you need to know the type 
that the library read).


But if you take a step back, I think you might find this solution 
is far from ideal.
Having worked on a JSON library myself, I can tell you they are 
all implemented with a tagged union. And converting a tagged 
union to a tagged union is no improvement.


Instead, I would recommend to just use the JSON directly. If you 
need to pass things around, you might want to deserialize it to a 
common format. For example, assuming your project is a process 
manager for Java program and you want to read a common set of 
arguments from a configuration file, you might want to just 
generate the strings:

```
auto myJSON = parseConfigFile("config.json");
string[] defaultJVMArgs = parseJVMArgs(myJSON);
auto processMonitor = new ProcessMonitor(defaultJVMArgs);
```

TL;DR: If you want to use loosely typed data in a strongly typed 
language, you need to come up with a common type. That common 
type is usually either a discriminated union (which a JSON object 
is, essentially) or something that is domain-specific.


Hope this helps. I had a quick look at asdf and couldn't see a 
support for tagged union, so you would probably need to provide 
your data structure with a `deserializeFromAsdf` method. If you 
want to do so, look into providing a wrapper to `SumType`, e.g.:


```
struct MyUnion (T...) {
SumType!T data;
alias data this;
SerdeException deserializeFromAsdf(Asdf data) { /* Fill in 
the SumType */ }

```

But I would recommend just using the JSON object if you can.


Re: Including a file

2021-07-18 Thread Mathias LANG via Digitalmars-d-learn

On Sunday, 18 July 2021 at 17:48:53 UTC, Vindex wrote:

On Sunday, 18 July 2021 at 17:31:24 UTC, Adam D Ruppe wrote:

On Sunday, 18 July 2021 at 17:28:07 UTC, Vindex wrote:
Error: file "thing.json" cannot be found or not in a path 
specified with -J


You need to specify the path where it is found with the -J 
switch to the compiler. Like `ldc2 -J. yourfile.d


I already compiled the library itself with -Jres. It turns out 
that this must be done twice? Once when compiling the library, 
the second time when compiling the program.


Is the inclusion done in a templated function, or in a global ?
If the `import` happens in a function that is not in a root 
module, it won't be necessary to use `-J` when linking the 
program:

```D
module root;

import nonroot;
import std.stdio;

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

// Some other file:
module nonroot;

string foo ()
{
string val = import("hello.txt");
return foo;
}
```

However, if the `import` is in a templated function, it might 
need to be instantiated in the calling module:

```
module root;

import nonroot;
import std.stdio;

void main ()
{
writeln(foo!"hello.txt"());
}

// Some other file:
module nonroot;

string foo (string path) ()
{
string val = import(path);
return foo;
}

```

This will error out because the `foo` function needs to be 
generated inside of the `root` module context:

```
nonroot.d(5): Error: need `-J` switch to import text file 
`hello.txt`

nonroot.d(6): Error: template `foo(string path)()` has no type
root.d(6): Error: template instance `nonroot.foo!"hello.txt"` 
error instantiating

```

An easy way for you to solve this might be to hide the value of 
your JSON file behind a simple function that returns it, so that 
the compiler never analyzes its body. If you use LDC and LTO, I 
doubt it'll make any difference.


Re: assert(false) and GC

2021-07-10 Thread Mathias LANG via Digitalmars-d-learn

On Saturday, 10 July 2021 at 01:38:06 UTC, russhy wrote:
On Saturday, 10 July 2021 at 01:23:26 UTC, Steven Schveighoffer 
wrote:


I think it's the throwing/catching of the `Throwable` that is 
allocating. But I don't know from where the allocation happens.


-Steve


i think you are right


Try to use `@nogc` instead, it'll show you it does not allocate.
A caveat though: A failing assert used to allocate before 
v2.097.0 (the latest version), it does not anymore.


However, as your test captures all GC allocation, it likely 
triggers while the runtime is initializing.


Re: vibe.d compilation error

2021-07-04 Thread Mathias LANG via Digitalmars-d-learn

On Sunday, 4 July 2021 at 12:36:24 UTC, seany wrote:


Is there any way, I can avoid this error?


You are using an old version of Vibe.d, change your dependency to 
"~>0.9.0".


Re: float price; if (price == float.nan) { // initialized } else { // uninitialized } ... valid ?

2021-06-29 Thread Mathias LANG via Digitalmars-d-learn

On Wednesday, 30 June 2021 at 04:03:24 UTC, someone wrote:

On Wednesday, 30 June 2021 at 03:51:47 UTC, Mathias LANG wrote:

... is far from pretty but it works as expected, thanks for 
your tip !


Can be made a bit prettier with UFCS:


```d
import std.math : isNaN;

float lnumStockPricePreceding;

foreach (float lnumStockPrice; ludtStockPriceEvolution.range)

   if (!lnumStockPricePreceding.isNan) {

  /// do something

   }

   lnumStockPricePreceding = lnumStockPrice;

}
```


Or even better, with ranges:

```d
import std.math : isNaN;

float lnumStockPricePreceding;

foreach (float lnumStockPrice; 
ludtStockPriceEvolution.range.filter!(f => !f.isNan))

  /// do something

   lnumStockPricePreceding = lnumStockPrice;

}
```


Re: float price; if (price == float.nan) { // initialized } else { // uninitialized } ... valid ?

2021-06-29 Thread Mathias LANG via Digitalmars-d-learn
On Wednesday, 30 June 2021 at 03:32:27 UTC, Vladimir Panteleev 
wrote:

On Wednesday, 30 June 2021 at 03:15:46 UTC, someone wrote:

Is the following code block valid ?


Comparison with `nan` always results in `false`:

See section 10.11.5:

https://dlang.org/spec/expression.html#equality_expressions

You can use the `is` operator to perform bitwise comparison, or 
use `std.math.isNaN`.


Side note: That doesn't apply to `if (myFloat)` or 
`assert(myFloat);`, unfortunately: 
https://issues.dlang.org/show_bug.cgi?id=13489


Re: Are D classes proper reference types?

2021-06-28 Thread Mathias LANG via Digitalmars-d-learn
On Monday, 28 June 2021 at 06:13:06 UTC, Ola Fosheim Grøstad 
wrote:

On Sunday, 27 June 2021 at 23:20:38 UTC, Mathias LANG wrote:
- It locks us in a position where we depend on an external 
committee / implementation to define our ABI.


Well, that could be an issue, but it is not likely to change 
fast or frequently so I don't think it is a high risk approach.


The issue is twofold: it requires us to follow upstream changes 
(the case you are thinking of), but also provides us from making 
non backward-compatible downstream changes (meaning we can't 
change it as we see fit if we realize there is potential for 
optimization).


In any case, if you feel like it's worth it @Ola, you could 
start to look into what it takes (druntime/dmd wise) and start 
to submit PR.


There is no point unless there is consensus. You first need to 
get consensus otherwise it is means throwing time into the 
garbage bin.


Waiting on "consensus" is an easy way to avoid doing any kind of 
work :)
I'm fairly sure most large achievements that have been undertaken 
by people in this community (that were not W) have been done 
without their (W's) blessing. People just went ahead and did 
it. But obviously those people cared more about getting things 
done than spending time discussing it on the forums.


Re: Are D classes proper reference types?

2021-06-27 Thread Mathias LANG via Digitalmars-d-learn

On Sunday, 27 June 2021 at 08:41:27 UTC, kinke wrote:
On Sunday, 27 June 2021 at 07:54:38 UTC, Ola Fosheim Grøstad 
wrote: [AFAIK, most C++ implementations put the - of course 
totally incompatible - *C++* TypeInfo into vtable slot -1.]


Actually my understanding is that it's part of the ABI:
Each virtual table address in the VTT is the address to be 
assigned to the respective virtual pointer, i.e. the address 
past the end of the typeinfo pointer (the address of the first 
virtual function pointer, if there are any), not of the first 
vcall offset.


[Source: Itanium ABI, 2.6.2 VTT 
Order](https://itanium-cxx-abi.github.io/cxx-abi/abi.html#vtable-ctor-vtt)


Regarding replacing D's ABI with C++, it *might* be possible 
today, but:

- It takes someone to care about it and want it;
- It's going to be a lot of work, so it should come with lots of 
benefit - I don't see much as of now;
- It locks us in a position where we depend on an external 
committee / implementation to define our ABI.


In any case, if you feel like it's worth it @Ola, you could start 
to look into what it takes (druntime/dmd wise) and start to 
submit PR. For dlang devs questions, I recommend to use the dlang 
slack.


Re: semi-final switch?

2021-06-17 Thread Mathias LANG via Digitalmars-d-learn
On Thursday, 17 June 2021 at 21:41:28 UTC, Steven Schveighoffer 
wrote:
A final switch on an enum complains if you don't handle all the 
enum's cases. I like this feature.


However, sometimes the data I'm switching on is coming from 
elsewhere (i.e. a user), and while I want to enforce that the 
data is valid (it's one of the enum values), I don't want to 
crash the program if the incoming value is not correct. But 
final switch doesn't let me declare a default case (to throw an 
exception instead).


If I use a non-final switch, then my code might forget to 
handle one of the cases.


Oh, and to throw a monkey wrench in here, the value is a 
string, not an integer. So I can't use std.conv.to to verify 
the enum is valid (plus, then I'm running a switch twice).


Any ideas on better ways to handle this?

-Steve


Well, if you receive an `enum` that have an out of bounds value, 
your problem lies in the caller, not the callee. You're breaking 
the most fundamental promise of a type, that is, the values it 
can take. And you obviously also break any `@safe` function by 
feeding it this value.


So instead of thinking in terms of `enum`, I would say, think in 
them of the value, and generate the switch:

```D
SWITCH: switch (myRawValue)
{
static foreach (EV; NoDuplicates!(EnumMembers!MyEnum))
{
case EV:
// Handle;
break SWITCH;
}
default:
throw new Exception("Invalid value: " ~ myRawValue);
}
```

Note that this can be encapsulated in its own function, like 
`validateEnum (EnumType) (BaseType!EnumType value)` (not sure if 
we have a `BaseType` template, but you get the point).


Re: Missing stacktrace on memory allocation failure

2021-06-02 Thread Mathias LANG via Digitalmars-d-learn

On Wednesday, 2 June 2021 at 17:52:12 UTC, mw wrote:
On Thursday, 12 November 2020 at 13:16:21 UTC, Steven 
Schveighoffer wrote:

On 11/12/20 4:22 AM, Per Nordlöw wrote:

Why don't I get a stack trace on Memory allocation exceptions?

In my case I only get:

src/core/exception.d(647): [unittest] Memory allocation failed
core.exception.OutOfMemoryError@src/core/exception.d(647): 
Memory allocation failed




Certain errors are flagged as not able to allocate memory. So 
you don't get a stack trace.


I think it's a huge mistake, and we don't need memory 
allocation to do stack trace printing. But that's the way it 
is.


Hit this one today, since it's a mistake, what does it take to 
fix it? or you are saying it's unfix-able in the current D 
runtime?


It is fixable, but it'll take a lot of work. The main blocker is 
that the interface that is exposed to the user relies on memory 
allocation.
Namely, the `TraceInfo` interface is: 
https://github.com/dlang/druntime/blob/2d8b28da39e8bc3bc3172c69bb96c35d77f40d2a/src/object.d#L2257-L2261


Note that:
1) `toString` returns a `string` (allocation);
2) The `opApply`'s delegate use a `char[]` as parameter;

What we *should* have is an `opApply` on a struct that contains 
all necessary info, which itself writes to a sink / OutputRange.
Such struct exists 
(https://github.com/dlang/druntime/blob/a17bb23b418405e1ce8e4a317651039758013f39/src/core/internal/backtrace/dwarf.d#L77-L160) but need to be exposed to user code.
Then *printing* the stack trace will no longer allocate. However, 
`defaultTraceHandler` still returns an object, so acquiring the 
handler will also need to be addressed. There have been talks of 
deprecating chained Exceptions, and that would make such a task 
much simpler.


Re: "this" as default parameter for a constructor.

2021-04-13 Thread Mathias LANG via Digitalmars-d-learn

On Sunday, 11 April 2021 at 20:38:10 UTC, Pierre wrote:

Hi,

I have a class with a reference to the parent object and a 
constructor that has the parent as parameter


class foo {
this ( foo p /* , other params */ ) {
parent = p;
}

foo parent;
}

Of cause, the parent is almost always the object that creates 
the new intance. So


auto f = new foo(this);

I'd like to set "this" ( the creator ) as default argument if 
the constructor :


this ( foo p = this ) {...}

I can't. But however, the function, the argument and the 
current object in body of the constructor are 3 different 
things and the compiler can distinguish each one.


Is there a way to pass the reference of the caller to the 
creator as default argument ?


Depending on what you are trying to do, I would recommend to 
instead go with nested classes if you can. E.g.

```D
class MyClass {
class MyChild {
this (int value) { this.value = value; }
private int value;
}
}

void main ()
{
auto mc = new MyClass;
auto child = mc.new MyChild(42);
}
```

It'll give you an automatic reference to the parent. Of course if 
you are trying to do something like linked list, where all 
elements have the same type, it won't work.
In this case, the `create` approach might be better. You should 
be able to cook something with a template `this` parameter to 
reduce boilerplate.


And regarding allowing `this` as default argument: Definitely no. 
While it could be possible with some stretch (e.g. we'll have to 
delay default parameter semantic to the call site, unlike what is 
currently done, and that would mess with things like overload 
resolutions and template type inference), it wouldn't be sound / 
it'd be very surprising. I for one would expect `this` to be the 
object referencing itself, not the `this` of my caller.


Re: using dub and -checkaction=context

2021-01-18 Thread Mathias LANG via Digitalmars-d-learn
On Sunday, 17 January 2021 at 20:42:06 UTC, Steven Schveighoffer 
wrote:

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


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

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

But now I get linker errors:

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



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


Yeah, that's probably it. Hm... this feature isn't very usable 
if I can't use it with dub. And the bug report you linked to 
also has an example that fails with straight dmd (even without 
unittests).


-Steve


Yeah, it's currently not usable, because DMD thinks the template 
is already instantiated in Phobos / druntime. I tried to work 
around it in my projects and it didn't work out.
I want to enable it by default but there's 2 issues blocking it 
ATM (see https://github.com/dlang/dmd/pull/11925). Once that PR 
is green, we can enable it when compiling druntime / Phobos and 
your linker errors will disappear.


Also, dub-wise, you can't really use `-preview` before the latest 
release. That's why we added 
https://github.com/dlang/dub/commit/cd9b30e04813108c05abf97d97a42daf466eabdb ...


Re: Vibe.d build on LDC error

2020-11-06 Thread Mathias LANG via Digitalmars-d-learn

On Friday, 6 November 2020 at 05:52:56 UTC, Vino wrote:

Hi All,

  When we try to build vide.d using ldc (dub build) we are 
getting the below error, openssl is already been installed 
(OpenSSL 1.0.2j-fips  26 Sep 2016), hence request your help on 
the same.


openssl.d:84: error: undefined reference to 'OPENSSL_init_ssl'
openssl.d:121: error: undefined reference to 'OPENSSL_sk_num'
openssl.d:128: error: undefined reference to 'OPENSSL_sk_value'
openssl.d:243: error: undefined reference to 'BIO_set_init'
openssl.d:244: error: undefined reference to 'BIO_set_data'
openssl.d:245: error: undefined reference to 'BIO_set_shutdown'
openssl.d:1382: error: undefined reference to 
'BIO_get_new_index'

openssl.d:1382: error: undefined reference to 'BIO_meth_new'
openssl.d:1384: error: undefined reference to 
'BIO_meth_set_write'
openssl.d:1385: error: undefined reference to 
'BIO_meth_set_read'
openssl.d:1386: error: undefined reference to 
'BIO_meth_set_ctrl'
openssl.d:1387: error: undefined reference to 
'BIO_meth_set_create'
openssl.d:1388: error: undefined reference to 
'BIO_meth_set_destroy'
openssl.d:899: error: undefined reference to 
'BN_get_rfc3526_prime_2048'

openssl.d:1288: error: undefined reference to 'BIO_set_init'
openssl.d:1290: error: undefined reference to 'BIO_set_data'
openssl.d:1298: error: undefined reference to 'BIO_get_shutdown'
openssl.d:1300: error: undefined reference to 'BIO_set_init'
openssl.d:1302: error: undefined reference to 'BIO_set_data'
openssl.d:1309: error: undefined reference to 'BIO_get_data'
openssl.d:1323: error: undefined reference to 'BIO_get_data'
openssl.d:1339: error: undefined reference to 'BIO_get_shutdown'
openssl.d:1342: error: undefined reference to 'BIO_set_shutdown'
openssl.d:1335: error: undefined reference to 'BIO_get_data'
collect2: error: ld returned 1 exit status
Error: /usr/bin/cc failed with status: 1
/Project/dlang/ldc-1.24.0/bin/ldc2 failed with exit code 1.

From,
Vino.B


Which Linux distribution ? Which version of Vibe.d ?
A recent enough Vibe.d should detect OpenSSL based on 1) 
pkg-config 2) the openssl binary. Make sure you have the 
development version of OpenSSL installed.
Additionally, v1.0.2 is quite old (and subject to security 
issues), so you might want consider upgrading. But even with that 
version, it should work.

You can force the usage of a certain configuration using:

```
"dependencies": {
"vibe-d": "~>0.9",
"vibe-d:tls": "*"
},
"subConfigurations": {
"vibe-d:tls": "openssl-1.0"
},
```

See: 
https://github.com/vibe-d/vibe.d/blob/70b50fdb9cd4144f1a5007b36e6ac39d4731c140/tls/dub.sdl#L99-L103


Re: Recommended way to use __FILE__/__LINE__ etc.

2020-10-22 Thread Mathias LANG via Digitalmars-d-learn

On Thursday, 22 October 2020 at 16:03:45 UTC, H. S. Teoh wrote:
On Thu, Oct 22, 2020 at 03:32:57PM +, Andrey Zherikov via 
Digitalmars-d-learn wrote:
There are two ways how __FILE__, __LINE__ etc. can se used in 
function parameters: as regular parameters and as template 
parameters:

[...]

What is recommended way?
What are pros/cons of each case?


I don't know what's the "recommended" way, but generally, I 
prefer to pass them as regular parameters. Otherwise you will 
get a lot of template bloat: one instantiation per file/line 
combination.


However, sometimes there is not much choice: if your function 
is variadic, then you pretty much have to use template 
parameters, 'cos otherwise you won't be able to pick up the 
__FILE__/__LINE__ of the caller with default arguments.



T


You will. This is possible since v2.079.0 (March 2018): 
https://dlang.org/changelog/2.079.0.html#default_after_variadic

So yeah, always pass them as function parameters to avoid bloat.


Re: More elaborate asserts in unittests?

2020-10-21 Thread Mathias LANG via Digitalmars-d-learn

On Wednesday, 21 October 2020 at 22:48:04 UTC, IGotD- wrote:
On Wednesday, 21 October 2020 at 22:41:42 UTC, Adam D. Ruppe 
wrote:


try compiling with dmd -checkaction=context


Thanks, that was simple and it worked. Speaking of this, 
shouldn't this be documented here for example.


https://dlang.org/spec/unittest.html

Just adding a friendly tip that -checkaction=context gives the 
user more information. I couldn't find this information 
anywhere.


Unfortunately this switch still has some bugs, so you can easily 
run into linker errors. I'm hoping to ultimately make it the 
default though.


Re: cannot call impure function

2020-10-04 Thread Mathias LANG via Digitalmars-d-learn

On Sunday, 4 October 2020 at 18:02:11 UTC, Michael wrote:

On Sunday, 4 October 2020 at 17:43:13 UTC, Michael wrote:

[...]
I used the dmg file: dmd.2.094.0.dmg


I reinstalled using the installation script (install.sh) and 
now it works. Still don't know why the dmg-based intstallation 
did not work.

https://dlang.org/install.html

Anyway, thanks for your responses!


I think there might have been a mismatch between the compiler 
used, and the Phobos library used. This might happen if you used 
multiple sources for installation, e.g.  brew / macports / dmg 
(install script is self contained and never affected).


Re: cannot call impure function

2020-10-04 Thread Mathias LANG via Digitalmars-d-learn

On Sunday, 4 October 2020 at 17:05:33 UTC, Michael wrote:

On Sunday, 4 October 2020 at 17:01:44 UTC, Paul Backus wrote:

On Sunday, 4 October 2020 at 16:48:24 UTC, Michael wrote:

Dear all,

Sorry for the potentially stupid question, but I'm a complete 
newbie to D. Why does compiling the following trivial code 
fail?


import std.stdio;

void main()
{
writeln(3.14);
}


Works fine for me using DMD 2.094.0 on Linux. What OS and 
compiler version are you using, and how did you install DMD?


DMD64 D Compiler v2.094.0
on macOS 10.15.6


I cannot reproduce locally (macOS 10.15.6 too). How did you 
install DMD ?


Re: Taking arguments by value or by reference

2020-10-04 Thread Mathias LANG via Digitalmars-d-learn

On Sunday, 4 October 2020 at 14:26:43 UTC, Anonymouse wrote:

[...]

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


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

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


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


If the struct adds overhead to copy, use `const ref`. But if you 
do, you might end up with another set of problems. Aliasing is 
one of them, and the dangers of it are discussed at length in the 
thread about `-preview=in` in general. The other issue is that 
`const ref` means you cannot pass rvalues.
This is when people usually turn towards `auto ref`. 
Unfortunately, it requires you to use templates, which is not 
always possible.


So, in short: `auto ref const` if it's a template and aliasing is 
not a concern, `const ref` if the copy adds overhead, and add a 
`const` non-`ref` overload to deal with rvalues if needed. If you 
want to be a bit more strict, throwing `scope` in the mix is good 
practice, too.


--

Now, about `-preview=in`: The aim of this switch is to address 
*exactly* this use case. While it is still experimental and I 
don't recommend using it in critical projects just yet, giving it 
a try should be straightforward and any feedback is appreciated.


What I mean by "should be straightforward", is that the only 
thing `-preview=in` will complain about is `in ref` (it triggers 
an error).


The main issue at the moment is that, if you use `dub`, you need 
to have control over the dependencies to add a configuration, or 
use `DFLAGS="-preview=in" dub` in order for it to work. Working 
on a fix to that right now.


For reference, this is what adapting code  to use `-preview=in` 
feels like in my project: 
https://github.com/Geod24/agora/commit/a52419851a7e6e4ef241c4617ebe0c8cc0ebe5cc
You can see that I added it pretty much everywhere the type 
`Hash` was used, because `Hash` is a 64 bytes struct but I needed 
to support rvalues.


Re: default arguments for const ref parameters in extern C++ functions

2020-09-14 Thread Mathias LANG via Digitalmars-d-learn

On Monday, 14 September 2020 at 18:58:44 UTC, 60rntogo wrote:

On Monday, 14 September 2020 at 17:11:59 UTC, k2aj wrote:
AFAIK the only way to have default ref arguments is to use a 
global variable:

---
extern(C++) struct Foo
{
  int x;
}
immutable foo1 = Foo(1);
extern(C++) void fun(const ref Foo foo = foo1);
---


Thanks. This appears to work, but feels like a hack. I can live 
with that, but I'm still wondering if there is a more idiomatic 
way of solving the problem.


D doesn't let rvalues bind to const ref (well, `in` will do that, 
but it's D-only).
What was described as "global variable", is more of a "manifest 
constant lvalue".
A (static) immutable variable with an initializer will always be 
CTFE-d and available at compile time, so in this case it is 
*exactly* what you need.


Also note that a default parameter doesn't affect the mangling / 
ABI, because it works exclusively on the caller side. Thus, you 
could just remove the default argument and your `extern(C++)` 
binding would work just fine. But if you want to provide the same 
API, `[static] immutable` + initializer is the way to go.


Re: in; scope; scope ref; DIP1000; documentation

2020-08-28 Thread Mathias LANG via Digitalmars-d-learn

On Thursday, 27 August 2020 at 18:49:19 UTC, James Blachly wrote:
Peeling off from Mathias Lang's thread in General about making 
'in' useful, for some novice questions:



1. The thread involves 'in' qualifier. Documentation 
(https://dlang.org/spec/function.html#param-storage) indicates 
that `in` is defined as `scope const` and should not be used as 
it is not implemented. **Is this [fact and recommendation] 
still true?**


I have a PR to update the documentation: 
https://github.com/dlang/dlang.org/pull/2845
I got feedback on it, just didn't have time to complete / finish 
it, will come back to it soon.


Is "scope ref" documented somewhere specifically? I found 
https://dlang.org/spec/function.html#scope-parameters which 
discusses the use of `scope` with ref type parameters, but the 
example given is pointer-based. Is it correct that `scope ref 
T` behaves the same as `scope T*` ?


Regarding `scope` more generally, DIP1000 shows as "superseded" 
-- **can I still rely on this document for guidance?** We have 
a `-dip1000` flag but a superseded DIP. The discordance is 
extremely confusing.


It is, for users and compilers developers alike. We're still 
waiting for Walter to write down the docs on that. If you look in 
the forums / PRs, you'll see that it's the most common feedback.


I am glad D is iterating quickly and improving on safety, but I 
have found that documentation may not well recent changes in 
this area. Consequently I am reluctant to use (newer) features 
related to memory safety. If this is all comprehensively 
documented somewhere please let me know!


We have a policy that every language change should come with a 
spec PR. It has improved documentation drastically, but there's 
still a way to go.


I hope the aforementioned PR will clarify the status of `in`. I'm 
currently focusing on making sure it works properly everywhere 
before the next release (in 1 or 2 weeks), hence why fixing that 
PR has taken the back-seat (the website gets auto-updated, so 
even if the PR doesn't make the deadline, it'll be deployed as 
soon as it gets merged).


Re: Which version of DMD does GDC 10 target

2020-08-20 Thread Mathias LANG via Digitalmars-d-learn

On Thursday, 20 August 2020 at 05:49:29 UTC, Arun wrote:

On Thursday, 20 August 2020 at 05:07:28 UTC, H. S. Teoh wrote:
On Thu, Aug 20, 2020 at 04:28:41AM +, Arun via 
Digitalmars-d-learn wrote:

Which version of DMD is GDC 10 based on?


Compile the following D program to find out:

-
static assert(0, "Compiler language version: " ~ 
__VERSION__.stringof);

-

I have this line in a file called langver.d, and whenever the 
exact language version isn't obvious, I compile it to find out 
the version. :-)  (And yes it deliberately asserts instead of 
using pragma(msg) so that I don't have to type -o- or -of- or 
-c or whatever to suppress actual code emission, just 
`$compiler langver.d`.)



--T


Nice trick. Thanks. For the benefit of others, GDC 10 is based 
on DMD 2.076. https://dlang.org/changelog/2.076.0.html


Side note, Using $() is better than `` for subshells, as it 
makes nesting much easier. ;-)


Side note: Usually a lot of bug fixes are backported to GDC, so 
even though it says 2.076 feature-wise, bugs that have been fixed 
much later might not be present.

Which is great because it makes bootstrapping *SO MUCH* easier.


Re: How import DUB packcages directly and compile with DMD without use dub.exe?

2020-07-16 Thread Mathias LANG via Digitalmars-d-learn

On Friday, 17 July 2020 at 01:27:09 UTC, Marcone wrote:

On Thursday, 16 July 2020 at 11:52:39 UTC, Andre Pany wrote:

On Thursday, 16 July 2020 at 11:06:01 UTC, Marcone wrote:

I just want import in file and run with dmd.


Execute dub build with verbose output. You will find the info 
how dub is calling dmd.


Kind regards
Andre


dub is calling dmd with 
-IC:\Users\Usuario\AppData\Local\dub\packages\scriptlike-0.10.3\scriptlike\src but I want dmd auto import any in dub packages, for example: -IC:\Users\Usuario\AppData\Local\dub\packages\.


You can alter your `sc.ini` config to add `-I` path.
But "auto-importing" package won't work, because packages are 
stored in a hierarchy that is `dub`-specific and DMD doesn't know 
about it. The piece of functionality you want sounds exactly like 
what dub is supposed to do, so why do you want to avoid it ?


Re: Interfacing with C++ std::shared_ptr and std::unique_ptr

2020-06-10 Thread Mathias LANG via Digitalmars-d-learn

On Wednesday, 10 June 2020 at 06:43:24 UTC, Andre Pany wrote:

Hi,

I would like to interface with the library 
https://github.com/NTNU-IHB/FMI4cpp

and have following class definitions in the header file:

``` c++
namespace fmi4cpp {

template
class fmu_base {

public:

const std::string guid() const {
return get_model_description()->guid;
}

const std::string model_name() const {
return get_model_description()->model_name;
}

virtual std::shared_ptr 
get_model_description() const = 0;


};

templateme_fmu>
class fmu_provider : public virtual 
fmu_base {


public:

virtual bool supports_cs() const = 0;

virtual bool supports_me() const = 0;

virtual std::unique_ptr  as_cs_fmu() const = 0;

virtual std::unique_ptr  as_me_fmu() const = 0;

};
```

While unique_ptr is already available in drunime library 
core.stdcpp.memory,
shared_ptr is missing. Does someone already have translated 
shared_ptr?


Also, the C++ classes make use of templates. Is it still 
possible to call these

classes from D?

Kind regards
Andre


Depending on your needs, it might be trivial. We use this, and it 
works accross all 3 platforms: 
https://github.com/bpfkorea/agora/blob/ddd65e2fc3975d9c14ad36bcf28e5cd32de08945/source/scpd/Cpp.d#L38-L64


As mentioned, you will need to have the instantiation done on the 
C++ side, but that's true for any template. Feel free to ask on 
slack #cpp-interop.


Re: Dub platform probes

2020-05-27 Thread Mathias LANG via Digitalmars-d-learn

On Thursday, 28 May 2020 at 02:28:07 UTC, Tim wrote:

On Wednesday, 27 May 2020 at 21:17:54 UTC, Andre Pany wrote:
I read through the source code. The probe file is created here 
https://github.com/dlang/dub/blob/master/source/dub/compilers/utils.d#L296
The function getTempFile determines a new random temp file 
name and stores the file path in a global variable. A module 
destructor loops through this string array list and deletes 
the temp files 
https://github.com/dlang/dub/blob/master/source/dub/internal/utils.d#L98


I wonder why in your case the temp files are not deleted.

Kind regards
Andre


Me too. I have noticed that sometimes I don't need to and other 
times I do. Maybe it is to do with program crashes where it 
isn't cleaned up? I'll keep a closer eye on it


Is the app you're building a server by any chance ?
There's a recurrent problem with `dub`:
- https://github.com/dlang/dub/issues/536
There's a fix for it, unmerged though as it needs some 
work/testing: https://github.com/dlang/dub/pull/1696





Re: How to target ldc compiler only in dub

2020-05-26 Thread Mathias LANG via Digitalmars-d-learn

On Tuesday, 26 May 2020 at 22:28:14 UTC, data pulverizer wrote:

Hi,

I am trying to build a package to target LDC compiler only. I 
have both dmd and ldc2 (1.18.0) installed on my system. The dub 
file is:


```
{
"authors": [
"Me"
],
"copyright": "Copyright © 2020, Me",
"dependencies": {
"mir-algorithm": "~>3.8.12",
"mir-random": "~>2.2.14"
},
"description": "Some Cool Stuff",
"license": "MIT",
"name": "myPackage",
"dflags": [
"-O", "--release", "--boundscheck=off",
"--ffast-math", "-mcpu=native"],
"toolchainRequirements": {
"dmd": "no",
"gdc": "no",
"ldc": ">=1.18.0"
},
"targetType": "executable"
}
```

I get the message:

```
Installed dmd 2.090.1 is not supported by myPackage. Supported 
compiler(s):

  - ldc: >=1.18.0
```

Thanks


Add a `dub.settings.json` with:
```
{
"defaultCompiler": "ldc2"
}
```

Like we did: 
https://github.com/bpfkorea/agora/blob/38b2c33cc56acdeeabce8158bf3231a1f51eb5b1/dub.settings.json


Re: Error running concurrent process and storing results in array

2020-05-05 Thread Mathias LANG via Digitalmars-d-learn

On Wednesday, 6 May 2020 at 03:41:11 UTC, data pulverizer wrote:


Is there something I need to do to wait for each thread to 
finish computation?


Yeah, you need to synchronize so that your main thread wait on 
all the other threads to finish.

Look up `Thread.join`.

Yes, that's exactly what I want the actual computation I'm 
running is much more expensive and much larger. It shouldn't 
matter if I have like 100_000_000 threads should it? The 
threads should just be queued until the cpu works on it?


It does matter quite a bit. Each thread has its own resources 
allocated to it, and some part of the language will need to 
interact with *all* threads, e.g. the GC.
In general, if you want to parallelize something, you should aim 
to have as many threads as you have cores. Having 100M threads 
will mean you have to do a lot of context switches. You might 
want to look up the difference between tasks and threads.


Re: Error running concurrent process and storing results in array

2020-05-05 Thread Mathias LANG via Digitalmars-d-learn

On Wednesday, 6 May 2020 at 03:25:41 UTC, data pulverizer wrote:

[...]


The problem here is that `process` is a delegate, not a function. 
The compiler *should* know it's a function, but for some reason 
it does not. Making the function static, or moving it outside of 
the scope of main, will fix it.


For reference, this will spawn 100 threads to do a simple 
computation so probably not what you would want, I expect. But I 
suppose this is just example code and the underlying computation 
is much more expensive ?


Re: odd atomicOp errors from vibe-core

2020-04-10 Thread Mathias LANG via Digitalmars-d-learn
On Friday, 10 April 2020 at 03:26:04 UTC, Steven Schveighoffer 
wrote:

On 4/9/20 11:22 PM, Stefan Koch wrote:
On Friday, 10 April 2020 at 01:54:14 UTC, Steven Schveighoffer 
wrote:
I'm building a library that uses vibe-core as an indirect 
dependency. Specifically, I'm testing the library with dub 
test.


[...]


Those are signed unsigned mismatches when it tries to lock.
that's probably in vibe-d


Can you explain why I do not get the errors when I have taken 
care of my errors?


It doesn't make a whole lot of sense to me.

-Steve


I've observed this behavior as well. From what  can tell, it's a 
false positive that only shows up in the presence of previous 
error. I'd say that has something to do with the way the compiler 
do semantic analysis. My money is on the fact that `core.atomic` 
is special, and that something else (bad error gagging, perhaps?) 
triggers an error. As far as I can tell, it is safe to ignore.


If you can reduce it to something small enough, I'd say it's 
worthy of an issue tho.


Re: Fixing race issues the right way

2020-04-05 Thread Mathias LANG via Digitalmars-d-learn

On Sunday, 5 April 2020 at 22:24:27 UTC, solidstate1991 wrote:
My game engine is currently broken due to some race issue I 
don't really know how to resolve.


It seems that the compiler tries to skip instructions that are 
not locked with a `writeln()` or something similar. Usually I 
can safely remove the writeln after compiling it once with that 
way. However I've once ran into an issue when a previously 
working code just started to emit random junk data depending on 
CPU usage, and in that case the aforementioned workaround only 
partially worked (delaying crashes, etc).


I've heard something about Mutex, however I lack the experience 
with multithreading.


Is there public code you can link to ?
Look for any usage of `__gshared`. Are you using `shared` as well 
? Turn on `-preview=nosharedaccess` to get better diagnostic. Are 
you using any `extern` code ? How do you communicate between 
threads ? Message passing, or simple shared memory ?


Re: How to deploy on GitHub pages

2020-03-31 Thread Mathias Lang via Digitalmars-d-learn

On Tuesday, 31 March 2020 at 12:52:09 UTC, Ahmat wrote:

Hi all,

I want to use vibe.d for my personal website hosted on Github 
pages. I am not familiar with vibe.d and I am confused about 
how to approach this.


Any suggestions, ideas ? I will appreciate your help.


You can't. Vibe.d is a server technology, but Github pages only 
host static content.
You can write HTML / CSS / JS, and host that, but you can't run a 
Vibe.d server.


Re: @future attribute / @future keyword?

2020-03-19 Thread Mathias Lang via Digitalmars-d-learn
On Wednesday, 18 March 2020 at 14:23:28 UTC, Steven Schveighoffer 
wrote:


Honestly, I think that concept was never fully implemented (or 
maybe followed properly). Simply because there has not been 
much complaint about symbols being added "too quickly".


99.99% of the time, you add a symbol to a module, and there are 
no ill effects. The problem at the time was a significant one 
for Sociomantic, I believe because of a change that they needed 
for switching from Tango to druntime.


If you grep druntime, there are 2 usages, both from about 2-3 
years ago. Both were either submitted by sociomantic, or asked 
to add the @__future attribute from them.


I'm guessing that either interest was lost in keeping this up, 
or didn't notice when things were added, and it didn't affect 
them. Seems like all the focus was on the exception hierarchy 
(which needs TLC anyway). Maybe someone from that org can 
identify how this has helped them.


The whole concept itself has some rather obscure use cases. 
Perhaps in the future there will be an obvious use case, and we 
will be glad that we have it.


-Steve


Yep that feature is completely under-documented. It ended up 
being important to Sociomantic because we introduced `message` in 
`Exception`, as our `Exception` are reusable and use a buffer to 
minimize allocations, but said `message` broke a bunch of code 
because other `Exception`-derived class had implemented their own 
method that clashed with that very common name. In addition, some 
shadowing might have been involved at the time, which made the 
issue painful to track down.


It is less important to mainstream D than it was to Sociomantic 
mainly due to the differences in our approaches. Sociomantic code 
relied heavily on OOP, while mainstream D does not. New symbols 
in Phobos are rare, and rarely conflict with other modules. 
Adding a new overload in an overload set is guaranteed to not 
conflict since the change from protection to visibility.


I like to see it this way: Any new virtual function (and 
potentially new field) in a derived class relies on the absence 
of such name existing in any of its ancestor. If it does exist, 
or is introduced, the compiler will complain about `override` not 
being used. On the other hand, a new symbol in a module does not 
have this requirement (there is still potential for breaking 
change: e.g. if you introduce an overload that conflict, for 
example adding a `const(char)[]` overload to a function that has 
a `const(char)*` overload and no `string` overload).


To answer the OP: It is still in the language, and there's a test 
for it in druntime 
(https://github.com/dlang/druntime/blob/master/test/exceptions/src/future_message.d). But yeah, no one uses it.


Re: " include imported modules in the compilation " should exclude di file

2020-03-18 Thread Mathias Lang via Digitalmars-d-learn

On Monday, 9 March 2020 at 13:55:08 UTC, Calvin P wrote:
The current compiler "-i=module_name" option will  include 
imported modules as source code.


When the module define from di file extension, I think compiler 
should avoid treat it as source file.


What do you think?


Sounds sensible. Can you raise a bug report ?


Re: DMD: Is it possible change compile time errors to runtime errors in Dlang?

2020-03-05 Thread Mathias Lang via Digitalmars-d-learn

On Friday, 6 March 2020 at 04:56:28 UTC, Marcone wrote:
Is it possible change compile time errors to runtime errors in 
Dlang?

If yes, how can I make it?


No it's not possible, D is a statically typed language.
Why would you want errors that can be caught at compile time to 
happen at runtimes ?


Re: about const ref

2020-02-11 Thread Mathias Lang via Digitalmars-d-learn
On Tuesday, 11 February 2020 at 07:51:04 UTC, Ferhat Kurtulmuş 
wrote:
I need to be sure about "const ref". Based on the following 
function, does it mean:


Type can be string or an integral type.

(a) k1 is not copied on function calls
(b) k1 cannot be modified inside function

Please correct me if I am wrong. Can storage class "in" be used 
to satisfy (a) and (b)?



void doIt(const ref Type k1){

}

Type k = ...;

doit(k);



You're correct for 'a' and 'b'. However `in` only entails 
`const`, so it is not an exact replacement.
Additionally, you might want to add `scope` to show that the 
parameter does not escape.


Note that a big limitation on `const ref` parameters at the 
moment is that it does not accept literals, which is something 
Andrei talked about a few years ago at DConf (or was it last 
year?).


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

2020-02-03 Thread Mathias Lang via Digitalmars-d-learn

On Friday, 31 May 2019 at 15:41:24 UTC, Anonymouse wrote:

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

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

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


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


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


Replying here despite the delay because this is one of the top 
post when one google for gcopts.


This will be possible with the new version of the runtime 
(>=2.091.0, not released yet).


It has been filled as 
https://issues.dlang.org/show_bug.cgi?id=20459 and was fixed in 
https://github.com/dlang/druntime/pull/2881 which means dub 
compiled with druntime >= 2.091 will allow you to do:

`dub -- --DRT-gcopt=profile:1`

And any other D program will ignore `--DRT` options if provided 
after the `--` delimiter.


Re: `This` reference not accessible when overloading an operator?

2020-01-21 Thread Mathias Lang via Digitalmars-d-learn

On Tuesday, 21 January 2020 at 20:48:44 UTC, Enjoys Math wrote:
I have an Integer class in integer.d.  A RationalNumber class 
in rational_number.d, and they each import each other (so that 
could be the issue).  However, this is not working:



   Symbol opBinary(string op : "/")(const Integer z) const
   {
  return new RationalNumber(this, z);
   }

Getting:

Error: class `rational_number.RationalNumber` member `this` is 
not accessible		
Error: template instance `integer.Integer.opBinary!"/"` error 
instantiating		


The error message says that the constructor of `RationalNumber` 
is not accessible, not the `this` reference of `integer.Integer`.


Re: DMD docker image

2020-01-19 Thread Mathias Lang via Digitalmars-d-learn

On Friday, 17 January 2020 at 16:43:17 UTC, Jan Hönig wrote:

I have created a docker image.
However the image size is not small (~500MB).
I wonder if others have a suitable dockerfile.
All i want is to install the current dmd release.

Does somebody have something similar?
Does somebody need something similar?

My dockerfile:

```
FROM ubuntu:latest
MAINTAINER Jan Hönig 

RUN apt-get update &&  apt-get install curl build-essential -y \
 && apt-get clean \
 && rm -rf /var/lib/apt/lists/*

RUN latest=$(curl -sS 
http://downloads.dlang.org/releases/LATEST) \

  && echo "DMD Release: $latest" \\
  && curl 
"http://downloads.dlang.org/releases/2020/dmd_${latest}-0_amd64.deb; -o dmd.deb \

  && dpkg -i "dmd.deb" \
  && rm "dmd.deb"
```


If you want a small image, Alpine Linux is definitely the way to 
go.
You can find `gcc-gdc` (however it's an old frontend, v2.076) in 
Alpine Linux's main repository.


Additionally, if you can find the latest `ldc` in the `testing` 
repository 
(https://forum.dlang.org/thread/oznltcuropwzxaakp...@forum.dlang.org).


I intend to add DMD, just didn't have to get to it yet. If you 
want to do it yourself, here's the APKBUILD: 
https://gitlab.alpinelinux.org/alpine/aports/merge_requests/2880


Re: how to copy const struct with indirections to mutable one (of the same type)

2016-11-29 Thread Mathias Lang via Digitalmars-d-learn

On Tuesday, 29 November 2016 at 10:46:04 UTC, drug wrote:

I had the following code:
```
import std.algorithm: equal;

[...]


You are not calling the (identity) opAssign here, but postblit.

To call identity opAssign, you need an already constructed 
instance:


```
Data mutable_data;
mutable_data = const_data;
```


Re: Can't understand the application of delegates in toString() functions

2016-11-07 Thread Mathias Lang via Digitalmars-d-learn

On Monday, 7 November 2016 at 16:22:17 UTC, Heisenberg wrote:
Hi there. I'm currently following Ali Çehreli's "Programming in 
D" book and I can't seem to be able to wrap my head around the 
of delegates in the toString() functions..


http://ddili.org/ders/d.en/lambda.html
(Bottom of the page)


Why? How can a delegate which returns nothing be used as an 
array which is going to be printed on the screen? And just how 
is it printed? The Documentation didn't make it much clearer.. 
the 'sink' is supposed to be the 'writer', isn't it? So what 
does it do? The arguments get interpreted and formatted into 
the string, but what happens after that?


P.S. I've just checked the book, it doesn't seem to be 
explained anywhere properly (the way formattedRead is)

P.P.S. I'm following the PDF version of the book


When you ask for a string (or more generally, an array), you put 
a specific construct on the way the data should be. For starters, 
the items have to be contiguous in memory. But most of the time, 
they aren't, and you end up allocating memory to put them 
contiguously.


A sink is a method to work around that problem. A simple example 
would be:


```
import std.stdio;

void main ()
{
   // A delegate that write to stdout
   auto dg = (const(char)[] v) { write(v); }
   ColoredPoint p;
   p.toString(dg);
   write("\n");
}
```

With this definition, every time `ColoredPoint` will want to 
output a chunk of data, it will call the delegate, which will 
print to stdout. When the function returns, we now all chunks 
have been appended, and we complete the line with a \n, flushing 
the output.


This is great to write memory-friendly algorithm:

```
void main ()
{
   AppendBuffer!char myBuffer;
   auto dg = (const(char)[] v) { myBuffer ~= v; }
   ColoredPoint p;
   p.toString(dg);
   // Now we can use myBuffer.data
}
```

With this example, you can see that, by just forwarding chunks to 
the delegate, we're able to let the caller to decide of the 
memory strategy to use. It can be plain GC allocation, it can be 
using `malloc` / `realloc`, it can use a static array and only 
aggregate up to a certain size, etc...


Re: Best way to clear dynamic array for reuse

2016-07-13 Thread Mathias Lang via Digitalmars-d-learn
On Wednesday, 13 July 2016 at 12:05:12 UTC, rikki cattermole 
wrote:

On 13/07/2016 11:59 PM, Miguel L wrote:

The options would be:

a=[];
a.length=0;
a=null;
...
any other?

Can you help me please?


All of those "options" do the same thing, remove all references 
to that data.


No they don't. The first and the third change the pointer, so one 
cannot reuse the array.


@Miguel: You want to use 
http://dlang.org/phobos/object.html#.assumeSafeAppend
See the example in the doc. To reset your buffer you can 
use`buff.length = 0` instead of taking a slice as the example 
does.


Re: Where does one post a proposal for a language change?

2016-07-12 Thread Mathias Lang via Digitalmars-d-learn

On Tuesday, 12 July 2016 at 16:45:18 UTC, DLearner wrote:


General/Issues/or...


P.R. to this repository: https://github.com/dlang/DIPs


Re: Diff between function and delegate

2016-06-27 Thread Mathias Lang via Digitalmars-d-learn

On Monday, 27 June 2016 at 19:34:06 UTC, "Smoke" Adams wrote:

I have

alias fnc = void function(Object);
alias del = void delegate();

Does func avoid the GC? I am passing in this to Object so I 
don't technically need a delegate or a "context". I want to be 
sure that I'm actually gaining something here by doing this.


I read somewhere that delegates only require the GC when they 
use objects outside their scope. Do delegates always use the GC 
or only in certain cases?


Delegate don't GC allocate when:
- You take a pointer to a member function
- The function accept a `scope` delegate and you pass a literal
- You use `scope myDG = (Params) { body... }`


Re: Is there anyway to make opApply @nogc?

2016-06-20 Thread Mathias Lang via Digitalmars-d-learn

On Monday, 20 June 2016 at 14:08:58 UTC, Gary Willoughby wrote:
Is there any way to make opApply @nogc? or provide the same 
foreach functionality without implementing a range interface?


I want to iterate over a piece of memory using a pointer. I 
thought about using opSlice but that doesn't provide 
information for an index in a foreach loop.


auto opSlice()
{
return this._pointer[0 .. size];
}

Anyone got any ideas?


Can't `opApply` with `auto` return type works since it infers 
attributes ?


Re: Need help with delegates and vibed

2016-03-20 Thread Mathias Lang via Digitalmars-d-learn

On Wednesday, 16 March 2016 at 20:08:40 UTC, Suliman wrote:
I can't understand how to get works delegates works from this 
doc http://vibed.org/api/vibe.http.client/requestHTTP


I see example, but when I am looking on Prototypes I really 
can't figure how to use them.


For example what does this mean:
 scope void delegate(scope HTTPClientRequest) requester,

it's function that point to method inside class?


No, its a delegate, essentially a fat pointer bundling a function 
and a context together.
It can be a pointer to a class member, e.g. 
``, but it can also

be a literal using the context of the function:

```
void foo ()
{
  string foo;

  scope requester = (scope HTTPClientRequest req) { 
req.header["foo"] = foo; }


  requestHTTP("http://google.com;, requester);
}
```

By default, `delegate`s are allocated on the heap (GC-allocated).
`scope` delegate means its allocated on the stack (which also 
means that if you return a `scope delegate`, you'll get random 
behaviour / segfault because your context points to an 
invalidated stack frame).




Why I can not call it like:

requestHTTP(url,
scope req,
scope res);

I am getting error:

Error: expression expected, not 'scope'
Error: found 'req' when expecting ','
Error: expression expected, not ','
Error: found 'scope' when expecting ','

---


You have two usage of `scope` here. First a `scope delegate` 
which is used to avoid memory allocation. This `scope delegate` 
takes parameter: the requester takes a request object (what will 
be send to the server), and the receiver takes a response object 
(what has been read from the connection as the response). Those 
object are marked as `scope`, which means the memory will be 
destroyed when you exit the `delegate`s. That's also to reduce 
memory allocation. If you want to save anything (like some 
headers value), you have to [i]dup it.



Is it's optional parameter?

scope void delegate(scope HTTPClientRequest) requester = 
cast(void delegate(scope HTTPClientRequest req))null


so I can place instead in just `null`?


Yes. The reason for the various overloads is performance vs 
convenience.
If you provide both requester and receiver, you can process 
request with a minimal amount of memory allocation. However, if 
you take the overload that returns an `HTTPClientResponse`, then 
it will have to allocate it (as well as all the data inside).


Re: size_t index=-1;

2016-03-19 Thread Mathias Lang via Digitalmars-d-learn
On Wednesday, 16 March 2016 at 21:49:05 UTC, Steven Schveighoffer 
wrote:
No, please don't. Assigning a signed value to an unsigned (and 
vice versa) is very useful, and there is no good reason to 
break this.


-Steve


I'm not talking about removing it completely. The implicit 
conversion should only happen when it's safe:


```
int s;
if (s >= 0) // VRP saves the day
{
  uint u = s;
}
```

```
uint u;

if (u > short.max)
  throw new Exception("Argument out of range");
// Or `assert`
short s = u;
```


Re: size_t index=-1;

2016-03-19 Thread Mathias Lang via Digitalmars-d-learn
On Wednesday, 16 March 2016 at 20:11:41 UTC, Steven Schveighoffer 
wrote:

On 3/16/16 2:40 PM, Laeeth Isharc wrote:
should it be a compiler warning to assign a negative literal 
to an

unsigned without a cast ?


Why? They implicitly convert.

int  x = -1;
uint y = x;

I don't see a difference between this and your code. And we 
can't change this behavior of the second line, too much 
arguably valid code would break.


-Steve


We can change it, and we should. But it should be deprecated 
properly, and we should put in place enough candy to make it 
viable (See 
http://forum.dlang.org/post/vbeohujwdsoqfgwqg...@forum.dlang.org 
).


Re: size_t index=-1;

2016-03-18 Thread Mathias Lang via Digitalmars-d-learn

On Wednesday, 16 March 2016 at 18:40:56 UTC, Laeeth Isharc wrote:
should it be a compiler warning to assign a negative literal to 
an unsigned without a cast ?


yes it should. https://issues.dlang.org/show_bug.cgi?id=3468


Re: Issues

2016-02-22 Thread Mathias Lang via Digitalmars-d-learn

On Monday, 22 February 2016 at 22:56:26 UTC, Andre wrote:


I was wondering how people in this D community think about the 
number of issues with NEW status...




NEW just means 'not resolved'. Things are rarely assigned, and 
usually go straight
from 'NEW' to 'RESOLVED'. An intermediate status, when a PR is 
open, could be assigned by the dlang bot, but I don't know if 
that would bring much.


It could scare individuals/organizations to start with D, when 
they get the impression that there are a large and growing 
number of issues that are open (for years). I know this is not 
a fair interpretation of what's going on, but it's a conclusion 
one could make.


And that's a fair point. Though the number of resolved issues 
grows much faster than the new ones.


- Is there a preferred way to clean things up? A resolution 
status? A maximum time?


It's a case by case basis really. Whenever you hit a new issue, 
search the bug tracker before opening a new one. You might find 
two or more issues related to the same bug. In this case, I 
recommend closing (as DUPLICATE) the one which is either the 
least documented, or the newer one.
Bear in minds issues are not created equals, as some are very 
broad / require significant design adjustment (e.g. 'object is 
not const correct'), while some are trivial (some broken links in 
the doc for example).


Some are also just enhancement request (valid or not), and it 
might be interesting to move them somewhere else (DIP most 
likely).


If you want to help triaging, I suggest going through the bug 
reports and trying to reproduce with the latest release (skipping 
the D1 only bugs). It's quite likely you'll find a decent amount 
of bugs that were already fixed, but hasn't been marked as such. 
You can then try to link them to Github P.R. (if possible) and 
close them.


Re: Declaring extern(C) declarations with template mixins

2016-01-12 Thread Mathias Lang via Digitalmars-d-learn

On Tuesday, 12 January 2016 at 21:22:46 UTC, Jacob Carlborg wrote:

Is this supposed to work:

template Foo()
{
extern(C) int printf(in char*, ...);
}

mixin Foo;

void main()
{
printf("foo\n");
}

It fails with a linker error, undefined symbol, due to not 
applying C mangling:


Undefined symbols for architecture x86_64:
  "__D4main8__mixin76printfUxPaYi", referenced from:
  __Dmain in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to 
see invocation)


https://issues.dlang.org/show_bug.cgi?id=12575


Re: goroutines vs vibe.d tasks

2015-07-01 Thread Mathias Lang via Digitalmars-d-learn

On Tuesday, 30 June 2015 at 15:18:36 UTC, Jack Applegame wrote:
Just creating a bunch (10k) of sleeping (for 100 msecs) 
goroutines/tasks.


Compilers
go: go version go1.4.2 linux/amd64
vibe.d: DMD64 D Compiler v2.067.1 linux/amd64, vibe.d 0.7.23

Code
go: http://pastebin.com/2zBnGBpt
vibe.d: http://pastebin.com/JkpwSe47

go version build with go build test.go
vibe.d version built with dub build --build=release test.d

Results on my machine:

go: 168.736462ms (overhead ~ 68ms)
vibe.d: 1944ms   (overhead ~ 1844ms)

Why creating of vibe.d tasks is so slow (more then 10 times)???


In your dub.json, can you use the following:

subConfigurations: {
vibe-d: libasync
},
dependencies: {
vibe-d: ~0.7.24-beta.3
},


Turns out it makes it much faster on my machine (371ms vs 
1474ms). I guess it could be a good thing to investigate if we 
can make it the default in 0.7.25.


Re: ddoc template error

2015-01-20 Thread Mathias LANG via Digitalmars-d-learn

On Tuesday, 20 January 2015 at 08:55:58 UTC, BlackEdder wrote:
Solved it. I had a _fromJSON comment somewhere else in the file 
and the underscore causes ddoc to fail




If you could reduce it to a manageable size and post it to 
https://issues.dlang.org/ that'll be super cool :)


Re: rebind of const class variables

2015-01-20 Thread Mathias LANG via Digitalmars-d-learn

On Tuesday, 20 January 2015 at 09:29:46 UTC, qqiang wrote:
I am writing a tree data structure, and I have the following 
code:


```D
final class Node {
private {
int val_;
Node parent_;
Node left_;
Node right_;
}

@property
const(Node) maximum() const {
auto ret = this;

while (ret.right_) {
ret = ret.right_;
}

return ret;
}
}
```

It failed to compile and complaint that `cannot modify const 
expression ret`。


Since `ret` is just a binding to a const class object, why 
can't I rebind it to another const class variable?


Must I use pointers to cope with this?

Thx


You are looking for 
http://dlang.org/phobos/std_typecons.html#.Rebindable




Why do std.traits use template foo(args...) instead of foo(alias arg) ?

2014-12-18 Thread Mathias LANG via Digitalmars-d-learn

An exemple being fullyQualifiedName:
https://github.com/D-Programming-Language/phobos/blob/master/std/traits.d#L415

I don't get this pattern. Is it documented somewhere ?


Re: Why do std.traits use template foo(args...) instead of foo(alias arg) ?

2014-12-18 Thread Mathias LANG via Digitalmars-d-learn

On Thursday, 18 December 2014 at 16:10:31 UTC, Dicebot wrote:
On Thursday, 18 December 2014 at 15:48:02 UTC, Mathias LANG 
wrote:

An exemple being fullyQualifiedName:
https://github.com/D-Programming-Language/phobos/blob/master/std/traits.d#L415

I don't get this pattern. Is it documented somewhere ?


Full pattern looks like this:

template foo(T...)
if (T.length == 1)

This is a way to workaround D template argument limitation - 
you can't have any parameter that accepts both types and 
symbols (`alias T` and `T` at once) other than variadic 
parameter. Limit variadic length to 1 and you emulate such 
accepts anything parameter.


Thanks for the precision. Is it something that is going to be 
fixed, or is it by design ?


Re: [static] foreach scope, template declaration ?

2014-09-26 Thread Mathias LANG via Digitalmars-d-learn
On Thursday, 25 September 2014 at 23:08:53 UTC, SlomoTheBrave 
wrote:
a way around this is not to use anySatisfy nor the template, 
for example this works as expected:


[...]



My problem is that in this example, attributes are in the same 
order as the parameter. But this come from a code generator, 
which takes class defined by the user, so I have to assume they 
might not be in the correct order :)


which is less abstruse. However I don't know if it has hurted 
your eyes too but the output lines order shows there is a 
problem too:



Current attr is: p1
Instantiated for: p1
Instantiated for: p2
Instantiated for: p3
Current attr is: p2
Current attr is: P3


instead of


Current attr is: p1
Instantiated for: p1
Current attr is: p2
Instantiated for: p2
Current attr is: P3
Instantiated for: p3


o!o


On Thursday, 25 September 2014 at 23:37:11 UTC, Ali Çehreli wrote:


Surprisingly, that indicates that anySatisfy did instantiate 
CmpName with all three string values, meaning that perhaps we 
don't have shortcut behavior for 'bool' eponymous templates.


This is documented 
(http://dlang.org/phobos/std_typetuple.html#.anySatisfy): 
Evaluation is *not* short-circuited if a true result is 
encountered; the template predicate must be instantiable with all 
the given items.


When I use myAnySatisfy instead of anySatisfy, I see that I am 
right: The last expression above does not stop instantiating 
after p1. In other words, even though myAnySatisfy!(F, T[$/2 
..  $ ] is unnecessary (because the first part of || is already 
'true'), it gets instantiated anyway.


[...]

This looks like an enhancement request.

Ali


I didn't consider this aspect, and there's definitely ground for 
optimization. However, let's say I replace the definition of 
MyClass with:



class MyClass {
@(UDAStruct(p3), UDAStruct(P2), UDAStruct(p1)) // P2 is 
a typo

  void func(int p1, string p2, float p3) {}
}



In this case, anySatisfy is right to instantiate all 3 templates 
on the first iteration. Here's the result:



$ dmd -unittest -run bug.d
Current attr is: p3
Instantiated for: p1
Instantiated for: p2
Instantiated for: p3
Current attr is: P2
Current attr is: p1


There is no needless instantiation in this case, yet we still 
have the same behaviour (static assert not triggered).


[static] foreach scope, template declaration ?

2014-09-25 Thread Mathias LANG via Digitalmars-d-learn

I'm a bit puzzled with the following behavior:


import std.typetuple, std.traits;

struct UDAStruct {
string identifier;
}

class MyClass {
@(UDAStruct(p1), UDAStruct(p2), UDAStruct(P3)) // P3 is 
a typo

  void func(int p1, string p2, float p3) {}
}

unittest {
alias Func = MyClass.func;
enum ParamNames = ParameterIdentifierTuple!Func;
enum ParamAttr = __traits(getAttributes, Func);

foreach (attr; ParamAttr) {
template CmpName(string PName) {
pragma(msg, Instantiated for: ~PName);
enum CmpName = (PName == attr.identifier);
}
pragma(msg, Current attr is: ~attr.identifier);
static assert(anySatisfy!(CmpName, ParamNames));
}

// Foreach does introduce a scope, as this produce no compile 
time error.

template CmpName(string test) { enum CmpName = test; }
static assert(CmpName!? == ?);
}

void main() {}


The output is (FE 2.066  2.065 tested):
148 geod24@barsoom2 ~ % dmd -unittest -run test.d
Current attr is: p1
Instantiated for: p1
Instantiated for: p2
Instantiated for: p3
Current attr is: p2
Current attr is: P3

Obviously one call tell it's not what I expected. It looks like 
DMD is reusing the instantiations of the template of the first 
loop for p2 and P3.
The 2 lines at the end check that foreach does introduce a scope, 
but it behaves differently than what we're use to.


Is there a way around this ?
I tried to move CmpName outside the loop, then declare `alias 
Cmp(string x) = CmpName(attr, x);` in the loop, but it doesn't 
help (I guess the same thing happens?).


Re: UFCS doesn't work in some cases

2014-09-09 Thread Mathias LANG via Digitalmars-d-learn

On Tuesday, 9 September 2014 at 17:58:16 UTC, Danyal Zia wrote:
As far as I know, UFCS are designed to make it easy to extend 
the class for specific applications, however, without the 
ability to use UFCS for those cases, it limits its usefulness. 
Are these oversights/bugs? Or is their any rationale behind the 
decision to not implement UFCS for them?


Danyal



The reason why local symbols are not considered by UFCS, is to 
avoid unexpected name conflicts.


Stated at the very bottom of: http://dlang.org/function.html


Re: DDoc and private members / mixins / UDAs

2014-06-25 Thread Mathias LANG via Digitalmars-d-learn

On Wednesday, 25 June 2014 at 18:49:27 UTC, Stefan Frijters wrote:
Let me preface this by admitting that I'm not sure I'm using 
the DDoc functionality properly at all, so let me know if my 
questions are bogus.


Is it possible to:
- Add private members to documentation?
- Have DDoc do its thing after mixins have been handled?
- Access UDAs?

To expand on the last point: in my code I currently use UDAs to 
annotate variables that can be set in an input file; at compile 
time I use __traits to find all of them and create a parser 
etc. for them. I would really like to be able to create a 
minimal documentation, which only includes all such 
UDA-annotated variables from all modules, so it can be used as 
a short manual for the end user, rather than being developer 
documentation. I was thinking of using a LaTeX template and 
using the absence or presence of the UDA to somehow insert a 
macro that is either just blank or actually adds the 
documentation.


Any tips to achieve this in a different fashion are also 
appreciated.


Kind regards,

Stefan Frijters


1) You might be interested by ddox [1] which provides more 
functionality and a nicer output than DDoc (actually, the phobos 
docs are being replacd by it).
As you can see in the example, you can filter what goes in and 
what doesn't, as well as the minimum protection level (so you can 
chose to put private in it).
Note that if you have a dub-based project, you can just run dub 
--build=ddox to get it working.


2) Yes for regular mixin, no for template mixins. Example:
mixin strToSym!(moduleName!moduleName); // Template mixin
mixin(int a = 42;);   // regular mixin

Will output (using dmd -Xfdocs.json module.d):
   {
name : strToSym!(\std.traits\),
kind : mixin,
line : 62
   },
   {
name : a,
kind : variable,
protection : private,
file : CppWrapper.d-mixin-63,
line : 63,
deco : i,
init : 42
   },


3) Nope. Again, example:
@(ThisIsAFunction)
void foo() {}

Ouputs in the docs.json:
   {
name : foo,
kind : function,
protection : private,
file : CppWrapper.d,
line : 66,
deco : FZv,
endline : 66
   },


Hope this helps !

[1]: https://github.com/rejectedsoftware/ddox


Re: DUB linking problem on WinXp

2014-06-19 Thread Mathias Lang via Digitalmars-d-learn

On Thursday, 19 June 2014 at 12:18:54 UTC, Orfeo wrote:

Under WinXp I got the following


AFAIK, D is not officially supported on Win XP.

That's probably why you don't have a meaningful stacktrace or 
error message.