Re: best/proper way to declare constants ?

2021-08-04 Thread someone via Digitalmars-d-learn

On Thursday, 5 August 2021 at 03:20:17 UTC, H. S. Teoh wrote:
On Thu, Aug 05, 2021 at 01:39:42AM +, someone via 
Digitalmars-d-learn wrote: [...]

What happens in the following case ?

public immutable enum gudtLocations = [
   r"BUE"d : structureLocation(r"arg"d, r"Buenos Aires"d, 
r"ART"d),
   r"GRU"d : structureLocation(r"bra"d, r"São Paulo"d, 
r"BRT"d),
   r"HHN"d : structureLocation(r"deu"d, r"Frankfurt am Main"d, 
r"CET"d),

   r"LHR"d : structureLocation(r"gbr"d, r"London"d, r"UTC"d),
   r"NYC"d : structureLocation(r"usa"d, r"New York"d, r"EST"d)
   ];

This is something that I also need at compilation time.

[...]

If you need a constant array value both at compile-time and 
runtime, one way to do it is to declare an enum that is used 
only by compile-time code, and the same enum is used once to 
declare the runtime static immutable.


Example:

enum ctValue = [ "my", "data", "here", ... ];

// Initialize this once with ctValue.
static immutable string[] rtValue = ctValue;

if (ctfe) {
// Compile-time: use ctValue
foreach (value; ctValue) {
...
}
} else {
// Runtime: use rtValue instead
foreach (value; rtValue) {
...
}
}


Nice and fine.

Problem is that in your example ctValue is int by default; e: 
my=0, data=1, etc


And what I need at compiled time are strings to build/name 
classes and the like.


I need a compile-time enum (or whatever) that gets me "NYSE" 
"NASDAQ" etc AND that I can use with static foreach {}


My code is far from right but it actually does the job right now:

public enum gudtLocations = [
   r"BUE"d : structureLocation(r"arg"d, r"Buenos Aires"d, 
r"ART"d),

   r"GRU"d : structureLocation(r"bra"d, r"São Paulo"d, r"BRT"d),
   r"HHN"d : structureLocation(r"deu"d, r"Frankfurt am Main"d, 
r"CET"d),

   r"LHR"d : structureLocation(r"gbr"d, r"London"d, r"UTC"d),
   r"NYC"d : structureLocation(r"usa"d, r"New York"d, r"EST"d)
   ];

public enum gudtExchanges = [
   r"B3"d : structureExchange(gudtLocations[r"GRU"d], r"B3"d, 
r"B3 formerly Bolsa de Valores de São Paulo (aka BOVESPA)"d, 
r"BRL"d),
   r"BCBA"d   : structureExchange(gudtLocations[r"BUE"d], 
r"BCBA"d, r"Bolsa de Comercio de Buenos Aires"d, r"ARS"d),
   r"LSE"d: structureExchange(gudtLocations[r"LHR"d], 
r"LSE"d, r"London Stock Exchange"d, r"GBP"d),
   r"NASDAQ"d : structureExchange(gudtLocations[r"NYC"d], 
r"NASDAQ"d, r"National Association of Securities Dealers 
Automated Quotations"d, r"USD"d),
   r"NYSE"d   : structureExchange(gudtLocations[r"NYC"d], 
r"NYSE"d, r"New York Stock Exchange"d, r"USD"d),
   r"XETRA"d  : structureExchange(gudtLocations[r"HHN"d], 
r"XETRA"d, r"Deutsche Börse"d, r"EUR"d)
   ]; /// byKeyValue is not available at compile‐time; hence the 
redundancy of IDs


And of course now I fully understand why it is not optimal at all.

Just be sure you don't use ctValue during runtime, otherwise it 
will incur an allocation per use.



T





Re: best/proper way to declare constants ?

2021-08-04 Thread someone via Digitalmars-d-learn
On Thursday, 5 August 2021 at 02:43:09 UTC, Steven Schveighoffer 
wrote:
The main difference between enums and static immutable is that 
the latter has an address at runtime.


This. Gotcha.

So the answer is, depends on what you are going to do with the 
data. There are use cases for both. If you just want an alias 
to represent the literal, I'd say use enum, it should work fine.


ACK. Now I understand the difference.

Thanks a lot for your detailed reply Steve !

One of the things D has as a plus is ... the community; very 
welcome indeed :)





Re: best/proper way to declare constants ?

2021-08-04 Thread H. S. Teoh via Digitalmars-d-learn
On Thu, Aug 05, 2021 at 01:39:42AM +, someone via Digitalmars-d-learn wrote:
[...]
> What happens in the following case ?
> 
> public immutable enum gudtLocations = [
>r"BUE"d : structureLocation(r"arg"d, r"Buenos Aires"d, r"ART"d),
>r"GRU"d : structureLocation(r"bra"d, r"São Paulo"d, r"BRT"d),
>r"HHN"d : structureLocation(r"deu"d, r"Frankfurt am Main"d, r"CET"d),
>r"LHR"d : structureLocation(r"gbr"d, r"London"d, r"UTC"d),
>r"NYC"d : structureLocation(r"usa"d, r"New York"d, r"EST"d)
>];
> 
> This is something that I also need at compilation time.
[...]

If you need a constant array value both at compile-time and runtime, one
way to do it is to declare an enum that is used only by compile-time
code, and the same enum is used once to declare the runtime static
immutable.

Example:

enum ctValue = [ "my", "data", "here", ... ];

// Initialize this once with ctValue.
static immutable string[] rtValue = ctValue;

if (ctfe) {
// Compile-time: use ctValue
foreach (value; ctValue) {
...
}
} else {
// Runtime: use rtValue instead
foreach (value; rtValue) {
...
}
}

Just be sure you don't use ctValue during runtime, otherwise it will
incur an allocation per use.


T

-- 
What did the alien say to Schubert? "Take me to your lieder."


Re: __FILE__

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

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

file test.d:

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

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

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

-

retult: [abc.d:4]

expect: [test.d:4]


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


Re: __FILE__

2021-08-04 Thread Steven Schveighoffer via Digitalmars-d-learn

On 8/4/21 10:27 PM, Ali Çehreli wrote:
I wonder whether this feature is thanks to 'lazy' parameters, which are 
actually delegates.


No, the default parameters are used directly as if they were typed in at 
the call site (more or less, obviously the `__FILE__` example is weird).


So:

```d
writeln(foo());
```

is just like you did:

```d
writeln(foo(bar()));
```

There are no lazy parameters involved.

-Steve


Re: best/proper way to declare constants ?

2021-08-04 Thread Steven Schveighoffer via Digitalmars-d-learn

On 8/4/21 10:27 PM, someone wrote:

On Thursday, 5 August 2021 at 02:06:13 UTC, Steven Schveighoffer wrote:

On 8/4/21 9:14 PM, H. S. Teoh wrote:

Unless you have a specific reason to, avoid using `enum` with string and
array literals, because they will trigger a memory allocation *at every
single reference to them*, which is probably not what you want.


Just want to chime in and say this is NOT true for string literals. 
Only array literals.


OK. Not for arrays then ... but for string literals ? which one then ?

static immutable string fileName = "list.txt";

vs

enum fileName = "list.txt";


The main difference between enums and static immutable is that the 
latter has an address at runtime. You cannot take the address of an enum 
(which only exists at compile time). You can think of an enum to be a 
substitute for typing out that expression directly. For array literals, 
this means, do a new allocation.


However, a string literal is a special case of an array which does NOT 
allocate -- it puts the string data into the read-only segment, and the 
literal references that data, which is why string enums do not allocate 
when used.


So the answer is, depends on what you are going to do with the data. 
There are use cases for both. If you just want an alias to represent the 
literal, I'd say use enum, it should work fine.


Off the top of my head for strings:

1. A static immutable loses its "C string compatibility", whereas an 
enum does not.
2. A static immutable can be passed as an alias to a template, and the 
template mangle only involves the variable name, whereas passing an enum 
will use the string *contents* for the template mangle. This can be a 
huge difference for symbol sizes.
3. A static immutable can be used as an argument to a reference 
parameter, an enum cannot.
4. A static immutable will consume space in your executable even if 
never used, an enum will not.


-Steve


Re: best/proper way to declare constants ?

2021-08-04 Thread someone via Digitalmars-d-learn
On Thursday, 5 August 2021 at 02:06:13 UTC, Steven Schveighoffer 
wrote:

On 8/4/21 9:14 PM, H. S. Teoh wrote:
Unless you have a specific reason to, avoid using `enum` with 
string and
array literals, because they will trigger a memory allocation 
*at every

single reference to them*, which is probably not what you want.


Just want to chime in and say this is NOT true for string 
literals. Only array literals.


OK. Not for arrays then ... but for string literals ? which one 
then ?


static immutable string fileName = "list.txt";

vs

enum fileName = "list.txt";


-Steve





Re: __FILE__

2021-08-04 Thread Ali Çehreli via Digitalmars-d-learn

On 8/4/21 7:17 PM, Steven Schveighoffer wrote:

>> The compiler has to evaluate the default argument as constant
>> expression in order to use it as default value..
>
> This is not true, you can use runtime calls as default values.

What??? I just checked and it works! :)

string bar() {
  import std.process;
  return ("BAR" in environment) ? environment["BAR"] : null;
}

string foo(string s = bar()) {
  return s;
}

void main() {
  import std.stdio;
  writeln(foo("hello world"));
  writeln(foo());
}

Run e.g. with

$ BAR=whaaat ./deneme

I wonder whether this feature is thanks to 'lazy' parameters, which are 
actually delegates.


Ali



Re: __traits() to get parameter details only ? ... hasMember looks up everything within

2021-08-04 Thread someone via Digitalmars-d-learn
On Thursday, 5 August 2021 at 01:47:36 UTC, Alexandru Ermicioi 
wrote:

On Wednesday, 4 August 2021 at 22:28:53 UTC, someone wrote:

Is that what you mean ?


Not really. I was assuming you were talking about @property 
methods, and if so you could declare such cases:


```
interface HasMutableLstrSymbolId {
 @property lstrSymbolId();
 @property lstrSymbolId(string id);
}

interface HasMutableLstrCurrencyId {
 @property lstrCurrencyId();
 @property lstrCurrencyId(string id);
}

class NyseTicker : HasMutableLstrSymbolId {
 //...
}

class NasdaqTicker : HasMutableLstrSymbolId, 
HasMutableLstrSymbolId  {

 // ...
}
```

Having this structure you would just need to check whether it 
implements right interface and then once you know it, just set 
the value. Note, that this approach won't work nicely if you 
have lots of fields to set. In this case I'd try a builder 
pattern, where you have a common builder interface which has 
Nasdaq and Nyse implementation that builds respective classes 
out of information available.


I'll find this very useful for other things I have in mind ... 
thanks for this one :)


Now from the other replies it seems you want to get constructor 
arguments.



Constructor itself is named __ctor internally


ah ... bingo !

I oftenly see this thing __ctor in the forums but never knew what 
the hell it was. This is what I need.


(you'll see it listed as such when fetching allMembers), 
therefore fetch the constructor overload set (you need this 
because D allows method overloading, and therefore all methods 
in overload set should be checked), and then iterate over it 
and check what you're interested in. You can then use 
std.traits.Parameters to fetch a tuple of param types, or 
std.traits.ParameterIdentifierTuple for fetching parameter 
names. As other people recommended you can check std.traits 
implementation to get insight on the compiler magic they rely 
to do this.


Regarding @property methods, even if they are half baked, they 
are still useful in denoting properties that can be fetched or 
assigned to a class. It is similar to setters & getters 
convention in Java, or [set,get] functionality from C# as far 
as I'm aware. Having properties marked with @property also 
allows template code to be aware which methods are actually 
representing a property on the object.


Yes, of course I am fully aware of what getters/setters are and 
thus I started using @property because I think it had some 
"special" functionality/whatever but after a month or so using 
them and seeing some comments here in the forums I assumed they 
were half-baked or even going away soon so I threw out them all. 
IIRC I think somewhere I read Ali saying there's nothing wrong 
implementing properties the old-way via functions because 
@property has nothing special about it but I can't state where I 
read what I am stating so take it with a grain of salt.


Also, it is not really necessary to prefix the name of each 
class or interface with 'class' or 'interface', since this 
information is already baked into the type itself, and in most 
of the time may be just unnecessary noise for reading the code.


Yes yes I know old habits die hard :)

I do name like this because I often have interfaceXXX alongside 
classXXX : interfaceXXX and this helps me keep track of what I am 
doing. I like to name as related-as-possible. I even still use 
the prefixed variable naming scheme that almost no new programmer 
use but this (at least for me) catches lots of errors on the fly 
-I rarely have a compiler error for a type-mismatch. In the end 
is what works for each-one.


Anyway I am changing the way I usually write code; I already 
switched behavior/style in many areas:


- private: public: sections instead of individually prefixing 
everything

- discarded once-and-for-all excessive cast() usage
- discarded in parameters and went back to const

Unneeded things I still do due to habit:

- explicitly initializing strings; eg: string lstrWhatever = null;
- explicitly initializing integers to 0
- explicitly checking bool's; eg: if (lbolWhatever == true) {}

Long-story-short: the more you learn the more you adapt to :)


Re: __FILE__

2021-08-04 Thread Steven Schveighoffer via Digitalmars-d-learn

On 7/26/21 1:05 PM, Stefan Koch wrote:

On Monday, 26 July 2021 at 12:01:23 UTC, Adam D Ruppe wrote:

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

__FILE__[0..$]


Why do you have that [0..$] there? It is probably breaking the 
__FILE__ magic.


Correct.
The compiler has to evaluate the default argument as constant expression 
in order to use it as default value..


This is not true, you can use runtime calls as default values.

Therefore it evaluates (__FILE__)[0 ..$]you first eval __FILE__ at CTFE 
within the module you are defining the function in.

And then you slice it from zero to length.


This might be how it is implemented, but it shouldn't be. `__FILE__` 
should be usable inside any expression as a default value, which should 
expand to the call-site for the function (as usual).


But this has nothing to do with CTFE as far as I know.

-Steve


Re: best/proper way to declare constants ?

2021-08-04 Thread Steven Schveighoffer via Digitalmars-d-learn

On 8/4/21 9:14 PM, H. S. Teoh wrote:

Unless you have a specific reason to, avoid using `enum` with string and
array literals, because they will trigger a memory allocation *at every
single reference to them*, which is probably not what you want.


Just want to chime in and say this is NOT true for string literals. Only 
array literals.


-Steve


Re: __traits() to get parameter details only ? ... hasMember looks up everything within

2021-08-04 Thread Alexandru Ermicioi via Digitalmars-d-learn

On Wednesday, 4 August 2021 at 22:28:53 UTC, someone wrote:

Is that what you mean ?


Not really. I was assuming you were talking about @property 
methods, and if so you could declare such cases:


```
interface HasMutableLstrSymbolId {
 @property lstrSymbolId();
 @property lstrSymbolId(string id);
}

interface HasMutableLstrCurrencyId {
 @property lstrCurrencyId();
 @property lstrCurrencyId(string id);
}

class NyseTicker : HasMutableLstrSymbolId {
 //...
}

class NasdaqTicker : HasMutableLstrSymbolId, 
HasMutableLstrSymbolId  {

 // ...
}
```

Having this structure you would just need to check whether it 
implements right interface and then once you know it, just set 
the value. Note, that this approach won't work nicely if you have 
lots of fields to set. In this case I'd try a builder pattern, 
where you have a common builder interface which has Nasdaq and 
Nyse implementation that builds respective classes out of 
information available.


Now from the other replies it seems you want to get constructor 
arguments. Constructor itself is named __ctor internally (you'll 
see it listed as such when fetching allMembers), therefore fetch 
the constructor overload set (you need this because D allows 
method overloading, and therefore all methods in overload set 
should be checked), and then iterate over it and check what 
you're interested in. You can then use std.traits.Parameters to 
fetch a tuple of param types, or 
std.traits.ParameterIdentifierTuple for fetching parameter names. 
As other people recommended you can check std.traits 
implementation to get insight on the compiler magic they rely to 
do this.


Regarding @property methods, even if they are half baked, they 
are still useful in denoting properties that can be fetched or 
assigned to a class. It is similar to setters & getters 
convention in Java, or [set,get] functionality from C# as far as 
I'm aware. Having properties marked with @property also allows 
template code to be aware which methods are actually representing 
a property on the object.


Also, it is not really necessary to prefix the name of each class 
or interface with 'class' or 'interface', since this information 
is already baked into the type itself, and in most of the time 
may be just unnecessary noise for reading the code.


Re: best/proper way to declare constants ?

2021-08-04 Thread someone via Digitalmars-d-learn

On Thursday, 5 August 2021 at 01:14:26 UTC, H. S. Teoh wrote:

1) If the constant is a POD (int, float, etc.), use:

enum myValue = ...;


crystal-clear.


2) If the constant is a string or some other array:

static immutable string myString = "...";


crystal-clear.


2) If the constant is a string or some other array:

static immutable Data[] myData = [ ... ];

Unless you have a specific reason to, avoid using `enum` with 
string and array literals, because they will trigger a memory 
allocation *at every single reference to them*, which is 
probably not what you want.


enum myArray = [ 1, 2, 3 ];
...
int[] data = myArray;   // allocates a new array
int[] data2 = myArray;  // allocates another array

// they are separate arrays with the same contents
assert(data !is data2);
assert(data == data2);

// allocates a temporary array, does the comparison, then
// discards the temporary
if (data == myArray) ...

foreach (i; 0 .. 10) {
int[] input = getUserInput(...);

// allocates a new array at every single loop iteration
if (input == myArray) { ... }
}


What happens in the following case ?

public immutable enum gudtLocations = [
   r"BUE"d : structureLocation(r"arg"d, r"Buenos Aires"d, 
r"ART"d),

   r"GRU"d : structureLocation(r"bra"d, r"São Paulo"d, r"BRT"d),
   r"HHN"d : structureLocation(r"deu"d, r"Frankfurt am Main"d, 
r"CET"d),

   r"LHR"d : structureLocation(r"gbr"d, r"London"d, r"UTC"d),
   r"NYC"d : structureLocation(r"usa"d, r"New York"d, r"EST"d)
   ];

This is something that I also need at compilation time.

Throwing away the enum and recoding as following:

static immutable structureLocation[stringUTF32] gudtLocations = [
   r"BUE"d : structureLocation(r"arg"d, r"Buenos Aires"d, 
r"ART"d),

   r"GRU"d : structureLocation(r"bra"d, r"São Paulo"d, r"BRT"d),
   r"HHN"d : structureLocation(r"deu"d, r"Frankfurt am Main"d, 
r"CET"d),

   r"LHR"d : structureLocation(r"gbr"d, r"London"d, r"UTC"d),
   r"NYC"d : structureLocation(r"usa"d, r"New York"d, r"EST"d)
   ];

gives me:

Error: non-constant expression `["BUE"d:structureLocation(true, 
"arg"d, null, "Buenos Aires"d, "ART"d), 
"GRU"d:structureLocation(true, "bra"d, null, "S\xe3o Paulo"d, 
"BRT"d), "HHN"d:structureLocation(true, "deu"d, null, "Frankfurt 
am Main"d, "CET"d), "LHR"d:structureLocation(true, "gbr"d, null, 
"London"d, "UTC"d), "NYC"d:structureLocation(true, "usa"d, null, 
"New York"d, "EST"d)]`


Don't do this. Use static immutable for arrays and strings, use 
enum only for PODs.


crystal-clear.


Re: best/proper way to declare constants ?

2021-08-04 Thread H. S. Teoh via Digitalmars-d-learn
On Thu, Aug 05, 2021 at 12:47:06AM +, someone via Digitalmars-d-learn wrote:
> What are the pros/cons of the following approaches ?

1) If the constant is a POD (int, float, etc.), use:

enum myValue = ...;

2) If the constant is a string or some other array:

static immutable string myString = "...";
static immutable Data[] myData = [ ... ];

Unless you have a specific reason to, avoid using `enum` with string and
array literals, because they will trigger a memory allocation *at every
single reference to them*, which is probably not what you want.

enum myArray = [ 1, 2, 3 ];
...
int[] data = myArray;   // allocates a new array
int[] data2 = myArray;  // allocates another array

// they are separate arrays with the same contents
assert(data !is data2);
assert(data == data2);

// allocates a temporary array, does the comparison, then
// discards the temporary
if (data == myArray) ...

foreach (i; 0 .. 10) {
int[] input = getUserInput(...);

// allocates a new array at every single loop iteration
if (input == myArray) { ... }
}

Don't do this. Use static immutable for arrays and strings, use enum
only for PODs.


T

-- 
It's amazing how careful choice of punctuation can leave you hanging:


best/proper way to declare constants ?

2021-08-04 Thread someone via Digitalmars-d-learn

What are the pros/cons of the following approaches ?

```d
/// first day with D:

public const dstring gstrWhatever = "...";

/// next:

public immutable dstring gstrWhatever = "...";

/// next:

public immutable dstring gstrWhatever;

this() {

   gstrWhatever = "...";

}

/// next (manifest-constant):

public immutable enum gstrWhatever = "...";
```

Are manifest-constants the proper way to go ?

In [http://ddili.org/ders/d.en/enum.html] Ali says:

"We have discussed that it is important to avoid magic constants 
and instead to take advantage of the enum feature ..."


```d
enum fileName = "list.txt";
```

"Such constants are rvalues and they are called manifest 
constants."


"It is possible to create manifest constants of arrays and 
associative arrays as well. However, as we will see later in the 
Immutability chapter, enum arrays and associative arrays may have 
hidden costs."


Re: __traits() to get parameter details only ? ... hasMember looks up everything within

2021-08-04 Thread someone via Digitalmars-d-learn

On Wednesday, 4 August 2021 at 22:22:29 UTC, Adam D Ruppe wrote:

On Wednesday, 4 August 2021 at 22:01:21 UTC, someone wrote:

No. I didn't know it ever existed :(


It is good to look at the source code implementations of some 
of those things too. Most are built out of language features 
and some of it is simpler to use directly (and some of it are 
pretty tricky that's educational to look at too).


I totally agree with you on this one; but, you can't expect me 
(nor anyone else) to gather a mountain of info on just a 
two-month learning curve coding with D. I learned a LOT, and a 
lot is not enough, time will do its thing, but more importantly, 
sometimes I am rethinking the way I usually write code because D 
has some terrific features -right now for me it is like seeing 
only the tip of iceberg.


Re: __traits() to get parameter details only ? ... hasMember looks up everything within

2021-08-04 Thread someone via Digitalmars-d-learn
On Wednesday, 4 August 2021 at 16:41:04 UTC, Alexandru Ermicioi 
wrote:


Since you're using classes consider just declaring an interface 
that denotes that implementor has this field, it would be much 
easier to check for it, and easier for compiler since it avoids 
compile time magic.


I am not sure I am following you regarding this one: you mean 
coding an interface for the sole-purpose to use traits more 
easily ? I mean, use it to unambiguously discern whether the 
required member exists since an interface won't have variables 
nor anything implementation-related which could confuse the check 
?


Like coding:

```d
private interface interfaceTickerCustom1 { ... } /// 
one-parameter granted
private interface interfaceTickerCustom2 { ... } /// 
two-parameters granted


public class classTickerCustomNYSE : interfaceTickerCustom1 {

   this(
  const dstring lstrSymbolID
  ) {

   }

}

public class classTickerCustomNASDAQ : interfaceTickerCustom2 {

   this(
  const dstring lstrSymbolID,
  const dstring lstrCurrencyID
  ) {

   }

}
```

And then checking for classTickerCustom{EchangeID} with traits 
for the existence of the interface the class is being tied to ?


Is that what you mean ?


Re: __traits() to get parameter details only ? ... hasMember looks up everything within

2021-08-04 Thread Adam D Ruppe via Digitalmars-d-learn

On Wednesday, 4 August 2021 at 22:01:21 UTC, someone wrote:

No. I didn't know it ever existed :(


It is good to look at the source code implementations of some of 
those things too. Most are built out of language features and 
some of it is simpler to use directly (and some of it are pretty 
tricky that's educational to look at too).




Re: __traits() to get parameter details only ? ... hasMember looks up everything within

2021-08-04 Thread someone via Digitalmars-d-learn
On Wednesday, 4 August 2021 at 16:41:04 UTC, Alexandru Ermicioi 
wrote:

On Wednesday, 4 August 2021 at 15:08:24 UTC, someone wrote:

However, __traits(hasMember, ...) checks for the existence of 
anything labeled lstrCurrencyID within the class (eg: 
unrelated variables with same name; not gonna happen, but, I 
like to code it the right way); so, question is: is there any 
way to search the parameter declarations only ?


Something akin to 
https://dlang.org/spec/traits.html#getParameterStorageClasses 
but for the parameter types/labels


What do you mean by parameter type?
Are you referring to @property functions or just whether there 
is a field in there?


Labels, identifiers I meant, I suppose I heavily redacted and 
types stuck, sorry for the confusion.


In both cases you need to get that symbol with 
__traits(getMember ...).
If it is about @property then check whether the symbol is a 
function and if so fetch the function attributes with  
functionAttributes template and check if it is marked as a 
property.


Nope. Nothing about @property. Furthermore, as a side-note: I 
removed all @property usage from my code and I am not using them 
anymore since this language feature seems to be half-baked from 
what I am seeing here in the forums.


If this is about field of the class then you can test with 
FieldNameTuple.


Since you're using classes consider just declaring an interface 
that denotes that implementor has this field, it would be much 
easier to check for it, and easier for compiler since it avoids 
compile time magic.


Best regards,
Alexandru.





Re: __traits() to get parameter details only ? ... hasMember looks up everything within

2021-08-04 Thread someone via Digitalmars-d-learn
On Wednesday, 4 August 2021 at 20:13:53 UTC, Steven Schveighoffer 
wrote:

On 8/4/21 11:08 AM, someone wrote:

Have you looked at 
[std.traits](https://dlang.org/phobos/std_traits.html) at all? 
It does a lot of stuff, including giving you parameter names 
and types.


No. I didn't know it ever existed :(

You mean something like:

```d
import std.traits : ParameterIdentifierTuple;

static if ([ParameterIdentifierTuple!classTickerCustom%1$s] == 
["lstrSymbolID", "lstrCurrencyID"]) {


   ...

}

```




Re: module search paths

2021-08-04 Thread Brian Tiffin via Digitalmars-d-learn

On Wednesday, 4 August 2021 at 05:01:59 UTC, Ali Çehreli wrote:

On 8/3/21 9:51 PM, Brian Tiffin wrote:

...

> Is there a go to quick and easy way of tracking down
> module members?

Searching for it at dlang.org usually works pretty well. 
Although, I hear that Adam's Phobos documentation site is 
better. (I don't use it just because I don't have a habit of it 
yet.)


Finally, I sometimes grep under /usr/include/dmd. Ultimate 
truth! :)


Ali


Just adding; here's some technical details for a Ubuntu 18.04 
32bit laptop, with gdc-11.1.0, dmd 2.097.1, ldc 1.8.0 (have yet 
to explore the LLVM options), and vibe out of current dub as of 
early Aug 2020+1, when looking for standard library ultimate 
truths.  *JSON in particular, but these paths are going to be the 
go to paths for now*.



```
/usr/include/d/vibe/vibe/data/json.d
/usr/include/dmd/phobos/std/json.d
/usr/lib/gcc/i686-linux-gnu/11/include/d/std/json.d
/usr/lib/gcc/i686-linux-gnu/9/include/d/std/json.d
/usr/lib/ldc/i386-linux-gnu/include/d/std/json.d
```

I have not done any builds from source yet, only `apt` package 
installs from main repos and gcc leading edge, so `/usr/local...` 
is not a complicating factor on this laptop.  
`/usr/lib/gcc/i686-linux-gnu/11/include/d/...` is where I have 
been finding truth for gdc-11 D.


Cheers, and another thanks.


Re: Relocation error

2021-08-04 Thread SealabJaster via Digitalmars-d-learn

On Wednesday, 4 August 2021 at 20:24:28 UTC, SealabJaster wrote:

..


Oops, please ignore, put it into lflags instead of dflags




Re: Relocation error

2021-08-04 Thread SealabJaster via Digitalmars-d-learn

On Wednesday, 4 August 2021 at 19:47:42 UTC, Paul Backus wrote:

...


I am now getting this error:

```
/usr/bin/ld: -f may not be used without -shared
```

Adding -shared:

```
/usr/bin/ld: 
.dub/build/test-debug-linux.posix-x86_64-dmd_v2.097.1-3DC2262935789AAE4203853EDDD1C5A4/libd.o: relocation R_X86_64_32 against symbol `_D7runtime10entrypoint13g_programArgsS4libd14datastructures5array__T5ArrayTAxaSQBp6memory9allocator15systemallocator15SystemAllocatorSQDsQDq6growth__T6GrowthVii0S_DQEwQEuQBe__T6GrowToVmi8ZQmFNaNbNiNfZSQGhQGfQCp__T6GrowBySQHbQGzQDj__TQCfVmi8ZQCnFNbNiZ9__lambda1ZQBwVii8S_DQIzQIxQFh__T11GrowByScaleVmi2ZQsFNaNbNiNfZSQKqQKoQGy__TQEjSQLgQLeQHo__TQChVmi2ZQCpFNbNiZQEfZQFuZQIjZQLr' can not be used when making a shared object; recompile with -fPIC

```

-fPIE gives the exact same results.


Re: __traits() to get parameter details only ? ... hasMember looks up everything within

2021-08-04 Thread Steven Schveighoffer via Digitalmars-d-learn

On 8/4/21 11:08 AM, someone wrote:

However, __traits(hasMember, ...) checks for the existence of anything 
labeled lstrCurrencyID within the class (eg: unrelated variables with 
same name; not gonna happen, but, I like to code it the right way); so, 
question is: is there any way to search the parameter declarations only ?


Have you looked at 
[std.traits](https://dlang.org/phobos/std_traits.html) at all? It does a 
lot of stuff, including giving you parameter names and types.


-Steve


Re: module search paths

2021-08-04 Thread Brian Tiffin via Digitalmars-d-learn

On Wednesday, 4 August 2021 at 09:41:45 UTC, Mathias LANG wrote:

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


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

Have good.


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


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


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


Thanks, Mathias.  So it's a trailing edge / leading edge thing.  
Ok with that.  I just got a workable install of DMD a few days 
ago, with 2.097.1.  Previous packages did not work on the old 
laptop I'm using to explore D.  Getting a workable DMD package 
was a boon too, adding dub and rdmd, which helps out a lot with 
other learning materials found on the web.


I'm not at the level where I build these tools from source yet.  
That's a few steps ahead.  And then the slow build of a mental 
knowledge base to know where and when to look for things that 
change or where articles may be ahead or behind in gdc D 
development details.


Being a GNU maintainer for a COBOL compiler, I was a GDC fanboy 
before I even tried it.  Willing to put up with a few edge cases 
while things build out and will always reach for gdc before 
trying the other 2 options.  ;-)


A life goal has been to see GnuCOBOL envelope all in it's path, 
via the C ABI.  gdc makes that easier with integrating all new 
things D with all the old things COBOL.  :-)


The last few weeks has seen a definite shift to D over C as a 
personal first choice for system and utility level programming, 
leading to a *lesser* shift to D over COBOL for application 
programming.


Learning more and more D makes it seems like it will be a first 
choice for most programming; low, mid and high level, in the 
small and in the large.  I may end up growing very spoiled in my 
old age.


Have good, make well.


Re: Relocation error

2021-08-04 Thread Paul Backus via Digitalmars-d-learn

On Wednesday, 4 August 2021 at 18:52:40 UTC, SealabJaster wrote:
However, I'm now running into the following linker error that I 
really don't know what to do with:


```
/usr/bin/ld: 
.dub/build/test-debug-linux.posix-x86_64-dmd_v2.097.1-6FDCEE655D96859081886B42E500F838/libd.o: relocation R_X86_64_32 against symbol [...] can not be used when making a PIE object; recompile with -fPIE

collect2: error: ld returned 1 exit status
```


You need to add `-fPIC` to your `dflags`. Normally this is done 
automatically by `/etc/dmd.conf`, but you've disabled that with 
`-conf=`.


Re: Relocation error

2021-08-04 Thread SealabJaster via Digitalmars-d-learn

On Wednesday, 4 August 2021 at 18:52:40 UTC, SealabJaster wrote:

...


Forgot to mention: Build with `dub run --compiler=dmd -c test`



Relocation error

2021-08-04 Thread SealabJaster via Digitalmars-d-learn
I'm currently working on a libc-less standard library for myself, 
and was working on Posix support recently.


However, I'm now running into the following linker error that I 
really don't know what to do with:


```
/usr/bin/ld: 
.dub/build/test-debug-linux.posix-x86_64-dmd_v2.097.1-6FDCEE655D96859081886B42E500F838/libd.o: relocation R_X86_64_32 against symbol `_D7runtime10entrypoint13g_programArgsS4libd14datastructures5array__T5ArrayTAxaSQBp6memory9allocator15systemallocator15SystemAllocatorSQDsQDq6growth__T6GrowthVii0S_DQEwQEuQBe__T6GrowToVmi8ZQmFNaNbNiNfZSQGhQGfQCp__T6GrowBySQHbQGzQDj__TQCfVmi8ZQCnFNbNiZ9__lambda1ZQBwVii8S_DQIzQIxQFh__T11GrowByScaleVmi2ZQsFNaNbNiNfZSQKqQKoQGy__TQEjSQLgQLeQHo__TQChVmi2ZQCpFNbNiZQEfZQFuZQIjZQLr' can not be used when making a PIE object; recompile with -fPIE

collect2: error: ld returned 1 exit status
```

I've uploaded the current state of the code [1] in case anyone 
has the free time to check it out, because I have 0 clue on how 
to solve this as I'm mostly a windows dev, and this is only 
happening on linux.


Using DMD 2.097, Ubuntu 20.24 on WSL2, ld 2.34.

p.s. I thought I'd end up saying the opposite, but the win32 API 
is much nicer so far.


[1] https://github.com/BradleyChatha/bcstd


Re: __traits() to get parameter details only ? ... hasMember looks up everything within

2021-08-04 Thread Alexandru Ermicioi via Digitalmars-d-learn

On Wednesday, 4 August 2021 at 15:08:24 UTC, someone wrote:

However, __traits(hasMember, ...) checks for the existence of 
anything labeled lstrCurrencyID within the class (eg: unrelated 
variables with same name; not gonna happen, but, I like to code 
it the right way); so, question is: is there any way to search 
the parameter declarations only ?


Something akin to 
https://dlang.org/spec/traits.html#getParameterStorageClasses 
but for the parameter types/labels


What do you mean by parameter type?
Are you referring to @property functions or just whether there is 
a field in there?


In both cases you need to get that symbol with __traits(getMember 
...).
If it is about @property then check whether the symbol is a 
function and if so fetch the function attributes with  
functionAttributes template and check if it is marked as a 
property.


If this is about field of the class then you can test with 
FieldNameTuple.


Since you're using classes consider just declaring an interface 
that denotes that implementor has this field, it would be much 
easier to check for it, and easier for compiler since it avoids 
compile time magic.


Best regards,
Alexandru.


__traits() to get parameter details only ? ... hasMember looks up everything within

2021-08-04 Thread someone via Digitalmars-d-learn
I have the following chunk of code that needs to conditionally 
instantiate existing classes (at compilation time) named 
classTickerCustom{ExchangeID} with one or ... two parameters (if 
any); eg:


```d
/// securities trading on exchange primary currency; eg: USD

... = new classTickerCustomNYSE("AMC");
... = new classTickerCustomNASDAQ("TSLA");

/// securities trading on exchange secondary currency; eg: EUR

... = new classTickerCustomNYSE("XXX", "EUR");
... = new classTickerCustomNASDAQ("YYY", "EUR");

/// not real cases ... of course
```

And I already have a working solution using:

```d
static if (__traits(hasMember, "...", "...") == true) {

   ...

}
```

More specifically:

```d
...

mixin(format!

   ` /// code chunk

   static if (__traits(hasMember, r"classTickerCustom%1$s"d, 
r"lstrCurrencyID"d) == true) { /// checking whether target class 
has an optional second parameter labeled lstrCurrencyID:


  classTickerCustom%1$s lobjTickerCustom%1$s = new 
classTickerCustom%1$s(

 ludtTicker.symbolID,
 ludtTicker.currencyID /// overriding exchange primary 
currency ID with given one

 );

   } else {

  classTickerCustom%1$s lobjTickerCustom%1$s = new 
classTickerCustom%1$s(ludtTicker.symbolID);


   }

   `(sudtExchange.ID) /// code chunk

); /// mixin ending

...
```

However, __traits(hasMember, ...) checks for the existence of 
anything labeled lstrCurrencyID within the class (eg: unrelated 
variables with same name; not gonna happen, but, I like to code 
it the right way); so, question is: is there any way to search 
the parameter declarations only ?


Something akin to 
https://dlang.org/spec/traits.html#getParameterStorageClasses but 
for the parameter types/labels


Re: Two major problems with dub

2021-08-04 Thread Steven Schveighoffer via Digitalmars-d-learn

On 8/4/21 4:18 AM, evilrat wrote:

On Wednesday, 4 August 2021 at 07:21:56 UTC, Denis Feklushkin wrote:

On Sunday, 1 August 2021 at 17:37:01 UTC, evilrat wrote:

vibe-d - probably because it handles DB connection and/or keep things 
async way, sure you probably can do it with Phobos but it will be 
much more PITA and less performant


It is because Postgres provides JSON types


Than again like I said it is library author mistake, if only JSON is 
ever used then it should depend on vibe-d:data specifically and not the 
whole vibe-d thing.


He is the library author. And [that's exactly what he 
does](https://github.com/denizzzka/dpq2/blob/c1f1c7c26f7e6cac7a34778dc580c92d8dec013b/dub.json#L12).


Note that when you depend on a subpackage, it downloads the entire 
repository (it has to), but will only build the subpackage.


-Steve


Re: Two major problems with dub

2021-08-04 Thread Adam D Ruppe via Digitalmars-d-learn

On Wednesday, 4 August 2021 at 08:18:34 UTC, evilrat wrote:
Than again like I said it is library author mistake, if only 
JSON is ever used then it should depend on vibe-d:data 
specifically and not the whole vibe-d thing.


It is also a problem with dub though since D, the language, 
supports this just fine.


If you use dmd -i, it only includes the specific modules you 
actually used. This can even get down to fine-grained functions 
if you code carefully, like if you use my dom.d you just need 
dom.d for most things. But call Document.fromUrl and now dmd -i 
pulls in my http2.d. Or Document.parseGarbage pulls in 
characterencodings.d.


It does all that transparently based on your actual function 
calls thanks to those things being templates with local imports. 
But dub can't express that at all; it is incapable of using D's 
full modular strengths.


This could be fixed.


Re: module search paths

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

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


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

Have good.


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


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


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


Re: Two major problems with dub

2021-08-04 Thread Guillaume Piolat via Digitalmars-d-learn
On Tuesday, 3 August 2021 at 00:54:56 UTC, Steven Schveighoffer 
wrote:


Given the way D works, and often template-heavy coding styles, 
I think it's going to be hard to do this correctly, without 
careful attention and lots of `version(has_xxx)` conditionals.


-Steve


I don't think optional dependencies are truly the answer.
There are ways to fix this otherwise is to break dependency 
chains when only a small part is used.

In this case:
- use a GC slice
- use malloc
- use std.experimental.allocator

My pet peeve is the isfreedesktop package. 
https://github.com/FreeSlave/isfreedesktop/blob/master/source/isfreedesktop.d package :)
Yes it is annoying, but with a bit of copy-paste you can break 
dependencies chain and avoid the npm situation where "640 
packages were installed"


Re: Two major problems with dub

2021-08-04 Thread evilrat via Digitalmars-d-learn
On Wednesday, 4 August 2021 at 07:21:56 UTC, Denis Feklushkin 
wrote:

On Sunday, 1 August 2021 at 17:37:01 UTC, evilrat wrote:

vibe-d - probably because it handles DB connection and/or keep 
things async way, sure you probably can do it with Phobos but 
it will be much more PITA and less performant


It is because Postgres provides JSON types


Than again like I said it is library author mistake, if only JSON 
is ever used then it should depend on vibe-d:data specifically 
and not the whole vibe-d thing.


Re: Two major problems with dub

2021-08-04 Thread Denis Feklushkin via Digitalmars-d-learn

On Sunday, 1 August 2021 at 17:18:39 UTC, Alain De Vos wrote:

A simple and small wrapper around for instance the C-library


Really, dpq2 is that wrapper


Re: Two major problems with dub

2021-08-04 Thread Denis Feklushkin via Digitalmars-d-learn

On Sunday, 1 August 2021 at 17:37:01 UTC, evilrat wrote:

vibe-d - probably because it handles DB connection and/or keep 
things async way, sure you probably can do it with Phobos but 
it will be much more PITA and less performant


It is because Postgres provides JSON types



Re: module search paths

2021-08-04 Thread Brian Tiffin via Digitalmars-d-learn

On Wednesday, 4 August 2021 at 05:01:59 UTC, Ali Çehreli wrote:

On 8/3/21 9:51 PM, Brian Tiffin wrote:

> I added an `import std.json;`.  That did not include the
> JSONType enum.

It works for me:

import std.json;

int main() {
  return JSONType.null_;
}

> Is there a go to quick and easy way of tracking down
> module members?

Searching for it at dlang.org usually works pretty well. 
Although, I hear that Adam's Phobos documentation site is 
better. (I don't use it just because I don't have a habit of it 
yet.)


Finally, I sometimes grep under /usr/include/dmd. Ultimate 
truth! :)


Ali


Cool, thanks, Ali.  I'll track through some source.  I may have 
blended some local files, (I did quite a few `dmd` installs 
during a flailing phase).


Have good.


Re: compare types of functions.

2021-08-04 Thread ag0aep6g via Digitalmars-d-learn

On 02.08.21 22:14, vit wrote:

Why this doesn't work:
```d
template DestructorType(T){

 alias Get(T) = T;

     alias DestructorType = Get!(typeof((void*){
     T tmp;
     }));
}

struct Foo{

     ~this()@safe{}
}
```


```d
void main(){
     //Error: static assert:  `is(void function(void*) pure nothrow 
@nogc @safe : void function(void*) @safe)` is false
     static assert(is(void function(void*)pure nothrow @safe @nogc : 
DestructorType!Foo));


}

```

but this work:
```d

void main(){

     alias X = void function(void*)@safe;


     static assert(is(void function(void*)pure nothrow @safe @nogc : 
DestructorType!Foo));


}
```


Looks like you found a compiler bug. An unused alias should have any effect.


Re: alias using Complex!Double in module ... linker error??

2021-08-04 Thread james.p.leblanc via Digitalmars-d-learn

On Wednesday, 4 August 2021 at 01:10:15 UTC, Mike Parker wrote:
On Tuesday, 3 August 2021 at 21:40:09 UTC, james.p.leblanc 
wrote:

[...]


The alias to Complex!double is a template instantiation. A 
template instantiation creates a symbol that needs to be 
linked. So you need to compile my_module.d along with my_main.d.


```
dmd my_main.d my_module.d
```

Or alternatively:

```
dmd -i my_main.d
```

double is a built-in type, so that alias doesn't create any 
symbols that need linking.


An alias in and of itself is a compile-time-only construct, but 
the symbols you assign it might require linking something.


Mike,

Aha... that makes sense now!

Thanks kindly for helping me understand what was happening with 
your
informative reply.  The fact of template instantiations and 
symbols

had escaped me completely.

I appreciate it.

Best Regards,
James