Re: Library object name collision

2023-01-24 Thread frame via Digitalmars-d-learn

On Tuesday, 24 January 2023 at 09:54:01 UTC, frame wrote:

Thanks! it works well with the `-op` switch, didn't know I can 
do with libraries. Only drawback is that every path now stored 
as absolute path - any way to store only a relative one?


Ah never mind, it seems only to do this with phobos related debug 
links


Re: Library object name collision

2023-01-24 Thread frame via Digitalmars-d-learn
On Tuesday, 24 January 2023 at 08:15:55 UTC, Richard (Rikki) 
Andrew Cattermole wrote:

On 24/01/2023 8:59 PM, frame wrote:
Also why have most objects an unique postfix in the name but 
those files havn't? It's mostly a `__ModuleInfoZ` or `__initZ` 
but not always.


Symbols which end in __ModuleInfoZ are symbols that hold 
per-module information for features like unittests and module 
constructors.


Symbols which end in __initZ hold information on types, 
specifically their default initialization state.


So if these two are missing, and they should be there, you have 
a problem.


It's a library - if any symbol is missing it will be a problem ;-)

Now wrt. LNK4255, I'm not sure why its doing this. You haven't 
shown how you're building. But if you're doing it manually you 
may want to try:


  -od=   write object & library files to directory
  -of=name output file to filename
  -op   preserve source path for output files


Doing it via dub, manually would be the `-lib` switch I guess.

Thanks! it works well with the `-op` switch, didn't know I can do 
with libraries. Only drawback is that every path now stored as 
absolute path - any way to store only a relative one?


Library object name collision

2023-01-24 Thread frame via Digitalmars-d-learn
When creating a linker library under Windows and having module 
a/b/foo.d but also d/c/foo.d the linker afterwards is bailing out:


.lib(foo.obj) : warning LNK4255: library contain multiple 
objects of the same name; linking object as if no debug info


And when I did inspect the library it confirmed that the compiler 
just places the objects twice - contents looks like this:


```
1.txt
1.types.obj
2.txt
2.types.obj
...
foo.obj
foo_1b34_260.obj
foo.obj
foo_1b44_991.obj
...
```
Which seems incorrect to me.

Does the compiler use an external command to create the library 
or does it itself?


Also why have most objects an unique postfix in the name but 
those files havn't? It's mostly a `__ModuleInfoZ` or `__initZ` 
but not always.


How to deal with this? I could rename the files but can't do that 
without changing the module name too which sucks.


Re: Why this function just decides to not call another function and do its thing instead?

2022-09-17 Thread frame via Digitalmars-d-learn
On Saturday, 17 September 2022 at 15:04:48 UTC, solidstate1991 
wrote:


And then instead just decides that the `localName` and 
`namespaceURI` pairs are not equal, and in those cases the 
Visual Studio debugger doesn't detect any entering into any of 
the `DOMString.equals` overrides, all while the debugger shows 
those strings are equal.


`opEquals` probably was not called if an operand was null. It 
seems that `Attr.localName` can return null.


Re: How to workaround on this (bug?)

2022-09-16 Thread frame via Digitalmars-d-learn

On Friday, 16 September 2022 at 23:06:35 UTC, H. S. Teoh wrote:

Basically, if you pass something to .fun by value, then that 
value must be destroyed by .fun once it's ready to return.  So 
if the value has a dtor, the dtor must be called upon exiting 
from .fun.  Since Variant has a throwing dtor, this means .fun 
may throw when it's about to return, which violates `nothrow`.


I understand why this happens but not why the compiler does not 
check if the value is actually destroyed in user code by 
`.destroy()`.


Thanks for your suggestion, I will consider this.


How to workaround on this (bug?)

2022-09-16 Thread frame via Digitalmars-d-learn

```d
import std.variant;

// error: destructor `std.variant.VariantN!32LU.VariantN.~this` 
is not `nothrow`

void fun(Variant v) nothrow
{

}

void main()
{
   fun(Variant());
}
```

A reference, pointer or slice works. I could do something on the 
caller site but the signature of `fun()` should remain like above.


Shorten template arguments in debug symbols?

2022-09-12 Thread frame via Digitalmars-d-learn
If I have a template that accepts tokenized code to build 
something, it will create the exact debug symbol with this 
argument supplied which makes the symbols hard to read and/or 
waste of memory.


Is there any way to truncate or transform it like that?
```
app.fun!"writeln(\"Hello, World\");" => app.fun!"_sym__13"
```

I can pass a pointer to the template but that results in the same 
symbol. Getting the raw integer value of the pointer instead 
isn't allowed in compile it seems.


Re: Dictionary of Templated Functions

2022-09-10 Thread frame via Digitalmars-d-learn
On Saturday, 10 September 2022 at 00:24:11 UTC, jwatson-CO-edu 
wrote:

Hello,
I'm trying to create a dictionary of templated function 
pointers.  The functions should return `bool` and take a 
differently-typed dynamics arrays `T[]` as an argument.


This won't work as you might expect. Your container would need to 
support multiple types and may need overloads of operators to 
become that magic.


But lets begin with a simple type. Consider your example fixed:

```d
alias FuncDict(T) = bool function(T[])[string]; // alias needs T 
as parameter too...


FuncDict!(string) lookup; // ...so we can instantiate a FuncDict 
with T = string


void main()
{
lookup["foo"] = function bool(string[] args) { return true; };
}
```

As you can see `T` is bound to `string` here and cannot be 
something else.




Re: synchronized/shared associative array .require error

2022-09-06 Thread frame via Digitalmars-d-learn

On Tuesday, 6 September 2022 at 10:28:53 UTC, Loara wrote:

On Saturday, 3 September 2022 at 14:07:58 UTC, frame wrote:
Not exactly, a synchronized class member function becomes 
automatically a shared one.


This is not present in official documentation so other 
compilers different from `dmd` aren't forced to assume it. This 
should be consider an experimental feature of D that users 
should be able to turn off if they want.


Hmm.. LDC does the same to me.

I think the whole synchronization class is an experimental 
feature :D




Re: Forked GC explained

2022-09-06 Thread frame via Digitalmars-d-learn
On Monday, 5 September 2022 at 18:35:02 UTC, Steven Schveighoffer 
wrote:

On 9/5/22 7:12 AM, frame wrote:
And what if the programmer has no actual reference but wrongly 
forced a `free()` through a pointer cast?


https://dlang.org/spec/garbage.html#pointers_and_gc

* Do not store pointers into non-pointer variables using casts 
and other tricks.

```d
void* p;
...
int x = cast(int)p;   // error: undefined behavior
```
The garbage collector does not scan non-pointer fields for GC 
pointers.


Note that this does not require the forked GC to cause this 
problem.


-Steve


Well, of course it would be the fault of the programmer. I did 
ask this because I just want to know if there is any catch of 
this (probably not intended/yet noticed) violation of some third 
party lib. I don't want do debug this :D


Re: Forked GC explained

2022-09-05 Thread frame via Digitalmars-d-learn
On Saturday, 3 September 2022 at 14:31:31 UTC, Steven 
Schveighoffer wrote:

On 9/3/22 9:35 AM, frame wrote:


What happens if a manually `GC.free()` is called while the 
forked process marks the memory as free too but the GC 
immediately uses the memory again and then gets the 
notification to free it from the forked child? Can this happen?


No, because if you can free it, you should have had a reference 
to it when you forked, which should mean it's not garbage.


And what if the programmer has no actual reference but wrongly 
forced a `free()` through a pointer cast?


```
| OP  | Memory M
---
Parent: | -   | Unreferenced, marked in use
---
Parent: | fork
---
Parent: | -   | Unreferenced, marked in use
Child:  | | Unreferenced, marked in use
---
Parent: | -   | Unreferenced, marked in use
Child:  | | Unreferenced, found M
---
Parent: | free| Unreferenced, marked not in use  <- error 
forced by programmer

Child:  | | Unreferenced, found M
---
Parent: | new | Referenced, re-used because it was marked free
Child:  | | Unreferenced, found M
---
Parent: | -   | Referenced, used
Child:  | | Done scanning. Please collect: M
---
Parent: | collect | M
Child:  | | exit
---
```
@wjoe is the GC aware of this to exclude M from the child result 
set because it has changed while the child was running?


There's a talk on it from the 2013 dconf by the inventor: 
https://dconf.org/2013/talks/lucarella.html


-Steve


Thanks for the link. The slides mentioning shared memory.


Re: synchronized/shared associative array .require error

2022-09-03 Thread frame via Digitalmars-d-learn

On Saturday, 3 September 2022 at 09:49:54 UTC, Loara wrote:

In current version of D language `synchronized` and `shared` 
are independent. In particular `shared` should be used only for 
basic types like integers for which atomic operations are well 
defined, and not for classes.


Not exactly, a synchronized class member function becomes 
automatically a shared one.


Forked GC explained

2022-09-03 Thread frame via Digitalmars-d-learn
I'm not sure I fully understand how it works. I know that the OS 
creates read only memory pages for both and if a memory section 
is about to be written, the OS will issue a copy of the pages so 
any write operation will be done in it's own copy and cannot mess 
up things.


But then is the question, how can memory be marked as free? The 
forked process cannot since it writes into a copy - how it is 
synchronized then?


Is the GC address root somehow shared between the processes? Or 
does the forked process communicate the memory addresses back to 
the parent?


If so, does the GC just rely on this?

Are freeing GC operations just locked while the forked process is 
running?


What happens if a manually `GC.free()` is called while the forked 
process marks the memory as free too but the GC immediately uses 
the memory again and then gets the notification to free it from 
the forked child? Can this happen?


Re: what's this error: allocatestack.c:384: advise_stack_range: Assertion `freesize < size' failed.

2022-08-23 Thread frame via Digitalmars-d-learn

On Tuesday, 23 August 2022 at 18:50:14 UTC, mw wrote:

Hi,

I got an error message when my program exits (the main 
functionality is done, I guess the error happened during D 
runtime's cleanup)


: allocatestack.c:384: advise_stack_range: Assertion `freesize 
< size' failed.


I suspect it somehow related to I pass some (object) pointers 
to foreign languages containers (C and Rust). But my main 
program seems behave correctly (I keep those pointers on the D 
side to prevent them from being GC-ed), this error only happens 
when the program exits.


Anyone can give me some hint where I should look at? (and where 
is the allocatestack.c?)


Thanks.


allocatestack.c is some thing of GLIBC, the line seems to match 
[1] but I don't think that will help you much. You will need to 
get a trace where the function is called.


[1] 
https://code.woboq.org/userspace/glibc/nptl/allocatestack.c.html


Re: Fixed-size OutBuffer that doesn't call .resize() automatically? (for database page buffers)

2022-08-19 Thread frame via Digitalmars-d-learn

On Friday, 19 August 2022 at 16:19:04 UTC, Gavin Ray wrote:
1. Calling `.toBytes()` on an `OutBuffer` will discard the 
extra bytes allocated past what was reserved and used. But this 
will still allocate the memory in the first place I guess (will 
the compiler optimize this away?)


It does allocate when it needs to. It grows but never shrinks 
again.


2. Copy the `OutBuffer` class into a new 
`FixedSizeOutBuffer(T)` and alter its behavior


3. Use `ubyte[PAGE_SIZE]` and manually write like below:



```d
static ubyte[4] bytes = new ubyte[4];
```
Looks still unnecessary - you are allocating thread local memory. 
Just use a static array.




```d
foreach (idx, ref slot; header.slots)
```
No need to reference `slot` here. You may prevent compiler 
optimizations.



```d
// Skip over free space
ubyte[] padding = new ubyte[header.freeSpacePointer];
padding[] = 0;
buf ~= padding;
```
Unnecessary, the initial value of `ubyte` is 0 and allocation is 
done automatically. Just set the slice length:

```d
buf.length += header.freeSpacePointer;
```


```d
foreach (idx, ref tuple; tuples)
```

Again, no need to reference


```d
move(buf.ptr, outbuf.ptr);
```

Not sure what that is. A simple
```d
outbuf[0 .. buf.length] = buf; // or whatever position to write 
in outbuf

```
should do it too.


Re: A GtkD issue

2022-08-18 Thread frame via Digitalmars-d-learn

On Friday, 19 August 2022 at 00:40:40 UTC, pascal111 wrote:


Now, I used cmd.exe and found this new errors:

"lld-link: error: undefined symbol: __D3gio5FileT12__ModuleInfoZ

referenced by



If you don't post the exact command you are using we can just 
assume what you did wrong:


The linker is unable to find the library. You will need to 
specify it via `-L` command line switch. If your environment 
setup fails to determine the paths, you can always specify it raw:


```
rdmd -m64 -I=src\gtkd -L=libs\gtkd.lib app.d
```

where:
`src` contains the `gtkd` folder copied from `GtkD-3.9\generated`
`libs` contains the file `gtkd.lib` created by the 
`GtkD-3.9\Build.d` output


Re: A GtkD issue

2022-08-15 Thread frame via Digitalmars-d-learn

On Saturday, 13 August 2022 at 01:14:09 UTC, pascal111 wrote:
I was following instructions from this link 
https://gtkdcoding.com/2019/01/11/-introduction-to-gtkDcoding.html to setup GtkD, and tried to run the example with VSCode and found these errors:




How do you start compiling in VsCode? Are you using an extension?

 \*  The terminal process 
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe 
-Command & 'rdmd' 'd:\Documents\My Projects\D\vdtest01.d'" 
terminated with exit code: 1. "


Try to execute commands in legacy cmd.exe, not powershell.

I used it in a small project a year ago, it works fine.


Re: My programs issues

2022-08-12 Thread frame via Digitalmars-d-learn

On Friday, 12 August 2022 at 20:16:26 UTC, pascal111 wrote:

I tried under Windows using alt+9 or 6 but with no hoped 
result, they printed another characters.


Maybe this wasn't clear. I meant keep pressing [Alt] and then 
[9], [6] (in turn) and then release [Alt]. It should print the 
character (96 = 0x60)


Re: My programs issues

2022-08-12 Thread frame via Digitalmars-d-learn

On Friday, 12 August 2022 at 18:43:14 UTC, pascal111 wrote:

On Friday, 12 August 2022 at 16:06:09 UTC, frame wrote:

On Thursday, 11 August 2022 at 20:30:54 UTC, pascal111 wrote:


https://github.com/pascal111-fra/D/blob/main/proj08.d


btw letters :D

Please use ` (ASCII: 0x60) instead of ' (0x27) for the 
markdown format header, eg.:


```D ...```

otherwise it won't be recognized here.


I don't see "`" in the keyboard!


No doubt about that :D

However, you can create the letter with your compose key (depends 
on your linux distribution, eg. [Shift] + [AltGr] but you may 
need to enable it first, see for example


https://ubuntuhandbook.org/index.php/2019/02/enable-set-compose-key-ubuntu-18-04/

Maybe just pressing [Alt] and 9,6 on the NUM pad works too.


Re: My programs issues

2022-08-12 Thread frame via Digitalmars-d-learn

On Thursday, 11 August 2022 at 20:30:54 UTC, pascal111 wrote:


https://github.com/pascal111-fra/D/blob/main/proj08.d


btw letters :D

Please use ` (ASCII: 0x60) instead of ' (0x27) for the markdown 
format header, eg.:


```D ...```

otherwise it won't be recognized here.


Re: Acess variable that was set by thread

2022-08-08 Thread frame via Digitalmars-d-learn

On Monday, 8 August 2022 at 10:17:57 UTC, ag0aep6g wrote:

By the way, is there some resource that recommends `__gshared` 
over `shared`? It seems that many newbies reach for `__gshared` 
first for some reason.


Would be also good if the specs would tell more about those 
"guards":


Unlike the shared attribute, __gshared provides no safe-guards 
against data races or other multi-threaded synchronization 
issues.


The only thing I see is that the compiler bails about type 
incompatibilities but how does it help in case of 
synchronization/locking issues?




Re: "chain" vs "~"

2022-08-08 Thread frame via Digitalmars-d-learn

On Monday, 8 August 2022 at 01:05:40 UTC, pascal111 wrote:

In next program, I used "insertInPlace", not "~" nor "chain", 
should I use "~" or it's the same as "insertInPlace"?


https://github.com/pascal111-fra/D/blob/main/coco.d


As you may noticed, `insertInPlace` has another purpose than just 
appending data. And it will create a new range (to call itself 
again), moves memory and places the item there, so it's rather 
inefficient than just appending a single item via "~".


Re: Unittest Absurdity

2022-08-05 Thread frame via Digitalmars-d-learn
On Friday, 5 August 2022 at 21:24:13 UTC, Steven Schveighoffer 
wrote:


That's not what I was talking about here. I'm talking about 
`-vcg-ast` not telling you how it's calling the function.


Thanks for clarification.

I had that in mind but wasn't sure. I first thought it just get 
optimized away and in case of name/type collision would create 
another name for the function but after testing with `static if` 
it really shows that this assumption was wrong :D


Re: Unittest Absurdity

2022-08-05 Thread frame via Digitalmars-d-learn
On Friday, 5 August 2022 at 15:24:16 UTC, Steven Schveighoffer 
wrote:


oof, I expected this to include the template parameters! I 
believe it normally does?

This is a bug that should be filed.

-Steve


Sorry, I don't get what you takling about?

The docs says:

The expression:
`a op= b`

is rewritten as:
`a.opOpAssign!("op")(b)`

There must no "=" to be applied.

The compiler creates this:
```d
opOpAssign!"/"
{
pure nothrow @nogc @safe void opOpAssign(S rhs)
{
}
}
```
as only valid call left. Fine for me since the other template is 
unused.


Same for your example:
```d
foo!("hi", int)
{
pure nothrow @nogc @safe void foo(int t)
{
}
}
```


Re: Arbitrary precision decimal numbers

2022-08-05 Thread frame via Digitalmars-d-learn

On Friday, 5 August 2022 at 14:03:36 UTC, Ruby The Roobster wrote:

Also, what about division and exponentiation.  You can't just 
forward them to BigInt and get a good result, BigInt will just 
round to an integer for these two.


There are divMod() and powmod() for BigInt but I have no idea how 
precise they really are.


Re: Arbitrary precision decimal numbers

2022-08-05 Thread frame via Digitalmars-d-learn
On Thursday, 4 August 2022 at 13:01:30 UTC, Ruby The Roobster 
wrote:
Is there any implementation in phobos of something similar to 
BigInt but for non-integers as well?  If there isn't is there a 
dub package that does this, and if so, which one?


We have this:

https://code.dlang.org/search?q=decimal

I end up using BigInt instead on a custom wrapper that stores the 
precision hint. To calculate with any number, it need to convert 
each value to the same base (eg. storing 10.234 simply results in 
a BigInt with value 10234 and the precision hint of 3) and then 
forward the operation to BigInt.


Re: Ranges

2022-08-05 Thread frame via Digitalmars-d-learn

On Thursday, 4 August 2022 at 22:14:26 UTC, Ali Çehreli wrote:


No element is copied or moved. :)

Ali


I know that :) I just found that this user has problems to 
understand basics in D, so I tried not to go in detail and keep 
at its kind of logical layer. It seems the better way to help 
until the user asks specific questions.


Re: Ranges

2022-08-04 Thread frame via Digitalmars-d-learn

On Thursday, 4 August 2022 at 13:08:21 UTC, pascal111 wrote:

1) Why the programmer needs to program "empty()", "front()", 
and "popFront()" functions for ranges while they exist in the 
language library? it seems there's no need to exert efforts for 
that. "https://dlang.org/phobos/std_range_primitives.html";


- These functions are wrappers to use something as range
- Ranges need to implement the functions to keep their data 
private, also there are complex types the need to handle data 
differently
- Ranges must implement the functions so other function can 
recognize it as such (eg. `isInputRange`) - there is no common 
interface, it's determined by compile time


2) "front()", and "popFront()" are using fixed constants to 
move forward the range, while they should use variables.


`front()` is always using the first element BUT `popFront()` 
copies all elements except the first one into the variable (and 
overwrites it), so it moves the data forward.


Re: How to find all modules in a package?

2022-08-03 Thread frame via Digitalmars-d-learn

On Wednesday, 3 August 2022 at 03:36:55 UTC, Domain wrote:
I want to find out all public functions in all modules in a 
package. Can I do that at compile time?


You can do something like that:

```d
static foreach (sym; __traits(allMembers, mixin("std.string")))
{
pragma(msg, sym.stringof);
}
```

Then you would have to check if `sym` is a template or function 
or something else.


Re: A look inside "filter" function defintion

2022-08-02 Thread frame via Digitalmars-d-learn

On Tuesday, 2 August 2022 at 14:58:52 UTC, pascal111 wrote:


Maybe this helps:

A template can be seen as a static struct too, so you can 
access its members with the scope operator "." and if there is 
only one member of the same name as the template ifself, the 
compiler auto completes it to this member.




I guess you mean if we will understand the templates concept as 
a static struct that the template is like the struct or - 
"records" in Pascal - that preserve its members values each 
time of calling through the runtime because they are "static". 
Isn't like that or what do you mean?


I don't know anything about Pascal - I can only say that the 
template scope can be seen like that from a logical point of view.


A function defined in a template is a static member of that 
template but not necessarily static context in runtime. It 
depends on the usage and scope.


But most library functions in Phobos are very simple like that 
and you have just to know that most functions are templates. They 
just may not require template arguments to be supplied and others 
do.




Re: A look inside "filter" function defintion

2022-08-02 Thread frame via Digitalmars-d-learn

On Tuesday, 2 August 2022 at 12:39:41 UTC, pascal111 wrote:

Instantiation seems some complicated to me. I read "If a 
template contains members whose name is the same as the 
template identifier then these members are assumed to be 
referred to in a template instantiation:" in the provided link, 
but I'm still stuck. Do you have a down-to-earth example for 
beginners to understand this concept?


There are obvious examples direct below.

Where do you get stuck?

Maybe this helps:

A template can be seen as a static struct too, so you can access 
its members with the scope operator "." and if there is only one 
member of the same name as the template ifself, the compiler auto 
completes it to this member.


You could always write out 
`name!(someTemplateArg).name(someRuntimeArg)`, we just prefer the 
short syntax `name!(someTemplateArg)(someRuntimeArg)` or 
`name(someRuntimeArg)` (if there are no template arguments or it 
could be auto deducted by the compiler). The last syntax shows 
that it can be called as a normal function while in fact it's a 
template.


Re: A look inside "filter" function defintion

2022-08-01 Thread frame via Digitalmars-d-learn

On Monday, 1 August 2022 at 23:35:13 UTC, pascal111 wrote:
This is the definition of "filter" function, and I think it 
called itself within its definition. I'm guessing how it works?


It's a template that defines the function called "Eponymous 
Templates":

https://dlang.org/spec/template.html#implicit_template_properties

A template generates code, it cannot be called, only instantiated.

The common syntax is just a shortcut for using it. Otherwise you 
would need to write `filter!(a => a > 0).filter([1, -1, 2, 0, 
-3])`. Like UFCS, some magic the compiler does for you.


Re: never seed this kind problem with localtime_r

2022-08-01 Thread frame via Digitalmars-d-learn

On Monday, 1 August 2022 at 13:31:15 UTC, test123 wrote:


please help me give any suggestion how to handle this problem.


errno = ?


Re: Breaking ";" rule with lambda functions

2022-08-01 Thread frame via Digitalmars-d-learn

On Monday, 1 August 2022 at 14:15:31 UTC, pascal111 wrote:
We all know the strange syntax of lambda function within filter 
algorithm like "auto r = chain(a, b).filter!(a => a > 0);". My 
note is, don't we break D rules by leaving ";" after lambda 
function syntax?!


Many of D rules are taken from C, we know that, so a general 
basic rule is to put ";" after each statement, so the previous 
statement of filter should be "auto r = chain(a, b).filter!(a 
=> a > 0;);"? Why D leaves ";" in this case?


In C ";" is a termination character, in D is more like to 
separate statements.


The lexer wouldn't need ";" for most cases like JavaScript and 
the expression syntax without ";" is better to read anyway.


However, the common settlement is to require a ";" where it makes 
logical sense and where it's still needed for the lexer. So we 
have this.


Re: Combining JSON arrays into a single JSON array -- better way than this?

2022-08-01 Thread frame via Digitalmars-d-learn

On Monday, 1 August 2022 at 09:01:35 UTC, ikelaiah wrote:


Based in your suggestion, the snippet is now more brief.


While your string attempt wasn't that bad, because loading all in 
memory while not necessary is wasted memory if you have large 
files to process. I would just process each file and write it to 
the file directly but it always depends on the intended purpose.


Re: Combining JSON arrays into a single JSON array -- better way than this?

2022-07-31 Thread frame via Digitalmars-d-learn

On Monday, 1 August 2022 at 04:24:41 UTC, ikelaiah wrote:

Hi,

I've written a cli tool to merge JSON files (containing JSON 
array) in the current folder as a single JSON file.


My algorithm:

1. Create a string to store the output JSON array as a string,
2. read each file
3. read each object in JSON array from input file
4. append the string representation of each JSON object in a 
string

5. Parse the result string as JSON
6. Save string representation of point 6 above.


If the JSON files are already parsed, why you stringify and 
reparse it? The assign operator of JSONValue allows it to use it 
as associative or plain array (JSON object / JSON array). Each 
member of such an array is of the same type: JSONValue. So to 
merge an array into another, you can simply iterate over its 
members and assign it into to a target array. To initialize as 
such just use `jsonResult.array = [];`


A plain array should be also mergeable via `jsonResult.array ~= 
j.array` (if `j` really is an array, you need to check the type 
first)


Re: Interfacing with user-supplied binary or obj file

2022-07-31 Thread frame via Digitalmars-d-learn

On Sunday, 31 July 2022 at 10:55:58 UTC, TheZipCreator wrote:
So I'm making an interpreter for my custom scripting language 
and I want to allow users to write libraries in languages other 
than said scripting language (for efficiency). For example, you 
should be able to write a mathematics library in D, compile it, 
then write a simple wrapper in my language and then be able to 
import it to your script to use (similar to a lot of Python 
libraries). So how exactly could I do this without requiring to 
user to recompile the interpreter every time they want to use a 
new library? Is there some way I could dynamically link in 
compiled .obj files?


Dynamically linking .obj files is basically wrapping all together 
to a shared library, loaded at runtime. So you need an interface 
that interops with your script language that must provide options 
to exchange input/output, registering functions that are callable 
from your script while your library is loaded and such stuff. The 
final logic is up to you.




Re: Obsecure problem 1

2022-07-30 Thread frame via Digitalmars-d-learn

On Saturday, 30 July 2022 at 23:40:44 UTC, pascal111 wrote:

Provide me a free solution better than code::blocks with 
available gdc compiler I found.



SDB@79


I don't know if's "better" but there is Visual Studio Code and 
IntelliJ IDEA for example.


Yeah ctrl+v doesn't work on XTERM, the middle mouse button 
should. I found this in the wild:


is super weird but in xterm you can copy just by selecting the 
text, the text is going to get copied to xwindows clipboard not 
to gnome one so ctrl+v or menus are not going to work for 
pasting you need to use the middle button of the mouse and in 
some windows shift+insert uses to work too.


so: select the text in the terminal keep it open go to any text 
editor or the browser and press the middle button to paste


if you are on a mac you can simulate the middle button pressing 
the touchpad with 3 fingers and if you have a 2 buttons mouse 
you can simulate the middle one pressing both at the same time.


A probably more sane option would be to configure codeblocks to 
use gnome-terminal instead of xterm, in settings -> environment 
-> general settings you can change it but it seems to close as 
soon as you try to launch the app


If that doesn't work you have to try another keyboard layout or 
such configuration or bind the function to another key if your 
middle mouse button is not present or is not recognized properly.


Re: Obsecure problem 1

2022-07-30 Thread frame via Digitalmars-d-learn

On Saturday, 30 July 2022 at 22:13:55 UTC, pascal111 wrote:

Because copying the running window contents is not allowed, I 
couldn't do it in Code::Blocks.


Not allowed? o.O

Did you try to select the text and insert it via middle mouse 
button in another window? Those terminals usually copy the text 
by selection automatically.





Re: Obsecure problem 1

2022-07-30 Thread frame via Digitalmars-d-learn

On Saturday, 30 July 2022 at 21:24:50 UTC, pascal111 wrote:
I've typed a code to enjoy with my library "dcollect", and 
found non-understandable error:

...


Running screen says:

https://i.postimg.cc/G3YyCmbF/Screenshot-from-2022-07-30-23-23-59.png


Why you don't copy the output instead?

A range violation is the safe error (if bound checking enabled) 
that is thrown if you access an index of a range or array that is 
out of bounds. You may try to access an index that is larger than 
elements in the array.





Re: Some user-made C functions and their D equivalents

2022-07-30 Thread frame via Digitalmars-d-learn

On Saturday, 30 July 2022 at 17:55:02 UTC, pascal111 wrote:


I don't understand much the posting details of this forum.



https://forum.dlang.org/help#about


It's simple: if you want to format/style your posts rather then 
just using plain text, enable the Markdown option. It's similar 
to Github-formatting.


Otherwise don't, because some tokens trigger a format where it 
makes no sense. To avoid that, just post in plain text mode by 
unchecking the option and make use of the preview option too.





Re: Some user-made C functions and their D equivalents

2022-07-28 Thread frame via Digitalmars-d-learn

On Thursday, 28 July 2022 at 20:20:27 UTC, pascal111 wrote:

I retyped again some function of C library I made before, but 
with D code:


It's a start but you need to learn.

- these functions can run into UB if you compile it without bound 
checking enabled


- when working with arrays or ranges it's better to use unsigned 
integers or just use `size_t` which represents unsigned integer 
for 32 or 64 bit. This avoids negative values and enables the 
maxmium value which can be provided on the plattform to access 
the highest element in the array.


- It's sure advanced topic but you should start to check your 
input from the beginning. Try what happens if you apply negative 
numbers or invalid offsets ;-)


I don't know which client you are using but please have an eye on 
proper format of your posts - see the "Markdown formatting" or 
disable the Markdown option below your input.


https://forum.dlang.org/help#about




Re: Some user-made C functions and their D equivalents

2022-07-28 Thread frame via Digitalmars-d-learn

On Thursday, 28 July 2022 at 16:45:55 UTC, pascal111 wrote:

Aha! "In theory, someone could inject bad code", you admit my 
theory.


The code would need to work and pass merge tests too. The merge 
reason must match in review. If someone fixes a task and 
additionally adds 100 LOC some should, will ask what this is 
about.


It's a extrem unlikely scenario. You may heard of linux kernel 
source that contains code that no one exactly knows about. But 
this some kind of bait. It's old code, reviewed years ago, not 
needed anymore but not knowing to be harmful. Completely 
different.


Anyway, code old or new may be harmful if it allows UB (undefined 
behaviour) and that is what hackers primarily use, not secret 
backdoors. This is why it's important to write CORRECT software 
that doesn't allow and cannot fall in a state of UB.


Re: Some user-made C functions and their D equivalents

2022-07-28 Thread frame via Digitalmars-d-learn

On Thursday, 28 July 2022 at 16:17:16 UTC, pascal111 wrote:

My friend, there is a wide deep secret world for hackers. We 
have no any idea about that world. Look, there is nothing 
called a 100% fact in our world. Believe me, what we see in 
software is just what "THEY" want us to see.


I think you have no idea how some processes work.

We have cryptographic digest methods to verify source code and 
final builds. In theory, someone could inject bad code if nobody 
would review it properly of course. But especially for compilers 
such code would be detected soon and no insane person in such 
projects would just merge code without reviewing it.


That applies for open source - not if you just download a 
compiled binary from a ftp server in the open web of course :D


Re: Some user-made C functions and their D equivalents

2022-07-28 Thread frame via Digitalmars-d-learn

On Thursday, 28 July 2022 at 14:57:36 UTC, pascal111 wrote:

well between US and some other countries like "Russia", and 
they are using US products like C compilers, so with some way 
we have a doubt that US developed compilers with a way to 
accept kind of messages or something like that, so my comment 
has no meaning to the compiler except if I knew the secret 
patterns or I do it accidentally.


Wait. You mean asterisks in comments may trigger some secret 
backdoor function in C-compilers? Come on :D


Re: Particular exceptions names

2022-07-27 Thread frame via Digitalmars-d-learn

On Tuesday, 26 July 2022 at 23:43:59 UTC, pascal111 wrote:
In next example code, it used user-made exception, but what if 
I'm looking for a particular exception? from where can I get 
particular exception to arise it?


There is no mechanism to find a particular exceptions in D. You 
have simple to know which exception can be thrown by studying the 
documentation or source code.


If you just want to give the user an information which exception 
was thrown in run time, use typeid:


```d
try { ... }
catch(Exception e) {
writefln("%s was thrown", typeid(e));
}
```



Re: Background thread, async and GUI (dlangui)

2022-07-21 Thread frame via Digitalmars-d-learn

On Thursday, 21 July 2022 at 13:27:49 UTC, Bagomot wrote:
I had this question: how can I get the value from the `task`, 
like how I can get from the `spawnLinked`(`ownerTid.send` and 
`receive`)?


I'm using a `taskPool` through `arr.parallel`, but it became 
necessary to collect the progress from all tasks into one 
variable.


In this case, I can't use `spawnLinked` because the worker is 
mutable, I get the "Aliases to mutable thread-local data not 
allowed" error.



The module creators want you to prevent from non-threadsafe 
actions. Merging into one variable can be such a non-threadsafe 
action, but it has not to be.


For example, if you have an array of fixed length or an already 
allocated one and each worker thread uses a fixed index to write 
into this result array variable then this operation may be 
threadsafe because each thread writes in different positions in 
the memory and the variable itself doesn't change.


If you are depending to overwrite an value instead, the operation 
is not considered threadsafe. For example just adding 1 + 2. 
Adding a value to an associative array is also not thread safe 
(it may re-allocate or re-index it's data)


We have basic tools to achieve this task. One is to lock actions 
with a synchronized block so each thread need to wait the other 
thread to complete before it can continue to execute the 
particular code position - and the other one are atomic 
operations that provide a better performance for simple 
operations because they are lock-free.


Why it's needed to know this? Because you may run into situations 
where have to deal with it, even the compiler keeps silent about.


https://dlang.org/spec/statement.html#synchronized-statement

```d
// parent:
int result;
// ...
// worker/parallel:
// each thread can only run this code if no other thread is 
currently running this code section => the OS is locking, this 
costs time

synchronized {
   result += 1;
}
```

https://dlang.org/phobos/core_atomic.html#.atomicOp

Usage of `atomaticOp` is simple, eg.

```d
// parent:
shared int result;
// ...
// worker/parallel:
// lock free, D-runtime ensures for a threadsafe operation
atomicOp!"+="(result, 1);
```

Looking on `atomicOp` you will see it want you to use a `shared` 
variable. And this is an easy way to make the compiler happy if 
you have mutual data. If you know what you are doing (not making 
thread unsafe-operations) then it's fine to just cast your data 
to `shared` that now can be sent or received.


```d
tid.send(cast(shared)mutualData);
```

A better approach is always to avoid such things completely and 
design your workflow to send and receive only simple data types 
(or immutable ones, which is also fine).


Also, I could make a new `Thread` for each task, but I think 
this is a bad idea. Also, I don't know how to send messages 
from child thread to parent thread.


The messagebox system from `std.concurrency` should also work 
with parallelism tools, meaning inside a worker thread use 
`std.concurrency.ownerTid` to get the parent Tid.


Looking for your task you might want to use a 
`WorkerLocalStorage` solution instead, look at the example:

https://dlang.org/phobos/std_parallelism.html#.TaskPool.WorkerLocalStorage



Re: std.signals: Error: static assert: "Aliases to mutable thread-local data not allowed."

2022-07-18 Thread frame via Digitalmars-d-learn

On Monday, 18 July 2022 at 10:22:16 UTC, Bagomot wrote:
Why can't I do it with `std.signals`? How the to do it if I 
can't create static event listeners?

```d
public void addEventListener(T : EventListener)(T listener) {
   connect(&listener.watch);
}
```


This error comes from somewhere else in your code by 
std.concurrency `spawn()`, `spawnLinked()` or `send()`.


Re: How to call a function from a dll created with d ?

2022-07-08 Thread frame via Digitalmars-d-learn

On Thursday, 7 July 2022 at 17:29:42 UTC, cc wrote:

Does importing dimedll into app.d properly NOT link in the 
functions that are exported to the DLL?  When I tried something 
similar with dmd, I had to create a .di file containing just 
stubs, otherwise it looked like it was ignoring the DLL and 
compiling in an additional copy of each fuction.


IMHO this is the expected behaviour since the compiler comes 
before the linker and `pragma(lib)` is a linker directive, so if 
dimedll.di is not present it looks for dimedll.d instead and just 
compiles the code.


The link to DLL is only present in the actual lib-file and only 
used by the linker.


The pitfall with DMD is that the automatic generated di-file is 
not usable as it contains a mixin that is meant for the DLL but 
not the application that links it, resulting in _ModuleInfoZ 
error while trying.


Re: How to call a function from a dll created with d ?

2022-07-04 Thread frame via Digitalmars-d-learn

On Sunday, 3 July 2022 at 16:48:52 UTC, frame wrote:

Only the -H switch or manual linker command generates a valid 
link to the DLL with DMD but then it's missing all the other 
library contents (also it needs `SimpleDllMain` or bails out 
linking errors to `_calloc` and Windows symbols) :\


`dmd -shared` / `dmd -H -shared` seems to work too (library 
contains link to DLL). Don't know why I had in mind that it would 
fail - maybe it did in the past.


However both DMD and LDC produces questionable header files for 
this task.


Re: How to call a function from a dll created with d ?

2022-07-03 Thread frame via Digitalmars-d-learn

On Sunday, 3 July 2022 at 12:54:45 UTC, kinke wrote:

On Sunday, 3 July 2022 at 08:15:38 UTC, frame wrote:

Are you sure?


100%, just try yourself.

Why would the symbol be defined in the executable? `dimedll.d` 
isn't compiled into the executable.


The code is using Phobos std.stdio.writeln templates, so the 
~20 KB for both exe and DLL are to be expected and IMO 
absolutely acceptable.


DMD's DLL support is waaay behind LDC's, especially once stuff 
gets more interesting than trivial examples.


Yeah, I tried LDC and there are differences:

The library file generated by LDC contains the link to the DLL.
The library file generated by DMD is missing that link.

So linking the DMD library would embed the symbol from the 
library - that was my confusion with your example.


Only the -H switch or manual linker command generates a valid 
link to the DLL with DMD but then it's missing all the other 
library contents (also it needs `SimpleDllMain` or bails out 
linking errors to `_calloc` and Windows symbols) :\


Also the -H switch doesn't work correctly. Without supplying 
-L/DLL flag too, I get link error:

```
1561: entry point must be defined
```


Re: How to call a function from a dll created with d ?

2022-07-03 Thread frame via Digitalmars-d-learn

On Saturday, 2 July 2022 at 20:43:41 UTC, Vinod KC wrote:


But I got this error message.
dime.obj : error LNK2001: unresolved external symbol 
__D7dimedll12__ModuleInfoZ

dime.exe : fatal error LNK1120: 1 unresolved externals
Error: linker exited with status 1120


I tried the -H switch. You can't rely on that. I comment the 
lines that shouldn't be there - then it should work:


dimedll.di
```d
// D import file generated from 'dimedll.d'
module dimedll;
// import core.sys.windows.dll;
// import std.stdio;
// mixin SimpleDllMain!();
export void testFunc();
```

dimedll.d:
```d
module dimedll;

import core.sys.windows.dll;
import std.stdio;

mixin SimpleDllMain;

export void testFunc() {
writeln("This is from dll");
}
```

app.d:
```d
module app;
import dimedll;

import std.stdio;
import std.stdio : log = writeln;

pragma(lib, "dimedll.lib");

void main() {   
   log("Lets build our own ime");
   testFunc();  
}
```

You should be able to change contents in the DLL and run the 
executable wihtout re-compiling (the library file should be round 
~2kB).


PS: ddemangle just waits for your input. You copy in the mangled 
symbol like `__D7dimedll12__ModuleInfoZ` and press enter ;-)


Re: How to call a function from a dll created with d ?

2022-07-03 Thread frame via Digitalmars-d-learn

On Saturday, 2 July 2022 at 14:06:03 UTC, kinke wrote:

With LDC, this is sufficient for this trivial example:

```d
module dimedll;

export void testFunc() { // export only needed when compiling 
with `-fvisibility=hidden`

import std.stdio;
writeln("This is from dll");
}
```

`ldc2 -shared dimedll.d` generates import lib + DLL.

```d
import dimedll : testFunc;

pragma(lib, "dimedll");

void main() {
import std.stdio;
writeln("Lets build our own ime");
testFunc();
}
```

`ldc2 -link-defaultlib-shared dime.d` generates the .exe and 
makes it share the druntime/Phobos DLLs with `dimedll.dll`. 
(More complex cases might need `-dllimport=all`).


```
C:\temp\dllTest>dime
Lets build our own ime
This is from dll

C:\temp\dllTest>dir
…
07/02/2022  03:54 PM   155 dime.d
07/02/2022  03:57 PM18,432 dime.exe
07/02/2022  03:57 PM19,679 dime.obj
07/02/2022  03:56 PM   162 dimedll.d
07/02/2022  03:57 PM20,480 dimedll.dll
07/02/2022  03:57 PM 7,534 dimedll.exp
07/02/2022  03:56 PM13,036 dimedll.lib
07/02/2022  03:57 PM21,233 dimedll.obj
```

On Posix, the only difference is that one would have to link 
`libdimedll.{so,dylib}` explicitly via `-L-ldimedll` instead of 
the `pragma(lib)`.



This is from dll


Are you sure? You import `testFunc` as normal import, the 
compiler ignores `pragma(lib)` - that's only for the linker which 
will ignore it too since the symbol is already in your 
executable. If you can run your exectuable without dimedll.dll 
present, then the function is **not** statically linked in.


A static linked function should generate a very small lib-file 
and yours look too big to me.


I don't know about LDC but with DMD I struggle with static linked 
DLLs because the library generated does not link to the DLL. To 
get right results, I need to pass the linker flag -`-L=/IMPLIB` 
(or `-L=/DLL` for 64bit) to generate a lib-file that is really 
linked to the DLL later.


Re: How to use templates in a separate library?

2022-06-24 Thread frame via Digitalmars-d-learn

On Thursday, 23 June 2022 at 23:50:42 UTC, monkyyy wrote:

On Thursday, 23 June 2022 at 08:12:32 UTC, CrazyMan wrote:

linking


make sure you use the -i flag when compiling


But note, that would be the opposite of using a library.


Re: Null terminated character

2022-06-23 Thread frame via Digitalmars-d-learn

On Thursday, 23 June 2022 at 17:27:51 UTC, frame wrote:

On Thursday, 23 June 2022 at 16:16:26 UTC, vc wrote:
I've try this '\0'*10 and didn't work, i want the results be 
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00


One way:

```d
import std.range;

repeat("\0", 10).join("");
```


If you just need an array:

```d
char[] n;
n.length = 10;
n[] = '\0';
```


Re: Null terminated character

2022-06-23 Thread frame via Digitalmars-d-learn

On Thursday, 23 June 2022 at 16:16:26 UTC, vc wrote:
I've try this '\0'*10 and didn't work, i want the results be 
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00


One way:

```d
import std.range;

repeat("\0", 10).join("");
```


Re: How to use templates in a separate library?

2022-06-23 Thread frame via Digitalmars-d-learn

On Thursday, 23 June 2022 at 08:12:32 UTC, CrazyMan wrote:

I have a separate library and some template interface in it

```d
interface IFoo(T)
{
 void setValue(const(T) value);
}
```

But when using it in the main program, it throws a linking 
error. I found that you can make a sourceLibrary that copies 
the code instead of creating a binary. But with it, I also get 
a linking error, and at the same time it is no longer 
associated with my interface, but with a third-party dependency 
(bindbc.opengl)


What can I do to fix this?


This is insufficient information to help you.

- Separate library could mean multiple things: a compiler 
library, a static linked binary, a SO/DLL binary.


- What error is thrown?

- Are you using `extern` declarations?

For a successful build the linker needs to get all symbols from 
any referenced source. The template isn't an actual symbol, it's 
just a information for the compiler to generate one. It says 
nothing about the symbol will be really generated or not. Also 
the linker needs to know if a library has to be used.


Re: getSymbolsByUDA in constructor/member functions

2022-06-16 Thread frame via Digitalmars-d-learn

On Thursday, 16 June 2022 at 09:29:36 UTC, Arafel wrote:

Classes can have static members just as structs, so I don't 
think you always need an instance for a class either.


Well, ok.

So if you call `getMember` from a member function, it adds the 
hidden `this` reference, and this has subtle consequences later 
on, even if `this.C` is practically just an alias for `C`.


I still think this is a bug in `getMember`, although perhaps 
not as obvious as I first thought.


Maybe you are right. I also don't see why the `this` reference 
should be there in the static call.


But it looks like a compiler bug since the output of 
`getSymbolsByUDA` is just an alias sequence and nothing should 
happen before consuming it?


This works fine too:

```d
class C
{
@E int a;

void foo()
{
alias seq = getSymbolsByUDA!(C, E);
static foreach (i; 0 .. seq.length)
{
pragma(msg, hasUDA!(seq[i], E));
}
}
}
```


Re: getSymbolsByUDA in constructor/member functions

2022-06-16 Thread frame via Digitalmars-d-learn

On Thursday, 16 June 2022 at 08:23:20 UTC, Arafel wrote:

As you can see, it's `getMember` who is returning a reference 
to the `this` instance. In my view, this is a bug according the 
documentation and examples [1]. It might be that classes behave 
differently, but then it should be documented.




In fact, it shouldn't work at all and you'd need to instantiate 
Def: `getMember` should fail because `x` and `y` are not static.


This is not true. `getMember` can return the symbol to the 
instance or the type/alias, depending if you pass `this` or 
`Def`. The last is static.


It makes no sense to use the attribute from a class without an 
instance.





Re: getSymbolsByUDA in constructor/member functions

2022-06-16 Thread frame via Digitalmars-d-learn

On Wednesday, 15 June 2022 at 12:26:40 UTC, cc wrote:


Why doesn't this work?  There is nothing in the foreach body.

```d
alias ALL = getSymbolsByUDA!(Def, XML);
pragma(msg, ALL.stringof);
```
reports `tuple(this.x, this.y)`.  Why is `this.` added?


I can only answer this partially, I guess `this` is just added 
because `getSymbolsByUDA` want an instance but `@XML` is only 
seen as a type. As instance, you need to write `@XML()` instead:


```d
class XML {
static opCall() {
return new XML();
}
}

class Def {
@XML() {
int x;
int y;
}
int z;

this() {
static foreach (sym; getSymbolsByUDA!(Def, XML)) {
}
}
}
```


Re: Comparing Exceptions and Errors

2022-06-07 Thread frame via Digitalmars-d-learn
On Tuesday, 7 June 2022 at 18:37:13 UTC, Steven Schveighoffer 
wrote:




My very common use of `scope(failure)` for my DB code:

```d
conn.exec("START TRANSACTION");
scope(success) conn.exec("COMMIT");
scope(failure) conn.exec("ROLLBACK");
```

This is hard to encapsulate into a type, as dtors only hook 
`scope(exit)` essentially.


-Steve


That's fine as the Throwable is still thrown but since 
`scope(failure)` acts as like catch-block, people may use it as 
replacement if there is something more to do.


I personally like the clean, short syntax when I don't care about 
the actual exception or if I know the called function has already 
handled the exception and just rethrows it:


```d
bool fun() {
 scope(failure) {
 // do something
 return false;
 }

 badCode();
 return true;
}
```

I know this is bad as I'm capturing a possible error here - but 
this is what an unexperienced coder would do, because it works. 
The better approach would be to use `scope(exception)`  (not 
typed, just as keyword) that allows to act only on Exceptions so 
one cannot break Exception vs Error paradigma and this also 
clarifies that usage of `scope(failure)` is potentially dangerous 
if you return from it.


Anyway, I just put that here - maybe you mention it in your blog.





Re: Comparing Exceptions and Errors

2022-06-07 Thread frame via Digitalmars-d-learn
On Friday, 3 June 2022 at 23:40:50 UTC, Steven Schveighoffer 
wrote:
During the last beerconf, I wrote a short blog post about how 
`Error` and `Exception` are different, and why you should never 
continue after catching `Error`s.


I know the thematics but I still wonder why we only have 
`scope(failure)` then? Anywhere where you will use this shiny 
thing with a return statement will also catch any error that have 
occurred. `scope(exit)` doesn't allow return statements, thus the 
only properly clean design would be an additional 
`scope(exception)` guard.


Re: Execute the Shell command and continue executing the algorithm

2022-05-31 Thread frame via Digitalmars-d-learn

On Monday, 30 May 2022 at 11:18:42 UTC, Alexander Zhirov wrote:


if (here is my condition termination of the program)


OT: Wouldn't it be great to have ArnoldC support? ;-)


Re: Compiler switch for integer comparison/promotion to catch a simple error

2022-05-30 Thread frame via Digitalmars-d-learn

On Monday, 30 May 2022 at 13:15:12 UTC, bauss wrote:


Good luck convincing Walter that this is a mistake :)


Well, I'm not talking about this is a mistake, just a C-thing I 
think. I wouldn't even ask him about that since it's in the spec.


If I could I would just clone a DMD build, disable output of the 
binary and just add flags to analyze this and other things to 
check wanted by the community.


Just a tool to check for additional bugs running before release - 
that of course would produce also false positives and should not 
be in the official compiler. But I'm far too unexperienced to 
understand the compiler and implement this - I wonder if anyone 
else ever had this idea?


Compiler switch for integer comparison/promotion to catch a simple error

2022-05-28 Thread frame via Digitalmars-d-learn

Is there a compiler switch to catch this kind of error?

```d
ulong v = 1;
writeln(v > -1);
```

IMHO the compiler should bail a warning if it sees a logic 
comparison between signed and unsigned / different integer sizes. 
There is 50% chance that a implicit conversion was not intended.


Re: Error: undefined symbol: _WinMain@16 When try compile no console

2022-05-26 Thread frame via Digitalmars-d-learn

On Thursday, 26 May 2022 at 16:56:49 UTC, Marcone wrote:

On Friday, 20 May 2022 at 13:16:00 UTC, frame wrote:

On Thursday, 19 May 2022 at 20:20:49 UTC, Marcone wrote:


I tried compiling now on x64 without console using 
-L/SUBSYSTEM:windows user32.lib -L/entry:mainCRTStartup -m64 
and it doesn't work. It compiles, but the program does not run 
afterwards. I also tried to add -m32omf But in this case the 
compilation error. How to solve this?


There is no support for OMF for x64, 64bit build is always 
MS-COFF.


If you specify -m64 you will generate x64 MS-COFF files.
If you specify -m32mscoff you will generate x86 32bit MS-COFF 
files.

If you specify -m32omf you will generate x86 32bit OMF files.

Maybe you need to clear your object files (if any) for a clean 
build.


If you tell the linker to entry on `mainCRTStartup`, it is 
expected to use that function from a C-runtime linked. As the 
compiler is free to select a library, this is the possible error 
source. Try different options for `-mscrtlib=libname` switch.


What do you mean by not running? Does it return an error code? 
(please start it in some debugger)


Re: Tracing/Profiling D Applications

2022-05-25 Thread frame via Digitalmars-d-learn
On Wednesday, 25 May 2022 at 21:35:07 UTC, Christian Köstlin 
wrote:

Is there also a way to get the "real"

threadid?


I'm using that functions inside threads:

core.sys.windows.winbase.GetCurrentThreadId on Windows
core.sys.posix.pthread.pthread_self on Unix (implied pthreads are 
used)





Re: Cannot check function address

2022-05-25 Thread frame via Digitalmars-d-learn
On Wednesday, 25 May 2022 at 14:09:31 UTC, Steven Schveighoffer 
wrote:


Yes, he acknowledged that too much was stripped. I also 
verified similar code works.


But the real problem was something else. He is saying in this 
message "why doesn't the compiler recognize that in comparing a 
function to null, I really wanted to compare a function 
*pointer* to null", but I don't see how the compiler can make 
that leap.


Often times, I wish the compiler could just read what I was 
thinking when I wrote the code, so it could give me 
thought-contextual errors but alas, it can't.


-Steve


The real problem was that I was locking my mind that the `fun` 
symbol was unique. In fact it was not. There was another code 
version where the `fun` symbol was declared as exported function 
and some import did read that code. My code was not affected from 
this bug since the call syntax for function and function pointer 
was the same. And I honestly never noticed that the compiler may 
says 'function' or 'function pointer'. It was always the same to 
me.


I should have test it with `__traits(getLocation)` before.


Re: Cannot check function address

2022-05-24 Thread frame via Digitalmars-d-learn
On Wednesday, 25 May 2022 at 05:56:28 UTC, Steven Schveighoffer 
wrote:


It's a case where the compiler can't divine what you were 
thinking when you wrote that code ;)


I see not in all cases but in mine. If the compiler sees the 
function isn't callable without arguments and it is inside an 
if-statement or `assert()` then it could at least suggest a 
pointer or ask: are you dumb? ;-)





Re: Cannot check function address

2022-05-24 Thread frame via Digitalmars-d-learn
On Wednesday, 25 May 2022 at 04:34:43 UTC, Steven Schveighoffer 
wrote:


Well, you can possibly work around the type system, but I don't 
know what the compiler thinks you have there.


This really bothers me and I put this test cases:


```d
static if (isSomeFunction!fun) pragma(msg,...)
static if (isFunctionPointer!fun) pragma(msg,...)
static if (isCallable!fun) pragma(msg,...)
```

It output mostly true except in one case where the compiler 
really sees a function, not a pointer.


Thanks, now the difference is clear to me, Adam was right. I 
guess I have forgotten some version-switch somewhere and it tries 
to compile none-suitable code which will be never used in runtime 
at this point.


This would have been more visible if the compiler just says: 
"function cannot be compared against null, only function 
pointer". That function vs function pointer is too subtle.




Re: Cannot check function address

2022-05-24 Thread frame via Digitalmars-d-learn
On Wednesday, 25 May 2022 at 03:41:17 UTC, Steven Schveighoffer 
wrote:


This is a compiler bug, at least I think so. Since the compiler 
is misbehaving, it's not clear how to make it behave.


-Steve


Well, ok, it's not my top priority and dustmite seems to run 
better on Unix - which I need to port anyway some time but not 
now.


But it must be possible to check if the function pointer is valid 
in Assembler? But I'm not familiar with asm to do it correctly - 
I would be very appreciative if someone could post an example how 
to do it in D.


So far, thank you for your time.


Re: Cannot check function address

2022-05-24 Thread frame via Digitalmars-d-learn
On Wednesday, 25 May 2022 at 02:42:26 UTC, Steven Schveighoffer 
wrote:


Just to be pedantic, you tried that call in the *exact place* 
the assert is failing to compile? D can be weird/surprising 
about name lookups.


Yes, of course ;-)



try:

pragma(msg, typeof(fun));


Outputs:
```
extern (C) void function(...)
```



If I do:

```d
extern(C) void foo(string) {}

pragma(msg, typeof(foo));
pragma(msg, typeof(&foo));
```

I get:

extern (C) void(string param)
extern (C) void function(string param)

The first is a function (yes, they have a type), and the latter 
is a function pointer.


But the compiler would complain if I call it as a type? And how 
could it call it later without an address to it - this works.



D should never call a function pointer without parentheses.


I'm very good in finding weird bugs ;-) Unfortunately, I cannot 
make an example. I already tried some changes/simplifications but 
cannot reproduce it outside the project.


But how can I help the compiler to use it as correct type? On 
invocation with arguments all works fine, but checking if the 
pointer is not null fails. It not even works with an assignment. 
Could some `static if()` maybe help or some asm trick?


Re: Cannot check function address

2022-05-24 Thread frame via Digitalmars-d-learn

On Tuesday, 24 May 2022 at 22:18:44 UTC, Adam D Ruppe wrote:

There's a big difference between a function and a function 
pointer.


Could you please clarify in this context?

`Fun` is basically generated by code like that:
```d
extern (Windows) void* GetProcAddress(void*, const char*);
auto fn = cast(T)GetProcAddress(lib, mangledName.toStringz);
```

If it is a function, you get its address with the & operator. 
But if it is supposed to be a function pointer, something is 
wrong with the declaration...


I have no idea what the correct term is but the debugger says 
`fun` is:

(if that `assert()` is removed and it compiles):
```
Type: void function(...)*
Value: 0x  null
```

I can get some address with `&fun` but deferencing then fails:
```d
auto addr = &fun;
assert(*addr); // Error: expression `*addr` of type `extern (C) 
void(...)` does not have a boolean value

```


Re: Cannot check function address

2022-05-24 Thread frame via Digitalmars-d-learn
On Wednesday, 25 May 2022 at 01:23:56 UTC, Steven Schveighoffer 
wrote:


"of course" I have no idea what your real code looks like, 
unless you post the real code.


While I get the point of trying to slim down the example to 
something postable, a very common problem with this kind of 
self-trimming is that you end up trimming out the problematic 
code. Why? Because if you noticed the problematic code, you 
wouldn't be posting here, you would just fix it. This, in fact, 
happens to me frequently.


Now, it's also possible that there is an actual compiler bug 
here, it certainly seems like it could be, but a full 
(non-)working example would be useful.


I still highly recommend trying code like:

```d
import std.traits;
pragma(msg, fullyQualifiedName!fun);
```

inside the place where your assert is failing. To me, if it's 
using the expected symbol for `fun` (or whatever it's called), 
then it should print the definition you expect from the module 
you expect. If not, maybe there is a name conflict, and it's 
picking the wrong one? These problems can be tricky to find.


-Steve


Sorry, this was not affront, it was meant as my POV that you may 
have problems to get my problem because I have (as usually) 
forgot to make this more visible that some code was truncated.


I tried your suggestion, as replied to Adam - the symbol is 
unique and it shows that correct location. It's not different 
from the error message.


However, this error has nothing to do with `assert()`. In fact 
the compiler allows nothing than invocation or this error will be 
triggered. Even that fails:


```d
// same error:
auto test = cast(void*)fun;
```



Re: Cannot check function address

2022-05-24 Thread frame via Digitalmars-d-learn
On Tuesday, 24 May 2022 at 19:09:52 UTC, Steven Schveighoffer 
wrote:


This doesn't seem valid for module-level code, assert is an 
instruction, not a declaration.

...
Try `std.traits.fullyQualifiedName!fun` to see where it's 
coming from.


expected 5 got 0 suggests it is finding some other fun, as 
a.fun only takes a single parameter.


Of course this `assert()` is actually inside `static this()` and 
there is only one declaration. I just want to show that the used 
symbol and call is the same.


Also this is **working** code. I just put the `assert()` there to 
ensure the function isn't called by a race condition before it 
was loaded (module constructors often have cyclic dependency, so 
I cannot put this in a more clean way).


Those asserts() are set in:

module A: module constructor
module B: some function

To also anwser to Adam: no, this symbol is unique. The first line 
of the error says:


```
Error: function `a.fun(string param)` is not callable using 
argument types `()`.

```

**Note that I have changed the actual module name and signature, 
it has orginal 5 arguments and very long names.**


The point is, it shouldn't be called in this line anyway?


Cannot check function address

2022-05-24 Thread frame via Digitalmars-d-learn

I have a function slot that may be loaded via a shared library.
I want to check if that function has an address but compiler (DMD 
2.100, Windows) instead tries to invocate the function?


```d
// --- module a:
alias F = extern (C) void function(string param);
F fun = someLibLoad!F("name");

assert(fun !is null); // compiles (also works in runtime)

// --- module b:
import a;

// same code:
//
// error: missing argument for parameter #1: ... with 2.098.1 or
// error: too few arguments, expected `5`, got `0` ... with 2.100
assert(fun !is null);
```

Usually that works fine as shown in module A but for some reason 
not in module B.
Workaround ideas? I tried casting to void* or ptrdiff_t but the 
compiler always tries to call the function -.-


Re: Error: undefined symbol: _WinMain@16 When try compile no console

2022-05-20 Thread frame via Digitalmars-d-learn

On Thursday, 19 May 2022 at 20:20:49 UTC, Marcone wrote:


I am using a main() function.
I am compiling on Windows x86 32 bits.
I am using DMD 2.100.0
This error is only in version 2.100.0 of DMD.


Did you try 2.099 too? Because the default build mode for 32bit 
was changed to MS-COFF and it smells a litte bit that you have 
used OMF before. MS-COFF format inserts the reference to the 
C-runtime library automatically.


Try the -m32omf switch.




Re: Unexplainable behaviour with direct struct assignment.

2022-05-19 Thread frame via Digitalmars-d-learn

On Wednesday, 18 May 2022 at 21:49:14 UTC, HuskyNator wrote:

After updating to `DMD 2.100.0` & `DUB 1.29.0`, I still get 
this behavior.
Only when I use `dub run --b=debug` however (default for me). 
`dub run --b=release` does return what one would expect.


I'm still on 2098.1, Windows 10 and get this at 64bit only

```
9.18366e-40
50
nan
```

but no matter if debug build or not.


Re: What are (were) the most difficult parts of D?

2022-05-14 Thread frame via Digitalmars-d-learn

On Saturday, 14 May 2022 at 04:31:48 UTC, zjh wrote:


D forum should add a "`author delete`" function.
Likewise, each post could add something like `votes` , good 
posts will naturally `come out` and be collected together.

It's really convenient for beginners of `d`.

This way, the similar answer does not have to be repeated.


My thoughts - I also mentioned this in another thread. I think 
the main problem is that this forum is linked as news group too 
with custom client software and not everyone is using the web 
interface, so there is less interest to bring this up.


But I really wish the online forum would show newbies more 
activity by implementing topic specific categories or tags, so 
you could find them easier and feel more like "home". Every 
larger app with a news feed also has possibility to 
categorize/filter it.


Re: Template shenannigans with multiple datatypes

2022-05-13 Thread frame via Digitalmars-d-learn

On Friday, 13 May 2022 at 07:32:16 UTC, Chris Katko wrote:

This is a kinda "dynamic language" feature but it feels like 
this information is theoretically, knowable at static, 
compile-time. I know what the variable types will be at 
compile-time, but I don't know how to put them all in one class 
and reference them automatically.


Like `std.json.JSONValue` or `std.variant.Variant` you can also 
use a struct with a type flag and possible data types that fit 
for you. Boolean and Integer may share the same memory location 
via `union` for example. Or just use the built one `Variant` type.


In case you only store the pointers to the data, you just need 
`void*[]` and proper casting.





Re: Type Parameter Deduction

2022-05-10 Thread frame via Digitalmars-d-learn

On Tuesday, 10 May 2022 at 13:14:20 UTC, Salih Dincer wrote:


must satisfy the following constraint:


That is your type protection here, a constraint.

Alternatively you can put the constraint in a function and make 
it more verbose:


```d
bool isAllowedType(T)()
{
static assert(!is(T == bool), "Nope");
return true;
}

void fun(T = int)(T arg)
if(isAllowedType!T)
{
//..
}

fun(0);  // ok
fun(false);  // not allowed
```


Re: Parameters of overloaded templated function

2022-05-10 Thread frame via Digitalmars-d-learn

On Tuesday, 10 May 2022 at 12:12:13 UTC, Tejas wrote:

Using aliases as parameters doesn't work(and the DIP that 
wanted to have this behaviour was de facto rejected)


https://github.com/dlang/DIPs/blob/master/DIPs/other/DIP1023.md

But considering you're passing it as an argument, not a formal 
parameter, it should've worked... Idk what's happening there


I have break it down to a `static if` after that the compiler 
gets confused:

```d
static if(__traits(isTemplate, overload)) {
  // compiler knows it is a template but error is something about 
an aliased function in further processing

}
```

However, changing it to `isSomeFunction!overload` and just 
passing the type argument otherwise, compiles. Not very clean, 
though.







Re: Type Parameter Deduction

2022-05-10 Thread frame via Digitalmars-d-learn

On Tuesday, 10 May 2022 at 09:26:46 UTC, Salih Dincer wrote:

However, the compiler catches other errors! How can I solve 
this problem?


Thanks...

SDB@79


What about something like this?

```d
auto inclusiveRange(T = int)(T f = T(0), T l = T(0), T s = T(1))
if(!is(T == bool))
{
//...
}
```


Re: Parameters of overloaded templated function

2022-05-10 Thread frame via Digitalmars-d-learn

On Tuesday, 10 May 2022 at 11:26:44 UTC, frame wrote:

On Tuesday, 10 May 2022 at 03:18:14 UTC, Tejas wrote:


Can you try


Makes no difference.


OK, I tried it in separate test and works. Weird, I already tried 
that before, there must be something wrong with my other template.


Thanks


Re: Parameters of overloaded templated function

2022-05-10 Thread frame via Digitalmars-d-learn

On Tuesday, 10 May 2022 at 03:18:14 UTC, Tejas wrote:


Can you try


Makes no difference.




Parameters of overloaded templated function

2022-05-09 Thread frame via Digitalmars-d-learn
So `__traits(getOverloads)` returns also templated members and 
`__traits(isTemplate)` can select those members. Unfortunately, 
`Parameters!` does not work with the templated member. How can I 
pass a symbol of T or A... to `Parameters!` as desired type 
without instantiating the template?


```d
fun(T, A...)(T arg, string foo, int bar, A args); // some overload
```

Assuming T is just an `int`, I cannot apply this type. The 
compiler is forgetting the actual overload:


```d
template getParams(alias overload) {
  static if (__traits(isTemplate, overload)) {
alias typed = overload!int // error: fun(...) matches more 
than one template declaration

alias getParams = Parameters!typed;
  }
}
```


Re: How to use destroy and free.

2022-04-25 Thread frame via Digitalmars-d-learn

On Monday, 25 April 2022 at 02:07:50 UTC, Ali Çehreli wrote:

>  import core.memory: GC;
 GC.free(GC.addrOf(cast(void *)(i.ptr)));
That is wrong because you did not allocate that address 
yourself.


Hmm? The GC did allocate here(?)


On 4/24/22 17:26, Salih Dincer wrote:

>MEM.free(i.ptr);
>// You don't need to addrOf(cast(void*)i)


Wrong.



Good point about i.ptr but that free() does not or should not 
do anything because it is "memory not originally allocated by 
this garbage collector":


  https://dlang.org/phobos/core_memory.html#.GC.free

Well... maybe it was allocated by that garbage collector and 
may be it points to the beginning of an allocated block but we 
don't know that. I wouldn't call free() on an array's memory.


Ali


And if it was, the freeing must be done with `GC.addrOf` or it 
will fail with larger arrays.


You will need the GC address to free the block. That is what 
`__delete` actually does - which was patched back recently, 
reported by Adam: https://issues.dlang.org/show_bug.cgi?id=21550


Re: What is the difference between a static assert and a unit test?

2022-04-21 Thread frame via Digitalmars-d-learn

On Thursday, 21 April 2022 at 22:26:57 UTC, Alain De Vos wrote:
I don't know when to use a static assert and when to use a unit 
test ?


There is `assert()`, `static assert()` and `unittest`.

`static assert()` is used while compiling, to find errors or 
circumstances that can lead to errors in runtime or just show 
type incompatibilities.


`assert()` is used at runtime to allow some checks before 
processing data.  It is evaluated at runtime and removed from 
code in release mode. Except `assert(0)` which will always emit 
an `AssertError` and will be never removed.


`unittest` is a just block that will be only compiled/executed 
when the `-unittest` switch will be applied to compiler command 
line. That's it.




Re: Odd behaviour of std.range

2022-02-22 Thread frame via Digitalmars-d-learn

On Tuesday, 22 February 2022 at 17:33:18 UTC, H. S. Teoh wrote:
On Tue, Feb 22, 2022 at 05:25:18PM +, frame via 
Digitalmars-d-learn wrote:

On Tuesday, 22 February 2022 at 13:25:16 UTC, bauss wrote:

> Welcome to the world of auto decoding, D's million dollar 
> mistake.


Well, I think it's ok for strings but it shouldn't do it for 
simple arrays

[...]

In D, a string *is* an array. `string` is just an alias for
`immutable(char)[]`.


I know, but it's also a type that says "this data belongs 
together, characters will not change, it's finalized" and it 
makes sense that it can contain combined bytes for a code point. 
`char[]` is just an array to work with. It should be seen as a 
collection of single characters. If you want auto decoding, use a 
string instead.


Re: Odd behaviour of std.range

2022-02-22 Thread frame via Digitalmars-d-learn

On Tuesday, 22 February 2022 at 13:25:16 UTC, bauss wrote:

Welcome to the world of auto decoding, D's million dollar 
mistake.


Well, I think it's ok for strings but it shouldn't do it for 
simple arrays where it's intentional that I want to process the 
character and not a UTF-8 codepoint.


Thank you all.


Re: Odd behaviour of std.range

2022-02-22 Thread frame via Digitalmars-d-learn

On Tuesday, 22 February 2022 at 12:53:03 UTC, Adam D Ruppe wrote:

On Tuesday, 22 February 2022 at 12:48:21 UTC, frame wrote:

What am I missing here? Is this some UTF conversion issue?


`front` is a phobos function. Phobos treats char as special 
than all other arrays.


Ah, ok. It directly attaches `front` to the string, regardless of 
the function. That is the problem.



It was a naive design flaw that nobody has the courage to fix.


... or ask why you're doing range operations on a string in the 
first place and see if the behavior actually kinda makes sense 
for you.


Because I needed a similar function to `tail` that takes care of 
the length and even it's trivial to implement it by myself, I 
just thought it's better to use a function that is already there.





Odd behaviour of std.range

2022-02-22 Thread frame via Digitalmars-d-learn

What am I missing here? Is this some UTF conversion issue?

```d
string a;
char[] b;

pragma(msg, typeof(a.take(1).front)); // dchar
pragma(msg, typeof(b.take(1).front)); // dchar
```


Re: curl error msg

2022-02-20 Thread frame via Digitalmars-d-learn

On Saturday, 19 February 2022 at 13:12:32 UTC, MichaelBi wrote:
when running the example in the std.net.curl on my windows, got 
following msg:


std.net.curl.CurlException@std\net\curl.d(4239): Failed to load 
curl, tried "libcurl.dll", "curl.dll"


does it mean i don't have those dll files? thx.


A libcurl.dll comes with the installer. It can be found by your 
program if it's located in the same folder as the executable or 
if the %PATH% environment variable contains the directory where 
the installer puts the DLL in.


You may find this path in the environment variable but it has to 
match 32/64bit. If your 64bit program tries to load the 32bit 
variant it will fail to load.


It's likely that your %PATH% environment variable contains the 
32bit path (eg. for DMD `C:\install-dir\dmd2\windows\bin` but not 
the path to `\bin64`.


So you have to adjust the environment variable or copy the DLL 
from this path to your program executable.


Re: Offline D documentation/tutorial

2022-02-13 Thread frame via Digitalmars-d-learn

On Sunday, 13 February 2022 at 20:48:45 UTC, Jordi Sayol wrote:

El 13/2/22 a les 12:22, frame via Digitalmars-d-learn ha escrit:
On Sunday, 13 February 2022 at 00:17:26 UTC, rikki cattermole 
wrote:
There are some files available at 
https://d-apt.sourceforge.io/


It would also nice to have a up-to-date CHM version of 
https://github.com/a11e99z/DlangChm


Are there any compiled sources?



In <https://d-apt.sourceforge.io/> there are CHM, EPUB, MOBI 
and PDF up to date


That's not the same because phobos lib isn't included and not 
that visual compact than DlangChm.




Re: Offline D documentation/tutorial

2022-02-13 Thread frame via Digitalmars-d-learn
On Sunday, 13 February 2022 at 00:17:26 UTC, rikki cattermole 
wrote:

There are some files available at https://d-apt.sourceforge.io/


It would also nice to have a up-to-date CHM version of 
https://github.com/a11e99z/DlangChm


Are there any compiled sources?


Order of object fields

2022-01-27 Thread frame via Digitalmars-d-learn
Is the order of fields guaranteed returned by `.tupleof` and 
`__traits(getMember,...)`, can I rely on this? I know that are 
different things, I mean just per each use case if I have more 
functions that traverses through all fields. Thx.


Re: Linkage question

2022-01-24 Thread frame via Digitalmars-d-learn
On Monday, 24 January 2022 at 18:30:02 UTC, Stanislav Blinov 
wrote:


The difference is in how arguments are being passed, which you 
seem to have discovered already :)



Would like to know where the linkage format is defined, thx.


It should be here: https://dlang.org/spec/abi.html although 
IIRC it might not be 100% up to date.


Ah, yes. Thanks. Maybe I should read it more carefully =)

It claims that the D calling convention matches C. But it seems 
that the arguments are pushed in order whereas C does it in 
reverse order and the -218697648 value is indeed my 3rd string 
pointer.





Linkage question

2022-01-24 Thread frame via Digitalmars-d-learn
If I declare a function as extern(C) inside a DLL, I have also to 
cast the function pointer as extern(C) or it fails calling, eg.


```d
// --- my.dll
export extern (C) void log(int mode, string a, string b, string 
c) {

  /* stuff */
}

// --- main.d
alias T = extern (C) void function(int, string, string, string);
auto fnPtr = cast(T)GetProcAddress(/* stuff */);
```

I understand that the linkage must match but besides the name 
mangling, what's happen here? What is the difference if I remove 
the `extern (C)` part from the T alias?


Doing that supplies 2nd and 3rd paramter as fine pointers but the 
1st argument comes wrong (eg. 10 becomes -218697648) and the last 
argument is garbage too, so the D-linkage format is something 
different.


Would like to know where the linkage format is defined, thx.


Re: How to do same as 'nmap' command from within a D program?

2022-01-22 Thread frame via Digitalmars-d-learn
On Saturday, 22 January 2022 at 20:55:38 UTC, Daren Scot Wilson 
wrote:


I don't see any D std.* libraries that do this. Are there a Dub 
packages I should look at?


If you really want to this in D without any external app or OS 
API you could just ping all possible hosts, see which respond and 
then use `getHostByAddr()` to find the hostname.


Another more professional way is to query the ARP protocol, where 
you send a packet as broadcast to all interfaces in the network 
to find a MAC for a given IP - if any host responses with a MAC, 
the host is up.


You have to build the packet data for yourself, there are 
examples on the web. The socket to use is family:INET, type:RAW 
and protocol:ICMP for ping or RAW for ARP or anything that isn't 
listed in D.


As you can see, it's required to test every possible IP out 
(except for any other discovery protocols supported by your 
network/router). For this reason, any OS does this scan 
periodically and caches the result. On UNIX you can just directly 
read the file `/proc/net/arp`, no need to use nmap.





alias and __VERSION__ condition doesn't play well

2022-01-17 Thread frame via Digitalmars-d-learn

At the very top of my module I have this declaration:

```d
static if (__VERSION__ >= 2098)
{
alias Foo = TypeA;
}
else
{
alias Foo = TypeB;
}
```

No problem inside the module itself but this doesn't work when 
imported from another module:

Error: undefined identifier `Foo`

While this workaround works:

```d
template getAlias()
{
static if (__VERSION__ >= 2098)
{
alias getAlias = TypeA;
}
else
{
alias getAlias = TypeB;
}
}
alias Foo = getAlias!();
```

Is there a reason for that?


  1   2   3   4   >