Re: A little help with Ranges

2021-08-26 Thread Stefan Koch via Digitalmars-d-learn

On Friday, 27 August 2021 at 02:17:21 UTC, Merlin Diavova wrote:

On Friday, 27 August 2021 at 02:10:48 UTC, Stefan Koch wrote:
On Friday, 27 August 2021 at 01:51:42 UTC, Merlin Diavova 
wrote:

Hi all,

I'm Merlin, I'm just starting out in D and super excited.

My questions are:-

1. In a range pipeline how does one handle the event of a 
filter range returning empty?


2. How does one unwrap a single result from a range operation?


Look forward to your assistance!

Merlin


1. you don't have to handle it.
it just won't go.

2. `takeOne` put it into the search on the dlang site


Thanks for the quick response!

Took a look at takeOne and yep that's the ticket.

What I meant about the handling an empty filter is, what if I 
want to take an alternative route if the filter returns empty?


You check if it's by calling empty.
or do you want a default value? I am sure there is a convince 
function for that somewhere in phobos.


Re: A little help with Ranges

2021-08-26 Thread Stefan Koch via Digitalmars-d-learn

On Friday, 27 August 2021 at 01:51:42 UTC, Merlin Diavova wrote:

Hi all,

I'm Merlin, I'm just starting out in D and super excited.

My questions are:-

1. In a range pipeline how does one handle the event of a 
filter range returning empty?


2. How does one unwrap a single result from a range operation?


Look forward to your assistance!

Merlin


1. you don't have to handle it.
it just won't go.

2. `takeOne` put it into the search on the dlang site


Re: Looping over Template Types ... possible?

2021-08-14 Thread Stefan Koch via Digitalmars-d-learn
On Saturday, 14 August 2021 at 20:07:21 UTC, james.p.leblanc 
wrote:

Good Evening/Day,

Suppose I have a number of function templates that each take
two types, say S and T.

I would like to exercise my routines over the combinations
of types:

set of all S:  ( double[], float[], Complex!double[], 
Complex!float[])

set of all T:  ( double, float)

Is something along the line of the following sketch possible?

foreach( s in S){
   foreach( t in T){

  foo!(S,T)( T x, S y);
  biz!(S,T)( T x, S y);

   }
}

I have done some searching for hints about this, but I perhaps
my search terms are not very good.

All hint and pointers thankfully received.

Best Regards,
James


it is possible

look for `AliasSeq`
in `std.meta`

foreach(T; AliasSeq!(float, double))
{
  ...
}


Re: No compile time bounds checking for static arrays?

2021-08-11 Thread Stefan Koch via Digitalmars-d-learn

On Wednesday, 11 August 2021 at 06:29:40 UTC, Tejas wrote:

```d
import std;
void main()
{
int[40] staticA;
auto c = staticA[0..50];//mistake
}```
results in:

```d
core.exception.RangeError@onlineapp.d(5): Range violation

??:? _d_arrayboundsp [0x55db29a0b645]
./onlineapp.d:5 _Dmain [0x55db29a0ae8c]
```

Is there a way to make this check compile time?


Without modifying the compiler? No.
Please file an enhancement request on issues.dlang.org.
This particular example is an easy fix.


Re: D compiler equivilent of "gcc -E" for debug/view template instantiation(generated) code?

2021-07-30 Thread Stefan Koch via Digitalmars-d-learn

On Friday, 30 July 2021 at 09:30:13 UTC, Mike Parker wrote:

On Friday, 30 July 2021 at 08:38:24 UTC, dangbinghoo wrote:



but, where's these switch option documented? it seems it not 
appears in dmd --help or man dmd, or online document 
https://dlang.org/dmd-linux.html





That's what he meant by "hidden" switch. I don't know why it 
isn't documented, but it probably should be.


The reason why it's not documented is because we don't want 
people to rely on the format of the output.

I guess if we put that disclaimer in the docs we could ...


Re: __FILE__

2021-07-26 Thread Stefan Koch via Digitalmars-d-learn

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..
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.

On the other hand if you use x = __FILE__ it recognizes that as a 
special constant expression which can be put into the callsite 
directly.




Re: Performance issue with fiber

2021-07-24 Thread Stefan Koch via Digitalmars-d-learn

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




There is your problem.

auto scheduler = new FiberScheduler;


The Fiber scheduler will spawn a new fiber for every job.
It will not use a fiber pool. Spawning a new fiber is expensive 
because of the stack allocation for it.
Also if I recall correctly it will run single-threaded but I am 
not 100% sure on that.
Just have a look at the running processes ... if you just see one 
than you are single threaded.




Re: Are D classes proper reference types?

2021-06-24 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 24 June 2021 at 07:28:56 UTC, kinke wrote:
On Thursday, 24 June 2021 at 06:50:44 UTC, Ola Fosheim Grøstad 
wrote:

[...]


(I don't think I've ever seen one); with `scope c = new 
Object`, you can have the compiler allocate a class *instance* 
on the stack for you, but `c` is still a *ref*.


The dmd frontend uses them all the time to avoid allocation 
overhead for Visitors.




Re: How to profile compile times of a source code?

2021-01-30 Thread Stefan Koch via Digitalmars-d-learn

On Saturday, 30 January 2021 at 23:34:50 UTC, Stefan Koch wrote:


this special version of dmd will generate a trace file which 
can be read with the included printTraceHeader tool


you will want to take a look at the PhaseHist command which shows 
you the compiler phase that took the most time.


Alternative I recommend using callgrind to profile where dmd 
spents most of it's time.

For that to be useful you need a debug build of dmd though.




Re: How to profile compile times of a source code?

2021-01-30 Thread Stefan Koch via Digitalmars-d-learn

On Saturday, 30 January 2021 at 22:47:39 UTC, Ahmet Sait wrote:
I'm looking for ways to figure out what parts of the code slows 
down the compiler other than brute force trial.


Can I use -vtemplates switch for this?
Would -v (verbose) switch helpful in some way?
How would I know if my bottleneck is ctfe or templates?
How do the compiler devs approach this issue?

I'm interested in all kinds of tricks to the point of debugging 
the compiler itself although anything less complicated would be 
appreciated.


I have a way of getting the profile data your are after.
Get the dmd_tracing_20942 branch from 
https://github.com/UplinkCoder/dmd

Compile that version of dmd.
this special version of dmd will generate a trace file which can 
be read with the included printTraceHeader tool




Re: Where is pragma Declaration in the grammar?

2020-12-04 Thread Stefan Koch via Digitalmars-d-learn

On Saturday, 5 December 2020 at 02:59:58 UTC, Paul Backus wrote:

On Saturday, 5 December 2020 at 00:57:04 UTC, Stefan Koch wrote:

Hi,

today I've been dusting my SDC fork and implemented a 
rudimentary version of pragma(msg).


I could pragmaStatement

as in void f()
{
   pragma(msg, typeof(f));
}

but not a declaration as in
pragma(msg, typeof(f))
without a function body.


They're under Attribute:

https://dlang.org/spec/grammar.html#Attribute

The syntax tree for `pragma(msg, typeof(f))` in a declaration 
context would be:


DeclDef
  AttributeSpecifier
Attribute
  Pragma
pragma(msg, typeof(f))
DeclarationBlock
  DeclDef
;


The Decldef is not optional.
This is for pragmas like pragma mangle that affect symbols.


Where is pragma Declaration in the grammar?

2020-12-04 Thread Stefan Koch via Digitalmars-d-learn

Hi,

today I've been dusting my SDC fork and implemented a rudimentary 
version of pragma(msg).


I could pragmaStatement

as in void f()
{
   pragma(msg, typeof(f));
}

but not a declaration as in
pragma(msg, typeof(f))
without a function body.

there is a StaticAssert is in the grammar under declaration, 
pragma is not.


Maybe it's stated differently?

Any help is appreciated.

Cheers,

Stefan


Re: lambdas with types

2020-11-21 Thread Stefan Koch via Digitalmars-d-learn

On Friday, 20 November 2020 at 14:08:23 UTC, jmh530 wrote:
Doing something like below fails because I don't seem to be 
able to make a templated lambda that just takes types. Is the 
only way to do something similar to create a separate function 
to handle the condition, or is there some other way to do 
something with similar flexibility?


import std.stdio: writeln;
import std.meta: allSatisfy;

void foo(Args...)(Args args)
if (allSatisfy!(x => is(x == double), Args))
{
writeln("works");
}

void main() {
foo(1.0, 2.0);
}


with type functions this syntax should work.


Re: is type checking in D undecidable?

2020-10-22 Thread Stefan Koch via Digitalmars-d-learn
On Thursday, 22 October 2020 at 18:33:52 UTC, Ola Fosheim Grøstad 
wrote:


In general, it is hard to tell if a computation is long-running 
or unsolvable.


You could even say ... it's undecidable :)


Re: Deprecation in traits

2020-09-30 Thread Stefan Koch via Digitalmars-d-learn

On Wednesday, 30 September 2020 at 08:33:58 UTC, Frak wrote:
On Tuesday, 29 September 2020 at 18:25:03 UTC, Steven 
Schveighoffer wrote:

On 9/29/20 1:08 PM, Frak wrote:

[...]


Because it's probably coming from a constraint, you probably 
can't figure out the exact usage. What's more annoying is that 
likely it is a spurious warning. A lot of traits "try 
something", and then alias to false or true depending on what 
works. But it's not going to make a difference in your code.


It's one of the most annoying things in the library. If you 
see this warning coming from *your* code, then you should fix 
it. But it will tell you the location if that was the case, 
not std.traits.


-Steve


That's REALLY REALLY annoying! I'm spending LOT of time trying 
to figure out the exact point to fix in the code.


Any idea? dustmite?


You can give me access to the code and I can find it out for you.
That's the best I have.


__traits for checking if a type is dynamic array (slice)

2020-08-18 Thread Stefan Koch via Digitalmars-d-learn

https://forum.dlang.org/post/ptgud7$16f6$1...@digitalmars.com

On Monday, 26 November 2018 at 14:02:15 UTC, Andrei Alexandrescu 
wrote:

On 11/26/18 4:04 AM, Per Nordlöw wrote:

Why is there no

- __traits(isArray, T)

alongside

- __traits(isStaticArray, T) and
- __traits(isAssociativeArray, T)



Thanks for bringing this to my attention, Per.

The core idea is to have __traits "primitive and ugly" and 
std.traits "convenient and nice". From that viewpoint, if 
isArray can be implemented as a library feature using 
primitives provided by traits, there is no need for making it.



when dmd already has `ENUMTY.Tarray` alongside

- ENUMTY.Tsarray and
- ENUMTY.Taarray


Justifying the feature by means of a detail in the compiler 
implementation is definitely undesirable.



and std.traits already has a wrapper for this at

https://dlang.org/phobos/std_traits.html#isDynamicArray

?


If the wrapper works well, use it and move on.


Thanks,

Andrei


I am in disagreement.

The is expressions are complicated both for a developer and the 
compiler.


If one promotes a wrapper template that shows just that the way 
of expressing it is too complicated.


low level tools should be simple, because if they are not simple 
they can't be low-level.




Re: Forcing inline functions (again) - groan

2020-07-15 Thread Stefan Koch via Digitalmars-d-learn

On Wednesday, 15 July 2020 at 13:38:34 UTC, Cecil Ward wrote:

I recently noticed
pragma(inline, true)
which looks extremely useful. A couple of questions :

1. Is this cross-compiler compatible?

2. Can I declare a function in one module and have it _inlined_ 
in another module at the call site?


I’m looking to write functions that expand to approx one or 
even zero machine instructions and having the overhead of a 
function call would be disastrous; in some cases would make it 
pointless having the function due to the slowdown.


pragma inline will work for dmd.
and it used to fail if it couldn't inline.
Now it just generates a warning.
So with -w it will still fail.

Afaik other compilers cannot warn if the in-lining fails but I 
might be wrong.
And ldc/gdc should be able to inline most code which makes sense 
to inline.


Re: Should a parser type be a struct or class?

2020-06-17 Thread Stefan Koch via Digitalmars-d-learn

On Wednesday, 17 June 2020 at 11:50:27 UTC, Per Nordlöw wrote:
Should a range-compliant aggregate type realizing a parser be 
encoded as a struct or class? In dmd `Lexer` and `Parser` are 
both classes.


In general how should I reason about whether an aggregate type 
should be encoded as a struct or class?


I would say a struct.

Parser in dmd does even inherit from Lexer.
It seems to be a quirky design.

Especially for multi-threaded parsing you might want to have more 
control over memory layout than classes usually give you.


Re: Why is there no range iteration with index by the language?

2020-06-09 Thread Stefan Koch via Digitalmars-d-learn

On Tuesday, 9 June 2020 at 23:53:16 UTC, Q. Schroll wrote:
Is there any particular reason why std.range : enumerate is a 
thing and


[...]


I don't think there is any particular reason. Other than that 
might shadow an opApply.

And C++ iterators didn't have it.


Re: Fastest way to check using if identifier has already been defined, using static if or similar?

2020-06-04 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 4 June 2020 at 14:20:45 UTC, Q. Schroll wrote:

On Thursday, 4 June 2020 at 09:03:40 UTC, Simen Kjærås wrote:

string exists(string s) {
return "__traits(compiles, { mixin(\"alias _ = "~s~";\"); 
})";

}


Little nitpicking, but D has many forms of string literals. 
Escaping is hard to read especially without syntax 
highlighting. Escaping to me is an old hack C did we shouldn't 
really use.


string exists(string s) {
return `__traits(compiles, { mixin("alias _ = ` ~ s ~ 
`;"); })`;

}

The _ as a name, to me, proves that a __traits(freshName), that 
returns a string that is distinct from every symbol name 
visible from the point it's defined,  would be useful in these 
occasions. Because if someone used _ as an identifier in a 
context where the `exisits` function is used, it might fail.


Don't have a unique name facility now?
... I remember seeing one.
Could have been a mirage I guess.


Re: Fastest way to check using if identifier has already been defined, using static if or similar?

2020-06-03 Thread Stefan Koch via Digitalmars-d-learn

On Wednesday, 3 June 2020 at 09:39:34 UTC, Basile B. wrote:

On Wednesday, 3 June 2020 at 09:03:22 UTC, drathier wrote:

[...]


You can use this template:

  enum Exists(alias T) = is(typeof(T));

I don't know if there's a faster way bu this technic is used, 
notatbly in phobos, to workaroud issues of double declaration 
in `static foreach`


Please don't promote templates like this as long as they are not 
really zero-cost.

They don't add much to compile time granted.
But Barnacles.



Re: Compilation memory use

2020-05-04 Thread Stefan Koch via Digitalmars-d-learn

On Monday, 4 May 2020 at 17:00:21 UTC, Anonymouse wrote:
TL;DR: Is there a way to tell what module or other section of a 
codebase is eating memory when compiling?


I'm keeping track of compilation memory use using zsh `time` 
with some environmental variables. It typically looks like this.


```
$ time dub build -c dev
Performing "debug" build using /usr/bin/dmd for x86_64.
[...]
Linking...
To force a rebuild of up-to-date targets, run again with 
--force.
dub build -c dev   9.47s  user 1.53s system 105% cpu 10.438 
total

avg shared (code): 0 KB
avg unshared (data/stack): 0 KB
total (sum):   0 KB
max memory:4533 MB
page faults from disk: 1
other page faults: 1237356
```

So it tells me the maximum memory that was required to compile 
it all. However, it only tells me just that; there's no way to 
know what part of the code is expensive and what part isn't.


I can copy dub's dmd command and run it with `-v` and try to 
infer that the modules that are slow to pass semantic3 are also 
the hungry ones. But are they?


Is there a better metric?


I do have a custom dmd build with tracing functionality, but the 
profiles are not very user friendly and woefully under-documented.


https://github.com/UplinkCoder/dmd/tree/tracing_dmd

You can use the source of the file `src/printTraceHeader.d` to 
see how the profile is written, and by extension read.


The actual trace file format is in `src/dmd/trace_file.di`

you have to throw the -trace=$yourfilename switch when compiling.

I am happy to assist with interpreting the results. though for 
big projects it's usually too much of a mess to really figure out.





Re: odd atomicOp errors from vibe-core

2020-04-09 Thread Stefan Koch via Digitalmars-d-learn
On Friday, 10 April 2020 at 01:54:14 UTC, Steven Schveighoffer 
wrote:
I'm building a library that uses vibe-core as an indirect 
dependency. Specifically, I'm testing the library with dub test.


[...]


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


Re: How do I disable the multithreaded GC?

2020-04-09 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 9 April 2020 at 20:56:59 UTC, Johan wrote:

On Thursday, 9 April 2020 at 20:42:18 UTC, Stefan Koch wrote:

Simple question, how do I keep the GC from spawning threads?

Cheers,
Stefan


https://dlang.org/changelog/2.087.0.html#gc_parallel


Thanks a lot.


How do I disable the multithreaded GC?

2020-04-09 Thread Stefan Koch via Digitalmars-d-learn

Simple question, how do I keep the GC from spawning threads?

Cheers,
Stefan


Re: Fixing race issues the right way

2020-04-05 Thread Stefan Koch via Digitalmars-d-learn

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


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


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


Look at your program in a debugger and see if it does spawn 
threads.

If it does find out where and why they are spawned.


Re: Find the heir.

2020-03-29 Thread Stefan Koch via Digitalmars-d-learn

On Sunday, 29 March 2020 at 14:04:53 UTC, TodNaz wrote:

Hello!

class A
{
   ...
}

class B : A
{
   ...
}

class C : A
{
   ...
}

A example1;
B example2 = new B(...);
A = example2;
auto heir = A.whoheir(); ///


The question in this code is: is it possible to track the class 
inheritor? Or is it beyond D?

Sorry if the question is fool ...


It is not generally known who has inherited a class from the 
parents perspective.




Re: Strange counter-performance in an alternative `decimalLength9` function

2020-02-26 Thread Stefan Koch via Digitalmars-d-learn

On Wednesday, 26 February 2020 at 00:50:35 UTC, Basile B. wrote:
So after reading the translation of RYU I was interested too 
see if the decimalLength() function can be written to be 
faster, as it cascades up to 8 CMP.


[...]


It can be made faster using binary search. Not by much though.

You'll get ceil(log2(numberofplaces)) cmps.


Re: Speeding up compilation of template-heavy code

2020-02-22 Thread Stefan Koch via Digitalmars-d-learn

On Saturday, 22 February 2020 at 12:24:56 UTC, drathier wrote:

On Saturday, 22 February 2020 at 11:53:38 UTC, Dennis wrote:
On Saturday, 22 February 2020 at 11:26:19 UTC, Per Nordlöw 
wrote:
Is there a dmd flag that shows the code after template 
instantiations has been performed?


The -vcg-ast flag does that.


The d.cg files still contain templates, so it appears like 
they're instantiated after -vcg-ast?


no. -vcg-ast runs directly before codegen.
All ast-rewriteing has already happend at that point.
The reason it contains the template declarations is because they 
are still in the ast.

There is no point in removing them.


Re: Speeding up compilation of template-heavy code

2020-02-22 Thread Stefan Koch via Digitalmars-d-learn

On Saturday, 22 February 2020 at 11:26:19 UTC, Per Nordlöw wrote:
We're looking for a way to speed up compilation of 
template-heavy code. So we are trying to find out which parts 
of the code that is most costly to compile.


Is there a dmd flag that shows the code after template 
instantiations has been performed? Or some other dmd flag that 
can help out finding hot-spots in the compiler in our case.


I have patches which add some tracing functionality.
Another approach is to throw the -v flag and just count which 
semantic steps seem to take a long time.


Re: betterC CTFE nested switch

2020-02-21 Thread Stefan Koch via Digitalmars-d-learn

On Friday, 21 February 2020 at 09:03:26 UTC, Abby wrote:

On Monday, 17 February 2020 at 19:02:50 UTC, Stefan Koch wrote:

Sorry I just realized I never published the code.
I am going to add it to ctfeutils.


Hi Stefan,
I'm sorry to bother you, I just wanted to kindly ask if you 
would upload the formatter to ctfeutils on github it would help 
me alot.


Thank you very much
Kind regards Abby


No problem I am a little busy lately.

In the meantime you can check if std.format : format would do the 
job.
Even though it will like be much slower than my CTFE optimized 
version.


Re: How to get the name of an object's class at compile time?

2020-02-18 Thread Stefan Koch via Digitalmars-d-learn

On Tuesday, 18 February 2020 at 03:33:21 UTC, Basile B. wrote:

On Monday, 17 February 2020 at 22:34:31 UTC, Stefan Koch wrote:


Upon seeing this I just implemented typeid(stuff).name;

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

With any luck this will be possible in the next release ;)


Can this work using `stuff.classinfo.name` too ?
This is the same as `typeid(stuff).name


Currently no. It's represented differently in the end tree.





Re: How to get the name of an object's class at compile time?

2020-02-17 Thread Stefan Koch via Digitalmars-d-learn
On Monday, 17 February 2020 at 18:49:55 UTC, Steven Schveighoffer 
wrote:

On 2/17/20 2:28 AM, Nathan S. wrote:

What I want is something like this:


string className(in Object obj) {
     return obj is null ? "null" : typeid(obj).name;
}


...except I want it to work in CTFE. What is the way to do 
this in D?


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

It's not doable. It really should be.

-Steve


Upon seeing this I just implemented typeid(stuff).name;

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

With any luck this will be possible in the next release ;)


Re: betterC CTFE nested switch

2020-02-17 Thread Stefan Koch via Digitalmars-d-learn

On Monday, 17 February 2020 at 11:51:03 UTC, Abby wrote:

On Monday, 17 February 2020 at 11:05:46 UTC, Stefan Koch wrote:

On Monday, 17 February 2020 at 10:18:32 UTC, Abby wrote:

[...]


I have a ctfe compatible string formatter, you should be to 
find it here

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

I hope that helps,

Regards, Stefan
:


Hi Stefan, thank you very much for your reply but I could not 
find the source code or package name anywhere in that forum 
thread, I was only able to find this 
https://github.com/UplinkCoder/ctfeutils on github, but it's 
empty for me. Can you please help and point me to somewhere so 
I can try it out?


Thank you very much

Kind regards Abby


Sorry I just realized I never published the code.
I am going to add it to ctfeutils.


Re: betterC CTFE nested switch

2020-02-17 Thread Stefan Koch via Digitalmars-d-learn

On Monday, 17 February 2020 at 10:18:32 UTC, Abby wrote:

Hi there guys,
I was trying to generated code during compile time. Bassicly 
I'm creating a tokenizer and I would like to generated nested 
switch using betterC.


[...]


I have a ctfe compatible string formatter, you should be to find 
it here

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

I hope that helps,

Regards, Stefan
:


Re: "register int n" alternative

2020-02-16 Thread Stefan Koch via Digitalmars-d-learn

On Sunday, 16 February 2020 at 13:48:43 UTC, Виталий Фадеев wrote:

Possible mark variable for force use register ?

Example C-code:
{
register char *buf;
long   pos;
register int   n;
register int   r;

if (!n)
return 0;
}


How to implement in D ?


Don't you get a warning from your c compiler a C compiler?
The register keyword as been deprecated for ages in C.
Since the compiler cannot actually guarantee that the variable 
will be a register.

As a result D does not have the register keyword.

in D simply allocating a local is enough (and compiling with 
optimization enabled), if there is a register free to put the 
variable in, that's what the optimizer will do.


If you don't want to be at the mercy of the optimizer you can 
always write a block of asm.

Which is what I usually do when I _really_ care.


Re: Unable to pass a D function member to a C callback

2019-11-02 Thread Stefan Koch via Digitalmars-d-learn

On Saturday, 2 November 2019 at 17:49:09 UTC, Luh wrote:

Hello,

When trying to pass a D function to the C callback, the 
compiler says:


'Error: cannot implicitly convert expression  
of type extern (C) bool delegate(const(short*) a, ulong b, 
void* c) to extern (C) bool function(const(short*), ulong, 
void*'


because my function is member of a class (compiles when the 
function is out of the class).


Is there any way to say to solve this ?
The wiki isn't very clear about the C callbacks:
https://dlang.org/spec/interfaceToC.html#callbacks

C code:

typedef bool (*onProcessCallback)(const short*, size_t, void*);



D Code:
-
class Game
{
onProcessCallback m_onProcessCb;

this()
{
m_onProcessCb =  // Error here
}

void onProcess()
{
// ...
}

extern(C) bool onProcessCb(const short* a, size_t b, void* c)
{
onProcess();
return true;
}
}

private extern(C)
{
// Should call onProcess() when executed by the C lib
	alias onProcessCallback = bool function(const short*, size_t, 
void*);

}
-


you are missing a static in your member function's signature.
The callback is not providing a this pointer.


Re: Eliding of slice range checking

2019-10-25 Thread Stefan Koch via Digitalmars-d-learn

On Wednesday, 23 October 2019 at 12:01:47 UTC, Per Nordlöw wrote:

On Wednesday, 23 October 2019 at 11:33:56 UTC, kinke wrote:
For your example, the template is inferred to be @safe, and 
`-release` only elides bounds checks in @system functions 
(corresponding to `-boundscheck=safeonly`). Use 
`-boundscheck=off` to elide it in all functions.


Thanks. But I'm talking about the compiler being able to figure 
out that the expression


haystack[0 .. needle.length]

_never_ (regardless of compiler flags) needs any range checking 
because it is _only_ run when


haystack.length >= needle.length

. Do you follow?


Actually what you want is that the compiler uses a loop-invariant 
to only to bounds-checking once on the first loop entry?


That's quite tricky to do for all cases.
What you can do manually is to index the .ptr property which will 
decay the array to a pointer, and on a pointer you cannot and 
therefore will not do boundschecking


just replace x = a[i] with x = a.ptr[i];


Re: x64 ABI

2019-10-14 Thread Stefan Koch via Digitalmars-d-learn

On Monday, 14 October 2019 at 16:02:28 UTC, Marcel wrote:
It appears that the ABI specification only describes the 
register convention for x86. Where can I find which registers 
get preserved across function calls for 64-bit targets?


It's the same as c++.

https://en.wikipedia.org/wiki/X86_calling_conventions#x86-64_calling_conventions


Re: initialize float4 (core.simd)

2019-09-21 Thread Stefan Koch via Digitalmars-d-learn

On Saturday, 21 September 2019 at 13:42:09 UTC, Bogdan wrote:

Well, this seems to be working:


float[4] doSimd(float[4] values, float delta)
{
  float4 v_delta = delta;

  float4 v_values = __simd(XMM.ADDPS,
   __simd(XMM.LODAPS, values[0]),
   v_delta);

  return [v_values[0], v_values[1],v_values[2],v_values[3]];
}


Not sure if it's correct though.


float4 x;
float x1, x2, x3, x4;
x[0] = x1;
x[1] = x2;
x[2] = x3;
x[3] = x4;



Re: Why are extern(C/C++) definitions and references mangled differently in separately compiled modules?

2019-09-06 Thread Stefan Koch via Digitalmars-d-learn

On Friday, 6 September 2019 at 15:09:22 UTC, Max Samukha wrote:

Consider the following two modules:

1. test.d:

module test;

import lib.a;

void main() {
foo();
}


2. lib/a.d:

module lib.a;

extern(C) void foo() {}


When compiled separately (dmd -c lib/a.d; dmd test.d a.o), the 
function in 'a.o' is mangled as 'foo', but the reference in 
'test.o' is mangled as '_D3lib1a3fooFZv', which leads to a link 
error. I would expect both of them to be either plain C 
mangling, or fully qualified D (better). What is the reason for 
current behavior?


If that is happening you hit a bug.
It seems unlikely though.


Re: D1 code to D2I

2019-08-22 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 22 August 2019 at 18:10:51 UTC, jicman wrote:

Greetings!

Is there any tool out there, I searched around and didn't find 
any, that would take ton of D1 code and convert it to D2?  
Thanks.


josé


There is:

https://github.com/sociomantic-tsunami/d1to2fix

It might be please ask any question you may have in this thread.


Re: Slow UDF call?

2019-08-17 Thread Stefan Koch via Digitalmars-d-learn
On Saturday, 17 August 2019 at 19:43:22 UTC, Giovanni Di Maria 
wrote:

Hi,
i have seen that a simple operation (in a loop) is faster than 
the equivalent UDF.
The first example takes 4 seconds, the second example takes 16 
seconds.

Local variables influence the speed of execution?
Thank you very much.
Giovanni

==

import std.stdio;
void main()
{
int a,b;
int s;
int k;
writeln("START");
for(k=1;k<=2_000_000_000;k++)
{
a=7;
b=20;
s=a+b;
}
writeln("Fine ",k," ",s);
}

==


import std.stdio;
void main()
{
int a,b;
int s;
int k;
writeln("START");
for(k=1;k<=2_000_000_000;k++)
{
a=7;
b=20;
s=somma(a,b);
}
writeln("Fine ",k," ",s);
}

int somma(int n1,int n2)
{
return n1+n2;
}


Yes they do

A function call has a cost.
In case of a function which performes a 1 cycle  (nominally 
without ILP) operation, the overhead of the function call 
dominates.

try compiling with -inline and compare again.


Re: Manipulating alias sequences

2019-07-15 Thread Stefan Koch via Digitalmars-d-learn

On Monday, 15 July 2019 at 13:40:29 UTC, Ben Ogles wrote:
I have written a simple function that can call another function 
over integral types with random arguments:


[...]


You cannot. meta-programming and compile-time evaluation are 
supposed to be deterministic,

and hence cannot take random values.



Re: Windows segfault, need brief help

2019-07-12 Thread Stefan Koch via Digitalmars-d-learn

On Friday, 12 July 2019 at 22:46:11 UTC, Anonymouse wrote:
I'm suddenly getting segfaults when running tests on Windows. 
It works fine on Linux. I reduced it to a few lines (plus a 
dependency) with dustmite, but they don't really make sense[1]. 
Nevertheless they do trigger the segfault.


Can someone with Windows 10 and dmd 2.087.0 try the following 
and see if it crashes please?



[...]


If it ends with an assertion failure, okay, darn. If it "exited 
with code -1073741819" I'll have confirmed it happens for more 
than just me and AppVeyor, and thus can go ahead and file a bug 
report.



[...]


[1]: 
https://github.com/zorael/tests/blob/wintestcrash/source/app.dx


maybe you haven't pushed?
I can't see it.


Re: Does -profile need the D runtime?

2019-05-18 Thread Stefan Koch via Digitalmars-d-learn

On Saturday, 18 May 2019 at 16:35:44 UTC, Robert M. Münch wrote:
I want to profile my windows app which has a WinMain(). One of 
the first statements in WinMain() within a try{} is:


Runtime.initialize();

But when I compile my app with -profile, it crashes on entry of 
WinMain(). Looks like this function is instrumented with code, 
that might need the D runtime. Is this the case?


Is there a way to flag specific functions as "don't profile"?


yes profiling does relay on druntime being present.

There is currently no such thing as "don't profile"


Re: Creating a RedBlackTree

2019-05-15 Thread Stefan Koch via Digitalmars-d-learn

On Wednesday, 15 May 2019 at 13:08:18 UTC, Bogdan wrote:
I don't have any experience with using templates. Is it 
possible to create a RB tree containing structs, where the 
nodes are ordered by one struct member?


```
import std.stdio;
import std.container;

enum KeyID: uint
{
KEY_A,
KEY_S,
KEY_D,
KEY_W
}

struct KeyController
{
KeyID ID;
bool isDown;
}


void main()
{
auto rbt = redBlackTree!KeyController;
}

```

When I run this I get a compile error:
```
Error: template instance 
`std.container.rbtree.RedBlackTree!(KeyController)` does not 
match template declaration RedBlackTree(T, alias less = "a < 
b", bool allowDuplicates = false) if 
(is(typeof(binaryFun!less(T.init, T.init

```


Key controller cannot be compared by less
which is why it fails, give it an opCmp and it'll work.


Re: CTFE in imported static initializers

2019-05-14 Thread Stefan Koch via Digitalmars-d-learn
On Tuesday, 14 May 2019 at 08:26:41 UTC, Steven Schveighoffer 
wrote:

On 5/13/19 9:39 PM, Steven Schveighoffer wrote:

Does anyone have a good answer for why this should happen, or 
should I file a bug?



It's been mentioned to me that type inference is used here. 
However, one could argue that the CTFE doesn't need to complete 
in order to infer the type, the function is not a template or 
auto function.


In addition, if I change the declaration to:

static string moddata = ...;

It still takes 1 second to compile mod1.

-Steve


try changing it to static immutable.


Re: CTFE sort of tuples

2019-05-02 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 2 May 2019 at 02:54:03 UTC, Andrey wrote:

Hello, I have got this code:


[...]


I want to sort array of tuples using "data" element in CTFE. 
But this code give me errors:

[...]


As I understand the function "sort" sometimes can't be run at 
CT because of reinterpreting cast.

In this case how to sort?


write a sort?

a bubble-sort should be sufficient for if the arrays are as short 
as in the example.


Re: alias fails to compile

2019-04-22 Thread Stefan Koch via Digitalmars-d-learn
On Monday, 22 April 2019 at 08:02:06 UTC, Arun Chandrasekaran 
wrote:

What am I doing wrong here?

struct A
{
union B
{
int bb;
}
B b;
alias aa = B.bb;
}

void main()
{
A a = A();
// a.b.bb = 4; // works
a.aa = 4; // fails
}


https://run.dlang.io/is/kXaVy2


You are aliasing B.init.bb;
You should try aliasing b.bb;

though I am not sure in that'll work since alias is really only 
meant for symbols.


Re: Poor regex performance?

2019-04-04 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 4 April 2019 at 10:31:43 UTC, Julian wrote:
On Thursday, 4 April 2019 at 09:57:26 UTC, rikki cattermole 
wrote:

If you need performance use ldc not dmd (assumed).

LLVM has many factors better code optimizes than dmd does.


Thanks! I already had dmd installed from a brief look at D a 
long
time ago, so I missed the details at 
https://dlang.org/download.html


ldc2 -O3 does a lot better, but the result is still 30x slower
without PCRE.


You need to disable the GC.
by importing core.memory : GC;
and calling GC.Disable();

the next thing is to avoid the .idup and cast to string instead.



Re: Build an alias array

2019-04-02 Thread Stefan Koch via Digitalmars-d-learn

On Tuesday, 2 April 2019 at 03:15:36 UTC, Alex wrote:
Is there any way to build an alias array at compile time that 
isn't too heavy in resources?

{...}


Hi Alex,

I agree that there should be a way to do that.

As soon as newCTFE is a releasable state, I'll work on that again 
:)


I'd be intereseted in your usecases, so I can asses the 
requirements better.


Thanks in advance!

- Stefan


Re: Why is my @pure function @system when placed in a struct?

2019-02-27 Thread Stefan Koch via Digitalmars-d-learn

On Wednesday, 27 February 2019 at 17:23:21 UTC, Q. Schroll wrote:
I have a template function `fImpl` I whish to instantiate 
manually using the new name `f`. Reason is simple: `f` should 
not be a template, but overloading it makes it easier that way.

Nothing's more simple in D:

[...]


the struct gets drawn into your delegate-context.
and I guess that taints  the function.


Re: How does Rebindable suppress the compiler's optimizations for immutable?

2019-02-14 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 14 February 2019 at 23:55:18 UTC, SimonN wrote:

std.typecons.Rebindable!(immutable A) is implemented as:

private union {
immutable(A) original;
A stripped;
}

...@trusted assignment operators...

@property inout(immutable(A)) get() @trusted pure nothrow 
@nogc inout

{
return original;
}

alias get this;

This conforms with the D safety spec: All access to the unsafe 
union goes through the @trusted get() and the trusted 
assignment operators.


Rebindable!(immutable A) r = a1;
// r.original is a1
r = a2;
// r.original is a2

But the compiler may assume that immutable variables -- such as 
the immutable(A) original -- never change and thus may optimize 
code. Since immutable(A) original is assignable in the union, 
such optimization would produce wrong behavior: In the final 
line, the compiler could think that r.original is a1 without 
examining r.original.


How does Rebindable prevent the compiler from optimizing 
according to immutable's rules?


It's easy. You cannot use immutable as the only basis of 
optimization.
You need to proof actual immutability via data-flow-analysis over 
the whole life-time of your immutable.
When you cannot guarantee actual immutability (within the frame 
of interest) don't perform optimizations which are dependent on 
it.


So much for the theory, in practice I think that most 
optimizations based on immutable are disabled.
Think of immutable as hint for the programmer, not for the 
compiler.


Re: How to ensure string compatibility In D?

2019-01-22 Thread Stefan Koch via Digitalmars-d-learn

On Tuesday, 22 January 2019 at 16:47:45 UTC, FrankLike wrote:
On Tuesday, 22 January 2019 at 16:18:17 UTC, Adam D. Ruppe 
wrote:

Use "mystring"w, notice the w after the closing quote.


Or toStringz is not work like c_str() in C++?


stringz creates a char*
but you need a wchar*


Re: Pass reference to void*

2019-01-09 Thread Stefan Koch via Digitalmars-d-learn

On Monday, 7 January 2019 at 13:15:44 UTC, Andre Pany wrote:

On Monday, 7 January 2019 at 13:01:57 UTC, Stefan Koch wrote:

On Monday, 7 January 2019 at 12:19:57 UTC, Andre Pany wrote:

[...]


From the function declaration  seems to be the correct 
thing to use here.

Have you checked that Open is not null ?


Yes, Open is not null and the strange thing is, everything is 
working fine for

DMD on windows. (I call a lot other dll functions afterwards).
By switching to LDC the subsequent calls to DLL functions are 
failing.


Thanks.

Kind regards
André


Might be an calling convention issue?

Are they declared with extern(Windows) ?


Re: Pass reference to void*

2019-01-07 Thread Stefan Koch via Digitalmars-d-learn

On Monday, 7 January 2019 at 12:19:57 UTC, Andre Pany wrote:

Hi,

I call a C function from a dll (SO on linux). While the 
following code works
fine for DMD on windows, there are strange errors for LDC on 
windows. Also the equivalent code does not work for DMD/LDC on 
linux.
(When calling other functions from the dll and passing the 
model reference, this functions are failing).


[...]


From the function declaration  seems to be the correct 
thing to use here.

Have you checked that Open is not null ?


Re: Converting an integer to a string with std.format.

2019-01-07 Thread Stefan Koch via Digitalmars-d-learn

On Sunday, 6 January 2019 at 21:53:31 UTC, Per Nordlöw wrote:
When converting a single integer to a string is `formatValue` 
preferred over `formattedWrite` in terms of compilation and 
run-time performance?


I've written my own itos function because using std.conv was too 
expensive.
see 
https://github.com/UplinkCoder/dmd/blob/newCTFE_reboot_20741/src/ctfe/bc_common.d#L95


if you do want to convert longs you'll need a bigger pow_table as 
well as a diffrent log10 function.


Re: Compile time opAssign/@property constraints

2019-01-04 Thread Stefan Koch via Digitalmars-d-learn

On Friday, 4 January 2019 at 11:45:24 UTC, Jacob Shtokolov wrote:

On Friday, 4 January 2019 at 10:34:07 UTC, Basile.B wrote:

Show us some code.


Here is the simple example:

https://run.dlang.io/gist/1a06dd703bea5548ee72b4713a7ce5f6

The thing I'm trying to do is to make an experimental port (for 
education purposes) of https://github.com/fthomas/refined 
library for Scala, which allows to set constraints on basic 
types like numeric, bool, string, etc.


For example, you can force an integer variable to take a range 
between 0 and 15. And if constraint is not satisfied, you get a 
compile time error.


There is no predicate in my example, but even if I add one 
(using alias template parameter), it shows the same error.


So is that possible in D?


You have'd to use a template to "construct" your variables;
struct ConstrainedInt
{
  int val;
  alias val this;
}

template makeConstrainedInt(int Value)
{
static assert(Value <= 15 && Value >= 0);
enum makeConstrainedInt = ConstrainedInt(Value);
}


However this relies on your virtue not to call constraintInt 
constructor directly.

and always use the template.


Re: Checking if CTFE is used?

2018-12-18 Thread Stefan Koch via Digitalmars-d-learn

On Tuesday, 18 December 2018 at 12:21:44 UTC, berni wrote:
Is there a way to check if a function is indeed executed at 
compile time or not? (Other than going through the whole 
executable binaries...)


I tried


static this()
{
  if (__ctfe) pragma(msg,"works");
  // some other stuff
}


but unfortunatley this "if" is also executed at compile time, 
when I put it into a function that is only called at runtime. 
When I try "static if" instead the compiler complains about 
"__ctfe" being not known at compile time.


Why would you need to know?


Re: D is supposed to compile fast.

2018-11-26 Thread Stefan Koch via Digitalmars-d-learn

On Friday, 23 November 2018 at 08:57:57 UTC, Chris Katko wrote:
Any time I see people mention the benefits of D, I see "compile 
times" "compile times" "compile times" over and over.


I'm using very modest amounts of templates, for a fairly small 
sized program (very early work toward a game), and I'm hitting 
~15 seconds compile time in LDC and ~7 seconds in DMD. And I'm 
not even compiling with optimizations!


ldc2 -w -ofextra  extra.d molto.d helper.d editor.d common.d 
map.d object_t.d animation.d ini.d  -L-L. $@-gc -d-debug=3  
-de -fdmd-trace-functions


dmd -w -ofextra extra.d molto.d helper.d editor.d common.d 
map.d object_t.d animation.d ini.d -profile=gc  -profile  -g 
-debug -color -L-L.


I keep putting stuff into new files, but it feels like it's 
compiling everything from scratch / not getting faster the way 
C++ does.


And I'm not even bringing up the 800MB of RAM required because 
I dared to import std.regex. (On a laptop with 2 GB of RAM. 
RIP. If I dare to have tabs open, the compile time goes into 
the minutes thanks to swapping.)


I've profiled your example, unsurprisingly allmost all of the 
compiletime is eaten by regex, which is executed at compile-time.
Most of the time there is actually taken by the 
template-instantiation and the templates which are involved in 
building the IR and such.


newCTFE helps out a little, but for this to be fast, std.regex 
would have to be rewritten with CTFE in mind.


Maybe you can generate a finite automaton for your regex offline 
using some other engine like which supports D or C.


That alone should cut a few seconds of your compile-times and 
prevent out-of-memory errors,


I hope this helps.

Cheers,

Stefan


Re: D is supposed to compile fast.

2018-11-23 Thread Stefan Koch via Digitalmars-d-learn

On Friday, 23 November 2018 at 08:57:57 UTC, Chris Katko wrote:
Any time I see people mention the benefits of D, I see "compile 
times" "compile times" "compile times" over and over.


[...]


If you can share the code privately I can use my custom profiling 
build of dmd to analyze the problem. just send me a mail 
(uplink{dot}coder{at}gmail{dot}com)


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-22 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 22 November 2018 at 15:38:18 UTC, Per Nordlöw wrote:

The natural way forward for D is to add static analysis in the 
compiler that tracks use of possibly uninitialized classes (and 
perhaps also pointers). This has been discussed many times on 
the forums. The important thing with such an extra warning is 
to incrementally add it without triggering any false positives. 
Otherwise programmers aren't gonna use it.


I'd say the problem here is not just false positives, but false 
negatives!


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-11-21 Thread Stefan Koch via Digitalmars-d-learn

On Wednesday, 21 November 2018 at 10:47:35 UTC, NoMoreBugs wrote:
On Monday, 19 November 2018 at 21:39:22 UTC, Adam D. Ruppe 
wrote:
On Monday, 19 November 2018 at 21:23:31 UTC, Jordi Gutiérrez 
Hermoso wrote:

What's the reasoning for allowing this?


The mistake is immediately obvious when you run the program, 
so I just don't see it as a big deal. You lose a matter of 
seconds, realize the mistake, and fix it.


What is your proposal for handling it? The ones usually put 
around are kinda a pain to use.


How hard would it be, really, for the compiler to determine 
that c was never assigned to, and produce a compile time error:


"c is never assigned to, and will always have its default value 
null"


That doesn't sound that hard to me.


For _TRIVIAL_cases this is not hard.

But we cannot only worry about trivial cases;
We have to consider _all_ cases.

Therefore we better not emit an error in a trivial case.
Which could lead users to assume that we are detecting all the 
cases.
That in turn will give the impression of an unreliable system, 
and indeed that impression would not be too far from the truth.


Re: how do I activate contracts for phobos functions in dmd

2018-11-02 Thread Stefan Koch via Digitalmars-d-learn

On Friday, 2 November 2018 at 14:10:35 UTC, Richard Palme wrote:

My guess is that I have to build phobos with:

$make -f posix.mak BUILD=debug

but then what do I do next? I'm using Linux and I built 
dmd+phobos manually by following this guide: 
https://wiki.dlang.org/Building_under_Posix


Which phobos functions are used in dmd?
there _should_ be none!


Re: CT BitArray

2018-10-31 Thread Stefan Koch via Digitalmars-d-learn
On Wednesday, 31 October 2018 at 23:14:08 UTC, Bastiaan Veelo 
wrote:
Currently, BitArray is not usable at compile time, so you 
cannot do

```
enum e = BitArray([1, 1, 1, 0]);
```
This gives
/dlang/dmd/linux/bin64/../../src/phobos/std/bitmanip.d(1190): 
Error: `bts` cannot be interpreted at compile time, because it 
has no available source code


IIUC, that is because `bts` comes from core.bitop but no source 
code is there. I am guessing these are filled in by compiler 
intrinsics or the like, and they are unavailable at CT, correct?


I suppose that alternative implementations of `btc`, `bts`, 
`btr`, `bsf` and `bt` could exist that do not use the runtime 
that could be used if(__ctfe) in the implementation of 
BitArray, that would make the above code work. Is this 
feasible? Is there precedent in phobos? Are there complications?


Thanks!


Oh that ... actually I can fix that with a small patch to dmd.

Tell me which version are you using and I'll make it for you.

Cheers,

Stefan


Re: x64 Privileged instruction

2018-09-12 Thread Stefan Koch via Digitalmars-d-learn
On Wednesday, 12 September 2018 at 10:42:08 UTC, Josphe Brigmo 
wrote:

x64 gives

Privileged instruction

but x86 gives

First-chance exception: std.file.FileException "C:\": The 
filename, directory name, or volume label syntax is incorrect. 
at std\file.d(4573)



which is much more informative...

seems like a bug to me.


More context needed.
What code does produce this behavior.


Re: Structures and CTFE

2018-09-03 Thread Stefan Koch via Digitalmars-d-learn

On Monday, 3 September 2018 at 15:08:57 UTC, agorkvmh wrote:

On Monday, 3 September 2018 at 15:00:33 UTC, Alex wrote:

On Monday, 3 September 2018 at 14:00:23 UTC, agorkvmh wrote:

[...]


Yes. Put a pragma where you static assert for Foo(1).pos 
equality with 2:


[...]


Thanks, by the way, the autocomplete suggests me '__ctfeWrite', 
what is it?


__ctfeWrite was an idea which never got implemented ...
it should be a no-op  iirc.


Re: Prime number

2018-08-02 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 2 August 2018 at 08:30:05 UTC, Greatsam4sure wrote:
I know D is very powerful from my little experience. What is 
the idiomatic way to get prime numbers say from 1-30 without 
using loops(outer and inner loop). Can map, filter, fold etc in 
algorithm be use.  Pls show some code with chain call.


I can easily achieve even numberd and odd numbers using filter. 
But prime numbers I have to use 2loops.


I will appreciate any help,just a newbie in D


you can cheat and download d_primes from dub :)



Re: extern(C++): Unresolved scalar deleting destructor

2018-07-24 Thread Stefan Koch via Digitalmars-d-learn
On Tuesday, 24 July 2018 at 15:48:28 UTC, Vladimir Marchevsky 
wrote:
After reading 2.081 patchnotes about improvements with binding 
to cpp classes, I'm trying to test it - with simple examples 
and Qt as cpp library.


My naive approach is to bind just a couple of used methods of 
specific classes (omitting others) and try to use it directly 
in D just with linking of default Qt5Core.lib. Sometimes it 
works just fine:


---app.d
import std.conv;
import std.stdio;

extern(C++) {
class QVariant {
this();
this(int);
this(double);
final ~this();

final int toInt(bool *ok = null) const;
final double toDouble(bool *ok = null) const;
}
}

void main()
{
QVariant a = new QVariant(5);
QVariant b = new QVariant(5.5);
writeln("a: " ~ a.toInt().to!string);
writeln("b: " ~ b.toDouble().to!string);
readln();
}
---

This example compiles and works like a charm.

Other classes like QObject or QCoreApplication do not link with 
error like this:


cpptest.obj : error LNK2001: unresolved external symbol 
""public: virtual void * __cdecl QObject::`scalar deleting 
destructor'(unsigned int)" (??_GQObject@@UEAAPEAXI@Z)"


There is no such symbol in Qt5Core.lib, obviously. Is it my 
mistake somewhere? Why do some classes require this destructor 
when it doesnt actually exist in lib? And why do other classes 
work without it?


Seems like it's virtual destructor could that be?

this qt5 binding: 
https://github.com/MGWL/QtE5/blob/master/source/qte5.d

seems to always define the constructor.



Re: turn range into tuple ?

2018-06-28 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 28 June 2018 at 09:26:10 UTC, Flaze07 wrote:

On Thursday, 28 June 2018 at 08:52:33 UTC, Simen Kjærås wrote:

On Thursday, 28 June 2018 at 08:36:54 UTC, Flaze07 wrote:
is there some sort of ways to turn range into tuple ? ( an 
array preferably )

e.g
uint[] arr = [ 10, 20, 30 ];
auto tup = rangeToTup( arr );
assert( tup[ 0 ] == 10 );
assert( tup[ 1 ] == 20 );
assert( tup[ 2 ] == 30 );


https://dlang.org/phobos/std_meta#aliasSeqOf

--
  Simen


what about during runtime ?


Tuples are compile-time entities.
However if you just want an array use std.range.array.


Re: turn range into tuple ?

2018-06-28 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 28 June 2018 at 08:36:54 UTC, Flaze07 wrote:
is there some sort of ways to turn range into tuple ? ( an 
array preferably )

e.g
uint[] arr = [ 10, 20, 30 ];
auto tup = rangeToTup( arr );
assert( tup[ 0 ] == 10 );
assert( tup[ 1 ] == 20 );
assert( tup[ 2 ] == 30 );


I think you are looking for `aliasSeqOf` in std.meta


Re: alias symbol name

2018-06-26 Thread Stefan Koch via Digitalmars-d-learn

On Tuesday, 26 June 2018 at 09:14:11 UTC, Radu wrote:

Consider this https://run.dlang.io/is/HyY2qG

---
void main()
{
import std.traits;
size_t s;

pragma(msg, typeof(s).stringof);
pragma(msg, mangledName!(typeof(s)));
pragma(msg, mangledName!s);
}
---

It outputs:
---
ulong
m
_D9onlineapp4mainFZ1sm
---

I'm looking for a way to get the `s` type symbol name (size_t) 
not whatever the alias is pointing to (ulong in this case).


Is there a way to obtain the alias symbol name?


__traits(identifier, sym);


Re: Determine if CTFE or RT

2018-06-24 Thread Stefan Koch via Digitalmars-d-learn

On Sunday, 24 June 2018 at 18:21:09 UTC, rjframe wrote:

On Sun, 24 Jun 2018 14:43:09 +, Mr.Bingo wrote:

let is(CTFE == x) mean that x is a compile time constant. 
CTFE(x)
converts a x to this compile time constant. Passing any 
compile time

constant essentially turns the variable in to a compile time
constant(effectively turns it in to a template with template 
parameter)




You can use __ctfe:

static if (__ctfe) {
// compile-time execution
} else {
// run-time execution
}


no that will not work.
it cannot be a static if.
it has to be an if.


Re: Debugging compile time memory usage

2018-06-24 Thread Stefan Koch via Digitalmars-d-learn

On Sunday, 24 June 2018 at 14:16:26 UTC, Kamil Koczurek wrote:
I recently wrote a brainfuck compiler in D, which loads the BF 
source at compile time, performs some (simple) optimizations, 
translates everything to D and puts it into the source code 
with a mixin.


I did manage to get some pretty good performance, but for some 
programs in brainfuck I have to use LDC instead of DMD because 
the latter runs out of memory. Is there a way for me to 
optimize my code in such a way that DMD will be able to compile 
it?


D code: https://pastebin.com/fg1bqwnd
BF program that works: 
https://github.com/erikdubbelboer/brainfuck-jit/blob/master/mandelbrot.bf
BF program that makes DMD crash: 
https://github.com/fabianishere/brainfuck/blob/master/examples/hanoi.bf


After putting BF code in code.bf and D in main.d, I compile it 
with the following command: dmd main.d -J./


Error msg: unable to fork: Cannot allocate memory
DMD version: DMD64 D Compiler v2.080.0-dirty


Check out https://github.com/UplinkCoder/bf-ctfe.

It uses all tricks which I know to use the least amount of memory.
(Which admittedly still is a lot)

Other then that. you'll have to wait for newCTFE to be stable 
enough for me to give green light for merging.




Re: Move and CTFE

2018-06-21 Thread Stefan Koch via Digitalmars-d-learn

On Wednesday, 30 May 2018 at 23:07:26 UTC, Jonathan M Davis wrote:


newCTFE is taking a very different approach to CTFE, and in 
theory, it will fix many of the problems that CTFE currently 
has, but it's taking Stefan quite a while to get it to where it 
needs to be to actually merge it.




To give some more context here:

I do intend newCTFE to be a drop-in replacement that offers the 
same functionality (including the very accurate error detection 
and precise error reporting)
Which was quite hard to achieve due to not being able of creating 
Error-Nodes from inside the interpreter.
I'd say for the amount of things that newCTFE currently 
_correctly_ handles it has been fast progress!


CTFE is the most well tested feature in dmd.
So there is no room for sloppiness or functional differences!
As you previously mentioned the newCTFE engine works on a 
completely different basis then the old engine does.
This does provide both speed and better debugging support, but 
comes at the cost of having to re-implement a complete backend 
and some parts of semantic analysis.




Re: How can I enforce an parameter to be constant know at compile time?

2018-06-12 Thread Stefan Koch via Digitalmars-d-learn

On Tuesday, 12 June 2018 at 18:27:17 UTC, Dr.No wrote:

I'd like help of compiler to check this:

consider this:

int f(int n) {
  m_n = n;
}

f(10); // ok
f(myTampleteFunction!(compileTimeParameter)); // ok
enum n = 10;
f(n); // I won't use this, but should also be ok
int x = 10;
f(x); // error
int g() { return 20; }
f(g); // error


How can I enforce that?


write a static assert :)


Re: WTF! new in class is static?!?!

2018-06-07 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 7 June 2018 at 21:07:26 UTC, DigitalDesigns wrote:

class A;

class B
{
   A a = new A();
}

auto b1 = new B();
auto b2 = new B();

assert(b1.a == b2.a)!!


I'm glad I finally found this out! This is not typical behavior 
in most languages is it?


I'd expect it to be translated to something like

class B
{
   A a;
   this()
   {
   a = new A();
   }
}

In C# it is different, can't remember if it is different in 
C++. This has caused bugs in my code because the fields are all 
pointing to the same data when I expected them to each have 
unique data ;/


This method is error prone and the behavior should be reversed, 
it should not break the majority of code. If one wants the 
current behavior then static new could be used or something 
else.


If you want a new one use a constructor call.
initalizers are support to be static, this only works because 
ctfe supports newing classes.




Re: Confusion/trying to understand CTFE keywords

2018-06-05 Thread Stefan Koch via Digitalmars-d-learn
On Tuesday, 5 June 2018 at 18:00:05 UTC, Steven Schveighoffer 
wrote:


No, it's definitely a bug. main is not being evaluated at 
compile time. The real result of this function should be a 
compile-time error -- __ctfe is a *runtime* value that is 
always defined based on whether you are __ctfe or not. 
Therefore, n must be a runtime value, and not usable as a 
static array dimension.


If the posted code is valid, then this should be valid as well:

static if(__ctfe)
   immutable n = 1;
else
   immutable n = 2;

But it's not.

-Steve


I see what you mean.
I fear fixing this bug will not be easy without breaking arguably 
valid uses.




Re: Confusion/trying to understand CTFE keywords

2018-06-05 Thread Stefan Koch via Digitalmars-d-learn
On Tuesday, 5 June 2018 at 13:27:35 UTC, Steven Schveighoffer 
wrote:

On 6/5/18 6:40 AM, Simen Kjærås wrote:

On Tuesday, 5 June 2018 at 09:36:22 UTC, Gopan wrote:

void main()
{
    immutable n = __ctfe ? 1 : 2;
    int[n] a;
    assert(a.length == n); // fails, wat
}


That's gotta be a bug - that should give a 'variable n cannot 
be read at compile time' error. The fact that n is immutable 
shouldn't be enough to use it at compile time. Filed as 
https://issues.dlang.org/show_bug.cgi?id=18945.


Indeed it is a bug. Interesting to see what the compiler sees 
as its AST:


import object;
void main()
{
immutable immutable(int) n = __ctfe ? 1 : 2;
int[1] a = 0;
assert(1LU == cast(ulong)n);
return 0;
}

This is what -vcg-ast spits out.

Note the int[1].

-Steve

This is not bug just not very intuitive.

Since you are declaring a static array the value of n needs to 
known at compiletime.
so it'll  try to evaluate n at an compile-time context in which n 
is 1.
however when code-generation for the function is done __ctfe will 
be false.

Causing the n variable to be initialized to 2.

Therefore n will not be equal to a.length.


Re: Deserialize json on runtime type with vibed

2018-05-13 Thread Stefan Koch via Digitalmars-d-learn

On Saturday, 12 May 2018 at 20:23:27 UTC, boolangery wrote:

Hi,

I want to do something like that:

The user first register some type associated to a string and a 
callback


registerHandler!Foo("foo", (res) {
  info("message received");
});


I want the callback to be called when a json packet containing 
the string "foo" arrives on a transport layer. Then the full 
json message is deserialized to Foo class using deserializeJson!


The type is known at runtime, so how can I use deserializeJson 
with a runtime type ?


Thanks in advance


via exposing a virtual method which instantiates the template.



Re: Concatenate strings at compile-time

2018-05-02 Thread Stefan Koch via Digitalmars-d-learn
On Wednesday, 2 May 2018 at 12:38:25 UTC, Jonathan M. Wilbur 
wrote:
I have a method that cannot be @nogc only because it 
concatenates strings for a long exception message, as seen 
below.


throw new ASN1ValuePaddingException
(
"This exception was thrown because you 
attempted to decode " ~
"an INTEGER that was encoded on more than the 
minimum " ~

"necessary bytes. " ~
notWhatYouMeantText ~ forMoreInformationText ~
debugInformationText ~ reportBugsText
);

Those variables you see are immutable. Is there a way that I 
can combine these strings together at compile time, rather than 
having a really long string that exceeds the 120 hard 
line-length limit?


This will be concatenated at compiletime and there will be no 
runtime overhead iff those are static immutable or enum.


Re: cast const pointer to non-const and change value yields neither result nor error

2018-04-30 Thread Stefan Koch via Digitalmars-d-learn

On Monday, 30 April 2018 at 12:35:06 UTC, Timoses wrote:

Hey,

reading through https://dlang.org/articles/const-faq.html and 
experimenting a bit:


```
immutable int i = 3;
const(int)* p = 

int* q = cast(int*)p;

assert(q == p && p == );

writeln(i); // 3
*q = 1; // Why does this have no effect at all? No 
error no nothing?!

writeln(i); // 3
```

When changing i to non-immutable the `*q=1` sets i to 1.

There is no error message. The `*q=1` simply has no effect at 
all. Also with `const int i`.


Is that intended?


Well yes.
Casting away immutable is undefined behavior.

This code will most probably not compile if you annotate it with 
@safe.

Precisely because it's undefined.



Re: Using an external Assembler with D

2018-04-26 Thread Stefan Koch via Digitalmars-d-learn

On Wednesday, 25 April 2018 at 20:31:46 UTC, solidstate1991 wrote:

On Wednesday, 25 April 2018 at 15:25:42 UTC, Stefan Koch wrote:

Pass stuff on the stack ;)
and use extern (C) functions.


Thanks! What about extern (D)? Is there a big chaos in the D 
ABI under x86?


I think the D abi is not actually properly spec'd. But I may be 
wrong about that.


Re: Using an external Assembler with D

2018-04-25 Thread Stefan Koch via Digitalmars-d-learn

On Tuesday, 24 April 2018 at 21:02:07 UTC, solidstate1991 wrote:
In order to make one of my own code more readable (and 
hopefully to avoid a lot of compiling errors under LDC, which 
don't happen in DMD for some reason), I'm planning to put my 
assembly functions into separate files for each system that 
needs them, mainly due to the lack of proper SIMD support, 
mainly due to these functions are relatively easy to implement. 
Here's a few questions of mine:


- Can I return vectors in XMM registers and accept arguments as 
vectors in them?
- How much is the D ABI differs on DMD and LDC for x86? I'm 
planning to support both (with mainly using DMD as a debug 
compiler for its speed), and want the most universal solution 
possible.


Pass stuff on the stack ;)
and use extern (C) functions.



Re: Rotate array in writefln?

2018-04-18 Thread Stefan Koch via Digitalmars-d-learn

On Wednesday, 18 April 2018 at 06:54:29 UTC, Chris Katko wrote:
I need to rotate an array by 90 degrees, or have writefln 
figure that out.


I need, say:

0 4 5 6
0 0 0 0
0 0 0 0
0 0 0 0

But it's outputting:

0 0 0 0
4 0 0 0
5 0 0 0
6 0 0 0

int [4][4] data;
file.writeln(format("%(%-(%d %)\n%)", data));


You can transpose the matrix :)


Re: How/where to hack DMD to generate docs for string mixed members.

2018-04-15 Thread Stefan Koch via Digitalmars-d-learn

On Sunday, 15 April 2018 at 05:20:31 UTC, 9il wrote:

Hey,

How/where to hack DMD to generate docs for string mixed members?

struct S
{
mixin("
 ///
 auto bar() {}
");
}

Best regards,
Ilya Yaroshenko


hmm you should be able to see docs for string mixins, if not.
try using -vcg-ast and try to run ddoc on the cg file


Re: Source expression passed to a lazy parameter

2018-04-09 Thread Stefan Koch via Digitalmars-d-learn

On Monday, 9 April 2018 at 08:27:50 UTC, Per Nordlöw wrote:
Is it possible to get the source expression sent to a lazy 
function?


So that I can implement something like

show(Arg)(lazy Arg arg)
{
writeln(arg.sourceof, arg);
}

used as

show(1+2+3);

will print

1+2+3:6


Because of the way D works with a given piece of code may not 
have a source-location or even a representation which is valid D 
source code.


Note: There is a way to fix this but it's very involved.

Step 1: you use cow (copy-on-write) when modifying AST nodes in 
semantic() or you keep distinct trees.
Step 2: you sanitize implicitly generated code to make sure it's 
actually valid code.
Step 3: you write the generated code, to a well-defined location 
such that source-of can point to a valid location.


also note that support for sourceof at compiletime will bloat the 
executable since it needs to store the source-text.


Re: Does the compiler inline the predicate functions to std.algorithm.sort?

2018-03-18 Thread Stefan Koch via Digitalmars-d-learn

On Sunday, 18 March 2018 at 12:59:06 UTC, tipdbmp wrote:
I can't read assembly but it seems to me that it doesn't: 
https://godbolt.org/g/PCsnPT
I think C++'s sort can take a "function object" that can get 
inlined.


Correct it does not get in-lined.
Even with -O3 it does not.

The reason is that the code the sort instantiation produces is 
too big for the inliner cost function.


If you have a look at the the cg file produced when you specify 
-vcg-ast you can see that it's a massive amount of code.


Re: signbit question

2018-03-15 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 15 March 2018 at 15:28:16 UTC, Miguel L wrote:

Why does std.math.signbit only work for floating point types?
Is there an analogue function for integer types? what is the 
best way to compare the sign of a float with the sign of an 
integer?

Thanks in advance


integers don't have a sign-bit.
since they are not necessarily singed.
However if an integer is signed and using 1-complement
you can either do sign = var < 0 or
sign = (var & (1 << (sizeof(var)*8 - 1));
though I cannot tell which one is faster you have to experiment.



Re: core.stdc.stdlib._compare_fp_t and qsort

2018-03-11 Thread Stefan Koch via Digitalmars-d-learn

On Sunday, 11 March 2018 at 23:12:30 UTC, Joe wrote:

I'm getting a compiler error in a qsort() call as follows:

qsort(recs, num_recs, (Record *).sizeof, compar);

Record is a struct, recs is a fixed array of pointers to 
Record's and num_recs is a size_t that holds the number of 
valid records.


compar is this:

int compar(const void *p1, const void *p2)
{
import core.stdc.string : strcmp;
const Record **rp1 = cast(Record **)p1;
const Record **rp2 = cast(Record **)p2;

return strcmp((*rp1).name.ptr, (*rp2).name.ptr);
}

The error is: Error: function testd.compar (const(void*) p1, 
const(void*) p2) is not callable using argument types ()


I don't quite understand what those parentheses mean: is it 
implying "no arguments" and if so, where would one provide 
arguments?


Joe


You have to pass a pointer to the function.
Otherwise it'll be a parenthsis-less call.
use :  qsort(recs, num_recs, (Record *).sizeof, );


Re: Forwarding arguments through a std.algorithm.map

2018-03-11 Thread Stefan Koch via Digitalmars-d-learn

On Saturday, 10 March 2018 at 20:48:06 UTC, Nordlöw wrote:

If I have a function

bool f(Rs...)(Rs rs)

is it somehow possible to map and forward all its arguments 
`rs` to another function


bool g(Rs...)(Rs rs);

through a call to some map-and-forward-like-function 
`forwardMap` in something like


bool f(Rs...)(Rs rs)
{
alias someArbitraryFun = _ => _;
return g(forwardMap!(someArbitraryFun)(rs));
}

?

What should the definition of forwardMap look like?

Does Phobos contain something like this already?


there is staticMap.


Re: Validity of cast(void*)size_t.max

2018-03-05 Thread Stefan Koch via Digitalmars-d-learn

On Monday, 5 March 2018 at 18:04:20 UTC, Nordlöw wrote:
On Monday, 5 March 2018 at 16:07:49 UTC, Steven Schveighoffer 
wrote:
No, I mean you call holeKey at *runtime*. Inlined, it's just 
returning a constant, so it should reduce to a constant.


A compile-time constant visible to the optimizer?


Yes indeed. For gdc and ldc the optimisation is guranteed and I 
am quite dmd can do this as well. As long as you don't have too 
many statements.


Re: Equivalent to Python with Statement

2018-02-27 Thread Stefan Koch via Digitalmars-d-learn

On Tuesday, 27 February 2018 at 16:17:20 UTC, Jonathan wrote:
I know Python's `with` statement can be used to have an 
automatic close action:

```
with open("x.txt") as file:
#do something with file
#`file.close()` called automatically
```

I know D's `with` statement does something different but is 
there some sort of equivalent?


In this case with(File("bla"))
will do the same.


Re: How do I trace that memory error?

2018-02-27 Thread Stefan Koch via Digitalmars-d-learn

On Monday, 26 February 2018 at 18:01:07 UTC, Marc wrote:
I've tried both gdb and windbg debugger both it either get a 
"received signal ?" from gdb or crash the GUI application 
(windbg).

The error is:

core.exception.OutOfMemoryError@src\core\exception.d(696): 
Memory allocation failed


How do I find out the source of the error?


I'd say allocating in a loop is a bad idea :)

perhaps you should start with posting the code that leads to this.


Re: Understanding the AST...

2018-02-22 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 22 February 2018 at 13:21:04 UTC, joe wrote:

On Monday, 12 February 2018 at 08:47:58 UTC, RazvanN wrote:

[...]


Follow up question...

Why is *.parent always null?
e.g.:

extern(C++) class MyVisitor(AST): ParseTimeTransitiveVisitor!AST
{
  override void visit(AST.Import i)
  {
assert(i.parent is null); // always true
  }

  override void visitFuncBody(AST.FuncDeclaration f)
  {
assert(f.parent is null); // always true
  }
}


I think parent is only set after sema.
and you are overriding the parsetime visitor.


Re: std.zip size limit of 2 GB?

2018-02-15 Thread Stefan Koch via Digitalmars-d-learn

On Thursday, 15 February 2018 at 11:56:04 UTC, Andre Pany wrote:

Hi,

I just noticed that std.zip will throw an exception if the 
source files exceeds 2 GB.
I am not sure whether this is a limitation of zip version 20 or 
a bug. On wikipedia a

size limit of 4 GB is mentioned. Should I open an issue?

[...]


It was partially changed in this PR: 
https://github.com/dlang/phobos/pull/2914/files

The the put methods where left at int must have been an oversight.


Re: unable to fork: Cannot allocate memory / core.checkedint / gtkd

2018-02-13 Thread Stefan Koch via Digitalmars-d-learn

On Tuesday, 13 February 2018 at 14:10:44 UTC, number wrote:
Ok, thanks for the info. I guess I'll just use printf then for 
larger enums.


To get the same convince you can use.
the enumToString from:

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

and writeln the result oft that.
however it'll cause an error if there are two enum memebrs with 
the same value.


Re: unable to fork: Cannot allocate memory / core.checkedint / gtkd

2018-02-13 Thread Stefan Koch via Digitalmars-d-learn

On Tuesday, 13 February 2018 at 12:17:31 UTC, number wrote:

On Sunday, 11 February 2018 at 15:05:26 UTC, number wrote:

On Sunday, 11 February 2018 at 13:17:13 UTC, number wrote:

unable to fork: Cannot allocate memory

if i comment-out the line..
writeln(GdkKeysyms.GDK_Escape);

then it compiles/links/runs fine.




I just tried again.
compiling the following code eats up my 4GB of RAM and fails. 
Please copy the enumeration
from: 
https://github.com/gtkd-developers/GtkD/blob/master/generated/gtkd/gdk/Keysyms.d

into the code.


import std.stdio;

void main()
{
writeln(GdkKeysyms.GDK_Escape);
}

public enum GdkKeysyms
{
...
}


Reducing the number of enum entries step by step finally will 
make the compilation succeed. Is it normal that it needs so 
much memory?


Yes unfortunately std.conv approaches the problem of printing 
enums with recursive templates  , which eat a ton of memory.


Re: Interactive Interpreter

2018-02-05 Thread Stefan Koch via Digitalmars-d-learn

On Monday, 5 February 2018 at 19:54:09 UTC, Jiyan wrote:
Is there any work for an interactive interpreter for D -maybe 
just for ctfe-able expressions?
It shouldnt be too hard to implement it regarding the fact, 
that ctfe is kinda doing what

an interpreter should do i guess.


There is https://github.com/dlang-community/drepl which should 
give you what you want.
As the person who builds newCTFE I can tell you that it is rather 
tricky :)


  1   2   3   >