Re: Why does Unconst exist?

2021-07-28 Thread user1234 via Digitalmars-d-learn

On Wednesday, 28 July 2021 at 05:38:44 UTC, Tejas wrote:
When I initially saw it, I was hopeful that it would allow me 
to bypass some of the restrictions of ```const``` , but it 
literally just takes a type and strips the ```const``` from it, 
you can't pass a variable to it in order to get rid of 
```const``` . What use does it serve then?


To manipulate types in template metaprogramming.

To remove `const` from a variable, `cast() stuff` is shorter than 
`cast(Unconst!(typeof(stuff))) stuff`, but  it also removes 
`shared` and `immutable.


Re: Destructors can't be @nogc?

2021-07-24 Thread user1234 via Digitalmars-d-learn

On Friday, 23 July 2021 at 20:24:02 UTC, Jim wrote:

Hello,

I've been playing with D and trying to understand how to work 
with @nogc. I must be doing something wrong, because even 
though I tagged the destructor for my class `@nogc`, I'm 
getting the following error: `.\min.d(27): Error: "@nogc" 
function "D main" cannot call non-@nogc function 
"object.destroy!(true, TestClass).destroy`


[...]
What is the problem here? Should I not call `destroy`? If so,


`destroy()` uses the runtime types informations to detect the 
most derived destructor (as you might cast from `TestClass` to 
least specialized, i.e `Object`). The type infos for classes 
stores the destructor in form of a function pointer that has not 
`@nogc` as part of its attributes.



what should I call instead?


get rid of `destroy()` and instead use your own allocator, 
virtual constructor (instead of `this(){}`) and virtual 
destructor (instead of `~this(){}`) in a base class.


e.g

```d
class Base
{
static auto make(T : Base, Args...)(Args args)
{
auto size = __traits(classInstanceSize, T);
auto memory = malloc(size)[0..size];
T t = emplace!(T)(memory);
t.construct(args); // call the most derived
return t;
}

void construct() @nogc
{
printf("Base constructor called\n");
}

void destruct() @nogc
{
printf("Base destructor called\n");
free(cast(void*) this);
}
}

class Derived : Base
{
override void construct() @nogc
{
super.construct(); // construct from base to most derived
printf("Derived constructor called\n");
}

override void destruct() @nogc
{
printf("Derived destructor called\n");
super.destruct(); // destruct from derived to base
  // finishing with the deallocation
}
}

void main(string[] args) @nogc
{
Base b = Base.make!(Derived);
b.destruct();
}
```

things get called correctly


Base constructor called

Derived constructor called
Derived destructor called
Base destructor called

That bypasses the runtime mechanism for classes construction and 
destruction.
But `new` and `destroy` must not be called anymore, you must get 
stick with your own system.




Re: Destructors can't be @nogc?

2021-07-24 Thread user1234 via Digitalmars-d-learn

On Sunday, 25 July 2021 at 01:17:06 UTC, user1234 wrote:
That bypasses the runtime mechanism for classes construction 
and destruction.
But `new` and `destroy` must not be called anymore, you must 
get stick with your own system.


and of course `cast(Object)` should be prohibited (maybe `opCast` 
overload can enforce that).





Re: Generate docs for generated code?

2021-07-23 Thread user1234 via Digitalmars-d-learn

On Friday, 23 July 2021 at 10:04:55 UTC, wjoe wrote:
Is there a way for the compiler to consider doc comments in 
auto generated, mixed in code?

E.g.
```D
string fooImpl = q{
   /// Bar does fancy things.
   const void bar() { /*do something fancy*/ }
};

/// This is Foo
struct Foo(A, B, C) {
  mixin(fooImpl);
}
```

So that the documentation for ```struct Foo``` has that of the 
member ```bar()``` ?


unfortunately no and this is considered as a 
[bug](https://issues.dlang.org/show_bug.cgi?id=2420)


Re: How to select the regex that matches the first token of a string?

2021-07-03 Thread user1234 via Digitalmars-d-learn

On Saturday, 3 July 2021 at 09:05:28 UTC, vnr wrote:

Hello,

I am trying to make a small generic lexer that bases its token 
analysis on regular expressions. The principle I have in mind 
is to define a token type table with its corresponding regular 
expression, here is the code I currently have:


[...]


storing the regex in a token is an antipattern.


Re: dlang vs crystal-language

2021-05-03 Thread user1234 via Digitalmars-d-learn

On Saturday, 1 May 2021 at 13:04:15 UTC, sighoya wrote:

On Wednesday, 28 April 2021 at 22:41:03 UTC, Alain De Vos wrote:
What are the strengths and weaknesses comparing the two 
languages ?
I can name a strength of dlang is the working binding to tk 
and gtk.


Just to say, Crystal is a neat language, feels like a static 
ruby.


Strengths:

- Poweful type inference
- lightweight julian/ruby like syntax
- nice lightweight macros, don't know if they were a good fit 
for D

- nice yield builtins
- feels like a lightweight Java
- nice high level feeling and is GCed

Weaknesses:

- as I said, it is hard to understand when type inference is 
used completely everywhere, said that this is crystals killer 
feature
- slow compilation time just because of the "type inferred 
everywhere" design


I seriously wonder if this is a criterion. For example Gitlab 
which is known to get updated each month, still uses Ruby in 
their backend. So their clients use scripts that could be 2x to 
20x faster if made in Crystal.



- the OOP system lacks specific features from other OOP systems
- hasn't the same support for low level programming as in D or 
Nim

- is relative unknown, although I don't know why.





Re: Since dmd 2.096.0: import `x.t` is used as a type

2021-04-30 Thread user1234 via Digitalmars-d-learn

On Friday, 30 April 2021 at 17:58:43 UTC, kdevel wrote:

dmd since 2.096.0 with ``t.d``

```t.d
module t;

class t {
}
```

and ``x.d``

```x.d
module x;
import t;

void main ()
{
   t x = new t;
}
```

reports

$ dmd -i x.d
x.d(6): Error: import `x.t` is used as a type
x.d(6): Error: import `x.t` is used as a type

Could not find this Change in 
https://dlang.org/changelog/2.096.0.html. Has this been "fixed" 
with some other issue?


Workaround:

```x.d
...
import t : t;
...
```


Likely a side effect of https://github.com/dlang/dmd/pull/12178 
but

according to me the new behavior is correct.


Re: Deriving a D-class from a CPP-class

2021-04-29 Thread user1234 via Digitalmars-d-learn

On Thursday, 29 April 2021 at 06:38:53 UTC, evilrat wrote:

On Wednesday, 28 April 2021 at 19:46:00 UTC, Alain De Vos wrote:


It is rather clear what I want to achieve but virtual 
functions give me headache because dlang does not now the word 
virtual.


It's virtual by default. The opposite is `final`.


by default, excepted if protection is private or package.


Re: Static array initialisation

2021-04-01 Thread user1234 via Digitalmars-d-learn

On Thursday, 1 April 2021 at 09:30:28 UTC, DLearner wrote:

On Wednesday, 31 March 2021 at 23:21:59 UTC, russhy wrote:

On Wednesday, 31 March 2021 at 17:54:38 UTC, DLearner wrote:

[...]


Can you show the print function?

Maybe the problem lies there?


Using rdmd, I believe the code below demonstrates the situation.

import std.stdio;
void main() {
   immutable uint  MemSize=100;  // Memory size in bytes.
   uint counter;
   uint idx;
   ubyte* WkPtr;
   ubyte WkUbyte;

// Memory Pool
   ubyte[MemSize]  MemPool = 8;  // Initialised to 8 for 
debugging.


   WkPtr = [0];

   counter = 1;
   while (counter <= 102) {

  idx = counter - 1;

  WkUbyte = *(WkPtr + idx);

  writeln("idx = ", idx, "WkUbyte = ", WkUbyte);

  counter = counter + 1;
   }
}


memset would fill a whole page even if the specified size is in 
the middle of a page. Try with 64, 4096 for example, instead of 
100.


Re: rdmd and D equivalent for PYTHONPATH?

2021-03-17 Thread user1234 via Digitalmars-d-learn

On Wednesday, 17 March 2021 at 07:13:31 UTC, Chris Piker wrote:

On Wednesday, 17 March 2021 at 06:07:01 UTC, user1234 wrote:


[...]


Very handy example.  Unfortunately it means that paths are 
embedded

in scripts, which is usually a bad idea.

[...]


You can use a local registry too. That should work but ten the 
dep version must be set to "*". See 
https://dub.pm/commandline.html#add-local


Re: rdmd and D equivalent for PYTHONPATH?

2021-03-17 Thread user1234 via Digitalmars-d-learn

On Wednesday, 17 March 2021 at 04:34:07 UTC, Chris Piker wrote:

On Wednesday, 17 March 2021 at 03:43:22 UTC, Chris Piker wrote:

Note: I'm aware of dub.  This isn't a question about dub.  I'm 
making scripts for local use, not redistributable binaries, so 
I would like to "install" mir-algorithm and similar libraries 
for my rdmd scripts to use.


Sorry to reply to myself, but I found something that will run
the scripts, though it still doesn't make use of local 
libraries.


   #!/usr/bin/env dub
   /+ dub.sdl:
   dependency "mir-algorithm" version="~>1.0"
   +/

   import mir.ndslice
...

Since dub seems to work a bit better as the "interpreter" then
rdmd (assuming you're connected to the Internet)


You can use local a specific local version too, for example the 
git repository


  #!/usr/bin/env dub
  /+ dub.sdl:
dependency "mir-algorithm" 
path="/home/x/repositories/mir/mir-algorithm"

  +/

In addition with --nodeps, no internet is required.




Re: D's Continous Changing

2021-03-04 Thread user1234 via Digitalmars-d-learn

On Thursday, 4 March 2021 at 09:21:12 UTC, Siemargl wrote:

On Thursday, 4 March 2021 at 06:43:57 UTC, user1234 wrote:


otherwise another solution is to check every two monthes the 
sanity of your projects. E.g a montly cronjob on a CI service 
and that uses latest DMD Docker image. If it fails you got an 
email... It certainly cooler to take 5 mins every two monthes 
than 7 hours 4 years.
Nice idea. Try do it with all hundreds of used in your projects 
libraries.


isObject, isArray, etc ;) ?


Re: D's Continous Changing

2021-03-03 Thread user1234 via Digitalmars-d-learn

On Thursday, 4 March 2021 at 05:44:53 UTC, harakim wrote:
For the record, I was able to resolve all of my issues in about 
7 hours. That included upgrading from DerelictSDL to bindbc and 
converting to use dub instead of make.


I hope my above post does not lead people to believe that I 
don't like D, because I otherwise wouldn't have lost track of 
time until midnight working on this project!


I also should mention that this project was probably last 
touched in 2017. I thought I pulled it out a year ago, but that 
was a different project.


otherwise another solution is to check every two monthes the 
sanity of your projects. E.g a montly cronjob on a CI service and 
that uses latest DMD Docker image. If it fails you got an 
email... It certainly cooler to take 5 mins every two monthes 
than 7 hours 4 years.


Re: DUB is not working correctly

2021-02-25 Thread user1234 via Digitalmars-d-learn

On Thursday, 25 February 2021 at 17:34:29 UTC, Maxim wrote:
In my opinion, that happens because of DUB can't accept my 
changes to the file. But how to make the manager admit it? I 
apologize to everyone who understood me wrong.


If you use an ide to edit the DUB receipt maybe it's possible 
that you forgot to save the project before retriggering a 
rebuild. If so then the file used by DUB is still in its previous 
state.





Re: Ugly c++ syntax

2021-02-06 Thread user1234 via Digitalmars-d-learn

On Friday, 5 February 2021 at 21:10:21 UTC, Rumbu wrote:

Can some C++ guru translate in D the template below?

I gave up after reading a lot, but I didn't manage to 
understand the meaning "&& ..."


template  static uint8_t 
composite_index_size(Tables const&... tables) { return 
(composite_index_size(tables.size(), 
impl::bits_needed(sizeof...(tables))) && ...) ? 2 : 4; }


Thanks.


modern cpp looks like 10 lines of decl for 1 of actual code.


Re: How to debug D on Linux

2021-01-13 Thread user1234 via Digitalmars-d-learn

On Wednesday, 13 January 2021 at 13:47:55 UTC, Roguish wrote:

On Wednesday, 13 January 2021 at 13:30:48 UTC, Roguish wrote:
Anything else I need to know when debugging on Linux, without 
an IDE?


One specific question I have is: what's the difference between 
-g and -debug and -d-debug?


Also, what does it mean to "always emit a stackframe" (compiler 
option -gs) ?


-g : generate dwarf info, the debug info, the most important
-debug : compiles the debug statements, e.g debug logging. not so 
important, this

 is a conditional compilation feature.
-gs: always emit a prelude/prologue. but dmd pretty much 
always do that even

 when not required (sigh).

You really mostly only requires -g. Then you have to learn gdb.
A few basis to get started, a session for a segfault is often like

  $ gdb ./myapp
  $ run

and when it crashes, note the source position, additionally

  $ bt
  $ p somevar
  $ p some.more.complex.expression

may already give interesting infos. If not, during a second 
session you will rather put breakpoints to see what happens 
before the access violation and step from that breakpoint to the 
code that accesses unowned memory.


  $ gdb ./myapp
  $ break .d 
  $ run

and then step by step, each time it pauses you inspect the 
interesting stuff.
Note that I may be wrong on the syntax of the commands as I 
always use an IDE GUI.


Re: Request assistance initializing struct instance at global scope

2020-12-06 Thread user1234 via Digitalmars-d-learn

On Monday, 7 December 2020 at 05:28:41 UTC, user1234 wrote:
On Monday, 7 December 2020 at 04:13:16 UTC, Andrew Edwards 
wrote:

Given:

===
extern(C):
char*[] hldr;
enum I = (1<<0);
struct S { char* ft; char** fm; int f; }

void main(){}
===

How do I initialize an instance of S at global scope?


You cant. At the global scope the initializers must be runnable 
at compile time, i.e using CTFE. I've tried to simplify what 
would be required:


---
extern(C):
char*[] hldr;
enum I = (1<<0);
struct S { char* ft; char** fm; int f; }

void main(){}

enum char[8] FirstLevel  = ['0'];
enum DoubleLevel = [0]; // here

S[] s = [
S(
FirstLevel.ptr,
DoubleLevel,  // error is here actually, 
interesting

0),
];
---

D is not able of that :

/tmp/temp_7F835402B0F0.d:9:28: Error: cannot use non-constant 
CTFE pointer in an initializer `&['0', '\xff', '\xff', '\xff', 
'\xff', '\xff', '\xff', '\xff'][0]`


sorry my example was bad, better one

---
extern(C):
char*[] hldr;
enum I = (1<<0);
struct S { char* ft; char** fm; int f; }

void main(){}

enum char[8] Stuff  = ['0'];
enum FirstLevel = Stuff.ptr; //  so char* OK

S[] s = [
S(
FirstLevel,   // char* OK
, // error here   char** NG at CTFE
0),
];
---


Re: Request assistance initializing struct instance at global scope

2020-12-06 Thread user1234 via Digitalmars-d-learn

On Monday, 7 December 2020 at 04:13:16 UTC, Andrew Edwards wrote:

Given:

===
extern(C):
char*[] hldr;
enum I = (1<<0);
struct S { char* ft; char** fm; int f; }

void main(){}
===

How do I initialize an instance of S at global scope?


You cant. At the global scope the initializers must be runnable 
at compile time, i.e using CTFE. I've tried to simplify what 
would be required:


---
extern(C):
char*[] hldr;
enum I = (1<<0);
struct S { char* ft; char** fm; int f; }

void main(){}

enum char[8] FirstLevel  = ['0'];
enum DoubleLevel = [0]; // here

S[] s = [
S(
FirstLevel.ptr,
DoubleLevel,  // error is here actually, 
interesting

0),
];
---

D is not able of that :

/tmp/temp_7F835402B0F0.d:9:28: Error: cannot use non-constant 
CTFE pointer in an initializer `&['0', '\xff', '\xff', '\xff', 
'\xff', '\xff', '\xff', '\xff'][0]`





Re: ParameterIdentifierTuple returns empty strings

2020-12-02 Thread user1234 via Digitalmars-d-learn

On Wednesday, 2 December 2020 at 11:46:26 UTC, Andre Pany wrote:

Hi,

I need to retrieve the parameter identifier but only empty 
strings are returned:

tuple("", "")

``` d
alias fpt = extern(C) nothrow void function(int a, int b);

void main()
{
import std.traits : ParameterIdentifierTuple;
pragma(msg, ParameterIdentifierTuple!(fpt));
}
```

Where is here the error?

Kind regards
André


If you look at the template [1] implementation, function pointers 
are rejected, apparently because of a `__parameters` limitation.


There something to report. Bad documentation at least.

[1]: 
https://github.com/dlang/phobos/blob/2c0660141748a13637ff473cbb7b0d52eb1c44db/std/traits.d#L1400


Re: New vs length on dymamic array

2020-11-09 Thread user1234 via Digitalmars-d-learn

On Monday, 9 November 2020 at 08:06:54 UTC, Andrey wrote:

Hello,

Are here any differences in creation of dynamic array with 
known size?



auto array = new wchar[](111);


and


wchar[] array;
array.length = 111;


It's the same. If the two are valid then you are in a function. 
So it's an alloca for the dynamic array payload (8+8 bytes on 
x86_64) then a LengthExpression that will lead to a GC.malloc, 
and finally a memset for all the elements default values.


Re: Question about: ("1.1").to!int;

2020-10-23 Thread user1234 via Digitalmars-d-learn
On Friday, 23 October 2020 at 13:57:41 UTC, Joseph Rushton 
Wakeling wrote:

On Wednesday, 21 October 2020 at 22:50:27 UTC, matheus wrote:
Since (1.1).to!int = 1, shouldn't the string value 
("1.1").to!int at least try to convert to float/double and 
then to int?


The thing is, that's a great way for hard-to-identify bugs to 
creep into code.  In these cases:


auto a = (1).to!int; // this works
auto b = ("1").to!int;   // this works
auto c = (1.1).to!int;   // this works and c = 1

... then what the programmer wants is unambiguous.  In the 
first case it's just converting int => int.  In the second, 
it's converting from a string that unambiguously represents an 
integer value, to an int.  And in the third, it's converting 
_at programmer request_ from a double to an int (which has a 
well-defined behaviour).


However, if ("1.1").to!int were to work, this would be the `to` 
function making a judgement call on how to handle something 
ambiguous.  And while that judgement call may be acceptable for 
your current use-case, it won't be for others.


In particular, if `to` just accepted any string numerical 
representation for conversion to int, how could the caller 
explicitly _exclude_ non-integer input, if that is their 
use-case?


So it's far better to require you, as the programmer, to make 
what you want unambiguous and explicitly write code that will 
(i) deserialize any numerical string that is acceptable to you 
and (ii) convert to integer.


The third case is just like `cast(int) 1.1` it's not _at 
programmer request_ from my point of view, it's just that the 
`to` template has not be more restrictive than the D `cast` 
expression. `to` should do at least what a `cast` do and do more 
when there's no rule for the two types that are involved.


Re: Renaming Flag!"" in API

2020-10-12 Thread user1234 via Digitalmars-d-learn

On Monday, 12 October 2020 at 10:24:44 UTC, FreeSlave wrote:

Let's say I use Flag type named 'myflagname' in API like this:

import std.typecons;

void func(Flag!"myflagname" flag)
{
//...
}

void main()
{
func(Yes.myflagname);
}

Later I realize that 'myflagname' is a bad name and I want to 
change it to something else. But if I do so, I break the 
existing code using this API as Flag with different name will 
be a different type and Yes.myflagname and No.myflagname won't 
fit in. I can't use alias as Yes and No relies on string 
literal.
Can this issue overcome somehow? Looks like a fundamental flaw 
with std.typecons.Flag.


Once encountered a similar situation. Flag was good but once you 
know your API, and as in my case I was the only user, I just 
replaced with a template param + constraint.
In the worst case, let's say you forget a bit the API, a DDOC 
popup can help.


example:

---
import std.typecons;

/* Params:  T = anything convertible to bool
t = indicates whether do this or do that  */
void func(T)(T t) if (is(T : bool)){}

void main()
{
enum yn { yes = true, no = false}
// all good, all same semantic
func(yn.yes);
func(true);
func(Yes.myflagname);
}
---


Re: Trying to create a trivial 64 bit D Lang DLL on a Windows 10 machine and cant get past linking.

2020-10-01 Thread user1234 via Digitalmars-d-learn
On Wednesday, 30 September 2020 at 11:45:53 UTC, Ferhat Kurtulmuş 
wrote:
On Tuesday, 29 September 2020 at 21:22:21 UTC, WhatMeWorry 
wrote:

module user;

export { int myAddSeven(int a, int b); }

[...]


it is better to use this template 
https://github.com/dlang/dmd/tree/master/samples/mydll


You don't have a DllMain.


yeah that's the problem, check [0] OP. The author makes 
commercial dll on windows so he knows what he speaks about


[0] 
https://forum.dlang.org/post/mscgsclxwtjcferfx...@forum.dlang.org


Re: Unable to open filename passed as command line argument

2020-09-03 Thread user1234 via Digitalmars-d-learn

On Thursday, 3 September 2020 at 10:47:04 UTC, Curious wrote:

Given the following:

=a==
void main(string[] args)
{
FILE* fp = fopen(args[1].ptr, "r");
if (!fp) throw new Exception("fopen");
}

=b==
void main(string[] args)
{
FILE* fp = fopen(args[1].dup.ptr, "r");
if (!fp) throw new Exception("fopen");
}

Why does a fail but b succeed?


version b works by accident/UB. You need to null terminate your 
filename if you use the C library functions:


---
void main(string[] args)
{
FILE* fp = fopen((args[1] ~ '\0').ptr, "r");
if (!fp) throw new Exception("fopen");
}
---

otherwise what you get as args are D dynamic arrays (a payload 
made of .ptr and .length) so you can use std.file or std.stdio to 
open a file using the "D main" arguments (it's not the like "C 
main").


---
void main(string[] args)
{
import std.stdio;
File f = File(args[1], "r");
}
---


Re: Tuple poilerplate code

2020-08-31 Thread user1234 via Digitalmars-d-learn

On Tuesday, 1 September 2020 at 02:08:54 UTC, JG wrote:
Is there anyway to remove the boilerplate code of dealing with 
tuples:


I find myself having to write things like this fairly often

auto someRandomName  = f(...); //where f returns a tuple with 
two parts

auto firstPart = someRandomName[0];
auto secondPart = someRandomName[1];


Is to possible to write something so that the above is 
essentially equivalent to:


assignTuple!(firstPart,secondPart) = f(...);

The closest I can produce is using a template mixin so that I 
would have to write:


mixin AssignTuple!(()=>f(...),"firstPart","secondPart");


---
void assignTuple(S, T...)(auto ref S s, auto ref T t)
{
static foreach (i; 0 .. S.length)
t[i] = s[i];
}

void main()
{
import std;
string a,b;
tuple("a", "b").assignTuple(a,b);
}
---


Re: Since DMD 2.089.0 and later, compiled .exe showing SFX zip and opening with winRar when use resource.

2020-08-18 Thread user1234 via Digitalmars-d-learn

On Tuesday, 18 August 2020 at 19:01:17 UTC, Marcone wrote:
When I compile the source .d code to .exe adding an icon using 
resource .res file in dmd 2.089.0 and later, the .exe file show 
SFX zip in it is properties and open with winRar. This ir 
normal or is a Bug? See images below.


Se image in this links:

SFX zip in it is properties: https://i.imgur.com/dH7jl5n.png
Opening with winRar: https://i.imgur.com/s7C9mZn.png


Try to extract the PE header and paste it here. It's possible 
that something interfer with SFX header... can be also winrar 
that interpret wrongly the header. You should be able to see 
quickly any problem with the help of this table 
http://faydoc.tripod.com/structures/15/1594.htm


Re: __vector(ubyte[32]) misalignment

2020-08-08 Thread user1234 via Digitalmars-d-learn

On Sunday, 9 August 2020 at 01:56:54 UTC, Bruce Carneal wrote:

On Sunday, 9 August 2020 at 01:03:51 UTC, Bruce Carneal wrote:
The .alignof attribute of __vector(ubyte[32]) is 32 but 
initializing an array of such vectors via an assignment to 
.length has given me 16 byte alignment (and subsequent seg 
faults which I suspect are related).


Is sub .alignof alignment expected here?  IOW, do I have to 
manually manage memory if I want alignments above 16?


Manually managing the alignment eliminated the seg faulting.

Additionally, I found that std.experimental.mallocator 
Mallocator.alignment is 16.


So, is the misalignment baked in at this point?


there's AlignedMallocator that allows to overrides the 
"platformAlignment".

To get vector spece Mallocator is indeed a bad choice.


Re: Picking function templates with __traits(getOverloads, ..., true)

2020-07-29 Thread user1234 via Digitalmars-d-learn
On Wednesday, 29 July 2020 at 23:57:21 UTC, Jean-Louis Leroy 
wrote:

This works:

[...]
I may be missing the obvious...or it's a compiler bug???


Yes and it's just been fixed, see 
https://github.com/dlang/dmd/pull/11431.

So uncommenting the second times works on ~master.




Re: Uploading coverage to Codecov doesn't work

2020-07-08 Thread user1234 via Digitalmars-d-learn

On Wednesday, 8 July 2020 at 15:55:58 UTC, Mitacha wrote:

Hello there,

I've been trying to setup bitbucket pipelines to submit 
coverage to codecov, but with no luck.
I use `dub run -b unittest-cov` and it generates .lst files 
correctly, then `bash <(curl -s https://codecov.io/bash) -t 
$CODECOV_TOKEN` is called, but all I get is:


```
==> Bitbucket detected.
project root: .
Yaml not found, that's ok! Learn more at 
http://docs.codecov.io/docs/codecov-yaml

==> Running gcov in . (disable via -X gcov)
==> Python coveragepy not found
==> Searching for coverage reports in:
+ .
--> No coverage report found.
Please visit http://docs.codecov.io/docs/supported-languages
```
No reports were uploaded.

The thing I'm concerned about is "--> No coverage report 
found.". I checked and token is supplied. I ran same commands 
locally and get same result.


Is there some magic configuration in yaml file necessary, to 
make that work?


You may have to specify the folder where the lst files are 
created. THis is done in the config file. Once I had to do this 
because I used 
https://dlang.org/phobos/core_runtime.html#.dmd_coverDestPath.


Re: Construct an used-defined hash table container type from an AA-literal expression

2020-07-05 Thread user1234 via Digitalmars-d-learn

On Sunday, 5 July 2020 at 21:38:12 UTC, Per Nordlöw wrote:

On Sunday, 5 July 2020 at 21:22:13 UTC, ikod wrote:

struct AA(K,V)
{
void opAssign(V[K] aa)
{
}
}

void main()
{
AA!(string, int) custom_aa;
custom_aa = ["one":1, "two":2];
}


Forget to mention that I want the assign call (to `opAssign`) 
in `main` to be non-(GC)heap allocating like when using C++'s 
std::initializer_list.


Hereh we go ;)

---
import std;

struct AA
{
void opIndexAssign(int v, string k) @nogc
{}
}

void main(string[] args) @nogc
{
AA myCustom;

enum literal = ["one":1, "two":2].stringof[1..$-1];
enum pairs   = literal.split(',').array;
static foreach (p; pairs)
{
myCustom[mixin(p.split(':')[0])] = mixin(p.split(':')[1]);
}
}
---


Re: Construct an used-defined hash table container type from an AA-literal expression

2020-07-05 Thread user1234 via Digitalmars-d-learn

On Sunday, 5 July 2020 at 21:06:32 UTC, Per Nordlöw wrote:
Is there a way to construct a custom written hash-table 
container (struct) from an AA-literal expression?


How about iterating the literal, e.g

---

foreach (k,v; ["one":1, "two":2])
{
myCustomAA[k] = v;
}

---


Re: dmd release schedule?

2020-07-04 Thread user1234 via Digitalmars-d-learn

On Saturday, 4 July 2020 at 20:48:02 UTC, drathier wrote:

On Sunday, 28 June 2020 at 10:44:26 UTC, drathier wrote:
Is there a release schedule anywhere for DMD? Any list of 
tasks to be the next release? I'm only finding 5+ year old 
things when searching.


Yes: https://dlang.org/changelog/release-schedule.html


This is only the calendar, not the content.

For the features, the main line is DIP driven. Big changes come 
from this, always. Then all the regressions, critical, major, 
industry, compiler crashes, bugs.


There are also tendencies, usually started from News Group 
discussions. For example since a few days the tendency is to work 
on reducing the memory use. A few weeks ago it was about 
templates and their cost.


Tendencies are not necessarily followed by many contributors. For 
example since several weeks  Wlater Bright is working on 
replacing the internal data structures used in the back end, and 
almost alone. Just to highlight the fact that there can be 
coherant (non random) initiatives.


Then the remainings bits are indivudally driven, good willing 
driven, mood driven...
for example if someone finds a problem and that he can fix it by 
himself then he does.


Re: Rules for Symbol Name Lookup seem contradictory

2020-06-21 Thread user1234 via Digitalmars-d-learn

On Monday, 22 June 2020 at 01:38:41 UTC, Manfred Nowak wrote:
https://dlang.org/spec/module.html#name_lookup contains under 
4.3.4 only two sentences.


While the first sentence explains, that the search ends
  "as soon as a matching symbol is found",
the second sentence implies that the search may continue until 
it is sure, that

  no other symbol "with the same name" can be found
in the current phase.

This means, that under sentence one the following code is free 
of errors and under sentence two the following code has to be 
rejected, because an ambiguity exists.


De facto the code compiles without error under dmd v2.092.1:

class C{
}
class D{
  C c;
  this(){
auto c= new C;
  }
}
void main(){
  auto d= new D;
}


Classes (non templatized) cannot be overloaded so in your example 
the rule that applies is that the one from the most inner scope 
is selected.
For functions and templates this is another story. As they can be 
part of overload set, they are all selected by name and then 
tried with the arguments (template or call args) and if two 
matches then the error happens.


Maybe that the spec is a bit vague as it doesn't mention that 
rules for lookups of non overloadable symbols are more simple.


Re: Passing a variable number of slices into a function

2020-06-21 Thread user1234 via Digitalmars-d-learn

On Monday, 22 June 2020 at 01:47:49 UTC, repr-man wrote:
Is there any way to pass an unknown number of slices into a 
function?  I'm trying to do something along the lines of:


void func(T)(T[] args...)
{
//...
}

That wasn't working,

[...]

Thanks for the help!


Can you provide more details for "that wasnt working" ? because

  void func(T)(T[] args...)
  {
writeln(args.length);
  }

  void main()
  {
int[] a,b;
func(a[0..$],b[0..$]);
  }

works, so there must be a missing detail.
Maybe each slice has different type ?


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

2020-06-17 Thread user1234 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?


You have the example of libdparse that shows that using a class 
can be a good idea [1] [2].
For DCD, the parser overrides a few thing because otherwise 
completion does not work properly or has scope issues. But TBH 
there's not many reasons to use a class otherwise.


[1] 
https://github.com/dlang-community/dsymbol/blob/master/src/dsymbol/conversion/package.d#L102
[2] 
https://github.com/dlang-community/dsymbol/blob/master/src/dsymbol/conversion/package.d#L138





Re: Alias function declaration.

2020-05-19 Thread user1234 via Digitalmars-d-learn

On Tuesday, 19 May 2020 at 22:04:49 UTC, MaoKo wrote:
Hello. I just want to find what is exactly the difference 
between:

alias _ = void function(int);
alias void _(int);
Because it's seem that the latter can't be used in the 
declaration of an array (eg: _[] ...).
I think the first is a pointer to function and the second is a 
function type itself but I'm not sure.


yes this is correct. To declare a function type using the first 
form is also possible:


alias TF1 = void(int);
alias void TF2(int);
static assert (is(TF1 == TF2));



Re: final struct ?

2020-05-19 Thread user1234 via Digitalmars-d-learn

On Tuesday, 19 May 2020 at 10:29:51 UTC, wjoe wrote:

On Tuesday, 19 May 2020 at 10:08:37 UTC, user1234 wrote:

On Tuesday, 19 May 2020 at 10:01:34 UTC, wjoe wrote:

[...]


It has no purpose. In D many attributes are allowed even if 
they have no meaning.
D-Scanner checks this kind of stuff, to some extent, but not 
the compiler.


Thank you.


A little sample to show you more cases of attributes that have no 
effect:


---
struct Foo
{
nothrow @nogc int field; // why not ?

void func()
{
void nested() const
{
field++;  // mutation is allowed because const is 
a noop

extern int j; // extern decl in a nested func...
}

nothrow i = 8;// just like auto
pure f = 9;   // just like auto
@safe s = 10; // just like auto
@system t = s;// just like auto
}
}

void main() { }
---


Re: final struct ?

2020-05-19 Thread user1234 via Digitalmars-d-learn

On Tuesday, 19 May 2020 at 10:01:34 UTC, wjoe wrote:
As I was reading a few source files of a library I found dozens 
of final struct declarations like this:


final struct Foo {

  const pure final nothrow bar() { ... }

}

What's this supposed to express ?

A final class is a class that can't be subclassed - structs 
can't be subclassed, so does that express something else or is 
the final redundant ?
Additionally since it's not possible to subclass a struct it's 
also not possible to override bar() - does 'final bar()' mean 
something else ?


The only relevant bits of my web search for 'dlang: final' were 
results for final class, virtual functions and final switch. Am 
I missing something ?


It has no purpose. In D many attributes are allowed even if they 
have no meaning.
D-Scanner checks this kind of stuff, to some extent, but not the 
compiler.


Re: Can’t use UFCS to create InputRange?

2020-04-29 Thread user1234 via Digitalmars-d-learn

On Wednesday, 29 April 2020 at 08:34:53 UTC, Ogi wrote:

struct R {}
int front(R r) { return 42; }
void popFront(R r) {}
bool empty(R r) { return false; }

void main() {
import std.range.primitives : isInputRange;
static assert(isInputRange!R);
}


Error: static assert:  `isInputRange!(R)` is false


Whats really weird is that if I replace isInputRange with its 
definition from std.range.primitives, it returns true:


import std;

struct R {}
int front(R r) { return 42; }
void popFront(R r) {}
bool empty(R r) { return false; }

void main() {
static assert(is(typeof(R.init) == R)
&& is(ReturnType!((R r) => r.empty) == bool)
&& is(typeof((return ref R r) => r.front))
&& !is(ReturnType!((R r) => r.front) == void)
&& is(typeof((R r) => r.popFront)));
}
This compiles.

What’s going on here?


The static checker doesn't see your free funcs because to do so 
it would have to import the whole module. (is it possible to do 
that ? no idea.)
Also your signature for the primitives are quite unusual (i.e not 
idiomatic). Usually they dont take param. Usually we pass a type 
that contains the member funcs matching to IsIntputRange.


Re: Working with cmd

2020-04-18 Thread user1234 via Digitalmars-d-learn

On Friday, 17 April 2020 at 21:38:23 UTC, Quantium wrote:

Are there any libs which can be used to access cmd commands?


You can pipe cmd.exe:

---
import std.process : pipeProcess, ProcessPipes;
ProcessPipes pp = pipeProcess(["cmd.exe"]);
pp.stdin.writeln("echo foobar");
pp.stdin.close;
assert(pp.stdout.readln() == "foobar\n");
---

there are other ways depending on what you really want to do.


Re: [dmd] Types and ScopeDsymbol

2020-04-02 Thread user1234 via Digitalmars-d-learn

On Wednesday, 1 April 2020 at 18:47:38 UTC, drug wrote:
Is it true that user defined types are resolved to ScopeDsymbol 
and basic types aren't?


a basic type does not need to introduce a scope since it has no 
members. All operators on them are supported natively and are no 
modifiable, so yes certainly.


From that (here I go OT) we can imagine a version of D with no 
basic integer types but just ubyte, and everything would be 
handled with operator overloads. All the other numeric types can 
be expressed using ubyte[] in some structs, although 
not very convenient for the C interop.


Re: Type sequence concatenation / associative array implementation

2020-02-12 Thread user1234 via Digitalmars-d-learn

On Wednesday, 12 February 2020 at 20:58:49 UTC, Marcel wrote:

Hello!
I have two questions:

1- How can I concatenate two type sequences?


alias Concatenated = AliasSeq!(TList1, TList2);

or maybe

alias Concatenated = AliasSeq!(TList1[0..$], TList2[0..$]);

since I don't remember if they nest or not.

2- How is the builtin associative array implemented? I think I 
read somewhere it's implemented like C++'s std::unordered_map 
but with BSTs instead of DLists for handling collisions: is 
this correct?


see druntime source.




Re: Some impressions/notes from a new D programmer

2020-02-12 Thread user1234 via Digitalmars-d-learn

On Wednesday, 12 February 2020 at 15:28:57 UTC, Anonymouse wrote:
Maybe there are some hard design decisions again 
$HOME/.dub/bin, unsure. It might be difficult to globally pull 
off if programs expect the binary to be placed in the source 
tree (for resources).


[1]: https://github.com/CyberShadow/Digger


It could just create some shortcuts in ~/bin. AFAIK this special 
folder got automatically added to the $PATH in RH and deb 
distributions. The less obvious solution is for Windows systems.


Re: Type Inference and Try Blocks

2020-01-20 Thread user1234 via Digitalmars-d-learn

On Monday, 20 January 2020 at 23:16:07 UTC, Henry Claesson wrote:
This isn't a D-specific "problem", but there may be D-specific 
solutions.
I have a function `doSomething()` that returns a Voldemort 
type, and this same function also throws. So, there's this:


try {
auto foo = doSomething();
} catch (AnException e) {
// Do stuff
}

The problem that I'm encountering is that I'd like, assuming no 
exception was thrown, to use foo outside the `try` (or 
`finally`) block to avoid nesting as any operations on `foo` 
from that point onward may also throw. Are there any constructs 
that act as alternatives to try/catch/finally so that I can do 
this?


(This issue could very well stem from poor design and not being 
familiar with programming using exceptions. So feel free to 
ignore.)


Thanks


The problem you have is not called type inference, it's called 
"scope".
In a particular scope you have symbols "S". In a sub scope you 
also have "S" but in the parent scope "S" are not existing 
anymore.




Re: CTFE and assoc array

2020-01-19 Thread user1234 via Digitalmars-d-learn

On Sunday, 19 January 2020 at 13:02:18 UTC, Andrey wrote:
On Saturday, 18 January 2020 at 21:44:35 UTC, Boris Carvajal 
wrote:


I read that thread. But:
Deprecation: initialization of immutable variable from static 
this is deprecated.

Use shared static this instead.


And we get? No CTFE with static immutable AA?


The problem is that the code for AA consists of runtime hooks.
So in practice even if your keys and values are available the 
compiler doesn't know how to build it and use it.


At some point what could be done is a kind of serialization at 
compile time and facilities for quick deser at runtime from the 
data segment but that doesn't change the fact that they could 
still not be used for CTFE or template metaprog.


Re: Practical parallelization of D compilation

2020-01-08 Thread user1234 via Digitalmars-d-learn
On Wednesday, 8 January 2020 at 04:40:02 UTC, Guillaume Lathoud 
wrote:

Hello,

One of my D applications grew from a simple main and a few 
source

files to more than 200 files. Although I minimized usage of
templating and CTFE, the compiling time is now about a minute.

I did not find any solution to take advantage of having multiple
cores during compilation, lest I would write a makefile, or 
split

the code into multiple packages and use a package manager.

(If I missed such a possibility, feel free to write it here.)


yeah there's one. DUB does the same as you script with the 
following options:


  dub build --parallel --build-mode=singleFile



Re: @disable("reason")

2020-01-08 Thread user1234 via Digitalmars-d-learn

On Wednesday, 8 January 2020 at 00:23:48 UTC, Marcel wrote:

Hello!
I'm writing a library where under certain conditions i need all 
the default constructors to be disabled. I would like to tell 
the user why they can't instantiate the struct.

Is there a way to do that?


class Example
{
@disable this() { pragma(msg, "not allowed..."); }
}

void main()
{
new Example();
}

outputs:


not allowed...
/tmp/temp_7F8C65489550.d(12,5): Error: constructor 
`runnable.Example.this` cannot be used because it is annotated 
with `@disable`


Because pragma(msg) are evaluated when encountered you can use 
abuse them.
By specification they're not allowed to modify the meaning of the 
program.


Re: Why same pointer type for GC and manual memory?

2019-11-15 Thread user1234 via Digitalmars-d-learn

On Wednesday, 13 November 2019 at 11:07:12 UTC, IGotD- wrote:
I'm trying to find the rationale why GC pointers (should be 
names managed pointers) are using the exact same type as any 
other pointer.


Doesn't this limit the ability to change the default GC type?
Doesn't this confusion make GC pointers just as unsafe as raw 
pointers?
Has there been any prior discussion about introducing managed 
pointers in D?


One other reason is that special pointers are not good for 
debugging and have a runtime cost... in D it's not like in a VM.


Re: std.container.array: Error: unable to determine fields of Test because of forward references

2019-10-31 Thread user1234 via Digitalmars-d-learn

On Thursday, 31 October 2019 at 12:37:55 UTC, user1234 wrote:
On Thursday, 31 October 2019 at 12:29:28 UTC, Tobias Pankrath 
wrote:

[...]


Try

struct S
{
 S*[] children;
}

because otherwise when you declare the array the compiler has 
not finished the semantic ana of S.


so S size is not known while S* size is known as it's a pointer


Re: std.container.array: Error: unable to determine fields of Test because of forward references

2019-10-31 Thread user1234 via Digitalmars-d-learn
On Thursday, 31 October 2019 at 12:29:28 UTC, Tobias Pankrath 
wrote:

My Problem:

--- (https://run.dlang.io/is/CfLscj)
import std.container.array;
import std.traits;

struct Test
{
   Test[] t;
}

struct Test2
{
   Array!Test2 t;
}

int main()
{
return FieldTypeTuple!Test.length + FieldTypeTuple!Test2;
}
---

I've found https://issues.dlang.org/show_bug.cgi?id=19407 but I 
am not using separate compilation, just `dmd test.d`.


I want to have a tree structure like

---
struct S
{
S[] children;
}
---

but I do not want to rely on the GC and thus wanted to use a 
custom array type. What's the best way to do this?


Try

struct S
{
 S*[] children;
}

because otherwise when you declare the array the compiler has not 
finished the semantic ana of S.


Re: Is this a new bug ?

2019-07-20 Thread user1234 via Digitalmars-d-learn

On Saturday, 20 July 2019 at 05:21:01 UTC, Newbie2019 wrote:

On Saturday, 20 July 2019 at 04:18:15 UTC, Adam D. Ruppe wrote:
show me what you're doing now and I'll see which case it is. 
Most the time I see these, the code is significantly 
simplified and bugs fixed by removing the usages of these 
strings..


I want to do this in betterC:

template asPure(string P, alias Fn) if 
(isFunctionPointer!(typeof())) {

enum N = __traits(identifier, Fn);
	enum string asPure = "private alias " ~ N ~ "_P = " ~ 
typeof().stringof ~ " pure;\n" ~ "__gshared immutable " ~ N 
~ "_P " ~ P ~"= cast(" ~ N ~ "_P) &" ~ N ~ " ;" ;

}


use `__traits(identifier)` instead of `.stringof`, see 
https://dlang.org/spec/traits.html#identifier.


as explained this is not a new bug, not even a bug according to 
me.


Re: Order of interfaces

2019-06-21 Thread user1234 via Digitalmars-d-learn

On Friday, 21 June 2019 at 20:42:00 UTC, Tomas wrote:

Does it matter in which order a class inherits from interfaces?

   class A : Interface1, Interface2{ ... }

   vs

   class A : Interface2, Interface1{ ... }

Conceptually it should not matter, but I'm getting really weird 
segfault errors with one version and no errors with the other 
version.


compiler segfault or segfault when the program runs ?

I still do not know what I'm doing wrong, but does anyone have 
an idea why the order might matter?


Re: CT/RT annoyance

2019-06-17 Thread user1234--- via Digitalmars-d-learn

On Monday, 17 June 2019 at 05:04:50 UTC, Bart wrote:

Consider

void foo(string A = "")(string B = "")
{
static if (A != "")
   do(A);
else
   do(B);
}

[...]


I see the annoyance but D clearly separates what is CT and RT so 
such a change would require a DIP. I don't even know if this is 
technically possible.


About what you want to achieve, note that import() is more used 
to include code, import lookup tables and this kind of things. It 
must not be seen as a CT way of reading files.


Re: Delegate / Error: cannot implicitly convert expression...

2019-06-15 Thread user1234 via Digitalmars-d-learn

On Saturday, 15 June 2019 at 17:42:04 UTC, ag0aep6g wrote:

On Saturday, 15 June 2019 at 17:24:45 UTC, user1234 wrote:

---
void foo(){writeln(__PRETTY_FUNCTION__);}

void main(string[] args)
{
void delegate() dg;
dg.funcptr = 
dg.ptr = null; // usually a "this" or a frame address
dg();
}
---

because dg.ptr would be used to retrieve the offset of the 
locals variable used in the parent stack or the address of a 
class instance (the this). But this is not required at all 
here. The opposite way would lead to various access violation.


That only works because foo doesn't have any parameters. When 
you add even just one, things will go wrong.


True if was forgetting that the context is a hidden parameter...
Maybe it depends on the calling convention too ?


Re: Delegate / Error: cannot implicitly convert expression...

2019-06-15 Thread user1234 via Digitalmars-d-learn

On Saturday, 15 June 2019 at 16:34:22 UTC, Robert M. Münch wrote:

On 2019-06-15 16:19:23 +, Anonymouse said:

By design, I think: "delegate and function objects cannot be 
mixed. But the standard function std.functional.toDelegate 
converts a function to a delegate."


Your example compiles if the assignment is changed to dg = 
toDelegate(); (given appropriate imports).


https://tour.dlang.org/tour/en/basics/delegates

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


Hmm... but this here compiles:

void main()
{
   import std.stdio: write, writeln, writef, writefln;
   void foo(int a) {return; }

   void test()
   {
void delegate(int) dg;

   dg = 
   }
}

See: https://run.dlang.io/is/U7uhAX

Is it because inside main() there is a stack frame? And with a 
global function there is none? I'm a bit confused...


yes. delegate is a function pointer + its context. At the global 
scope there's no context. Actually the following works fine:


---
void foo(){writeln(__PRETTY_FUNCTION__);}

void main(string[] args)
{
void delegate() dg;
dg.funcptr = 
dg.ptr = null; // usually a "this" or a frame address
dg();
}
---

because dg.ptr would be used to retrieve the offset of the locals 
variable used in the parent stack or the address of a class 
instance (the this). But this is not required at all here. The 
opposite way would lead to various access violation.


Re: Is there any performance penalty for static if?

2019-05-15 Thread user1234 via Digitalmars-d-learn

On Wednesday, 15 May 2019 at 22:03:39 UTC, Ferhat Kurtulmuş wrote:

Hi,

Maybe I already know the answer, but have to be sure about 
this. I am emulating this cpp code "int val = mat.at(row, 
col)" like:


T at(T)(int row, int col){
static if (T.stringof == "float"){
return getFloatAt(row, col);
} else static if (T.stringof == "double"){
return getDoubleAt(row, col);
} else static if (T.stringof == "int"){
return getIntAt(row, col);
} else static if (T.stringof == "ubyte"){
return getUCharAt(row, col);
} else static if (T.stringof == "byte"){
return getSCharAt(row, col);
} else static if (T.stringof == "short"){
return getShortAt(row, col);
}
}
This works as expected, and I know conditions of "static if" is 
determined at compile time  and I assume no speed penalty here?


You've been given the answer but about this particular piece of 
code, rather use the "is" expression


  static if (is(T == float)) {}
  else static if (is(T == double)) {}

etc.


Re: Nothing at all compiles with -m64 on Windows

2019-05-11 Thread user1234 via Digitalmars-d-learn

On Saturday, 11 May 2019 at 09:59:25 UTC, Anonymouse wrote:

On Tuesday, 7 May 2019 at 17:33:22 UTC, Ron Tarrant wrote:
I've had this happen, too. I don't know for sure, but I think 
it may be because the installers aren't prepared to do 
updates, not on Windows, anyway.


My best success for updating has been to scrape D completely 
off my drive (ie. uninstall DMC and DMD using Control Panel > 
Programs and Features) then reinstall from scratch.


I only had DMD installed, but I uninstalled it and reinstalled 
to no effect.


Removing Visual Studio 2017 did fix it though, which is both a


This is because -m64 work in two ways un der win. Either with MS 
stuff or MinGW+LLD-link. If after removing VS it worked then this 
indicate that building with MS stuff is broken (but MinGW+LLD is 
fine). It's maybe a bug due to the fact that -m64 is the default 
now.



relief and to some dismay.





Re: Static struct?

2019-04-24 Thread user1234 via Digitalmars-d-learn

On Wednesday, 24 April 2019 at 21:12:10 UTC, JN wrote:
I noticed a construct I haven't seen before in D when reading 
the description for automem - 
https://github.com/atilaneves/automem


 static struct Point {
int x;
int y;
}


What does "static" do in this case? How does it different to a 
normal struct?


It's like if it's declared at the global scope, meaning that it 
doesn't know the context and cant access, if declared in a 
function, the stack frame. Now dependeding on the location, 
static can be a noop.


module foo;

static struct One {} // noop

void bar()
{
int i;
static struct Two { void stuff(){ i = 42:} } // error
}

void baz()
{
int i;
struct Three { void stuff(){ i = 42:} } // ok
}




Re: Help with Regular Expressions (std.regex)

2019-03-03 Thread user1234 via Digitalmars-d-learn

On Sunday, 3 March 2019 at 18:32:14 UTC, user1234 wrote:

On Sunday, 3 March 2019 at 18:07:57 UTC, Samir wrote:
or  // sorry i don't have the regex API in mind

  import std.array: array;
  import std.alogrithm.iteration : map;
  auto allMatches = matchAll(line, pattern).map(a => 
a.hit).array;


oops forgot the bang

  auto allMatches = matchAll(line, pattern).map!(a => 
a.hit).array;





Re: Help with Regular Expressions (std.regex)

2019-03-03 Thread user1234 via Digitalmars-d-learn

On Sunday, 3 March 2019 at 18:07:57 UTC, Samir wrote:
I am belatedly working my way through the 2018 edition of the 
Advent of Code[1] programming challenges using D and am stumped 
on Problem 3[2].  The challenge requires you to parse a set of 
lines in the format:

#99 @ 652,39: 24x23
#100 @ 61,13: 15x24
#101 @ 31,646: 16x28

I would like to store each number (match) as an element in an 
array so that I can refer to them by index.  For example, for 
the first line:


m = [99, 652, 39, 24, 23]
assert(m[0] == 99);
assert(m[1] == 652);
// ...
assert(m[4] == 23);

What is the best way to do this?  (I will worry about 
converting characters to integers later.)


I have the following solution so far based on reading Dmitry 
Olshansky's article on std.regex[3] and the std.regex 
documention[4]:


import std.stdio;
import std.regex;

void main() {
auto line= "#99 @ 652,39: 24x23";
auto pattern = regex(r"\d+");
auto m   = matchAll(line, pattern);
writeln(m);
}

which results in:
[["99"], ["652"], ["39"], ["24"], ["23"]]

But this doesn't seem to be an iterable array as changing 
writeln(m) to writeln(m[0]) yields

Error: no [] operator overload for type RegexMatch!string

Changing the line to writeln(m.front[0]) yields
99

but m.front doesn't allow me to access other elements (i.e. 
m.front[1]):

requested submatch number 1 is out of range

??:? _d_assert_msg [0x4dc27a]
??:? inout pure nothrow @trusted inout(immutable(char)[]) 
std.regex.Captures!(immutable(char)[]).Captures.opIndex!().opIndex(ulong) [0x4d8d57]

??:? _Dmain [0x49ffc8]

I've tried something like
foreach (m; matchAll(line, pattern))
writeln(m.hit);

which is close but doesn't result in an array.  Do I need to 
use matchFirst?


Thanks in advance.
Samir

[1] https://adventofcode.com/2018
[2] https://adventofcode.com/2018/day/3
[3] https://dlang.org/articles/regular-expression.html
[4] https://dlang.org/phobos/std_regex.html


Hello, Something like this should work:

  import std.array: array;
  auto allMatches = matchAll(line, pattern).array;

or  // sorry i don't have the regex API in mind

  import std.array: array;
  import std.alogrithm.iteration : map;
  auto allMatches = matchAll(line, pattern).map(a => a.hit).array;


What happened with `writeln` is that it iterates the `matchAll` 
results which is an input range, which is lazy. `.array` stores 
the results in an array.


Re: Is it feasible to slowly rewrite a C++ codebase in D?

2018-06-20 Thread user1234 via Digitalmars-d-learn
On Wednesday, 20 June 2018 at 18:47:10 UTC, Jordi Gutiérrez 
Hermoso wrote:

I'm specifically thinking of the GNU Octave codebase:

http://hg.savannah.gnu.org/hgweb/octave/file/@

It's a fairly old and complicated C++ codebase. I would like to 
see if I could slowly introduce some D in it, anywhere.


- This can be a problem if the project is very active. This issue 
was noticed by the people who converted DMD compiler from C++ to 
D and finally a dedicated tool was used, improved until some CI 
tests passed.


Now, as I understand it, I would need to begin with making 
`main` a D function, because D needs to initialise the runtime. 
Is this correct?


- The runtime can be initialized by hand if it's required, see 
core.runtime.Runtime.initialize()





Re: Ambiguous template parameter names

2018-05-02 Thread user1234 via Digitalmars-d-learn

On Wednesday, 2 May 2018 at 20:32:43 UTC, jmh530 wrote:
In the function below, there is a template parameter and a 
normal parameter both with the same name. However, the function 
returns the normal parameter. The template parameter is 
effectively ignored. I was surprised by this behavior.


Is this a bug or intentional? I did not see it documented 
anywhere.



```
int foo(int val)(int val)
{
return val;
}

void main()
{
assert(foo!1(2) == 2);
}
```


i think this is a bug and that it should be reported. The main 
problem is that you cant even use the val (the template parameter 
one) in a static if.


Re: Program exited with code 1

2018-04-19 Thread user1234 via Digitalmars-d-learn

On Thursday, 19 April 2018 at 08:13:00 UTC, Andrey wrote:

Hello,
I wrote a small test code with WinApi:


import core.runtime;
import std.utf;

import core.sys.windows.windows;
import core.sys.windows.wingdi;

class Test
{
public this() nothrow
{

}
}

extern(Windows)
int WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR lpCmdLine, 
int nCmdShow)

{
new Test(); // error is here
return 0;
}


When I run it, there is an error: Program exited with code 1.

If I comment "new Test();" - no error happens. Why?


The run-time is not already initialized but the "new" operator 
relies on it.


Re: How do you check for nonempty string?

2018-04-13 Thread user1234 via Digitalmars-d-learn

On Friday, 13 April 2018 at 17:41:00 UTC, Adam D. Ruppe wrote:

On Friday, 13 April 2018 at 17:38:39 UTC, Dr.No wrote:

string s = null;
if(s !is null && s[0] == '/')


is this correct?


No, that doesn't work if the string = "a"[$..$] for example

Just use

if(s.length && s[0])

instead


just `if (s.length)` is enough.




Re: Help optimizing code?

2018-01-01 Thread user1234 via Digitalmars-d-learn

On Monday, 1 January 2018 at 15:23:19 UTC, Adam D. Ruppe wrote:

On Monday, 1 January 2018 at 15:09:53 UTC, Lily wrote:
I started learning D a few days ago, coming from some very 
basic C++ knowledge, and I'd like some help getting a program 
to run faster.


So a few easy things you can do:

1) use `float` instead of `real`. real sucks, it is really slow 
and weird. Making that one switch doubled the speed on my 
computer.


Yes I've also adviced double. Double is better if the target arch 
is X86_64 since part of the operations will be made with SSE. 
With "real" the OP was **sure** to get 100% of the maths done in 
the FPU (although for all the trigo stuff there's no choice)




2) preallocate the imageData. before the loop, 
`imageData.reserve(width*height*3)`. Small savings on my 
computer but an easy one.


3) make sure you use the compiler optimization options like 
`-O` and `-inline` on dmd (or use the gdc and ldc compilers 
both of which generally optimize better than dmd out of the 
box).



And if that isn't enough we can look into smaller things, but 
these overall brought the time down to about 1/3 what it 
started on my box.





Re: Help optimizing code?

2018-01-01 Thread user1234 via Digitalmars-d-learn

On Monday, 1 January 2018 at 15:09:53 UTC, Lily wrote:
I started learning D a few days ago, coming from some very 
basic C++ knowledge, and I'd like some help getting a program 
to run faster. The code is here: 
https://github.com/IndigoLily/D-mandelbrot/blob/master/mandelbrot.d


Right now it runs slower than my JavaScript Mandelbrot renderer 
on the same quality settings, which is clearly ridiculous, but 
I don't know what to do to fix it. Sorry for the lack of 
comments, but I can never tell what will and won't be obvious 
to other people.


- The first thing is to compile with the best options:

dmd mandelbrot.d -O -release -inline -boundscheck=off

- You append a lot, which can cause reallocs for imageData; Try

   import std.array;
   Appender!(ubyte[]) imageData;

   The code will not have to be changed for "~=" since Appender 
overloads this operator.


- I'd use "double" instead of "real".


Re: What could this OptLink Error mean?

2017-12-29 Thread user1234 via Digitalmars-d-learn

On Friday, 29 December 2017 at 16:11:20 UTC, Dukc wrote:
I was building one example of DLangUi (dub build 
--build-mode=allAtOnce --build=debuglinker) and it did compile 
but the linker started to complain. I did notice it seemed to 
be related to the standard library, so I updated it and 
DRuntime to the lastest master, rebuilt them and replaced 
phobos.lib with the result. I also removed the binary and .dub 
directory from DLangUI to force Dub to rebuild it, which it 
did. Still the linker complains, but about a different symbol:


..\..\lib\dlangui.lib(colors)
 Error 42: Symbol Undefined __d_switch_string

Does anybody have an idea what could be causing this?


The deps have to be rebuild too. Assuming paths and everything is 
okay (should be the case when you build ~master as indicated in 
the wiki) just add --force.


Re: Don't expect class destructors to be called at all by the GC

2017-12-20 Thread user1234 via Digitalmars-d-learn
On Thursday, 21 December 2017 at 02:57:00 UTC, Mike Franklin 
wrote:

"Don't expect class destructors to be called at all by the GC"

I was a bit shocked to read that here: 
https://p0nce.github.io/d-idioms/#The-trouble-with-class-destructors


The document tries to clarify with:
"The garbage collector is not guaranteed to run the destructors 
for all unreferenced objects."


Unfortunately, that doesn't really shed much light on this 
oddity.  So, specifically, under what circumstances are 
destructors not called?


Thanks,
Mike


When the GC is unaware of a class instance (an "unreferenced 
object") it won't call its destructor. This happens when you use 
alternative memory management strategy, for example using 
Mallocator and make you get an unreferenced object that you have 
to manage yourself.


Re: Sort in return statement

2017-12-08 Thread user1234 via Digitalmars-d-learn

On Saturday, 9 December 2017 at 03:24:52 UTC, codephantom wrote:

On Saturday, 9 December 2017 at 02:45:35 UTC, rjframe wrote:


`sort` returns a SortedRange of ushorts, not an array of 
ushorts. Make it:


```
import std.array : array;
return sort(numbers.take(8)).array;
```

--Ryan


That's it!

Thanks Ryan.


You can also return a lazy range:

```
auto draw8Numbers()
{
 import std.meta : aliasSeqOf;
 import std.range : iota, take;
 ushort[] numbers = [ aliasSeqOf!(iota(1,46)) ];
 import std.random : randomShuffle;
 randomShuffle(numbers);
 import std.algorithm.sorting : sort;
 return sort(numbers[].take(8));
}

void main()
{
import std.array;
ushort[] nbrs = draw8Numbers.array; // evaluated after 
return, during assingment

}
```


Re: Does dmd not always compile all of the source code?

2017-12-07 Thread user1234 via Digitalmars-d-learn
On Wednesday, 6 December 2017 at 19:19:09 UTC, A Guy With a 
Question wrote:
On Wednesday, 6 December 2017 at 18:09:45 UTC, Steven 
Schveighoffer wrote:

On 12/6/17 12:17 PM, Steven Schveighoffer wrote:

So why wouldn't the compiler fail? Because it has no idea yet 
what you mean by Nullable. It doesn't even know if Nullable 
will be available or not. You could even import Nullable, but 
Nullable!T may be an error.


To give an example of why the compiler waits until 
instantiation:


class C(T) : T
{
   void foo() { doesthisexist(); }
}

class D { void doesthisexist(); }

auto x = new C!D; // OK
auto y = new C!Object: // fail

-Steve


It also doesn't parse or do semantic checks on unit tests 
unless you add the flag...apparently.


This compiles...

unittest
{
WHY DOESNT THE COMPILER FIND A PROBLEM HERE!?
}

It seems D's fast compile times are achieved by skipping 
semantic checking and even parsing when it doesn't feel it's 
needed. I strongly disagree with this decision. This could 
leave complex dormant time bombs that break builds unexpectedly 
and even accidentally.


That's why measuring the level of coverage obtained by the 
unittests is important.
It's not just about the templates, standard if conditions that 
are never tested can also be time bombs, standard functions that 
are never tested can also be time bombs. Even more pernicious in 
a way.


Re: Debugging shared libs on windows

2017-12-06 Thread user1234 via Digitalmars-d-learn

On Wednesday, 6 December 2017 at 21:17:55 UTC, Tofu ninja wrote:

On Wednesday, 6 December 2017 at 21:12:20 UTC, Tofu ninja wrote:
I am compiling with -m64 -shared -debug -g and a .pdb is 
generated but visual studio says the dll was not compiled with 
debug information, am I missing something or is this not 
supported?


DMD32 D Compiler v2.076.0


Actually never mind, -gf worked


what is -gf ? it's not documented here 
https://dlang.org/dmd-windows.html#switches


Re: Template specialisation, "Generic type locking", offline stdlib docs and case-based template question

2017-11-30 Thread user1234 via Digitalmars-d-learn

On Friday, 1 December 2017 at 03:39:12 UTC, helxi wrote:

1. Template specialisation.
Why is this useful?:
T getResponse(T = int)(string question); And how does it differ 
from

int getResponse(string question); ?


Good Q. Without thinking more it looks like a pointless example. 
The only difference i see is that the templatized version won't 
get compiled unless used.


Context: http://ddili.org/ders/d.en/templates.html : Section: 
"Default template parameters"


2. "Generic locking".
Is it possible to specialise templates for a certain group of 
types? For example

auto fn(T)(T arg)
auto fn(T : int, double, float, ulong)(T arg); //shares same 
behaviour
auto fn(T : char, string, dchar, wchar, dstring, wstring)(T 
arg); // shares same behavior


You can use template constraints:

auto fn(T)(T arg)
if (is(T==int) || is(T==double) || is(T==float) || is(T==ulong)){}

auto fn(T)(T arg)
if (is(T==char) || is(T==string) || is(T==dchar) || 
is(T==wchar)){}




3. "Offline docs".
Is there any offline documentation of the stdlib? Like 
https://en.cppreference.com/mwiki/index.php?title=Cppreference:Archives=95461


Yes, distributes with each release. look inside the 7z archive. 
On linux it's setup

here: /usr/share/dmd/html/d/phobos/


4. Case based question regarding templates:

class Stack(T)
{
private:
T[] data;
public:
this(T)(T[] data){ /*..*/}
this(T)(){}

   //...

}

void main()
{
auto s = new Stack!int;
}

Says:
 Error: template app.Stack!int.Stack.__ctor cannot deduce 
function from argument types !()(), candidates are:
source/app.d(6,2):app.Stack!int.Stack.__ctor(T)(T[] 
data)

source/app.d(9,2):app.Stack!int.Stack.__ctor(T)()

Why is Stack!int a ctor()() instead of a ctor(int)()?


You must use another identifier here

class Stack(T)
{
private:
T[] data;
public:
this(TT)(TT[] data){ /*..*/}
this()(){}
//...
}


Re: Basic questions about D lang?

2017-11-29 Thread user1234 via Digitalmars-d-learn

On Wednesday, 29 November 2017 at 11:32:51 UTC, Jayam wrote:

In D lang,
[...]
3. Can we make library file and use that in any project like 
'Util class' ?


Of course ! Plenty of them can be found here: 
https://code.dlang.org/?sort=updated=library




Re: Strange error when compiling with dmd, not with ldc

2017-11-29 Thread user1234 via Digitalmars-d-learn

On Wednesday, 29 November 2017 at 10:55:35 UTC, user1234 wrote:

On Wednesday, 29 November 2017 at 06:18:09 UTC, Fra Mecca wrote:

[...]


You must also use a type constructor later, when a 
Configuration is declared:


```
immutable(Configuration) config;
config.toString.writeln; // okay this time
```

What happens is that all the member functions have the 
`immutable` attribute, but the instance you declared was not 
itself `immutable`.


actually this:

```
immutable struct Configuration {
@property string toString(){return "";}
}
```

is like:

```
struct Configuration {
@property string toString() immutable {return "";}
}
```

I would personally prefer the second form. Why ? Because the 
variable members will be set immutable anyway when an instance 
is declared.


And about the DMD vs LDC thing, i thing that the difference can 
be simply explained by the fact that LDC uses a slightly older 
compiler front end version, meaning that after 1 or 2 updates, 
the same error would happen.


Now i don't know which change in particular has been made 
recently in the front-end. Maybe the semantic of the leading 
qualifier when "immutable struct {}" is used but i would bet too 
much on that.


Re: Strange error when compiling with dmd, not with ldc

2017-11-29 Thread user1234 via Digitalmars-d-learn

On Wednesday, 29 November 2017 at 06:18:09 UTC, Fra Mecca wrote:

I have this struct:

immutable struct Configuration {
string title;
string baseurl;
string url;
string email;
string author;
string parser;
string target;
string urlFormat;
string urlFormatCmd;

short port;

string[] ignore;
string[] extensions;

@property string toString()
{
auto urlF = (urlFormatCmd ? "url_format_cmd: " ~ 
urlFormatCmd : "") ~ "\n";

return
"title: "~ title ~ "\n" ~
"baseurl: "  ~ baseurl ~ "\n" ~
"url: "  ~ url ~ "\n" ~
"email: "~ email ~ "\n" ~
"author: "   ~ author ~ "\n" ~
"parser: "   ~ parser ~ "\n" ~
"target: "   ~ target ~ "\n" ~
"url_format: "   ~ urlFormat ~ "\n" ~
"ignore: "   ~ to!string(ignore)[1 .. $ - 1] ~ "\n" 
~
"extensions: "   ~ to!string(extensions)[1 .. $ - 1] ~ 
"\n" ~

urlF;
}
}

and this function:

void show_config()
{
writef("%s", parse_config(
exists("config.sdl") ? "config.sdl" : 
"").toString);

}


Whenever I compile with ldc2 I get no errors, while with dmd I 
get:


source/configuration.d(105,27): Error: immutable method 
configuration.Configuration.toString is not callable using a 
mutable object



What is the problem?


You must also use a type constructor later, when a Configuration 
is declared:


```
immutable(Configuration) config;
config.toString.writeln; // okay this time
```

What happens is that all the member functions have the 
`immutable` attribute, but the instance you declared was not 
itself `immutable`.


actually this:

```
immutable struct Configuration {
@property string toString(){return "";}
}
```

is like:

```
struct Configuration {
@property string toString() immutable {return "";}
}
```

I would personally prefer the second form. Why ? Because the 
variable members will be set immutable anyway when an instance is 
declared.


Re: On Attributes

2017-11-27 Thread user1234 via Digitalmars-d-learn
On Monday, 27 November 2017 at 20:07:08 UTC, A Guy With a 
Question wrote:
On Monday, 27 November 2017 at 19:41:03 UTC, Adam D. Ruppe 
wrote:

On Monday, 27 November 2017 at 19:10:04 UTC, A Guy With a
One thing that is bugging me is having to mark up all of my 
declarations with attributes.


Meh, you could also just ignore the attribute crap. Only 
reason I ever mess with them is if someone who is using them 
tries to use my code... otherwise you can pretend the spam 
doesn't exist and be more productive.


Yeah, I'm leaning towards that direction. It seems they could 
have been useful if they were the default. But opting into them 
doesn't seem as useful, unfortunately. I'll probably continue 
fiddling with them, but I might just abandon using them.


I also rarely put the attributes (although sincerely i think that 
my funcs are pure 99% of them time) but take care because 
recently it was announced that better code will be generated if 
there are scope(exit) / try-finally inside nothrow funcs:


https://forum.dlang.org/thread/ovbduq$m3a$1...@digitalmars.com


Re: convert string to ubyte[]

2017-11-11 Thread user1234 via Digitalmars-d-learn

On Saturday, 11 November 2017 at 15:48:59 UTC, Mike Parker wrote:

On Saturday, 11 November 2017 at 15:38:18 UTC, aki wrote:
auto bytes = cast(immutable(ubyte)[])s;

Of course, if you need a mutable array you should dup:

auto bytes = cast(ubyte[])s.dup;


Not only "should" but he "must" otherwise with string literals 
he'll get a violation access error.


Re: Strange AV in asm mode (code only for amd64)

2017-11-06 Thread user1234 via Digitalmars-d-learn

On Sunday, 5 November 2017 at 14:25:24 UTC, user1234 wrote:

On Sunday, 5 November 2017 at 13:43:15 UTC, user1234 wrote:

[...]


Hmmm it was just the amount of nops.

---
import std.stdio;

alias Proc = size_t function();

size_t allInnOne()
{
asm pure nothrow
{
naked;
mov RAX, 1;
ret;
nop;nop;
mov RAX, 2;
ret;
}
}

void main()
{
Proc proc1 = 
Proc proc2 = cast(Proc) (cast(void*) + 8);
writeln(proc1(), " ",proc2());
}
---


That's a nice trick against static analysis. I imagine well an 
attacker trying to fight against the first part, even if never 
executed, assuming he found that this function got executed and 
then he assumes that the code get executed from the start.


Re: Strange AV in asm mode (code only for amd64)

2017-11-05 Thread user1234 via Digitalmars-d-learn

On Sunday, 5 November 2017 at 14:27:18 UTC, Eugene Wissner wrote:

On Sunday, 5 November 2017 at 13:43:15 UTC, user1234 wrote:

[...]


One of the problems is that "naked" is missing in your 
assembly. If you write


asm pure nothrow
{
 naked;
 mov RAX, 1;
 ret;
 nop;nop;nop;nop;nop;nop;nop;
 mov RAX, 2;
 ret;
}

writeln(proc1()) works. Without "naked" dmd generates the 
prologue and epilogue for your function. Inside the assembly 
you return from the function without restoring the stack. It 
causes the segfault. So you have to write the prologue before 
returning or use nacked assembly.
With "naked" and "Proc proc2 = cast(Proc) (cast(void*)proc1 + 
8);" the example works.


Yeah thanks, i figured it out too. Also there was too much nops.


Re: Strange AV in asm mode (code only for amd64)

2017-11-05 Thread user1234 via Digitalmars-d-learn

On Sunday, 5 November 2017 at 13:43:15 UTC, user1234 wrote:

[...]


Hmmm it was just the amount of nops.

---
import std.stdio;

alias Proc = size_t function();

size_t allInnOne()
{
asm pure nothrow
{
naked;
mov RAX, 1;
ret;
nop;nop;
mov RAX, 2;
ret;
}
}

void main()
{
Proc proc1 = 
Proc proc2 = cast(Proc) (cast(void*) + 8);
writeln(proc1(), " ",proc2());
}
---



Strange AV in asm mode (code only for amd64)

2017-11-05 Thread user1234 via Digitalmars-d-learn

Hello, try this:

---
import std.stdio;

alias Proc = size_t function();

size_t allInnOne()
{
asm pure nothrow
{
mov RAX, 1;
ret;
nop;nop;nop;nop;nop;nop;nop;
mov RAX, 2;
ret;
}
}

void main()
{
Proc proc1 = 
Proc proc2 = cast(Proc) (cast(void*)proc1 + 16);
writeln(proc1(), " ", proc2());
}
---

The call to proc1() gens a SEGFAULT after the first RET.
Remove the call to proc1() and it works.

Why that ?


Re: How to find the content of core.sys.* ?

2017-10-28 Thread user1234 via Digitalmars-d-learn

On Saturday, 28 October 2017 at 11:41:16 UTC, Ryan Frame wrote:

On Tuesday, 17 May 2016 at 06:56:36 UTC, rikki cattermole wrote:

On 17/05/2016 6:55 PM, chmike wrote:

Hello,

The nice and handy documentation of dlang doesn't provide any 
info on
the core.sys. How can I find out all the things that are in 
there ?


https://github.com/dlang/druntime/tree/master/src/core/sys


So is there a reason it's not being documented? I've got a 
deprecation message saying to switch from std.c.linux.linux to 
core.sys.posix.*


Generally I'd assume undocumented features mean "don't use 
this", or at least "use at your own risk" (I believe that's why 
deprecated features are removed from the docs before they're 
pulled from the code). It looks like doc comments are pretty 
sparse in core/sys - is that the only reason docs aren't being 
generated?


It's not documented because everything is already well documented 
either at microsoft, posix reference, c reference etc. It would 
be copy and paste monkey work to do that.


Re: DMD Callstacks

2017-10-24 Thread user1234 via Digitalmars-d-learn

On Tuesday, 24 October 2017 at 06:49:37 UTC, abad wrote:
On Monday, 23 October 2017 at 12:41:09 UTC, Márcio Martins 
wrote:
What is everyone doing to get proper file name and line number 
info for callstacks with DMD?


addr2line just gives me ??:0


You could try compiling with the -debug-switch. Of course if 
this turns out to be the fix, it doesn't help with std code.


"-debug" activates the debug condition. To get file and line it's 
"-g" (generate debug infos), although this won't have any effect 
for phobos since the static library is already compiled.


Re: is(this : myClass)

2017-10-20 Thread user1234 via Digitalmars-d-learn
On Friday, 20 October 2017 at 21:42:32 UTC, Jonathan M Davis 
wrote:
On Friday, October 20, 2017 21:32:48 Patrick via 
Digitalmars-d-learn wrote:
The compiler seems to reject the following code in a class 
method:


bool test = is(this : myClass);

Could some please explain this?


"this" is not a type.


Strangely this is not always true, in other contexts this is seen 
as atype, although probably a bug


class Foo
{
class Bar : this {}
static assert(is(Bar : Foo));
}



Re: Trait to identify if a type is a struct one

2017-10-18 Thread user1234 via Digitalmars-d-learn

On Wednesday, 18 October 2017 at 15:16:21 UTC, drug wrote:

18.10.2017 18:11, pham пишет:
Is there a way to identify if a type is a struct, something 
like isStruct

similar to isArray.

struct X
{
}

isStruct!X == true?

Also, there are isAbstractClass & isFinalClass but want to 
check if type is a class regardless? something like isClass?


Thanks
Pham


if (is(X == struct))
{
   ...
}


static if (is(X == struct))
{
   ...
}

ptherwise lots of strnage errors ;)



Re: testing if data is allocated on the stack or heap

2017-10-17 Thread user1234 via Digitalmars-d-learn

On Tuesday, 17 October 2017 at 17:27:17 UTC, Biotronic wrote:

On Tuesday, 17 October 2017 at 15:33:02 UTC, drug wrote:

[...]


I have very little knowledge about sbrk, so here's my solution.

Tested on win32 and win64.

[...]


Nice solution. Is `stackStart` thread local on purpose?


Re: readln of german Umlaute (terminal.d) / readln)

2017-10-17 Thread user1234 via Digitalmars-d-learn

On Tuesday, 17 October 2017 at 15:02:29 UTC, Adam D. Ruppe wrote:
Or try this newest commit 
https://github.com/adamdruppe/arsd/blob/master/terminal.d and 
see if it works better for you.


in the commit message: ~~ascii~~ ANSI.


Re: Assert and undefined behavior

2017-10-11 Thread user1234 via Digitalmars-d-learn

On Wednesday, 11 October 2017 at 09:27:49 UTC, John Burton wrote:

[...]
I therefore feel like I ought to not use assert and should 
instead validate my assumptions with an if statement and a 
throw or exit or something.


Yes, that's the way of doing. assert() are just used to test the 
program. the -release option in DMD disable all the assert() 
(excepted assert(0) which is a bit special), so that in a release 
version, only Throwable objects can be used after a failure 
detected.




Re: Add a precompiled c++ obj file to dub

2017-10-07 Thread user1234 via Digitalmars-d-learn

On Sunday, 8 October 2017 at 02:58:36 UTC, Fra Mecca wrote:

On Saturday, 7 October 2017 at 23:54:50 UTC, user1234 wrote:

On Saturday, 7 October 2017 at 19:56:52 UTC, Fra Mecca wrote:

Hi all,
I am writing a backend that is partly Vibe.d and partly 
clucene in c++.
I have some object files written in c++ and compiled with g++ 
that are not considered by dub during the linking phase and 
throws `function undefined error ` every time.


Is there a way to tell dub to let dmd handle that .o files?


Yes, add this to your JSON:

  "sourceFiles-linux-x86_64" : [
"somepath/yourobject.o"
  ],


I tried the sourceFiles approach, it failed and I could 
reproduce that in some days.


At the end I added them as linking options (lflags) but it is 
kinda odd that it works given that everything is supplied to 
dmd as -Lobj.o


Huh, i'm surprised but well, if it works for you.
My advice was based on 
https://github.com/BBasile/dbeaengine/blob/master/dub.json 
(object file is passed to dmd) which works, I often use it.


Re: Add a precompiled c++ obj file to dub

2017-10-07 Thread user1234 via Digitalmars-d-learn

On Saturday, 7 October 2017 at 19:56:52 UTC, Fra Mecca wrote:

Hi all,
I am writing a backend that is partly Vibe.d and partly clucene 
in c++.
I have some object files written in c++ and compiled with g++ 
that are not considered by dub during the linking phase and 
throws `function undefined error ` every time.


Is there a way to tell dub to let dmd handle that .o files?


Yes, add this to your JSON:

  "sourceFiles-linux-x86_64" : [
"somepath/yourobject.o"
  ],


Re: Why does BinaryHeap sometime cause compile-error in foeach?

2017-09-30 Thread user1234 via Digitalmars-d-learn
On Saturday, 30 September 2017 at 09:27:23 UTC, Shigeki Karita 
wrote:

https://dpaste.dzfl.pl/cd605899d050

why this code cannot convert to foreach (over Structs and 
Classes with Ranges).


auto h = new BinaryHeap!(int[])(new int[0]);
typeof(h).stringof.writeln;
static assert(isInputRange!(typeof(h)));
h.insert(3);
h.insert(1);
h.insert(2);
// Error: invalid foreach aggregate `h`
// foreach (e; h) e.writeln;
for (; !h.empty; h.popFront()) {
  auto e = h.front();
  e.writeln;
}


https://dlang.org/spec/statement.html#foreach-with-ranges


The reason why it doesn't work is much more simple than you 
think: h is not a BinaryHeap, it's a pointer to.


Try "foreach (e; *h) e.writeln;" and it works.




Re: generating @property from structs

2017-09-30 Thread user1234 via Digitalmars-d-learn
On Saturday, 30 September 2017 at 08:20:44 UTC, Nicholas Wilson 
wrote:

struct MyType
{
void* ptr;
static struct Info
{
@(42) int foo;
}

// Should be generated by the mixin below
@property int foo()
{
 int ret;
 getMyTypeInfo(ptr,42,int.sizeof,);
 return ret;
}
mixin generateInfo!getMyTypeInfo;
}

extern(C) void getMyTypeInfo(void*,int, size_t,void*);

How do I write generateInfo info?

mixin template generateInfo(alias func)
{
foreach(field; typeof(this).Info.tupleof)
{
//???
}
}

I know I'll probably have to resort to string mixins, but how 
do I get the attribute so that I call
func(ptr,attibute, T.sizeof, )? There will be a couple of 
values that dont have an attribute but they are all of known 
types and I want to handle them separately.


Thanks
Nic


You can use a struct that contains the value because apparently 
without you can only retrieve a specific value:


---
struct ValueHolder{int value;}

struct Foo
{
@ValueHolder(42) int foo;

int getTheValueDuringTheCall(string member)()
{
import std.traits;
alias uda = getUDAs!(__traits(getMember, Foo, member), 
ValueHolder);

static if (uda.length == 1)
return uda[0].value;
else
return 0;
}

void test()
{
import std.stdio;
writeln(getTheValueDuringTheCall!"foo");
}
}

void main()
{
Foo foo; foo.test();
}
---

I mean that `getUDAs!(__traits(getMember, Foo, member), int);` 
wouldn't work.


Re: static this not run?

2017-09-30 Thread user1234 via Digitalmars-d-learn
On Saturday, 30 September 2017 at 06:15:41 UTC, Nicholas Wilson 
wrote:
No "initialising onError", the static this is not even being 
run!

I'm using LDC master.

See also https://github.com/libmir/dcompute/issues/32


LDC 1.4, DMD 2.076, DMD ~master and finally GDC all give the 
expected result here


"initialising onErrorinitialising onError: funcptr = 0xaddress>"


each time using:

---
enum Status {success,}

class StatusException : Exception
{
this(Status s) {this.s = s;super("");}
Status s;
}

void delegate(Status) onError;

static this()
{
import core.stdc.stdio;
printf("initialising onError");
onError = (Status s) { throw new StatusException(s);};
printf("initialising onError: funcptr = 0x%x", 
onError.funcptr);

}

void main()
{
import std.stdio;
writeln(onError.funcptr);
}
---





Re: Is it possible to specify the address returned by the address of operator?

2017-09-28 Thread user1234 via Digitalmars-d-learn

On Thursday, 28 September 2017 at 00:11:56 UTC, DreadKyller wrote:

On Wednesday, 27 September 2017 at 23:24:58 UTC, user1234 wrote:
Notice how dereferencing the pointer did not call the 
overloaded function, because a pointer to Test is not the same 
type as a Test.


Yeah, this is rather made to implement fat pointers.




Re: Is it possible to specify the address returned by the address of operator?

2017-09-27 Thread user1234 via Digitalmars-d-learn
On Wednesday, 27 September 2017 at 21:01:36 UTC, Jesse Phillips 
wrote:
On Wednesday, 27 September 2017 at 16:35:54 UTC, DreadKyller 
wrote:
My question is about overloading, several operators can be 
overloaded in D, one of the ones that can't apparently is the 
address of operator (). My question is have I simply 
missed it or does it actually not exist, and if it's not 
overloadable, is there any reason why this was decided? 
Because there's been numerous times that it'd be useful to me, 
just recently with how much I use the operator because of 
OpenGL I decided to ask.


My answer is that & is a defined operation on all addressable 
memory. Unlike other operators which don't exist until you 
"overload" them.


Yes but the dereference operator can be overloaded. The reasoning 
doesn't stand, unless that's recognized as an inconsistency.


Re: Why isn't there more if(__ctfe) in std.math ?

2017-09-23 Thread user1234 via Digitalmars-d-learn
On Saturday, 23 September 2017 at 18:23:12 UTC, Juraj Mojzis 
wrote:

Hi,
browsing trough phobos bugzilla I found a couple of open issues 
regarding CTFE and basic math functions ( Issue 4177, 5227).
It looks to me that at least floor/ceil could by fixed by a 
simple:

if (__ctfe) return simple_floor_impl(x);

But that looks too easy and would surely be implemented 
already. So I would like to ask what the real problems are.


Thanks,
Juraj


"if (__ctfe) {}" is a test happening at runtime. Both the if and 
the else branches got compiled, this implies:

- more code to cache
- slower code
just to allow CTFE.


CTFE rounding can be more simply done using cast(int), although 
for negative numbers the behavior is not the same.


Re: Problems with function as parameter

2017-09-22 Thread user1234 via Digitalmars-d-learn

On Friday, 22 September 2017 at 04:32:08 UTC, Josh wrote:
As an aside, in that doc it says "The .funcptr property of a 
delegate will return the function pointer value as a function 
type". So I also tried 
Mix_ChannelFinished(().funcptr); and this compiled, 
but caused a segfault when
the callback ran. What would have caused this? Is it because 
it's a C function?


No it's because in this function are used variables that are 
specific to the class instance (the this). If there weren't this 
would work, even if it's not a good idea to do that:



struct Foo
{
int a;
void needThisYeahReally(){a = 0;}
void needThisButWorkWithout(){}
}

void main()
{
Foo foo;
{
auto dg = 
dg.funcptr();
}
{
auto dg = 
// dg.funcptr(); // segfault because of access to this.a
}
}


Using a pointer to a static member function was the right thing 
to do.


Re: cannot access frame of function

2017-09-18 Thread user1234 via Digitalmars-d-learn

On Monday, 18 September 2017 at 18:49:54 UTC, ag0aep6g wrote:

On 09/18/2017 08:25 PM, user1234 wrote:

On Monday, 18 September 2017 at 14:45:25 UTC, Alex wrote:

[...]

import std.algorithm.iteration : sum, cumulativeFold;

void main()
{
double[5] a;

[...]>> auto asum = a[].sum;
[...]

asum is a lazy range and the error comes from this.


asum is not a range. It's a double.

Let's say that if you replace  asum by 1.23 then the code 
compiles.


Doesn't work for me. This still fails compilation with the same 
error:



import std.algorithm.iteration : sum, cumulativeFold;
void main()
{
double[5] a;
auto asum = 1.23;
auto jProbs = a[].cumulativeFold!((a, b) => (a + b)/asum);
}



Aw right, i had put 1.23 directly in the lambda. So, OP, you can 
dismiss my comment.


Re: cannot access frame of function

2017-09-18 Thread user1234 via Digitalmars-d-learn

On Monday, 18 September 2017 at 14:45:25 UTC, Alex wrote:

Hi all,
given this code:

import std.algorithm.iteration : sum, cumulativeFold;

void main()
{
double[5] a;
a = 0;
foreach(el; a) assert(el == 0);
a[0] = 1.0;
a[1] = 2.0;
a[2] = 3.0;
a[3] = 4.0;
a[4] = 5.0;
foreach(el; a) assert(el != 0);
auto asum = a[].sum;
auto jProbs = a[].cumulativeFold!((a, b) => (a + b)/asum);
}

the last line does not compile.

I found
http://forum.dlang.org/post/mailman.4097.1499105927.31550.digitalmars-d-b...@puremagic.com
and
https://issues.dlang.org/show_bug.cgi?id=11886

What I do not understand, how my example differs from the fixed 
bug?


asum is a lazy range and the error comes from this.
Let's say that if you replace  asum by 1.23 then the code 
compiles.


Re: Performance Issue

2017-09-06 Thread user1234 via Digitalmars-d-learn

On Tuesday, 5 September 2017 at 09:44:09 UTC, Vino.B wrote:

Hi,

 The below code is consume more memory and slower can you 
provide your suggestion on how to over come these issues.


string[][] csizeDirList (string FFs, int SizeDir) {
ulong subdirTotal = 0;
ulong subdirTotalGB;
auto Subdata = appender!(string[][]);
auto dFiles = dirEntries(FFs, SpanMode.shallow).filter!(a 
=> a.isDir && !globMatch(a.baseName, "*DND*")).map!(a => 
tuple(a.name, a.size)).array;

  foreach (d; dFiles) {
auto SdFiles = dirEntries(join(["?\\", d[0]]), 
SpanMode.depth).map!(a => tuple(a.size)).array;

foreach (f; parallel(SdFiles,1))
{ subdirTotal += f[0]; }
subdirTotalGB = 
(subdirTotal/1024/1024);
		if (subdirTotalGB > SizeDir) { Subdata ~= [d[0], 
to!string(subdirTotalGB)]; }

subdirTotal = 0;
}
return Subdata.data;
}

From,
Vino.B


Try to suppress the globMatch. according to the glob, just a 
ctRegex would do the job or even more simple `!a.canFind("DND")`.


  1   2   >