Re: how do i fix this node_dlang error?

2021-06-07 Thread NotSpooky via Digitalmars-d-learn

On Tuesday, 8 June 2021 at 03:04:39 UTC, Mike Parker wrote:

On Tuesday, 8 June 2021 at 00:58:12 UTC, Jack wrote:

the dll which I was just build with dub command? how I have a 
version mismatch if they're the very same file?


Electron embeds node and does not use whatever you have on your 
system. So if there’s a mismatch between the embedded version 
and the one you linked against, you can see the error you’re 
seeing.


I don't use Windows often, my bad for incompatibilities there.

I updated Electron, node and DMD. After running

console.log (process.versions)

in Electron I get:

{
  node: '14.16.0',
  v8: '9.1.269.28-electron.0',
  uv: '1.40.0',
  zlib: '1.2.11',
  brotli: '1.0.9',
  ares: '1.16.1',
  modules: '89',
  nghttp2: '1.41.0',
  napi: '7',
  llhttp: '2.1.3',
  openssl: '1.1.1',
  icu: '68.1',
  unicode: '13.0',
  electron: '13.1.1',
  chrome: '91.0.4472.77'
}

So I changed node.lib in node_dlang with the version from 
https://nodejs.org/download/release/v14.16.0/win-x64/


However, I get an Error: A dynamic link library (DLL) 
initialization routine failed.


So I'll have to check what's happening now. It might be some API 
change in Node-API or something spookier.

These days I'm quite busy but will do my best to fix this.


Re: how to enable safeD ? dmd.conf ? dmd switch ?

2021-06-07 Thread someone via Digitalmars-d-learn

On Tuesday, 8 June 2021 at 04:24:38 UTC, H. S. Teoh wrote:


Annotate your functions with @safe.


https://dlang.org/spec/function.html#function-safety
Best Practices: Mark as many functions @safe as practical.

ACK



Re: how to enable safeD ? dmd.conf ? dmd switch ?

2021-06-07 Thread H. S. Teoh via Digitalmars-d-learn
On Tue, Jun 08, 2021 at 02:47:18AM +, someone via Digitalmars-d-learn wrote:
> https://dlang.org/articles/safed.html
> https://dlang.org/dmd-linux.html#switches
> http://ddili.org/ders/d.en/functions_more.html
> 
> Neither man dmd nor man dmd.conf appear to have a related/switch
> setting.
> 
> Does it means safeD is achieved by placing @safe attributes all over
> the place ? Or is it achieved by setting some global switch elsewhere
> ? Am I missing something ?

Annotate your functions with @safe.


T

-- 
Those who don't understand D are condemned to reinvent it, poorly. -- Daniel N


Re: how to enable safeD ? dmd.conf ? dmd switch ?

2021-06-07 Thread someone via Digitalmars-d-learn

On Tuesday, 8 June 2021 at 03:54:47 UTC, Jack wrote:


better read carefully how the attribute work


Good advice. I think I am going too fast. Thank you :)


Re: how to enable safeD ? dmd.conf ? dmd switch ?

2021-06-07 Thread Jack via Digitalmars-d-learn

On Tuesday, 8 June 2021 at 03:32:31 UTC, someone wrote:

On Tuesday, 8 June 2021 at 02:59:28 UTC, rikki cattermole wrote:

SafeD is an old name given to the attributes @safe @trusted 
@system.


I have the Alexandrescu's book on hand so that explains it.

There is no switch nor any special behavior now that it has 
long been added to mainline D.


So DMD now enforces it by default ? Will it complain if I make 
something out of the ordinary then ?


better read carefully how the attribute work, if you need 
aditional switches or anything,
for example, if you want to use return scope parameter and make 
the compiler give a compiler error if you set this parameter to a 
variable outside the function's scope, you have to use -dip25 
-dip1000 switches


Re: how to enable safeD ? dmd.conf ? dmd switch ?

2021-06-07 Thread someone via Digitalmars-d-learn

On Tuesday, 8 June 2021 at 02:59:28 UTC, rikki cattermole wrote:

SafeD is an old name given to the attributes @safe @trusted 
@system.


I have the Alexandrescu's book on hand so that explains it.

There is no switch nor any special behavior now that it has 
long been added to mainline D.


So DMD now enforces it by default ? Will it complain if I make 
something out of the ordinary then ?


Re: how do i fix this node_dlang error?

2021-06-07 Thread Mike Parker via Digitalmars-d-learn

On Tuesday, 8 June 2021 at 00:58:12 UTC, Jack wrote:

the dll which I was just build with dub command? how I have a 
version mismatch if they're the very same file?


Electron embeds node and does not use whatever you have on your 
system. So if there’s a mismatch between the embedded version and 
the one you linked against, you can see the error you’re seeing.


Re: how to enable safeD ? dmd.conf ? dmd switch ?

2021-06-07 Thread rikki cattermole via Digitalmars-d-learn



On 08/06/2021 2:47 PM, someone wrote:

https://dlang.org/articles/safed.html
https://dlang.org/dmd-linux.html#switches
http://ddili.org/ders/d.en/functions_more.html

Neither man dmd nor man dmd.conf appear to have a related/switch setting.

Does it means safeD is achieved by placing @safe attributes all over the 
place ? Or is it achieved by setting some global switch elsewhere ? Am I 
missing something ?


SafeD is an old name given to the attributes @safe @trusted @system.

There is no switch nor any special behavior now that it has long been 
added to mainline D.


how to enable safeD ? dmd.conf ? dmd switch ?

2021-06-07 Thread someone via Digitalmars-d-learn

https://dlang.org/articles/safed.html
https://dlang.org/dmd-linux.html#switches
http://ddili.org/ders/d.en/functions_more.html

Neither man dmd nor man dmd.conf appear to have a related/switch 
setting.


Does it means safeD is achieved by placing @safe attributes all 
over the place ? Or is it achieved by setting some global switch 
elsewhere ? Am I missing something ?


Re: best approach to code hierarchical classes ?

2021-06-07 Thread someone via Digitalmars-d-learn

On Tuesday, 8 June 2021 at 02:05:27 UTC, Paul Backus wrote:

Your module and class are both named `classComputers`, with an 
`s` at the end. You should change one of the to have a 
different name so that there's no ambiguity.


dmd output:

./dm.d(49): Error: undefined identifier `classComputer` in module 
`dmclassescomputers`, did you mean class `classComputers`?
./dm.d(50): Error: undefined identifier `classComputer` in module 
`dmclassescomputers`, did you mean class `classComputers`?
./dm.d(51): Error: undefined identifier `classComputer` in module 
`dmclassescomputers`, did you mean class `classComputers`?
./dm.d(53): Error: no property `outer` for type 
`dmclassescomputer.classComputer`


file [dm.d] as following:

```d
import dmclassescomputers = dmclassescomputers;
///import dmclassescomputer = dmclassescomputer;

import std.string;
import std.stdio;

void main (

   ) {

   auto lobjComputers = new 
dmclassescomputers.classComputers(r"lab"c);
   lobjComputers ~= lobjComputers.new 
dmclassescomputers.classComputer(r"dell"c); /// <- line 49
   lobjComputers ~= lobjComputers.new 
dmclassescomputers.classComputer(r"ibm"c);
   lobjComputers ~= lobjComputers.new 
dmclassescomputers.classComputer(r"apple"c);

   lobjComputers[1].name = r"lenovo"c;

   foreach(lobjComputer; lobjComputers) { writeln(r"["c ~ 
lobjComputer.outer.network ~ r" network has "c ~ 
lobjComputer.name ~ r"]"c); }


}
```

file [dmclassescomputers.d] as following:

```d
module dmclassescomputers;

import std.string;

class classComputers {

   classComputers lhs;
   classComputers rhs;

   int opApply(int delegate(dmclassescomputer.classComputer) dg) 
{ /// boilerplate code to handle the class's default collection


  int lintResult = 0; /// must find a better name

		foreach (lobjComputer; computers) { /// looping over the 
computers starting in current node


			lintResult = dg(lobjComputer); /// passing single object to 
the loop body


if (lintResult != 0) { break; }

}

  if (lintResult != 0 && lhs ! is null) { lintResult = 
lhs.opApply(dg); } /// recursing child nodes
  if (lintResult != 0 && rhs ! is null) { lintResult = 
rhs.opApply(dg); } /// recursing child nodes


  return lintResult;

   }

   public dmclassescomputer.classComputer[] computers; alias 
computers this; /// ie: default property


   private string pstrNetwork;

   final @property string network() { return this.pstrNetwork; }
   final @property void network(in string lstrNetwork) { 
this.pstrNetwork = lstrNetwork.strip(); }


   this(
  string lstrNetwork
  ) {

  this.network = lstrNetwork;

   }

   import dmclassescomputer;

}
```

file [dmclassescomputer.d] as following:

```d
module dmclassescomputer;

import std.string;

class classComputer {

   private string pstrName;

   final @property string name() { return this.pstrName; }
   final @property void name(in string lstrName) { this.pstrName 
= lstrName.strip(); }


   this(
  string lstrName
  ) {

  this.name = lstrName;

   }

}
```



Re: best approach to code hierarchical classes ?

2021-06-07 Thread Paul Backus via Digitalmars-d-learn

On Tuesday, 8 June 2021 at 01:17:05 UTC, someone wrote:

On Tuesday, 8 June 2021 at 00:54:41 UTC, someone wrote:

Are there alternatives to nested classes for such scenarios ?


Self-reply: I created two files for classComputers and 
classComputer and I replaced the nested-classComputer code 
within classComputers with:


import classComputers;

But it won't go:

Error: undefined identifier `classComputer` in module 
`classComputers`, did you mean class `classComputers`?


Your module and class are both named `classComputers`, with an 
`s` at the end. You should change one of the to have a different 
name so that there's no ambiguity.


Re: best approach to code hierarchical classes ?

2021-06-07 Thread someone via Digitalmars-d-learn

On Tuesday, 8 June 2021 at 00:54:41 UTC, someone wrote:

Are there alternatives to nested classes for such scenarios ?


Self-reply: I created two files for classComputers and 
classComputer and I replaced the nested-classComputer code within 
classComputers with:


import classComputers;

But it won't go:

Error: undefined identifier `classComputer` in module 
`classComputers`, did you mean class `classComputers`?


Re: how do i fix this node_dlang error?

2021-06-07 Thread Jack via Digitalmars-d-learn

On Tuesday, 8 June 2021 at 00:00:50 UTC, Mike Parker wrote:

On Monday, 7 June 2021 at 22:24:03 UTC, Jack wrote:


I think the entry point function is ```void atStart(napi_env 
env) {}``` so there's no DllMain...


DLLMain is not strictly required. It's called by the system 
loader when the DLL is first loaded into the process. The 
MainFunction for node is just a means for having a 
cross-platform approach to initialization: node will load your 
shared library then call the MainFunction. So you can 
initialize the runtime in DLLMain or in your atStart function. 
Shouldn't matter.


i see

Your problem may be unrelated to D, though. It appears to be a 
common error when developing native code for Electron. Googling 
for "electron {paste error message here}" or for "electron dll 
initialization" turns up several results.


I'm googling this has been hours, none of the solutions worked 
for me, including rebuild the native module with electron-rebuild 
package


Some cursory reading shows that the issue may be a version 
mismatch between the version of node the dll was linked with 
and that used by Electron.


the dll which I was just build with dub command? how I have a 
version mismatch if they're the very same file?


best approach to code hierarchical classes ?

2021-06-07 Thread someone via Digitalmars-d-learn
Consider the following code in what I used nested-classes for the 
first time within D:


```d
import std.string;
import std.stdio;

class classComputers {

   classComputers lhs;
   classComputers rhs;

   int opApply(int delegate(classComputer) dg) { /// boilerplate 
code to handle the class's default collection


  int lintResult = 0; /// must find a better name

		foreach (lobjComputer; computers) { /// looping over the 
computers starting in current node


			lintResult = dg(lobjComputer); /// passing single object to 
the loop body


if (lintResult != 0) { break; }

}

  if (lintResult != 0 && lhs ! is null) { lintResult = 
lhs.opApply(dg); } /// recursing child nodes
  if (lintResult != 0 && rhs ! is null) { lintResult = 
rhs.opApply(dg); } /// recursing child nodes


  return lintResult;

   }

   public classComputer[] computers; alias computers this; /// 
ie: default property


   private string pstrNetwork;

   final @property string network() { return this.pstrNetwork; }
   final @property void network(in string lstrNetwork) { 
this.pstrNetwork = lstrNetwork.strip(); }


   this(
  string lstrNetwork
  ) {

  this.network = lstrNetwork;

   }

   class classComputer {

  private string pstrName;

  final @property string name() { return this.pstrName; }
  final @property void name(in string lstrName) { 
this.pstrName = lstrName.strip(); }


  this(
 string lstrName
 ) {

 this.name = lstrName;

  }

   }

}

void main (

   ) {

   classComputers lobjComputers = new classComputers(r"lab"c); 
/// ie: the lab network


   lobjComputers ~= lobjComputers.new classComputer(r"dell"c);
   lobjComputers ~= lobjComputers.new classComputer(r"ibm"c);
   lobjComputers ~= lobjComputers.new classComputer(r"apple"c);
   lobjComputers[1].name = r"lenovo"c;

   foreach(lobjComputer; lobjComputers) { writeln(r"["c ~ 
lobjComputer.outer.network ~ r" network has "c ~ 
lobjComputer.name ~ r"]"c); }


}
```

As expected, the above code produces:

[lab network has dell]
[lab network has lenovo]
[lab network has apple]

Now think of wider hierarchical structures, let's say 6~9 to 
begin with or greater; eg: computers.computer.devices.firmware... 
and so on.


Coding such scenario with nested classes will produce a huge code 
base within the same module. My first approach, obviously, was to 
put each class in its own module and in main() I instantiate the 
primary one and the child objects/classes are instantiated either 
directly in main or say, by each class' own add()/remove() 
methods. This works as expected. However, I can't manage to 
traverse the tree from main() like something.parent.somethingelse 
(like I can do with outer for the nested classes example I gave 
you) nor I am able to access parent members within the classes 
own bodies.


Are there alternatives to nested classes for such scenarios ?


Re: regarding what seems (to me) unnecessary casts on integer expressions

2021-06-07 Thread someone via Digitalmars-d-learn

On Monday, 7 June 2021 at 14:12:14 UTC, H. S. Teoh wrote:
Here's my solution to D's short integer cast-madness: abstract 
it away in an infectious wrapper type.


Your workaround seems interesting. Will look further into the 
concept in the coming days. I am learning the D-ways and there's 
so much to gather that it will take me some time to get started 
-I mean, evidently D has many strong-points as being highlighted 
in the D gems section in the tutorial, but, what really comes to 
mind after a week-or-so coding with it, is its flexibility: there 
are a lot of ways to do x stuff.


Re: how do i fix this node_dlang error?

2021-06-07 Thread Mike Parker via Digitalmars-d-learn

On Monday, 7 June 2021 at 22:24:03 UTC, Jack wrote:


I think the entry point function is ```void atStart(napi_env 
env) {}``` so there's no DllMain...


DLLMain is not strictly required. It's called by the system 
loader when the DLL is first loaded into the process. The 
MainFunction for node is just a means for having a cross-platform 
approach to initialization: node will load your shared library 
then call the MainFunction. So you can initialize the runtime in 
DLLMain or in your atStart function. Shouldn't matter.


Your problem may be unrelated to D, though. It appears to be a 
common error when developing native code for Electron. Googling 
for "electron {paste error message here}" or for "electron dll 
initialization" turns up several results.


Some cursory reading shows that the issue may be a version 
mismatch between the version of node the dll was linked with and 
that used by Electron.





Asking for D solution

2021-06-07 Thread Alexander Tretyak via Digitalmars-d-learn

Hello.

I'm looking for someone who has plenty of experience in the D 
programming language.


I have some task, which I hope will be added to Rosetta Code.
This task is based on pqmarkup, and is called pqmarkup-lite.

The specialty of this task is formatting characters of pqmarkup 
{paired quotation marks themselves, and Н, Р, С, Т, О, which 
allow both Latin and Cyrillic writing} go beyond ASCII. This 
significantly complicates working with input UTF-8 string 
directly (especially in languages [like C++] which have no 
built-in UTF-8 support).


I've already translated the [original implementation in 
Python](https://github.com/pqmarkup/pqmarkup-lite/blob/master/pqmarkup_lite.py) of this task into C++ (there are two implementations: [using u16string](https://github.com/pqmarkup/pqmarkup-lite/blob/master/cpp/utf16/utf16.cpp) and [using UTF-8 string](https://github.com/pqmarkup/pqmarkup-lite/blob/master/cpp/utf8/utf8.cpp)).
Also there is a [Nim 
translation](https://github.com/pqmarkup/pqmarkup-lite/blob/master/nim/pqmarkup_lite1.nim) by Luc Secouard.


And now I'm looking for people who can translate this task into 
other languages (D, Rust, Swift, etc.), and then I will compare 
all implementations by code readability and by performance.


So, can someone provide the most idiomatic D solution to this 
task?

I can pay for that (not very much though).


Re: how do i fix this node_dlang error?

2021-06-07 Thread Jack via Digitalmars-d-learn

On Monday, 7 June 2021 at 20:37:19 UTC, MoonlightSentinel wrote:

On Monday, 7 June 2021 at 19:03:44 UTC, Jack wrote:

actually i didnt so I just added:

```d
shared static this()
{
Runtime.initialize();
}

shared static ~this()
{
Runtime.terminate();
}
```

but it didn't change anything


That doesn't work because `Runtime.initialize()` is responsible 
to execute the module ctors. You could try 
`pragma(crt_constructor)`[1] instead.


[1] https://dlang.org/spec/pragma.html#crtctor


I see, thanks for pointing out. I think the entry point function 
is the one set by MainFunction in the exportToJs template so I 
guess there's no need to this or DllMain.  the 
[example](https://github.com/NotSpooky/node_dlang/blob/master/examples/type_examples/source/example.d) from the node_dlang have no other entry function than the defined by MainFunction template


Re: how do i fix this node_dlang error?

2021-06-07 Thread Jack via Digitalmars-d-learn

On Monday, 7 June 2021 at 20:13:03 UTC, frame wrote:

On Monday, 7 June 2021 at 02:33:38 UTC, Jack wrote:


What am I missing?


If this runs under Windows, there is no dlopen(), maybe a 
wrapper to LoadLibrary() but this will need to call a DllMain() 
in the DLL if I am not wrong. Is there a DllMain?


I think the entry point function is ```void atStart(napi_env env) 
{}``` so there's no DllMain...


Re: how do i fix this node_dlang error?

2021-06-07 Thread Jack via Digitalmars-d-learn

On Monday, 7 June 2021 at 20:13:03 UTC, frame wrote:

On Monday, 7 June 2021 at 02:33:38 UTC, Jack wrote:


What am I missing?


If this runs under Windows, there is no dlopen(), maybe a 
wrapper to LoadLibrary() but this will need to call a DllMain() 
in the DLL if I am not wrong. Is there a DllMain?


I just noticied that's supposed to have a DllMain even tho the 
[code 
example](https://github.com/NotSpooky/node_dlang/blob/master/examples/type_examples/source/example.d) from node_dlang doesn't have one and it was working(?) I added one in my code but it give same error. I added like this:


```d
module foo;

import std.stdio : stderr;
import node_dlang;
import core.sys.windows.windows;
import core.sys.windows.dll;

mixin SimpleDllMain;

extern(C):

void atStart(napi_env env)
{
import std.stdio;
writeln (`Loaded D native library!`);
}

int ultimate()
{
return 43;
}

mixin exportToJs! (ultimate, MainFunction!atStart);
```


Re: how do i fix this node_dlang error?

2021-06-07 Thread MoonlightSentinel via Digitalmars-d-learn

On Monday, 7 June 2021 at 19:03:44 UTC, Jack wrote:

actually i didnt so I just added:

```d
shared static this()
{
Runtime.initialize();
}

shared static ~this()
{
Runtime.terminate();
}
```

but it didn't change anything


That doesn't work because `Runtime.initialize()` is responsible 
to execute the module ctors. You could try 
`pragma(crt_constructor)`[1] instead.


[1] https://dlang.org/spec/pragma.html#crtctor



Re: how do i fix this node_dlang error?

2021-06-07 Thread frame via Digitalmars-d-learn

On Monday, 7 June 2021 at 02:33:38 UTC, Jack wrote:


What am I missing?


If this runs under Windows, there is no dlopen(), maybe a wrapper 
to LoadLibrary() but this will need to call a DllMain() in the 
DLL if I am not wrong. Is there a DllMain?




Re: regarding what seems (to me) unnecessary casts on integer expressions

2021-06-07 Thread someone via Digitalmars-d-learn

On Monday, 7 June 2021 at 12:53:29 UTC, russhy wrote:
Everything is public by default, and you can't overload and 
derive from structs so final has no effect. There less visual 
noise.


Gotcha !

I started using final (and the like) on classes a couple of days 
ago and I suppose I unconsciously dragged them to the structures, 
which, as you say, they can't be derived so it is non-sense.


Also: trying to suit my coding style to D code -a work in 
progress.


Re: is it possible to have a default property for any given class ?

2021-06-07 Thread someone via Digitalmars-d-learn

On Monday, 7 June 2021 at 16:10:08 UTC, Jack wrote:
I think you meant to implement ranges? you can implement in the 
way you wanted: ```foreach(lobjComputer; lobjComputers)``` ...


Thanks for your reply !

I am aware that ranges are one of D's gems, I did take an 
overview of them last night or the night before but did not get 
immersed in them too much. Will look at them.


The first thing that came to mind was to implement them as a 
collection as I always did on other languages, but I suppose 
ranges could be an alternative.


... but the recommend approach is to get this array through the 
array index operator


When you say so, you mean you prefer arrays over ranges or, that 
you disagree with the recommended approach for whatever reasons ? 
Could you elaborate ?




Re: is it possible to have a default property for any given class ?

2021-06-07 Thread someone via Digitalmars-d-learn

On Monday, 7 June 2021 at 15:55:36 UTC, H. S. Teoh wrote:

Thanks for your reply. It was very illustrating.

It's very simple. Whenever some non-array object appears on the 
right side of a foreach() statement, the compiler looks for a 
method on the object called .opApply. If it exists, the loop 
body is passed to that method as a delegate.  IOW:


```d
// This:
foreach (item; myCollection) {
/* loop body here */
}

// Gets translated to this:
myCollection.opApply((item) { /* loop body here */ });
```

Given that, your .opApply method doesn't really do what you 
want. It should instead be written like this:


// N.B.: dg is NOT the type of the collection, but the
// individual item you want to iterate over.

```d
int opApply(int delegate(classComputer) dg)
{
// Loop over the computers in the current node first
foreach (computer; computers) {
// Pass single item to loop body.
auto ret = dg(computer);

// N.B.: do NOT assume a non-zero return value
// will always be 1; it may not be if your loop
// body contains `break` or `continue`.
if (ret) return ret;
}

// Now recurse child nodes
if (lhs) {
auto ret = lhs.opApply(dg);
if (ret) return ret; // again, don't assume it will be 1
}
if (rhs) {
auto ret = rhs.opApply(dg);
if (ret) return ret; // again, don't assume it will be 1
}
return 0;
}
```


For the sake of clarity (to me) and, given I never liked code 
with multiple returns, I rewrote your code (providing I am not 
introducing flaws) as following:


```d
class classComputers {

   classComputers lhs;
   classComputers rhs;

   int opApply(int delegate(classComputer) dg) { /// boilerplate 
code to handle the class's default collection


  int lintResult = 0;

		foreach (lobjComputer; computers) { /// looping over the 
computers starting in current node


			lintResult = dg(lobjComputer); /// passing single object to 
the loop body


if (lintResult != 0) { break; }

}

  if (lintResult != 0 && lhs) { lintResult = lhs.opApply(dg); 
} /// recursing child nodes
  if (lintResult != 0 && rhs) { lintResult = rhs.opApply(dg); 
} /// recursing child nodes


  return lintResult;

   }

   public classComputer[] computers; alias computers this; /// 
ie: default property


}
```

It seems it works perfectly well.

Also, your:

```d
alias computers this;
```

was very clever, indeed :)


Re: how do i fix this node_dlang error?

2021-06-07 Thread Jack via Digitalmars-d-learn

On Monday, 7 June 2021 at 17:22:48 UTC, MoonlightSentinel wrote:

On Monday, 7 June 2021 at 02:33:38 UTC, Jack wrote:

What am I missing?


Does your code / `node_dlang` initialize Druntime before 
calling `writeln`?


actually i didnt so I just added:

```d
shared static this()
{
Runtime.initialize();
}

shared static ~this()
{
Runtime.terminate();
}
```

but it didn't change anything


Try replacing the `writeln` with `puts` (from 
`core.stdc.stdio`) which doesn't require an initialized runtime.


I've tried just removed the writeln() call it didn't change 
anything either


Re: how do i fix this node_dlang error?

2021-06-07 Thread MoonlightSentinel via Digitalmars-d-learn

On Monday, 7 June 2021 at 02:33:38 UTC, Jack wrote:

What am I missing?


Does your code / `node_dlang` initialize Druntime before calling 
`writeln`?
Try replacing the `writeln` with `puts` (from `core.stdc.stdio`) 
which doesn't require an initialized runtime.


Re: is it possible to have a default property for any given class ?

2021-06-07 Thread Jack via Digitalmars-d-learn

On Monday, 7 June 2021 at 15:26:27 UTC, someone wrote:

Consider the following code:

```d
class classComputer {

   private string pstrName;

   final @property string name() { return this.pstrName; }
   final @property void name(in string lstrName) { 
this.pstrName = lstrName; }


   this(
  string lstrComputerName
  ) {

  this.pstrName = lstrComputerName;

   }

}

class classComputers {

   classComputers lhs;
   classComputers rhs;

   int opApply(int delegate(classComputers) dg) { /// 
boilerplate code to handle the class's default collection


  if (lhs && lhs.opApply(dg)) return 1;
  if (dg(this)) return 1;
  if (rhs && rhs.opApply(dg)) return 1;
  return 0;

   }

   public classComputer[] computers; /// how can I tag this as 
the default property ?


}

void main (

   ) {

   classComputers lobjComputers = new classComputers;
   lobjComputers.computers ~= new classComputer("dell");
   lobjComputers.computers ~= new classComputer("ibm");
   lobjComputers.computers ~= new classComputer("apple");
   lobjComputers.computers[1].name = r"lenovo";

   foreach(lobjComputer; lobjComputers.computers) { 
writeln(lobjComputer.name); }


   ///foreach(lobjComputer; lobjComputers) { 
writeln(lobjComputer.name); } /// with default property (if 
possible)


I think you meant to implement ranges? you can implement in the 
way you wanted: ```foreach(lobjComputer; lobjComputers)``` but 
the recommend approach is to get this array through the array 
index operator. It would go like this:


```d
class classComputer
{

   private string pstrName;

   final string name() { return this.pstrName; }
   final void name(in string lstrName) { this.pstrName = 
lstrName; }


   this(string lstrComputerName = null) {

  this.pstrName = lstrComputerName;

   }

   classComputer lhs;
   classComputer rhs;

   int opApply(int delegate(classComputer) dg) { /// boilerplate 
code to handle the class's default collection


  if (lhs && lhs.opApply(dg)) return 1;
  if (dg(this)) return 1;
  if (rhs && rhs.opApply(dg)) return 1;
  return 0;

   }

   public classComputer[] computers; /// how can I tag this as 
the default property ?


   auto opIndex() nothrow
   {
  return Range(computers);
   }

   protected static struct Range
   {
  private classComputer[] a;
  auto front() { return a[0]; }
  auto back() { return a[$ - 1]; }
  void popFront() { a = a[1 .. $]; }
  bool empty() { return a.length == 0; }

 size_t opDollar() { return a.length; }

 auto opSlice(size_t start, size_t end)
 {
 return a[start .. end];
 }
}
}

void main ()
{

   import std.stdio : writeln;

   auto lobjComputers = new classComputer;
   lobjComputers.computers ~= new classComputer("dell");
   lobjComputers.computers ~= new classComputer("ibm");
   lobjComputers.computers ~= new classComputer("apple");
   lobjComputers.computers[1].name = r"lenovo";

   foreach(lobjComputer; lobjComputers[]) { 
writeln(lobjComputer.name); }


   ///foreach(lobjComputer; lobjComputers) { 
writeln(lobjComputer.name); } /// with default property (if 
possible)


}
```



}
```







Re: is it possible to have a default property for any given class ?

2021-06-07 Thread H. S. Teoh via Digitalmars-d-learn
On Mon, Jun 07, 2021 at 03:26:27PM +, someone via Digitalmars-d-learn wrote:
> Consider the following code:
> 
> ```d
> class classComputer {
[...]
> }
> 
> class classComputers {
> 
>classComputers lhs;
>classComputers rhs;
> 
>int opApply(int delegate(classComputers) dg) { /// boilerplate code to
> handle the class's default collection
> 
>   if (lhs && lhs.opApply(dg)) return 1;
>   if (dg(this)) return 1;
>   if (rhs && rhs.opApply(dg)) return 1;
>   return 0;
> 
>}
> 
>public classComputer[] computers; /// how can I tag this as the default
> property ?

alias computers this;

> 
> }
> 
> void main (
> 
>) {
> 
>classComputers lobjComputers = new classComputers;
>lobjComputers.computers ~= new classComputer("dell");
>lobjComputers.computers ~= new classComputer("ibm");
>lobjComputers.computers ~= new classComputer("apple");
>lobjComputers.computers[1].name = r"lenovo";
> 
>foreach(lobjComputer; lobjComputers.computers) {
> writeln(lobjComputer.name); }
> 
>///foreach(lobjComputer; lobjComputers) { writeln(lobjComputer.name); }
> /// with default property (if possible)
> 
> }
> ```
> 
> The above code works correctly, however, avoiding the redundancy of
> lobjComputers.computers will be a plus.
> 
> Also tell me if the collection is implemented the right way, it is my
> first code using the opApply() delegate which I don't deeply
> understand for the time being.

It's very simple. Whenever some non-array object appears on the right
side of a foreach() statement, the compiler looks for a method on the
object called .opApply. If it exists, the loop body is passed to that
method as a delegate.  IOW:

// This:
foreach (item; myCollection) {
/* loop body here */
}

// Gets translated to this:
myCollection.opApply((item) { /* loop body here */ });


Given that, your .opApply method doesn't really do what you want. It
should instead be written like this:

// N.B.: dg is NOT the type of the collection, but the
// individual item you want to iterate over.
int opApply(int delegate(classComputer) dg)
{
// Loop over the computers in the current node first
foreach (computer; computers) {
// Pass single item to loop body.
auto ret = dg(computer);

// N.B.: do NOT assume a non-zero return value
// will always be 1; it may not be if your loop
// body contains `break` or `continue`.
if (ret) return ret;
}

// Now recurse child nodes
if (lhs) {
auto ret = lhs.opApply(dg);
if (ret) return ret; // again, don't assume it will be 1
}
if (rhs) {
auto ret = rhs.opApply(dg);
if (ret) return ret; // again, don't assume it will be 1
}
return 0;
}


T

-- 
Which is worse: ignorance or apathy? Who knows? Who cares? -- Erich Schubert


is it possible to have a default property for any given class ?

2021-06-07 Thread someone via Digitalmars-d-learn

Consider the following code:

```d
class classComputer {

   private string pstrName;

   final @property string name() { return this.pstrName; }
   final @property void name(in string lstrName) { this.pstrName 
= lstrName; }


   this(
  string lstrComputerName
  ) {

  this.pstrName = lstrComputerName;

   }

}

class classComputers {

   classComputers lhs;
   classComputers rhs;

   int opApply(int delegate(classComputers) dg) { /// boilerplate 
code to handle the class's default collection


  if (lhs && lhs.opApply(dg)) return 1;
  if (dg(this)) return 1;
  if (rhs && rhs.opApply(dg)) return 1;
  return 0;

   }

   public classComputer[] computers; /// how can I tag this as 
the default property ?


}

void main (

   ) {

   classComputers lobjComputers = new classComputers;
   lobjComputers.computers ~= new classComputer("dell");
   lobjComputers.computers ~= new classComputer("ibm");
   lobjComputers.computers ~= new classComputer("apple");
   lobjComputers.computers[1].name = r"lenovo";

   foreach(lobjComputer; lobjComputers.computers) { 
writeln(lobjComputer.name); }


   ///foreach(lobjComputer; lobjComputers) { 
writeln(lobjComputer.name); } /// with default property (if 
possible)


}
```

The above code works correctly, however, avoiding the redundancy 
of lobjComputers.computers will be a plus.


Also tell me if the collection is implemented the right way, it 
is my first code using the opApply() delegate which I don't 
deeply understand for the time being.


Re: Any 3D Game or Engine with examples/demos which just work (compile&run) out of the box on linux ?

2021-06-07 Thread evilrat via Digitalmars-d-learn

On Monday, 7 June 2021 at 14:02:14 UTC, Prokop Hapala wrote:


Basically I'm desperate do find anything which encapsulates 
OpenGL calls into some nice D-lang classes to learn from it. I 
don't really want to use Dagon, nor Godot. What I want is to 
use it as learning resources fro learning graphics programming 
in Dlang.


Rewriting my graphics engine from C++ to Dlang is huge barrier 
for me, sice I don't know Dlang enough. I want to see some nice 
Tricks and convenience of Dlang features applied to graphics 
programming.


Ability to compile without much hessel is minimal requirement 
for me.
The only thing which I was able to compile up to no was dmech, 
which is nice for physics but very old OpenGL


Ok then, no dagon won't help you that much IMHO. There is 
definitely a lot of projects on github with some basic 
engine-like functionality which encapsulates VBO, shaders, and 
stuff. Nothing specific that comes to mind but they do exist.(uh, 
maybe serpent engine?)


They are however mostly quickly hacked up student's homework 
rather than designed solid projects, so I again suggest you to 
try godot for anything serious. It's all shaders after all, doing 
VBO and render pipeline setups is not that much fun.


For learning graphics programming however D is ok, but you will 
definitely almost on your own, still github is your friend, look 
for existing projects on github (for example dash) on how it can 
be done.


As for actual language features that might help - that will be 
reflection and meta-programming.
With them you can generate everything from the code - VBO's, 
render passes, etc...

Make declarative DSL from that to rule them all!
It's fancy and all, but it is only slightly better than C++ (esp. 
since it has shitty OpenGL/vulkan loaders and clumsy build tools) 
and there's nothing new compared to it.


And final option would be to make bindings for your existing C++ 
code, either manually or with tools (like my own generator)

https://github.com/Superbelko/ohmygentool



Re: Any 3D Game or Engine with examples/demos which just work (compile&run) out of the box on linux ?

2021-06-07 Thread drug via Digitalmars-d-learn

07.06.2021 17:02, Prokop Hapala пишет:
Basically I'm desperate do find anything which encapsulates OpenGL calls 
into some nice D-lang classes


Did you try gfm? specifically its 7th version - 
[gfm7](https://github.com/drug007/gfm7)?
It has nice 
[classes](https://github.com/drug007/gfm7/tree/master/opengl/gfm/opengl) 
to wrap OpenGL but the online documentation is currently unavailable. 
But the library itself is pretty nice documented.


Ask me if you will help with it.


Re: regarding what seems (to me) unnecessary casts on integer expressions

2021-06-07 Thread H. S. Teoh via Digitalmars-d-learn
On Sat, Jun 05, 2021 at 01:46:45AM +, someone via Digitalmars-d-learn wrote:
[...]
> As I am writing code today I am encountering a lot of these situations.
> 
> cast(ushort)(this.pintBottom1 - 1)
> 
> My first walkaround for this was intuitive:
> 
> this.pintBottom1 - cast(ushort) 1 /// I didn't know if eg: 1S was
> possible which should have been the proper way to handle it
> 
> ... since pintBottom was already defined as ushort, but it didn't work
> also, so I ended with cast(ushort)(this.pintBottom1 - 1). I don't
> understand how to write typed code in D then. What's the point of
> declaring, for instance ushort's if then nothing will treat them as
> ushort's and I have to manually cast() everything to ushort() all the
> time ?

Here's my solution to D's short integer cast-madness: abstract it away
in an infectious wrapper type.  Save the following code into a file
called nopromote.d, import it, and whenever you have an expression
involving shorts, bytes, etc., that you don't want to write a cast for,
just insert .np (for "no-promote") somewhere in the expression (see
unittests below for concrete examples).


/**
 * Truncating wrapper around built-in narrow ints to work around stupid
 * casts.
 */
module nopromote;

enum isNarrowInt(T) = is(T : int) || is(T : uint);

/**
 * A wrapper around a built-in narrow int that truncates the result of
 * arithmetic operations to the narrow type, overriding built-in int promotion
 * rules.
 */
struct Np(T)
if (isNarrowInt!T)
{
T impl;
alias impl this;

/**
 * Truncating binary operator.
 */
Np opBinary(string op, U)(U u)
if (is(typeof((T x, U y) => mixin("x " ~ op ~ " y"
{
return Np(cast(T) mixin("this.impl " ~ op ~ " u"));
}

/**
 * Truncating unary operator.
 */
Np opUnary(string op)()
if (is(typeof((T x) => mixin(op ~ "cast(int) x"
{
return Np(cast(T) mixin(op ~ " cast(int) this.impl"));
}

/**
 * Infectiousness: any expression containing Np should automatically use Np
 * operator semantics.
 */
Np opBinaryRight(string op, U)(U u)
if (is(typeof((T x, U y) => mixin("x " ~ op ~ " y"
{
return Np(cast(T) mixin("u " ~ op ~ " this.impl"));
}
}

/**
 * Returns: A lightweight wrapped type that overrides built-in arithmetic
 * operators to always truncate to the given type without promoting to int or
 * uint.
 */
auto np(T)(T t)
if (isNarrowInt!T)
{
return Np!T(t);
}

// Test binary ops
@safe unittest
{
ubyte x = 1;
ubyte y = 2;
auto z = x.np + y;
static assert(is(typeof(z) : ubyte));
assert(z == 3);

byte zz = x.np + y;
assert(zz == 3);

x = 255;
z = x.np + y;
assert(z == 1);
}

@safe unittest
{
byte x = 123;
byte y = 5;
auto z = x.np + y;
static assert(is(typeof(z) : byte));
assert(z == byte.min);

byte zz = x.np + y;
assert(zz == byte.min);
}

@safe unittest
{
import std.random;
short x = cast(short) uniform(0, 10);
short y = 10;
auto z = x.np + y;
static assert(is(typeof(z) : short));
assert(z == x + 10);

short s = x.np + y;
assert(s == x + 10);
}

// Test unary ops
@safe unittest
{
byte b = 10;
auto c = -b.np;
static assert(is(typeof(c) : byte));
assert(c == -10);

ubyte ub = 16;
auto uc = -ub.np;
static assert(is(typeof(uc) : ubyte));
assert(uc == 0xF0);
}

version(unittest)
{
// These tests are put here as actual module functions, to force optimizer
// not to discard calls to these functions, so that we can see the actual
// generated code.
byte byteNegate(byte b) { return -b.np; }
ubyte ubyteNegate(ubyte b) { return -b.np; }

byte byteTest1(int choice, byte a, byte b)
{
if (choice == 1)
return a.np + b;
if (choice == 2)
return a.np / b;
assert(0);
}

short shortAdd(short a, short b) { return a.np + b; }

// Test opBinaryRight
byte byteRightTest(byte a, byte c)
{
auto result = a + c.np;
static assert(is(typeof(result) : byte));
return result;
}

unittest
{
assert(byteRightTest(127, 1) == byte.min);
}

short multiTest1(short x, short y)
{
return short(2) + 2*(x - y.np);
}

unittest
{
// Test wraparound semantics.
assert(multiTest1(32767, 16384) == short.min);
}

short multiTest2(short a, short b)
{
short x = a;
short y = b;
return (2*x + 1) * (y.np/2 - 1);
}

unittest
{
assert(multiTest2(1, 4) == 3);
}
}

// vim:set ai sw=4 ts=4 et:



T

-- 
The two rules of success: 1. Don't tell everything you know. -- YHL


Re: Any 3D Game or Engine with examples/demos which just work (compile&run) out of the box on linux ?

2021-06-07 Thread Prokop Hapala via Digitalmars-d-learn

thanks, evilrat

Anyway I tried dagon in past and I don't see why bother with 
it, better stick with something that can handle industry 
standard formats such as FBX, another issue is shaders fused in 
right in the engine.
As an alternative the only thing probably worth checking is 
godot-d which is native interface for scripting in Godot 
Engine. This engine has its quirks though (my most hated 
"feature" is that it requires you to create script config for 
each your native class).


Basically I'm desperate do find anything which encapsulates 
OpenGL calls into some nice D-lang classes to learn from it. I 
don't really want to use Dagon, nor Godot. What I want is to use 
it as learning resources fro learning graphics programming in 
Dlang.


Rewriting my graphics engine from C++ to Dlang is huge barrier 
for me, sice I don't know Dlang enough. I want to see some nice 
Tricks and convenience of Dlang features applied to graphics 
programming.


Ability to compile without much hessel is minimal requirement for 
me.
The only thing which I was able to compile up to no was dmech, 
which is nice for physics but very old OpenGL


Re: Receiving "pthread_mutexattr_init" during compilation when using FileLogger.

2021-06-07 Thread Mike Parker via Digitalmars-d-learn

On Monday, 7 June 2021 at 11:31:13 UTC, tastyminerals wrote:



It's interesting how there is no information about class 
instantiation at module level anywhere in the docs. Even the 
Ali's book does not explicitly say that you cannot instantiate 
a class this way. Maybe I totally missed it but just doing the 
key search on "scope", "global", "module" in class related 
chapters didn't give me any results.


It's covered by this:

https://dlang.org/spec/declaration.html#global_static_init

The Initializer for a global or static variable must be 
evaluatable at compile time. Runtime initialization is done 
with static constructors.


It obviously could be more explicit. I'll add a note to my todo 
list to make it so.


Re: regarding what seems (to me) unnecessary casts on integer expressions

2021-06-07 Thread russhy via Digitalmars-d-learn
Everything is public by default, and you can't overload and 
derive from structs so final has no effect


there less visual noise:

```D
struct gudtPosition {

   void reset() { pintLeft1 = pintTop1 = pintRight1 = pintBottom1 
= 0; }


   private ushort pintLeft1 = 0;
   private ushort pintTop1 = 0;
   private ushort pintRight1 = 0;
   private ushort pintBottom1 = 0;

   const ushort left1() { return this.pintLeft1; }
   const ushort top1() { return this.pintTop1; }
   const ushort right1() { return this.pintRight1; }
   const ushort bottom1() { return this.pintBottom1; }

   ushort left0() { return this.pintLeft1 = 0 ? 0 : 
cast(ushort)(this.pintLeft1 - 1); }
   ushort top0() { return this.pintTop1 = 0 ? 0 : 
cast(ushort)(this.pintTop1 - 1); }
   ushort right0() { return this.pintRight1 = 0 ? 0 : 
cast(ushort)(this.pintRight1 - 1); }
   ushort bottom0() { return this.pintBottom1 = 0 ? 0 : 
cast(ushort)(this.pintBottom1 - 1); }


   void left1(const ushort lintPosition) { this.pintLeft1 = 
lintPosition; }
   void top1(const ushort lintPosition) { this.pintTop1 = 
lintPosition; }
   void right1(const ushort lintPosition) { this.pintRight1 = 
lintPosition; }
   void bottom1(const ushort lintPosition) { this.pintBottom1 = 
lintPosition; }


   string caption0() { return /// eg: from (24,24) to (48,48)
  r"from ("c ~
  std.format.format(r"%d"c, this.left0) ~
  r","c ~
  std.format.format(r"%d"c, this.top0) ~
  r") to ("c ~
  std.format.format(r"%d"c, this.right0) ~
  r","c ~
  std.format.format(r"%d"c, this.bottom0) ~
  r")"c;
   }

   string caption1() { return /// eg: from (24,24) to (48,48)
  r"from ("c ~
  std.format.format(r"%d"c, this.pintLeft1) ~
  r","c ~
  std.format.format(r"%d"c, this.pintTop1) ~
  r") to ("c ~
  std.format.format(r"%d"c, this.pintRight1) ~
  r","c ~
  std.format.format(r"%d"c, this.pintBottom1) ~
  r")"c;
   }

}
```


Re: Receiving "pthread_mutexattr_init" during compilation when using FileLogger.

2021-06-07 Thread tastyminerals via Digitalmars-d-learn

On Monday, 7 June 2021 at 11:29:44 UTC, tastyminerals wrote:

On Monday, 7 June 2021 at 10:36:23 UTC, Mike Parker wrote:

On Monday, 7 June 2021 at 09:29:08 UTC, tastyminerals wrote:

I getting
```
import/core/sync/mutex.d(87,36): Error: 
`pthread_mutexattr_init` cannot be interpreted at compile 
time, because it has no available source code

```
compile time error. One of those D exceptions which doesn't 
say where it happened in your code so you need to comment out 
the lines that might cause it one by one :D


I found that this was caused by the "FileLogger" which I 
create at the top of the file. But why?


You can't initialize classes at module scope. You can declare 
them, but then they must be initialized in a function or a 
module constructor. Normally for a type `MyClass` in module 
`foo`, you'd see an error like this:


```D
Error: variable `foo.MyClass` is a thread-local class and 
cannot have a static initializer. Use `static this()` to 
initialize instead.

```

I guess CTFE runs before the check that catches this, though, 
and the `FileLogger` constructor ultimately triggers the error 
your seeing.
I see, I only remember that one cannot create associative 
arrays in global scope. This is explicitly written in the 
language reference.



It's interesting how there is no information about class 
instantiation at module level anywhere in the docs. Even the 
Ali's book does not explicitly say that you cannot instantiate a 
class this way. Maybe I totally missed it but just doing the key 
search on "scope", "global", "module" in class related chapters 
didn't give me any results.





Re: Receiving "pthread_mutexattr_init" during compilation when using FileLogger.

2021-06-07 Thread tastyminerals via Digitalmars-d-learn

On Monday, 7 June 2021 at 10:36:23 UTC, Mike Parker wrote:

On Monday, 7 June 2021 at 09:29:08 UTC, tastyminerals wrote:

I getting
```
import/core/sync/mutex.d(87,36): Error: 
`pthread_mutexattr_init` cannot be interpreted at compile 
time, because it has no available source code

```
compile time error. One of those D exceptions which doesn't 
say where it happened in your code so you need to comment out 
the lines that might cause it one by one :D


I found that this was caused by the "FileLogger" which I 
create at the top of the file. But why?


You can't initialize classes at module scope. You can declare 
them, but then they must be initialized in a function or a 
module constructor. Normally for a type `MyClass` in module 
`foo`, you'd see an error like this:


```D
Error: variable `foo.MyClass` is a thread-local class and 
cannot have a static initializer. Use `static this()` to 
initialize instead.

```

I guess CTFE runs before the check that catches this, though, 
and the `FileLogger` constructor ultimately triggers the error 
your seeing.
I see, I only remember that one cannot create associative arrays 
in global scope. This is explicitly written in the language 
reference.
It's interesting how there is no information about class 
instantiation at module level anywhere in the docs. Even the 
Ali's book does not explicitly say that you cannot instantiate a 
class this way. Maybe I missed it but just doing the key search 
on "scope", "global", "module" in class related chapters didn't 
give me any results.


Re: How to cross build a RISC-V target betterC code using LDC on x86-64 machine

2021-06-07 Thread Kagamin via Digitalmars-d-learn

https://forum.dlang.org/post/koxqrqqzadfefbgkd...@forum.dlang.org


Re: Receiving "pthread_mutexattr_init" during compilation when using FileLogger.

2021-06-07 Thread Mike Parker via Digitalmars-d-learn

On Monday, 7 June 2021 at 09:29:08 UTC, tastyminerals wrote:

I getting
```
import/core/sync/mutex.d(87,36): Error: 
`pthread_mutexattr_init` cannot be interpreted at compile time, 
because it has no available source code

```
compile time error. One of those D exceptions which doesn't say 
where it happened in your code so you need to comment out the 
lines that might cause it one by one :D


I found that this was caused by the "FileLogger" which I create 
at the top of the file. But why?


You can't initialize classes at module scope. You can declare 
them, but then they must be initialized in a function or a module 
constructor. Normally for a type `MyClass` in module `foo`, you'd 
see an error like this:


```D
Error: variable `foo.MyClass` is a thread-local class and cannot 
have a static initializer. Use `static this()` to initialize 
instead.

```

I guess CTFE runs before the check that catches this, though, and 
the `FileLogger` constructor ultimately triggers the error your 
seeing.


Receiving "pthread_mutexattr_init" during compilation when using FileLogger.

2021-06-07 Thread tastyminerals via Digitalmars-d-learn

I getting
```
import/core/sync/mutex.d(87,36): Error: `pthread_mutexattr_init` 
cannot be interpreted at compile time, because it has no 
available source code

```
compile time error. One of those D exceptions which doesn't say 
where it happened in your code so you need to comment out the 
lines that might cause it one by one :D


I found that this was caused by the "FileLogger" which I create 
at the top of the file. But why?


```d
import std.experimental.logger: FileLogger;

auto fileLogger = new FileLogger("last.log");
```

Moving the FileLogger instantiation to a function fixes the issue 
though.