Re: Implementation Details

2024-05-27 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 28/05/2024 12:54 PM, Ruby The Roobster wrote:
As of late, I have taken up an interest in learning about how the D 
language is implemented at a compiler level, specifically the GC 
implementation.  Unfortunately, the source code is poorly documented, 
and is too large to simply read all of it in a reasonable amount of 
time.  If anyone here can help me, or at least point me to relevant 
resources, I would be very grateful.


From a theory standpoint this book should give you a pretty good 
overview of how GC's work. It is the book I recommend for introduction 
to GC's.


https://www.amazon.com/Garbage-Collection-Handbook-International-Perspectives-dp-1032218037/dp/1032218037/ref=dp_ob_title_bk

But yes that GC is very hard to get into, and its been tacked on over 
the years which make it even harder to untangle. Plus there is a memory 
allocator in there too.


Re: Problem with clear on shared associative array?

2024-05-27 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 28/05/2024 12:36 PM, Andy Valencia wrote:

On Monday, 27 May 2024 at 04:04:03 UTC, mw wrote:

Pls NOTE: it is
a   `sharded` (meaning trunk-ed) NON-concurrent map,
not `shared` concurrent map.


Assuming I put it in shared memory, in what way is it not able to be 
used concurrently?  It seems to have the needed lock operations?


Thanks,
Andy


A concurrent data structure handles all of this for you.

AA's are not concurrent because it doesn't offer any protection.

Protecting a data structure with a mutex doesn't make it concurrent, but 
it may allow you to use it concurrently safely. Subtle difference!


Re: Goto skipping declarations

2024-05-03 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 04/05/2024 8:38 AM, Jonathan M Davis wrote:

In any case, I expect that the compiler is just going dumb here because of
the label for some reason, and one or more of the checks that it's supposed
to be doing is being missed.


It is very simple code.

A reverse search over the double linked list for the goto from the label.

I looked into it fairly recently as an example of type state analysis D 
is already designed against.


Re: dynamic linker flags with dub

2024-04-29 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 30/04/2024 10:20 AM, KytoDragon wrote:
I want to use dll-style hot-reloading for a windows application which 
requires a different name for the PDB file for each compilation. 
(windows locks the pdb file when loading the dll and the compiler can't 
create a new pdb with the same name). How can I achieve this with dub? 
Is there a way to inject variables into the linker flags?


E.g. something like this in the dub.json:

"lflags-windows-ldc": ["/PDB:foo_%random%.pdb"]


Your best bet probably is to use dub as a library, and change your 
``targetName`` or ``targetPath`` on each compilation.


Alternatively you could generate your dub file with the change in it 
each time that depends upon the actual library (which would be a 
``sourceLibrary``).


Re: Digger on Windows -- should it work?

2024-04-19 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 20/04/2024 9:28 AM, Ivan Kazmenko wrote:

Hi.

I'd like to test locally whether a commit 
(https://github.com/dlang/dmd/pull/16400) fixes an issue 
(https://issues.dlang.org/show_bug.cgi?id=24440).  The GitHub 
instructions in the PR tell to use Digger for a quick and easy check, 
but it fails to build on Windows with the following message:


<...>
std.file.FileException@std\file.d(454): 
<...>\work\repo\dmd\src\win32.mak: The system cannot find the file 
specified.

<...>

And yeah, there is no such file there.  Only osmodel.mak and posix.mak 
of the relevant kind.


So, nowadays, is Digger supposed to work on Windows?  It did, the last 
time I tried, but that was several years ago.


Ivan Kazmenko.


Yes it should work.

The make files for dmd should be gone.

So I don't know why its referring to them.


Re: "Error: `TypeInfo` cannot be used with -betterC" on a CTFE function

2024-04-14 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 15/04/2024 10:36 AM, Liam McGillivray wrote:
Well, it did work when I tried it (using a string variable, not a 
literal of course). It displayed as it is supposed to. But from the 
information I can find on the web it looks like strings are sometimes 
but not |always| zero-terminated. Not a great look for the language. Are 
there any rules to determine when it is and when it isn't (for string 
variables)?


String literals, which are constants that the compiler puts into ROM of 
the object file, are zero terminated because it doesn't cost anything to 
do this.


At runtime, unless you explicitly append the null terminator, no string 
contains it.


D's strings are slices, pointer + length. These are superior in both 
performance (not having to strlen all the time) and are safer (bounds 
checked access).


Null terminated strings are a technical debt due to legacy constraints. 
We would all be better off if C supported slices. Plenty of notable 
exploits couldn't of happened if they were used instead.


Re: How to set include paths of a c source in dub when using importc

2024-04-13 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 14/04/2024 8:59 AM, Ferhat Kurtulmuş wrote:


These don't work for me:

"dflags": ["-Iinclude"]

"importPaths": [
     "include"
],

The importc docs do not help either.


Appears it hasn't been documented in new dub docs.

It is ``cSourcePaths`` and ``cImportPaths``.

https://github.com/dlang/dub-docs/issues/91


Re: What I thought was straightforward blew up in my face..

2024-04-10 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

```c
void SDL_GetVersion(SDL_version * ver);
```

It doesn't return anything.

Its return type is void.

See the argument list where it lists the types of the arguments:

``template writeln is not callable using argument types !()(string, void)``

Which aligns with the arguments you passed to ``writeln``.


Re: How can I tell D that function args are @nogc etc.

2024-04-10 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
Place your attributes on the right hand side of the function, not the 
left side.


Use the left side for attributes/type qualifiers that go on the return type.

```d
bool[7] stagesToProcess = false;

bool shouldDoInStages(int index) @nogc nothrow @safe
{
 return stagesToProcess[index];
}

bool shouldDoNever(int index) @nogc nothrow @safe
{
 return false;
}

template processSafely(int low, int high)
{
 alias ShouldDoFnT = bool function(int) @nogc nothrow @safe;

 uint processSafely(ShouldDoFnT shouldDo) @nogc nothrow @safe
 {
 assert(low < high);
 uint stepsProcessed;
 for (int ii = low; ii <= high; ii++)
 {
 if (shouldDo(ii))
 {
 stepsProcessed++;
 }
 }
 return stepsProcessed;
 }
}

void main()
{
 stagesToProcess = [false, false, true, true, false, true,
false];
 uint count = processSafely!(1, 4)();
 assert(count == 2);
}
```


Re: "Error: `TypeInfo` cannot be used with -betterC" on a CTFE function

2024-04-10 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 10/04/2024 2:50 PM, Liam McGillivray wrote:
On Tuesday, 9 April 2024 at 23:50:36 UTC, Richard (Rikki) Andrew 
Cattermole wrote:
The string mixin triggers CTFE, if ``EnumPrefixes`` wasn't templated, 
that would cause codegen and hence error. If you called it in a 
context that wasn't CTFE only, it would codegen even with template and 
would error.


For quite a long time we emitted -betterC errors during semantic, we 
learned that this was all around a bad idea and moved (hopefully all 
but I doubt it) into the glue code. So only if it codegens will it error.


Well then, perhaps this is a bug (though a useful bug in my case).


Not a bug, this took us quite a while to get reliable.



Re: "Error: `TypeInfo` cannot be used with -betterC" on a CTFE function

2024-04-09 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 10/04/2024 11:21 AM, Liam McGillivray wrote:
On Sunday, 7 April 2024 at 08:59:55 UTC, Richard (Rikki) Andrew 
Cattermole wrote:

Unfortunately runtime and CTFE are the same target in the compiler.

So that function is being used for both, and hence uses GC (appending).


Are you sure that string appending was really the problem that caused 
the "TypeInfo" build error? I forgot about this, but I had already had a 
working CTFE function with string appending before adding the new one 
that lead to this error. The symbols that it generates could be used in 
the program compiled with `betterC`.


No, for a string it shouldn't trigger the need for TypeInfo. But that 
wouldn't have worked regardless.



```
string EnumPrefixes(T)(string oldName, string prefix) {
     string result = "enum " ~ oldName ~ " {\n";
     static foreach(member; __traits(allMembers, T)) {
     result ~= "    " ~ prefix ~ member ~ " = " ~ 
__traits(getMember, T, member).to!int.to!string ~ ",\n";

     }
     return result ~ "}\n";
}
```

The purpose of this was that the enums used by the C library were too 
verbose. I had changed them from things like `KeyboardKey.KEY_C` to 
`Key.C`. I wanted to leave the new enums written directly in the module 
since these were recommended for use, but then generate the old ones 
with CTFE for backwards compatibility. The function above was used like 
`mixin(EnumPrefixes!Key("KeyboardKey", "KEY_"));`, and the compiler 
would allow it even when building with `betterC`.


The string mixin triggers CTFE, if ``EnumPrefixes`` wasn't templated, 
that would cause codegen and hence error. If you called it in a context 
that wasn't CTFE only, it would codegen even with template and would error.


For quite a long time we emitted -betterC errors during semantic, we 
learned that this was all around a bad idea and moved (hopefully all but 
I doubt it) into the glue code. So only if it codegens will it error.


Re: "Error: `TypeInfo` cannot be used with -betterC" on a CTFE function

2024-04-09 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn



On 09/04/2024 12:48 PM, Liam McGillivray wrote:
On Tuesday, 9 April 2024 at 00:02:02 UTC, Richard (Rikki) Andrew 
Cattermole wrote:

```d
enum Value = (a, b) {
return a + b;
}(1, 2);
```

This alone should be a CTFE only function.

But if we want template parameters, we'd need to wrap it with the 
template.


```d
template Value(int a, int b) {
enum Value = () {
    return a + b;
}();
}

int value = Value!(1, 2);
```

Does that help?


I had to reread this a few times to get a sense of what this is. I might 
have just got it. This is effectively a CTFE function for generating a 
constant based on the sum of two numbers, right? Doing `int value = 
Value!(1, 2);` would set `value` to 3, right?


Yes.

I suppose this was a good new thing to learn, though I'm still quite far 
from being able to construct a function from another function using a 
template.


I suppose that if I wanted it to make a function from another function, 
I may be able to do it in a template using some `static foreach` to make 
arrays of function parameters, and then combine them together without 
the use of strings, instead using placeholders (aliases or whatever 
they'd be called) and maybe the `tupleof` function. Am I headed in the 
right direction (if you can understand my weak attempt to describe the 
direction I'm thinking of going in)?


``tupleof`` isn't a function, its a property to get a "tuple" a sequence 
of fields for a struct/class.


However most likely you'd have to resort to string mixins if you're 
messing about with parameters like I think? you are asking for.


I'm not entirely sure what you're wanting there.


Re: "Error: `TypeInfo` cannot be used with -betterC" on a CTFE function

2024-04-08 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn



On 09/04/2024 11:42 AM, Liam McGillivray wrote:
On Monday, 8 April 2024 at 08:12:22 UTC, Richard (Rikki) Andrew 
Cattermole wrote:

```d
template Foo(Args) {
enum Foo = () {
    return Args.init;
}();
}
```

Something like that should work instead.


I'm sorry, but I can't comprehend any of your example. What would be 
fed into `Args`? I don't understand how this works, or how I would 
use it for what I want.


You would replace it with whatever template parameters you want 
(including nothing). It's there as a place holder.


Same for the return on the closure.

But the main thing to understand is that the closure that gives the 
enum a value, that'll be CTFE only, no runtime target.


Are you saying that this is a way to guarantee that the code is 
compile-time only?


More or less.

I still understand very little of this code. I'm not experienced in D 
metaprogramming; just the function I posted above was a major 
achievement for me. I don't understand how I would use the code you gave 
in place of the function I have written and posted above.


Let's break it down.

The expression that initializes the ``func`` variable, this is a 
closure. The ``a`` and ``b`` are function parameter names (types do not 
need to be provided).


```d
alias FuncType = int function(int, int);

FuncType func = (a, b) {
return a + b;
};

int value = func(1, 2);
```

The alias is used to give a name to the function pointer type.

Next, let's combine the function pointer storage variable with the 
result with the call.


```d
int value = (a, b) {
return a + b;
}(1, 2);
```

We can swap the type ``int`` for the ``enum`` keyword, this produces a 
compile time constant that is an ``int`` that has the value 3.


```d
enum Value = (a, b) {
return a + b;
}(1, 2);
```

This alone should be a CTFE only function.

But if we want template parameters, we'd need to wrap it with the template.

```d
template Value(int a, int b) {
enum Value = () {
return a + b;
}();
}

int value = Value!(1, 2);
```

Does that help?


Re: Setting up CI for Dub project on Github

2024-04-08 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 09/04/2024 1:20 AM, Dmitry Olshansky wrote:
I haven’t done any research on the subject, would be nice if somebody 
pointed me to good example of how it’s done.


—
Dmitry Olshansky
CEO @ Glowlabs
https://olshansky.me


In case you haven't already found:

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


Re: "Error: `TypeInfo` cannot be used with -betterC" on a CTFE function

2024-04-08 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 08/04/2024 10:45 AM, Liam McGillivray wrote:
On Sunday, 7 April 2024 at 08:59:55 UTC, Richard (Rikki) Andrew 
Cattermole wrote:

Unfortunately runtime and CTFE are the same target in the compiler.


:-(
Will this ever be changed?


A tad unlikely, it would be a rather large change architecturally to dmd.


```d
template Foo(Args) {
enum Foo = () {
    return Args.init;
}();
}
```

Something like that should work instead.


I'm sorry, but I can't comprehend any of your example. What would be fed 
into `Args`? I don't understand how this works, or how I would use it 
for what I want.


You would replace it with whatever template parameters you want 
(including nothing). It's there as a place holder.


Same for the return on the closure.

But the main thing to understand is that the closure that gives the enum 
a value, that'll be CTFE only, no runtime target.


Re: "Error: `TypeInfo` cannot be used with -betterC" on a CTFE function

2024-04-07 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

Unfortunately runtime and CTFE are the same target in the compiler.

So that function is being used for both, and hence uses GC (appending).

```d
template Foo(Args) {
enum Foo = () {
return Args.init;
}();
}
```

Something like that should work instead.


Re: CTFE write message to console

2024-04-04 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

Oh hey!

https://github.com/dlang/dmd/pull/16250

It was implemented literally 2 weeks ago!

Nightly should have it https://github.com/dlang/dmd/releases/tag/nightly


Re: CTFE write message to console

2024-04-04 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn



On 05/04/2024 4:04 AM, Carl Sturtivant wrote:
On Thursday, 4 April 2024 at 14:06:19 UTC, Richard (Rikki) Andrew 
Cattermole wrote:


```d
static assert(0, "message");
```

Or if it is known to be CTFE'd

```d
assert(0, "message");
```

Just a warning, its a one time use only for both.

No other way to do it.


That's ... unfortunate.

Some search of the forum led me to some [decade plus old 
discussion](https://forum.dlang.org/post/j1n1m2$24p0$1...@digitalmars.com) 
of a possible CTFE writeln function that would be a no-op at runtime, 
which to my surprise led me to find 
[core_builtins.__ctfeWrite](https://dlang.org/phobos/core_builtins.html#.__ctfeWrite) but when I tried it out, it compiled yet output no text to the console. Given your remarks I suppose I should have expected this.


Ah yes, I forgot about that particular thing, doesn't see much use as 
far as I'm aware.


It should be working though.


Re: How to resolve two packages requiring different versions of another package?

2024-04-04 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 05/04/2024 3:29 AM, WhatMeWorry wrote:

   Error: Unresolvable dependencies to package bindbc-loader:

   bindbc-opengl 0.13.0 depends on bindbc-loader ~>0.3.0
   bindbc-sdl 1.4.7 depends on bindbc-loader ~>1.1.0


https://github.com/BindBC/bindbc-opengl/issues/47


Re: CTFE write message to console

2024-04-04 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 05/04/2024 2:54 AM, Carl Sturtivant wrote:
I'm writing CTFE on Windows, latest DMD compiler. How should I write a 
message to the console (stderr) from a CTFE function call during 
compilation?


```d
static assert(0, "message");
```

Or if it is known to be CTFE'd

```d
assert(0, "message");
```

Just a warning, its a one time use only for both.

No other way to do it.


Re: Had to reinstall my Raspberry Pi, how do I set up LDC2's environment values permamently?

2024-03-19 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 19/03/2024 10:50 PM, solidstate1991 wrote:
Due to a screwup on my part, I had to reinstall my Pi's OS (was quicker 
than looking up the potential solution), and since I don't need multiple 
separate versions of D, I want to do away with the 
`activate`/`deactivate` scripts, especially as this method isn't liked 
by certain applications. I once solved this, but I forgot it since it's 
a very unintuitive process.


What I did in my linux VM is in .bashrc script, was to add 
``~/.local/bin/ldc*/bin`` to the PATH variable, and simply extract ldc 
out into ``~/.local/bin`` manually.


Whereas for a Gitlab CI I used the install script with:

```sh
source $(realpath -m $(curl -fsS https://dlang.org/install.sh | bash -s 
get-path dmd --install)/../../../activate)

```

Does either of this help you?


Re: Challenge: Make a data type for holding one of 8 directions allowing increment and overflow

2024-03-16 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
Bit fields are currently going through the DIP process, although because 
of ImportC having it, its just a matter of turning them on and adding 
the parser stuff.


However there is a major drawback to it and is why you'll still need to 
use a struct and that is you can't take a pointer to it.


Re: DUB error I can't make sense of

2024-03-16 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 16/03/2024 8:23 PM, Per Nordlöw wrote:

https://github.com/nordlow/phobos-next/releases/tag/v0.6.10

fails to build as

```
../../.dub/cache/phobos-next/0.6.10/code/phobos-next-test-library-unittest-nyN4MEoglVgAJ1A9GyL6uA/dub_test_root.d(11,15):
 Error: module `nxt.algorithm.comparsion` from file 
src/nxt/algorithm/comparison.d must be imported with 'import 
nxt.algorithm.comparsion;'
```

and I have no clue how to fix it.

Do you?


``module nxt.algorithm.comparsion;``

comparsion doesn't look much like comparison to me ;)


Re: Challenge: Make a data type for holding one of 8 directions allowing increment and overflow

2024-03-14 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn



On 15/03/2024 12:47 PM, Basile B. wrote:

On Thursday, 14 March 2024 at 23:39:33 UTC, Liam McGillivray wrote:
On Thursday, 14 March 2024 at 01:58:46 UTC, Richard (Rikki) Andrew 
Cattermole wrote:

[...]


I tried to rework the functions to use bitwise operations, but it was 
difficult to figure out the correct logic. I decided that it's not 
worth the hassle, so I just changed the value storage from `bool[3]` 
to `ubyte`. Now it works much more like your version.

https://github.com/LiamM32/Open_Emblem/blob/c2014ab3f77e89c0cedcd6dbf7f8362ebfac33a9/source/common.d

I did a little reading, so now I understand what it means when you 
have `&= 7`. But I want to ask, is this faster than `%= 8`? If not, I 
would like to change it to the latter for readability.


`%=8` will be codegened using slower intructions w/o optimz enabled but 
with `&=7` you directly get the right instruction, which does not 
involves integer division. See https://godbolt.org/z/74vbba5aG


Yes, it'll depend upon how smart the compiler is at optimizing and it 
may not occur in non-optimizing builds.


The modulas instructions are based upon division, this is an incredibly 
expensive operation.


https://stackoverflow.com/a/8022107

The division instruction on Haswell for integers ranges from 9 cycles 
for 8bit, all the way up to 36 cycles for 64bit.


Re: Challenge: Make a data type for holding one of 8 directions allowing increment and overflow

2024-03-13 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
There appears to be a few things that you may not be aware of based upon 
this implementation.


The cost of an add + increment then a bitwise and is only 2-4 cycles on 
a Haswell cpu. Depending upon if its working solely in registers (via 
inlining) or its operating on ram.


The cost of a move from ram into a register is about 1 cycle, but can 
have latencies around 3 cycles if not cached.


Whereas if you need to do branching (if statement, loops), this is an 
unpredictable cost and loops where a simple bitwise operation can be 
done is out right non-optimized.


As for methods like to:

```d
static immutable string[] table = ["north", ...];
return table[this.value];
```

That's two moves from ram to register.

In essence in your design, you have blown out the cost by a significant 
margin well beyond the 12% that is described as being the minimum to 
consider optimization.


If you want to understand where the 12% number comes from I suggest 
reading the paper "Structured Programming with go to Statements" by 
Donald Knuth.


As for exceptions, totally not required. You can solve this by simply 
making your state private so nobody else can mutate it. Bounds checking 
will ensure if the state is corrupted it'll error out if you use the 
lookup method I suggested above.


Understanding what I have said is very important for game engine 
programmers. So if you're interested in it beyond some hobbyist 
endeavors you have some reading up to do ;)


Re: Challenge: Make a data type for holding one of 8 directions allowing increment and overflow

2024-03-12 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 13/03/2024 11:00 AM, Liam McGillivray wrote:
I'm not familiar with the syntax of the line |value &= 7;|. Is it 
equivalent to writing |value = value % 7;|?


& is a bitwise and.

LSB 123456789 MSB

& 7

LSB 12300 MSB

Anyway, you used an int, but I used an array of 3 bools. I'm guessing 
that mine uses less memory, but I'm not sure how memory it adds when 
it's a struct with functions.


Due to alignment, it'll probably use just as much.

Mine only needs a single ``byte``, at 7 bits it's more than enough.

But ``int`` doesn't make much difference unless you are packing 
instances together ``align(0):`` and realistically cpus are optimized 
for 32bits not 8.


Re: Disable wrilten buf in docker

2024-03-12 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On D's side you can use ``stdout.flush;`` to force it to flush.

I don't think there is a way to force flushing via CLI.


Re: Challenge: Make a data type for holding one of 8 directions allowing increment and overflow

2024-03-12 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
By taking advantage of integer wrapping and a bitwise and, its quite a 
simple problem to solve!


Challenge for the reader: add support for binary operations and toString 
support.


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

```d
struct Direction {
private int value;

Direction opUnary(string op:"++")() {
value++;
value &= 7;
return this;
}

Direction opUnary(string op:"--")() {
value--;
value &= 7;
return this;
}

void opOpAssign(string op:"+")(int amount) {
value += amount;
value &= 7;
}

void opOpAssign(string op:"-")(int amount) {
value -= amount;
value &= 7;
}

enum Direction N = Direction(0);
enum Direction NE = Direction(1);
enum Direction E = Direction(2);
enum Direction SE = Direction(3);
enum Direction S = Direction(4);
enum Direction SW = Direction(5);
enum Direction W = Direction(6);
enum Direction NW = Direction(7);
}

unittest {
 Direction direction = Direction.N;
 direction++;
 assert(direction == Direction.NE);
 direction+=3;
 assert(direction == Direction.S);
 direction--;
 assert(direction == Direction.SE);
 direction-=4;
 assert(direction == Direction.NW);
}
```


Re: DMD windows and Clang's llvm-link.exe

2024-03-09 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 10/03/2024 4:46 PM, Carl Sturtivant wrote:
suggesting that there's a reason version 9 instead of 17 of lld is being 
used in the latest DMD installation, that may be relevant what I'd like 
to try. Any idea what that might be?


Yes, nobody has updated it.

https://github.com/dlang/installer/blob/50f5825e9d9bf44afb9108f0c1a01a8038d2f156/.github/workflows/build_windows.yml#L22

The ldc one should match whatever LLVM is which is newer.


Re: DMD windows and Clang's llvm-link.exe

2024-03-09 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 10/03/2024 11:02 AM, Carl Sturtivant wrote:
I'd like to see if I can get dmd to work correctly with Clang rather 
than MS tools. Can anyone share any experience they've had with this or 
any understanding of the situation?


lld is used and distributed with dmd and ldc.

That is known to work.

If you have MSVC, it'll prefer that however.


Re: Why am I getting segfaults when doing `foreach` with arrays of references?

2024-03-09 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 09/03/2024 8:49 PM, Liam McGillivray wrote:
But that begs the question; why? Don't dynamic arrays always start with 
a length of 0? If the array was only extended when valid objects were 
appended using the append operator |~=|, and none of those objects were 
deleted (as I the destructor was never called), why would some of the 
array elements be null?


The default initialization state of a pointer (regardless of type) in D 
is null.


I.e.

```d
Object[] array;
array.length = 2;
array[0] = new Object;

assert(array[0] !is null);
assert(array[1] is null);

array ~= new Object;

assert(array[0] !is null);
assert(array[1] is null);
assert(array[2] !is null);
```


Re: Why am I getting segfaults when doing `foreach` with arrays of references?

2024-03-08 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
Something that I have noticed that you are still doing that was pointed 
out previously is having a pointer to a class reference.


Stuff like ``Tile* currentTile;`` when it should be ``Tile currentTile;``

A class reference is inherently a pointer.

So when you checked for nullability in the foreach loop of mission:

```d
if (startTile.occupant !is null && (*startTile.occupant) !is null) {
```

is what it should've looked like.

```d
import std.stdio : writeln;

void main() {
Object o = new Object;
writeln(cast(void*)o); // 7F2780EFD000
}
```


Re: Can a D library have some types determined by the client program?

2024-03-07 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn



On 08/03/2024 4:09 PM, Liam McGillivray wrote:
On Thursday, 7 March 2024 at 22:18:40 UTC, Richard (Rikki) Andrew 
Cattermole wrote:

There are two ways to do this.

1. Use templates. https://tour.dlang.org/tour/en/basics/templates
2. Use a factory function. 
https://tour.dlang.org/tour/en/basics/delegates


```d
class Map(ATile : Tile) {
ATile[] tiles;
}
```


Thank you. Is this first example you gave the template? Is the syntax 
`(ATile : Tile)` saying that ATile must be a derived class of Tile? If 
this isn't worse in any way than your second example, then I don't know 
why I wouldn't choose this one.


Typically in D we use templates quite heavily, but what you are wanting 
is probably more familiar to you via the OOP method with a factory of 
some kind.


I suppose that if I do this, then the derived class `Mission` would be 
declared like `class Mission : Map(GridTile)`, right?


``class Mission : Map!GridTile`` but right idea.

When I tried adding that parameter to the Map class, on attempting to 
build it it complained that references to Map in other classes were 
incomplete, as they didn't include a parameter. I suppose I must make my 
other classes templates too.


Something strange that I just realized is that (without doing any of the 
changes you suggested to me), I have a reference to a Map object as one 
of the class variables in Unit, yet it has allowed me to place a Mission 
object in it's place. It no longer allows me if I change it to a 
pointer. Why is it sometimes possible to put a derived class in a place 
meant for the class it inherits from?


That should always be allowed.


Re: Can a D library have some types determined by the client program?

2024-03-07 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

There are two ways to do this.

1. Use templates. https://tour.dlang.org/tour/en/basics/templates
2. Use a factory function. https://tour.dlang.org/tour/en/basics/delegates

```d
class Map(ATile : Tile) {
ATile[] tiles;
}
```

Or:

```d
class Map {
Tile[] tiles;
Tile delegate(string params) factory;

this() {
factory = (string params) {
return new Tile;
};

foreach(i; 0 .. 10) {
tiles ~= factory("");
}
}
}
```

The factory delegate is a very rough way to do it, there are other ways 
to describe it including an overridable method.


The design pattern: https://en.wikipedia.org/wiki/Factory_method_pattern


Re: Hidden members of Class objects

2024-03-06 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn



On 07/03/2024 1:28 PM, Carl Sturtivant wrote:

On Wednesday, 6 March 2024 at 23:45:00 UTC, H. S. Teoh wrote:
In D, there's a pointer to the vtable and another pointer to a Monitor 
object (used for synchronized methods).  There was talk about getting 
rid of the Monitor field years ago, but nothing has happened yet.


Very interesting: is the monitor field ever touched by compiled D code 
at any point nowadays? Or is it just vestigial?


Yes its opt-in. https://dlang.org/spec/statement.html#synchronized-statement



Re: Question on shared memory concurrency

2024-03-03 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

A way to do this without spawning threads manually:

```d
import std.parallelism : TaskPool, parallel, taskPool, defaultPoolThreads;
import std.stdio : writeln;
import std.range : iota;

enum NSWEPT = 1_000_000;
enum NCPU = 4;

void main() {
import core.atomic : atomicLoad, atomicOp;

shared(uint) value;

defaultPoolThreads(NCPU);
TaskPool pool = taskPool();

foreach(_; pool.parallel(iota(NSWEPT))) {
atomicOp!"+="(value, 1);
}

writeln(pool.size);
writeln(atomicLoad(value));
}
```

Unfortunately I could only use the default task pool, creating a new one 
took too long on run.dlang.io.


I also has to decrease NSWEPT because anything larger would take too long.


Re: importC with gc-sections not work on linux

2024-02-26 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 27/02/2024 1:28 AM, Dakota wrote:
When I use importC to build a c library, there is a lot unused symbol 
missing.


I try add `-L--gc-sections` to dmd to workaround this issue.


This removes symbols, not keeps them.

You want the linker flag: ``--no-gc-sections``

"Enable garbage collection of unused input sections. It is ignored on 
targets that do not support this option. The default behaviour (of not 
performing this garbage collection) can be restored by specifying 
‘--no-gc-sections’ on the command line. Note that garbage collection for 
COFF and PE format targets is supported, but the implementation is 
currently considered to be experimental."


https://sourceware.org/binutils/docs/ld/Options.html


Re: importC error Error: undefined identifier `__builtin_unreachable`

2024-02-26 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 26/02/2024 10:34 PM, Dakota wrote:

undefined identifier `__builtin_clz`


Done.

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


Re: importC error Error: undefined identifier `__builtin_unreachable`

2024-02-26 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn



On 26/02/2024 9:04 PM, Dakota wrote:

I try one more importC case, get this error:

```sh
Error: undefined identifier `__builtin_unreachable`
```

any tips to fix this?


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


Re: Error when using `import`.

2024-02-24 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn



On 24/02/2024 11:51 PM, Liam McGillivray wrote:
On Saturday, 24 February 2024 at 10:34:25 UTC, Richard (Rikki) Andrew 
Cattermole wrote:

A few things.

Module names should be lower case.


I capitalised the first letter in the class names so that I can make 
instances of them in lowercase. Should I rename the classes, modules, 
and filenames to all be lowercase?


It appears to be solved now after adding module declarations to the 
beginning of each file in all-lowercase. This is despite the classes and 
the class names still being capitalized. I'm still getting errors, but 
they appear to be unrelated.


Thank you.


As far as naming goes, the recommendations from the D style guidelines 
are quite good.


https://dlang.org/dstyle.html

However I suspect that you are treating module names as symbols, and 
while this is the case it can be done, you should avoid doing that until 
you understand the basics.


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


Re: Error when using `import`.

2024-02-24 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

A few things.

Module names should be lower case.

Each file, needs the full module declaration.


source/foo/bar.d:

```d

module foo.bar;

```


source/app.d:

```d

module app;

import foo.bar;

```


Directories matter, this allows the import path search (via the use of 
the -I switch) to locate modules based upon the filename relative to the 
directory in the search.





Re: std.uni.CodepointSet from range of pairs of integers

2024-02-18 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 19/02/2024 5:33 PM, Carl Sturtivant wrote:
On Monday, 19 February 2024 at 01:42:03 UTC, Richard (Rikki) Andrew 
Cattermole wrote:

I can understand ``pure``.

https://github.com/dlang/phobos/blob/master/std/uni/package.d#L2075

It is literally on the constructor.

Now @safe I don't know. My best guess would be for some reason the 
constructor is getting inferred as it (templates get inferred).


What about needing a forward range, not just an input range? It would 
seem it just needs to iterate through a sequence of pairs of integers.


Indeed, nothing in that function body would suggest it needs to be a 
forward range.


Ah yup, the body was changed but never updated its template conditional.

https://github.com/dlang/phobos/commit/c9f1c42ed3a8bb92e48bf400ce2f31f434a99905


Re: std.uni.CodepointSet from range of pairs of integers

2024-02-18 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

I can understand ``pure``.

https://github.com/dlang/phobos/blob/master/std/uni/package.d#L2075

It is literally on the constructor.

Now @safe I don't know. My best guess would be for some reason the 
constructor is getting inferred as it (templates get inferred).


Re: Are exceptions caught in unittests?

2024-02-15 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

This should be working.

I don't know what is going on.

All I can suggest is to use a debugger to see if it is indeed throwing 
and then catching.


Re: std.uni CodepointSet toString

2024-02-09 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 09/02/2024 9:04 PM, Danilo wrote:
Instead of bug fixing and stabilization, people concentrate on getting 
new stuff like ˋ:blubˋ into the language.


Umm, I take it that you didn't know that one of the reasons we spent the 
past year focusing on bug fixing and stabilization is because of my work 
trying to get shared library support resolved?


My focus is upon making D's foundations stable, and that work comes in 
many forms and yes some of that is in new features which help resolve 
other problems in the ecosystem.


Whether it be getting D's identifiers able to express recent C versions 
and hence interoperability, making sure how we represent and work with 
symbols actually work without error in common situations or just fixing 
random bugs where something minor was messed up some place. They are all 
stabilization and bug fixing tasks that I have some thing to do with.


People are doing what they can to make D better, and we are all aware 
for those of us who actively contribute that D has a very large backlog 
of bugs that need resolving.


Re: std.uni CodepointSet toString

2024-02-07 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 08/02/2024 6:11 AM, H. S. Teoh wrote:

Do we know why the compiler isn't getting it right?  Shouldn't we be
fixing it instead of just turning off elision completely?


Of course we should.

It has been reported multiple times, with different examples trigger the 
switch symbol error.


Re: std.uni CodepointSet toString

2024-02-07 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 08/02/2024 5:36 AM, Carl Sturtivant wrote:
On Wednesday, 7 February 2024 at 11:49:20 UTC, Richard (Rikki) Andrew 
Cattermole wrote:

```
undefined reference to 
`_D4core9exception__T15__switch_errorTZQsFNaNbNiNeAyamZv'

collect2: error: ld returned 1 exit status
Error: linker exited with status 1
```


Use ``-allinst``, that is a template emission bug.


!
Thanks, at least I can continue now, though presumably the cure has its 
own problems.


```
$ dmd --help | grep allinst
   -allinst  generate code for all template instantiations
```
Unclear exactly how -allinst does this, given type parameters, and it 
will affect all of the many templates I use in source with CodepointSet.


Can you shed any light?


Basically the compiler will by default try to elide templates it thinks 
isn't used.


However it doesn't always get this right, which this flag overrides by 
turning it off.


Re: std.uni CodepointSet toString

2024-02-07 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

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


Re: std.uni CodepointSet toString

2024-02-07 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 07/02/2024 7:27 PM, Carl Sturtivant wrote:

Need help working around a linkage problem.
```d
import std.uni, std.conv, std.stdio, std.format;

void main() {
 //auto c1 = unicode.InBasic_latin;
 auto c1 = CodepointSet('a','z'+1);
 writeln(c1.to!string);
 writeln(format("%d", c1));
 writeln(format("%#x", c1));
 writeln(format("%#X", c1));
 writefln("%s", c1);
}
```
doesn't link, but does link with the commented out CodepointSet instead. 
Combines code from these examples at the following URLs.

https://dlang.org/phobos/std_uni.html#InversionList
https://dlang.org/phobos/std_uni.html#.InversionList.toString
```
$ dmd --version
DMD64 D Compiler v2.107.0
Copyright (C) 1999-2024 by The D Language Foundation, All Rights 
Reserved written by Walter Bright

$ dmd cset2.d
/usr/bin/ld: cset2.o: in function 
`_D4core8internal7switch___T14__switch_errorZQrFNaNbNiNfAyamZv':

cset2.d:(.text._D4core8internal7switch___T14__switch_errorZQrFNaNbNiNfAyamZv[_D4core8internal7switch___T14__switch_errorZQrFNaNbNiNfAyamZv]+0x19):
 undefined reference to 
`_D4core9exception__T15__switch_errorTZQsFNaNbNiNeAyamZv'
collect2: error: ld returned 1 exit status
Error: linker exited with status 1
```


Use ``-allinst``, that is a template emission bug.


Re: Branching of a discussion in forums?

2024-01-29 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 30/01/2024 5:06 AM, Alexandru Ermicioi wrote:
On Monday, 29 January 2024 at 14:59:23 UTC, Richard (Rikki) Andrew 
Cattermole wrote:
If you are using a NewsGroup reader like ThunderBird it should be 
possible to branch off and post in a different one.


What about web interface?


I don't think it has the capability to do that.


Re: Branching of a discussion in forums?

2024-01-29 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
If you are using a NewsGroup reader like ThunderBird it should be 
possible to branch off and post in a different one.


Although nobody does that, normally people rename the subject instead.


Re: Partial function application (Currying)

2024-01-20 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 21/01/2024 9:55 AM, atzensepp wrote:
import std.stdio; // Overloads are resolved when the partially applied 
function is called // with the remaining arguments. struct S { static 
char fun(int i, string s) { return s[i]; } static int fun(int a, int b) 
{ return a * b; } } void main() { alias fun3 = partial!(S.fun, 3); 
writeln(fun3("hello")); // 'l' writeln(fun3(10)); // 30 }


This worked:

```d
import std.functional;
import std.stdio;

// Overloads are resolved when the partially applied function is called
// with the remaining arguments.
struct S
{
static char fun(int i, string s)
{
return s[i];
}

static int fun(int a, int b)
{
return a * b;
}
}

void main()
{
alias fun3 = partial!(S.fun, 3);
writeln(fun3("hello")); // 'l'
writeln(fun3(10)); // 30
}
```


Re: Partial function application (Currying)

2024-01-20 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
Not really any other way to do it, create context (i.e. struct, or 
stack) and have a delegate point to both it and a patch function.


It'll be how partial is implemented.

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


Re: Understanding the Use of Nested Import and Selective Import in D

2024-01-16 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
Yes, I try to place my imports at the most general location that makes 
sense.


Sometimes that is at the module level, other times its in a single function.

Or anywhere in between (such as a struct).


Re: Problems using rawWrite in an experiment with WAVs in D

2023-12-27 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
Because WaveHeader has no pointers in it, only raw memory, assuming it 
is all in the cpu endianesss and with ``align(1)`` you can slice that 
block of stack memory and write from that.


```d
file.rawWrite((cast(ubyte*))[0 .. WaveHeader.sizeof]);
```

However I would recommend doing it field by field.

A lot more work, but allows you to handle endianness issues and remove 
alignment concerns. Also changing of field sizes if required.


Same principles as the code above.


Re: std.int128 not working with -betterC enabled

2023-12-22 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 23/12/2023 11:41 AM, Matheus Catarino wrote:

Would there be any reason not to use |core.int128|?

Currently, I used it to make a TigerbeetleDB client (Zig database) in D 
(betterC). 
https://github.com/batiati/tigerbeetle-clients-benchmarks/blob/f86216834bd04e1e06bede2a2e31b64df0dc98f1/d/modules/tb_client.d#L12 


Yes there is.

With -betterC, it is not linked in. Therefore it will fail to link.

Note: ldc/gdc may recognize it and switch it to backend specific things 
instead of using those functions, which will work.


Re: std.int128 not working with -betterC enabled

2023-12-20 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 21/12/2023 10:51 AM, Renato wrote:
On Wednesday, 20 December 2023 at 19:11:15 UTC, Richard (Rikki) Andrew 
Cattermole wrote:

Yes that is to be expected.

It is not templated, and hasn't been compiled into your program.


How do I compile that into my program?


You copy the file from druntime into your project, and add it to your 
programs compile command.


Re: std.int128 not working with -betterC enabled

2023-12-20 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

Yes that is to be expected.

It is not templated, and hasn't been compiled into your program.


Re: D is a great language, but I've had a bad experience getting started

2023-12-14 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 15/12/2023 2:02 AM, Renato wrote:

How do you tell dub to "build and link in a single step"?


This should do it:

``--combined --build-mode=allAtOnce``


Re: D is a great language, but I've had a bad experience getting started

2023-12-14 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

Welcome!



Regarding the problems with dub on OSX, that'll be due to separate build 
+ link steps.


It should work ok if you build and link in a single step with the 
workaround applied.




DC is an environment variable that should point to the D compiler.

As a variable this particular one has some sort of story with it, I just 
can't remember it.


We'd need to know what is requesting it to find out how to resolve it. 
Please try again with ``-v`` that should tell us what is wanting it.


Re: import issue?

2023-11-22 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 23/11/2023 5:34 AM, DLearner wrote:
Is the encapsulation issue resolved if the struct itself is held in 
another module, and imported from that module into both the 'main' and 
'Ex_mod' files?


Each module is its own encapsulation unit.

As long as you are using the same distinct type in both modules, the 
issues are resolved.


Where the distinct type is defined does not matter for matching of 
function parameters.


Re: import issue?

2023-11-22 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

You have two ``SA`` structs, each in different encapsulations.

Each of them are different, even if they have similar members.

In D types that look the same do not combine, they are distinct.

You can see this by comparing the mangling of each.

``pragma(msg, SA.mangleof);``


Re: D: How would one make a shared dynamically linked D library?

2023-11-08 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

Currently stick to ldc.

Dub's defaults will "just work" except:

- On *nix where you have to either set/patch the ``RPATH`` or set 
``LD_LIBRARY_PATH``.
- For executables on Windows in which you need to set the dflag 
``-dllimport=all``.



From a README of mine (for Posix):


To get the loading of sidero shared libraries you will need to set the 
LD path before execution.


E.g. export 
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:~/projects/ProjectSidero/eventloop/examples/networking


or you can patch the binary:

patchelf --force-rpath --set-rpath 
~/projects/ProjectSidero/eventloop/examples/networking ./example_networking


Re: Installing DMD on Windows

2023-10-20 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
I've gone ahead and reported it, most likely nobody has used VS2022 
professional edition.


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


Re: strange link error: _My_struct__xtoHashFNbNeKxSQBlQBoQBiZm _My_struct__xopEqualsMxFKxSQBlQBoQBiZb

2023-10-16 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 17/10/2023 4:18 PM, mw wrote:
Is string basic types? as I showed one earlier Foo {one string and two 
ints}, my other struct only has double and long, it also has the same 
link errors about toHash and opEquals.


string is not a basic type, its a slice, which means pointer.


Re: strange link error: _My_struct__xtoHashFNbNeKxSQBlQBoQBiZm _My_struct__xopEqualsMxFKxSQBlQBoQBiZb

2023-10-16 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 17/10/2023 2:17 PM, mw wrote:

It's just my own module and type name, nothing special or interesting.


Doesn't matter.

Because I now can't demangle it and figure out what its trying to find 
without doing that by hand. Every character in a symbol name is 
significant, you can't remove some of it without changing the meaning of 
something else.


Regardless its probably not something like template elision from what 
you have said so it might be a compiler bug and I won't be much help 
there. Of course I can't know for certain without the full symbol 
hierarchy or the symbol name.


Re: strange link error: _My_struct__xtoHashFNbNeKxSQBlQBoQBiZm _My_struct__xopEqualsMxFKxSQBlQBoQBiZb

2023-10-16 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 17/10/2023 2:15 PM, mw wrote:
On Tuesday, 17 October 2023 at 01:11:13 UTC, Richard (Rikki) Andrew 
Cattermole wrote:

They are for structs as well.


Ah?! I use quite a few struts, but I never have provided such two methods.


Indeed, they are generated by the compiler, not user provided.

They are needed when you have fields that are not basic types like other 
structs.


Re: strange link error: _My_struct__xtoHashFNbNeKxSQBlQBoQBiZm _My_struct__xopEqualsMxFKxSQBlQBoQBiZb

2023-10-16 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 17/10/2023 1:58 PM, mw wrote:
Oh the <_My_struct> part is my simplification, it is mangled as 
something like : _D6..<_My_struct>..__xtoHashFNbNeKxSQBlQBoQBiZm


When dealing with linker errors, please do not simplify, it can make 
problems unsolvable.


Re: strange link error: _My_struct__xtoHashFNbNeKxSQBlQBoQBiZm _My_struct__xopEqualsMxFKxSQBlQBoQBiZb

2023-10-16 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

They are for structs as well.


Re: strange link error: _My_struct__xtoHashFNbNeKxSQBlQBoQBiZm _My_struct__xopEqualsMxFKxSQBlQBoQBiZb

2023-10-16 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

xtoHash and xopEquals are generated by the compiler automatically.

Curiously those two symbol names are not demangling.

Given this, I suspect the best thing to do is file a bug report with ldc 
with the code that generated the linker error.


Re: Forcing my module to be initialized first

2023-10-16 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
Okay, after looking at gtkd, I don't think this can be solved with 
module constructors or swapping out to lazy initialization.


One way that might work however is to use a crt_constructor as that runs 
before the D stuff. However it would now hard code your program to your 
system. Over all my suspicion is that there is something wrong with your 
system related to library lookup paths and that should be fixed instead.


```d
void main() {
import std.stdio;
import std.process;
writeln(environment["GTK_BASEPATH"]);
}

pragma(crt_constructor) extern(C) void myEnvironmentVarSetter() {
import core.sys.posix.stdlib : putenv;
putenv(cast(char*)"GTK_BASEPATH=~/bin/gtk".ptr);
}
```


Re: Forcing my module to be initialized first

2023-10-15 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 16/10/2023 4:31 PM, dan wrote:
I suppose if i could figure out a way to make all other modules depend 
on my module this would happen, but the module which uses the variable i 
want to set is in some already-compiled dynamic library that i would 
prefer not to touch.


If its in a shared library, then that shared library gets setup prior to 
your binary.


There is nothing that you can do. You gotta override rather than initialize.


Re: allocated object address as high as 46th bit (i.e in the 131072 GB range)

2023-10-09 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
As far as I'm aware, no cpu that you can get ahold of support more than 
48bit of address space at the hardware level.


There is simply no reason at this time to support more, due to the fact 
that nobody has implemented anywhere near that maximum.


Also worth noting, the address a block of memory is, has no relation to 
the hardware. A kernel will instruct the cpu to map it wherever it 
pleases per process.


Re: Is it possible to create a kernel for an operating system in D?

2023-09-25 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
Indeed it is. Many people have done projects in this vein, the language 
isn't the limitation.


If you use the -betterC switch, you can fairly quickly get up and going 
and program a kernel as if you were using C, except with a nicer 
language. All other considerations like linker scripts ext. still apply 
however.


Re: Detect 8-bit alligned type TXY by TX,TY.

2023-09-19 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

I assume what you are wanting is to get the alignment for a given type?

https://dlang.org/spec/property.html#alignof

If instead you want the offset of a given field that's different.

``T.field.offsetof``

https://dlang.org/spec/struct.html#struct_field_properties

Note: alignment cannot be represented by a type, it can only be 
represented by a number (for instance it could be 3).


Re: Which function returns a pair after division ? (integer,frac)

2023-09-18 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

There are no operators for this, not that you need one.

```d
void func(int numerator, int denominator, out int quotient, out int 
remainder) {

quotient = numerator / denominator;
remainder = numerator % denominator;
}
```

This will produce with ldc2 -O3:

```
void example.func(int, int, out int, out int):
mov r8, rdx
mov eax, edi
cdq
idivesi
mov dword ptr [r8], eax
mov dword ptr [rcx], edx
ret
```

Embrace modern backends, they are amazing!


Re: malloc error when trying to assign the returned pointer to a struct field

2023-09-08 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 08/09/2023 7:59 PM, rempas wrote:
|Fatal glibc error: malloc.c:2594 (sysmalloc): assertion failed: 
(old_top == initial_top (av) && old_size == 0) || ((unsigned long) 
(old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) 
old_end & (pagesize - 1)) == 0)|


I would strongly suggest that you log all memory sizes that are 
allocated, and double check that you do free.


Also turn on ASAN in ldc.

http://johanengelen.github.io/ldc/2017/12/25/LDC-and-AddressSanitizer.html


Re: malloc error when trying to assign the returned pointer to a struct field

2023-09-08 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 09/09/2023 2:20 AM, rempas wrote:
Do they have automatic symbol order resolution? Which is, testing 
symbols that other symbol depend on first? Or is it random?


No, for this you need ModuleInfo. The order is sequential on what it 
sees first.


Personally I test using full D rather than -betterC.

For dub:

```json
"configurations": [
{
"name": "library",
"targetType": "dynamicLibrary",
"versions": [
"DynamicSideroBase"
],
"buildOptions": [
"betterC"
]
},
{
"name": "static",
"targetType": "staticLibrary",
"buildOptions": [
"betterC"
]
},
{
"name": "unittest"
},
{
"name": "executable",
"targetType": "executable"
}
]
```


Re: malloc error when trying to assign the returned pointer to a struct field

2023-09-08 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
In case you didn't know, all you need to get unittests working in 
-betterC is:


```d
foreach (module_; allModules) {
foreach (unitTest; __traits(getUnitTests, 
module_)) {
unitTest();
}
}
```

You'd need to provide allModules somehow, like dub does.

https://github.com/dlang/dub/blob/2ea883833adf085095b07a7dba8250fb3db79a71/source/dub/project.d#L1937


Re: D DLL crashes if not run on the main thread

2023-09-05 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
Assuming it works outside of a DLL, you're probably missing the runtime 
initialization calls.


Mix SimpleDllMain in (or do your own). 
https://github.com/dlang/dmd/blob/9639d72ea0883808feff7aba71d87c5a78fb7f92/druntime/src/core/sys/windows/dll.d#L577


Re: D DLL crashes if not run on the main thread

2023-09-05 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
Whatever is going on, that function you showed would not call into 
druntime. So I don't think it's related.


As of right now I have no tips as I'm tired, but I suspect its on the 
.net end.


Re: I don't understand betterC

2023-09-01 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
``size_t`` is defined in ``object.d`` which is implicitly imported into 
all modules.


If it cannot be found, one of three things is happening:

1) You have messed with some cli args related to picking druntime/phobos
2) You have defined a module called object.
3) You have a broken compiler install.


Re: I don't understand betterC

2023-08-31 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

```d
extern(C) int main()
{
import core.stdc.stdio;

string hello = "hello";
printf(hello.ptr);

return 0;
}
```

1) You forgot to import ``core.stdc.stdio``
2) String literal is of type string (which is an alias to 
``immutable(char)[]``).
3) A slice is a pointer + length, and C doesn't understand slices, so 
you must explicitly pass in the pointer from the slice (the compiler 
would do this for you if you had the literal in the arguments list 
instead of the variable).


Re: Visual Studio 2022 no longer debugs D program, need an alternative debugger for Windows

2023-08-26 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 27/08/2023 6:47 AM, solidstate1991 wrote:

On Saturday, 26 August 2023 at 17:57:22 UTC, jmh530 wrote:

You should report this to bugzilla.


I'm using it in an unusual way. Since VisualD does not support dub, I 
have to rely on VSCode as my main editor, then load the executable in an 
empty C++ project in VS. This worked so far.


On the other hand, I'm having some good results with x64dbg, except I 
don't know how can I get locals to be displayed (which is the x64dbg is 
capable of, except all tutorials for it is about reverse engineering).


Not unusual. However I attributed the breakage to -betterC + DLL's. 
Which clearly isn't the issue.


Re: Cool pattern or tragic?

2023-08-25 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

I do something similar with my error types.

I have a method called assumeOkay. It'll assert if it isn't ok.

There is also unsafeGetLiteral for slice based types.

All @system.


Re: std.experimental.allocator

2023-08-13 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 14/08/2023 4:10 AM, ryuukk_ wrote:
Also if you want people to use D for games, you want an allocator API 
that doesn't use RAII, same for exceptions btw


After thinking about it a bit, this would suggest to me that you are 
trying to solve a problem that I would outright recommend against using 
an abstraction to solve.


Memory allocators that only deal with fixed sized memory blocks, that 
are specific to a thread are going to have the best performance. If this 
is the case you don't need an abstraction at all.


A rough pseudo code where no RCAllocator would be used:

```d
module particles;

private __gshared FreeList!(AllocatorList!(Region!(SystemMapper, 
__traits(classInstanceSize, Particle allocator;


final class Particle {
int lifeLeft;

void free() {
allocator.dispose(this);
}

static Particle create() {
return allocator.make!Particle();
}
}
```

Of course you'd only call free/create as part of a particle manager, but 
this should still demonstrate that an abstraction isn't required if you 
understand your data and memory lifetimes well enough to see any 
performance improvement by using a memory allocator library.


Re: std.experimental.allocator

2023-08-13 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
Yeah you're right Ternary should probably be replaced, although 
amazingly it has never caused problems so far.


But I cannot agree about RAII. Its a valid tool for managing lifetimes 
of memory allocators. Memory allocators must be able to store per 
instance state and that state must not accidentally die on you. If it 
does that is a great way to give the user a very bad day.


We are certainly aiming for different things, for instance I don't trust 
my (future) users when it comes to memory safety. So they get very well 
hand held in all aspects. Including locking of RCAllocator internally 
and using RC there.


But internally to API's if you need to optimize you'd use the composable 
allocator structs directly, rather than the expensive (in comparison) 
RCAllocator.




Re: stb library and importC

2023-08-13 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 14/08/2023 3:23 AM, ryuukk_ wrote:
On Sunday, 13 August 2023 at 06:43:10 UTC, Richard (Rikki) Andrew 
Cattermole wrote:
I would argue that this should be done by dmd as it knows where the VS 
installation is and it'll catch people out who aren't using dub.


Oh better, let's try to send a PR to dmd then for today, it shouldn't be 
hard if you say it already know where VS is


Knowing where VS is, is the easy part (although it is logic that has 
been fine tuned over a 10 year period, so not something you'd want to 
duplicate).


Getting the environment variables that are set up by a cobweb of batch 
scripts is the hard part.


We are not the first to need to do this either! 
https://stackoverflow.com/questions/2123/get-environment-variables-of-child-process-in-vc


Re: std.experimental.allocator

2023-08-13 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
Mine (-betterC) 
https://github.com/Project-Sidero/basic_memory/tree/main/source/sidero/base/allocators


Similar scope to one in Phobos.

On that note I'm still waiting a year+ for Atila to get back to me about 
talking about where to go for std.experimental.allocators.


Re: stb library and importC

2023-08-13 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
I would argue that this should be done by dmd as it knows where the VS 
installation is and it'll catch people out who aren't using dub.


Re: What is a dchar ?

2023-07-25 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
The spec says they are unsigned, so if ldc is using sign extension, that 
is probably a bug.


Re: Which D compiler is the most maintained and future-proof? [DMD GDC and LDC]

2023-07-24 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 25/07/2023 1:26 AM, devosalain wrote:

I could be interesting to also compare the licenses of the 3 compilers.


There isn't a huge difference between them.

The frontend, druntime and most of phobos (minus zlib and curl) are all 
Boost regardless of compiler.


That just leaves backends, which depends upon GCC and LLVM. So if you 
can use GCC and Clang, your fine to use GDC and LDC.


Re: Which D compiler is the most maintained and future-proof? [DMD GDC and LDC]

2023-07-24 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn



On 25/07/2023 1:30 AM, cc wrote:
Is there any list of known significant "gotchas" with moving to LDC from 
DMD?  Any unexpected surprises to watch out for or be careful for?  I'm 
thinking of all the "features" of DMD that are now considered verboten 
by many users (e.g. compiling with -release, disabling of asserts or 
array bounds checking, etc). Known edge cases of compiler optimization 
causing different behavior between vendors?


No, there is no list.

The main gotcha I know of is inline assembly being a bit different. Also 
the glue code for LDC hasn't got ``extern(Objective-C)`` implemented 
currently. I don't know about GDC.


Over all, if you are familiar with GCC & Clang, you'll be ok. A lot of 
the flags from dmd have a comparable version (if not split up further) 
in LDC and GDC.


Re: Which D compiler is the most maintained and future-proof? [DMD GDC and LDC]

2023-07-24 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

There isn't a huge concern with which one you use.

Its quite common to use dmd for development, and ldc for release for 
example.


They all share the same frontend, so they really only differ between 
them by their glue code to the relevant backend and some modules in 
druntime that are optional. Oh and inline assembly, although there is 
some compat code in ldc/gdc for dmd style.


If dmd dies, so does ldc/gdc basically. Each one sees active development 
although gdc only has one developer. Ldc keeps up with the dmd releases 
pretty well.


Re: Garbage Collectors

2023-07-19 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 19/07/2023 11:13 PM, IchorDev wrote:
On Wednesday, 19 July 2023 at 10:50:07 UTC, Richard (Rikki) Andrew 
Cattermole wrote:


Copying out the conservative GC, register it under a different name 
and getting that to compile and link without recompiling druntime 
would be a good place to begin without having to understand how GC's 
work.


That sounds pretty easy, but I don't really see how would that be 
particularly helpful to allowing a different style of GC to be registered?


druntime supports registering of GC's not compiled with druntime.

But because some of the machinery isn't available to you, you would have 
to recreate it.


So in practice you cannot find a GC on the dub-registry to try it out. 
Even if one were to exist, you would have to do a new build of 
druntime/phobos special which isn't the easiest thing to do.


https://github.com/dlang/dmd/blob/master/druntime/src/core/gc/registry.d#L39

Regardless, its a barrier to anyone wanting to try writing a GC to 
experiment with (or port one).


Re: Garbage Collectors

2023-07-19 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 19/07/2023 9:02 PM, IchorDev wrote:
On Wednesday, 19 July 2023 at 08:27:18 UTC, Richard (Rikki) Andrew 
Cattermole wrote:

Its not as simple as porting to the API unfortunately.

We don't have barriers of any kind, so that removes most GC designs 
you would want to use today. We are very close to maxing out what we 
can do as a result.


A whole pile of logic is hidden in rt, so you have no choice but to 
either do the work to fix that, or recompile druntime with your GC.


I'm mostly a frontend person, but is what would need doing there? Is 
there any existing discussion about that?


Not really, last time I tried, I didn't document what was hidden.

Copying out the conservative GC, register it under a different name and 
getting that to compile and link without recompiling druntime would be a 
good place to begin without having to understand how GC's work.




Re: Garbage Collectors

2023-07-19 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

Its not as simple as porting to the API unfortunately.

We don't have barriers of any kind, so that removes most GC designs you 
would want to use today. We are very close to maxing out what we can do 
as a result.


A whole pile of logic is hidden in rt, so you have no choice but to 
either do the work to fix that, or recompile druntime with your GC.


Re: Garbage Collectors

2023-07-19 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

On 19/07/2023 7:44 PM, Sergey wrote:
Forking GC was introduced some time ago. But I don't think it is quite 
different from regular 
(https://forum.dlang.org/post/tf8mbo$1jvp$1...@digitalmars.com)


It is a modification of the conservative GC. Rather than a unique GC 
implementation and is upstreamed.



There are some posts about it GCs, but I don't think anything was released.
https://forum.dlang.org/thread/jquklsqxtfgvsezrc...@forum.dlang.org?page=1
https://forum.dlang.org/post/yonbmhifafbyjhwpc...@forum.dlang.org


The only GC design I know of that is semi-interesting is Rainer's 
concurrent GC for Windows.


http://rainers.github.io/visuald/druntime/concurrentgc.html

This has not been upstreamed.


Re: How to free memory ater use of "new" to allocate it.

2023-07-16 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
Steven is right, was quite late when I said that so it'll work but not 
for the reasons I thought it would.


Re: How to free memory ater use of "new" to allocate it.

2023-07-16 Thread Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn

Yes.

For basic types like int's, you don't need to destroy the array.

As long as you don't slice the array and store that in i, you don't need 
to call addrOf too.


  1   2   3   >